diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6fb2081c1..7a2e0ae21 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,6 +28,7 @@ jobs: runs-on: ubuntu-latest outputs: code: ${{ steps.paths.outputs.code }} + diskimage: ${{ steps.paths.outputs.diskimage }} steps: - uses: actions/checkout@v4 with: @@ -38,14 +39,16 @@ jobs: # A release tag always runs the whole gate: the tag is what ships, so # nothing about its contents may skip a check. case "${{ github.ref }}" in - refs/tags/*) echo "code=true" >> "$GITHUB_OUTPUT"; exit 0 ;; + refs/tags/*) printf 'code=true\ndiskimage=true\n' >> "$GITHUB_OUTPUT"; exit 0 ;; esac base="${{ github.event.pull_request.base.sha }}" [ -n "$base" ] || base="${{ github.event.before }}" code=true + diskimage=true if [ -n "$base" ] && git cat-file -e "$base^{commit}" 2>/dev/null; then git diff --name-only --no-renames "$base" HEAD > "$RUNNER_TEMP/changed" code=false + diskimage=false while IFS= read -r file; do case "$file" in # Nothing here can change what the gate builds, runs or measures. @@ -54,15 +57,20 @@ jobs: *.md | docs/* | LICENSE | NOTICE | .github/ISSUE_TEMPLATE/*) ;; *) code=true ;; esac + case "$file" in + # What makes or tests a disk image: the disk-image job. + tools/dmg/* | tools/appbundle/* | cmd/viva/package* | go.mod | go.sum | .github/workflows/ci.yml) diskimage=true ;; + esac done < "$RUNNER_TEMP/changed" else echo "no base commit to compare with; running the gate" >&2 fi echo "code=$code" >> "$GITHUB_OUTPUT" + echo "diskimage=$diskimage" >> "$GITHUB_OUTPUT" { echo "### changed files" head -50 "$RUNNER_TEMP/changed" 2>/dev/null | sed 's/^/ /' || true - echo "code=$code" + echo "code=$code diskimage=$diskimage" } >> "$GITHUB_STEP_SUMMARY" # Formatting and the Linux type-check of every package. Both are the same on @@ -174,7 +182,7 @@ jobs: run: | sudo apt-get install -y xvfb libxcb-shape0 libgtk-3-0 || { sudo apt-get update && sudo apt-get install -y xvfb libxcb-shape0 libgtk-3-0; } - xvfb-run -a -s '-screen 0 1280x1024x24 -noreset' go test ./internal/platform/linux -run '^Test(PreviewNativeX11Contract|NotificationNativeX11|TrayWindowQueuedRedrawBeforeInput|TrayWindowRepaintsLaterExposure)$' -count=1 -v + xvfb-run -a -s '-screen 0 1280x1024x24 -noreset' go test ./internal/platform/linux -run '^Test(PreviewNativeX11Contract|NotificationNativeX11|TrayWindowQueuedRedrawBeforeInput|TrayWindowRepaintsLaterExposure|AFileDragOutReachesAnotherClient)$' -count=1 -v GDK_BACKEND=x11 VIVA_TEST_GTK_NOTIFICATION=1 xvfb-run -a go test -tags vivagtk ./internal/platform/linux -run '^TestGTKNotificationFocusHints$' -count=1 -v - name: Native X11 global shortcut env: @@ -367,6 +375,8 @@ jobs: # WARP is a Windows API: this cannot run anywhere else. The file icon and # native structure ABI tests are here for the same reason: they build only # on Windows. + - name: directory picker initial location + run: go test ./internal/platform/windows ./app -run '^Test(FileDialogInitialDirectory|DriverInterceptsOpenDirectory)$' -count=1 -v - name: Material contracts and controls (WARP) run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|OpeningMaximized|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|FontWeights|(The)?MonoWeights|(The)?InterfaceWeights|EveryListedFamilyResolves|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI|ResizePresents|WindowSwapChain|LiveResize|FlipWindowResize|RedrawWaits|ContinuousRedraw|NoOpFrame|SameSize|ZeroSize|ResizeTimer|RedrawQueue|NativeRedrawMessage|CompositionSupersededFrame|DragPreview|QueuedMenuKeysLeaveTerminalCompositionWithItsOwner|MenuKeysPreserveSystemChordsAndShift|TerminalMenuStopsCapturingWhenWindowLosesFocus|DisabledIMEOffersMenuShortcutDuringComposition)' -count=1 -v - name: Web view partitions @@ -385,6 +395,8 @@ jobs: run: go test ./internal/platform/windows -run '^TestNativeGlobalShortcutRegistration$' -count=1 -v - name: Native Direct2D text origins and hidden labels run: go test ./internal/platform/windows -run '^Test(DirectTextLayoutOriginByValue|HiddenNativeEditorDoesNotDrawColorEmoji|TextEngineRasterizesProportionalText)$' -count=1 -v + - name: Promised file drag + run: go test ./internal/platform/windows -run '^Test(ThePromiseDataObject|ThePromiseStream|ThePromiseEnumerator|PromiseNames)' -count=1 -v # The installer contracts, including WinVerifyTrust's struct layout, only # compile and run on Windows. - name: Update installer contracts @@ -440,6 +452,26 @@ jobs: - name: compare run: go run ./tools/perfhistory compare -threshold 0.20 -min-ns 100 /tmp/base.txt < /tmp/head.txt + # The tests that make real disk images with hdiutil. The disk image service of a + # shared macOS runner fails now and then whatever the code does (busy, not + # mountable, permission denied), so these run when a change can affect how an + # image is made, not on every change; the darwin job skips them. Their logic + # is tested on every change against a stand-in hdiutil. + disk-image: + needs: changes + if: needs.changes.outputs.diskimage == 'true' + runs-on: macos-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + - name: disk images made with hdiutil + env: + VIVA_DISK_IMAGE_TESTS: "1" + run: go test ./tools/dmg ./cmd/viva -run 'DiskImage|BuiltImage' -count=1 + # The single check to require in branch protection. It reports success when # every job this change needed passed and the rest were skipped, so a # documentation-only pull request is green without running anything and a @@ -447,7 +479,7 @@ jobs: passed: name: ci passed if: always() - needs: [changes, lint, dev-attributes, cross-vet, web, web-browser, test, darwin, windows-materials, windows-arm64-text, benchmarks] + needs: [changes, lint, dev-attributes, cross-vet, web, web-browser, test, darwin, disk-image, windows-materials, windows-arm64-text, benchmarks, size] runs-on: ubuntu-latest steps: - name: every job this change needed passed @@ -462,17 +494,12 @@ jobs: esac done - # Release sizes on every change, without blocking: hello is over its own - # alarm limit while the ui/components boundary decision (see - # docs/benchmarks/2026-11-12-size-attribution-darwin-arm64.md) is open, so - # the job records the number on each run and the hard limit returns with - # the boundary. Builds the same targets benchmarks/size.sh checks on a - # release machine; remove continue-on-error when the limit is honest again. + # Release sizes on every change, reported in the job summary to watch across + # changes; benchmarks/size.sh judges no size against a fixed limit. size: needs: changes if: needs.changes.outputs.code == 'true' runs-on: macos-latest - continue-on-error: true steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 diff --git a/.github/workflows/text-input.yml b/.github/workflows/text-input.yml index c4c35f253..28c7b02ba 100644 --- a/.github/workflows/text-input.yml +++ b/.github/workflows/text-input.yml @@ -165,11 +165,11 @@ jobs: if: runner.os == 'Linux' run: | for backend in x11 wayland; do - tests='^TestGTKNativeSeatKeyboardAfterContentClick$' + tests='^TestGTKNative(SeatKeyboardAfterContentClick|InputMethodWindowTeardown)$' if [ "$backend" = wayland ]; then - tests='^Test(GTKNative(SeatKeyboardAfterContentClick|WaylandSeatHideShow|WaylandWidgetExternalFocus|WaylandAttachFailure|WaylandInputRegions)|GTKWaylandWindowAttrLP64Layout)$' + tests='^Test(GTKNative(SeatKeyboardAfterContentClick|InputMethodWindowTeardown|WaylandSeatHideShow|WaylandPointerKeepsFcitxPreedit|WaylandWidgetExternalFocus|WaylandAttachFailure|WaylandInputRegions)|GTKWaylandWindowAttrLP64Layout)$' fi - xvfb-run -a -s '-screen 0 800x600x24' env VIVA_GTK_SEAT_NATIVE=1 VIVA_GTK_SEAT_REMAP=1 VIVA_GTK_NATIVE_WIDGET_FOCUS=1 VIVA_GTK_ATTACH_NATIVE=1 VIVA_GTK_REGION_NATIVE=1 VIVA_GTK_IME_NATIVE=1 VIVA_FCITX_ENGINE=pinyin G_DEBUG=fatal-criticals VIVA_FCITX_TEST_BINARY="$RUNNER_TEMP/viva-ibus-frontend.test" VIVA_IBUS_TEST_RUN="$tests" sh internal/ibus/testdata/native-fcitx-service.sh "$backend" + xvfb-run -a -s '-screen 0 800x600x24' env VIVA_GTK_SEAT_NATIVE=1 VIVA_GTK_SEAT_REMAP=1 VIVA_GTK_NATIVE_WIDGET_FOCUS=1 VIVA_GTK_ATTACH_NATIVE=1 VIVA_GTK_REGION_NATIVE=1 VIVA_GTK_CLOSE_NATIVE=1 VIVA_GTK_IME_NATIVE=1 VIVA_FCITX_ENGINE=pinyin G_DEBUG=fatal-criticals VIVA_FCITX_TEST_BINARY="$RUNNER_TEMP/viva-ibus-frontend.test" VIVA_IBUS_TEST_RUN="$tests" sh internal/ibus/testdata/native-fcitx-service.sh "$backend" done - name: Linux text callback ordering if: runner.os == 'Linux' @@ -191,7 +191,7 @@ jobs: run: go test ./internal/platform/linux -run '^TestLinux(TextInputAlignmentMatchesGlyphCaretUnderlineAndPointer|RightToLeftAlignmentUsesLineWidthNotLogicalEndCaret|CandidateWindowFollowsAlignmentWhenNativeOverlaysAreHidden)$' -count=1 - name: GTK input method teardown ordering if: runner.os == 'Linux' - run: go test -tags vivagtk ./internal/platform/linux -run '^TestGTKDestroyDetachesInputMethodBeforeNativeWidget$' -count=1 -v + run: go test -tags vivagtk ./internal/platform/linux -run '^TestGTK(DestroyDetachesInputMethodBeforeNativeWidget|WaylandUnmapEndsPointerActivatedIME|WaylandIMECursorTracksContentOrigin)$' -count=1 -v - name: Linux clipboard, compositing and icon contracts if: runner.os == 'Linux' run: | diff --git a/README.md b/README.md index 74dbca185..d7ce5d63c 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ Wayland client and needs the system's GTK 3), and a Vulkan loader and driver for and DirectWrite. Viva loads the system libraries at runtime and bundles none of them. -The current release is `v0.6.7`; name it explicitly (`@v0.6.7`) to pin it. Guides, +The current release is `v0.6.8`; name it explicitly (`@v0.6.8`) to pin it. Guides, the API reference, and a component catalog with live previews live in [`website/`](website/); run it with `npm run dev` there, or read them on [vivaui.dev](https://vivaui.dev/en/), which is also available in diff --git a/README.zh-CN.md b/README.zh-CN.md index 0e8023e63..275e6a871 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -34,7 +34,7 @@ viva dev . # hot reload: save a file, the window updates and keeps its st 环境要求:Go 1.26 或更新版本(缺失时 viva 会自己下载)。macOS 上需要 Xcode 命令行工具,因为 Viva 通过 cgo 访问 Cocoa 和 Metal;Linux 上需要带系统 XCB、Pango 和 Cairo 库的 X11(可选的 GTK 3 外壳用 `-tags vivagtk` 构建,是原生 Wayland 客户端,需要系统的 GTK 3),Vulkan 加载库和驱动用于 GPU 加速,缺失时窗口用 CPU 渲染;Windows 上需要 Win32、Direct3D 11 和 DirectWrite。Viva 在运行时加载系统库,自身不捆绑任何一个。 -当前版本是 `v0.6.7`;要固定版本就写明(`@v0.6.7`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。 +当前版本是 `v0.6.8`;要固定版本就写明(`@v0.6.8`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。 下面的一切描述的都是这个仓库:它的测量、它自己的程序,以及如何开发框架本身,而不是如何用框架。 diff --git a/app/app.go b/app/app.go index 41571c992..678b56158 100644 --- a/app/app.go +++ b/app/app.go @@ -113,6 +113,22 @@ type Config struct { // supplied it. Without one the panel is centered on the screen. Anchor StatusAnchor ClearColor Color + // Transparent composites the window over the desktop: the part of the canvas + // left at ClearColor's alpha shows what is behind the window. It makes a + // ClearColor of zero mean fully transparent instead of the default fill, and + // is how a window asks for per-pixel transparency at creation. Ask + // CapabilityTransparentWindow first; where it is missing the window is + // opaque and takes the default fill. On Linux the window must be a + // WindowCustomTitlebar one and a compositing manager must own the screen; + // OnTransparentChange says whether it did. + Transparent bool + // OnTransparentChange is told once the window exists whether the desktop + // really shows through it. It reports false where Transparent could not be + // honored at run time: a Linux desktop with no compositing manager, or a + // window kind without an alpha surface. A window that asked for Transparent + // then paints as if it were opaque. It runs on the window thread; update + // paint state without blocking, and schedule a repaint. + OnTransparentChange func(active bool) // WindowBorderColor is read at every paint and names the color of the // border Windows 11 draws around a custom-titlebar window. The system // composites that border against what is behind the window rather than @@ -266,6 +282,11 @@ type Config struct { // application-owned native editor. Returning nil disables native editing. // The callback runs on the window thread after painting. TextInput TextInputProvider + // TextMenu asks for the menu a text field opens on a secondary press: the + // system's own on macOS and Windows, with these words. Nil leaves it to the + // page, which draws one of its own where the platform has none to show. + // The words are read when the menu opens, so a language change reaches it. + TextMenu *TextMenuLabels // OnCloseRequest, when set, intercepts window close (the red traffic // light). Call allow to close the window immediately or later; never // calling it keeps the window open. @@ -337,8 +358,11 @@ func (config Config) normalize() (Config, error) { return Config{}, err } + if !Supports(CapabilityTransparentWindow) { + config.Transparent = false + } color := config.ClearColor - if color == (Color{}) && config.WindowMode != windowPreview { + if color == (Color{}) && config.WindowMode != windowPreview && !config.Transparent { config.ClearColor = Color{Red: 0.055, Green: 0.065, Blue: 0.09, Alpha: 1} } else if !validColor(color) { return Config{}, fmt.Errorf("app: clear color components must be between 0 and 1") diff --git a/app/app_test.go b/app/app_test.go index 57ad7c7e3..b33f3da0e 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -69,3 +69,26 @@ func TestSystemIntegrationValidation(t *testing.T) { t.Fatal("SendNotification accepted empty notification") } } + +func TestTransparentWindowKeepsAZeroClearColorWhereSupported(t *testing.T) { + config, err := (Config{Transparent: true}).normalize() + if err != nil { + t.Fatal(err) + } + if Supports(CapabilityTransparentWindow) { + if !config.Transparent || config.ClearColor != (Color{}) { + t.Fatalf("a transparent window lost its clear color: %+v", config) + } + return + } + if config.Transparent || config.ClearColor.Alpha != 1 { + t.Fatalf("an unsupported transparent window must stay opaque: %+v", config) + } +} + +func TestOpaqueWindowKeepsTheDefaultFill(t *testing.T) { + config, err := (Config{}).normalize() + if err != nil || config.Transparent || config.ClearColor.Alpha != 1 { + t.Fatalf("a window without Transparent must stay opaque: %+v, %v", config, err) + } +} diff --git a/app/application.go b/app/application.go index 1594eb75a..d618e2743 100644 --- a/app/application.go +++ b/app/application.go @@ -5,6 +5,7 @@ import ( "fmt" "sync" "sync/atomic" + "time" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/keymap" @@ -73,6 +74,37 @@ func (application *Application) Post(fn func()) { application.host.Post(fn) } +// PostAfter is Post after a delay: fn runs on the event-loop thread once d has +// passed, through the same host post as Post. It does not wait for a window to +// paint, so a hidden, minimized, or covered window still runs the work on time; +// anything it changes is read by the next wake or paint that comes. +// +// A non-positive d posts on the next loop turn. The returned stop cancels the +// call: after stop returns fn will not start, and stop is idempotent and safe +// from any goroutine. Each call owns one timer until fn runs or stop is called; +// PostAfter starts no goroutine, and an application that never calls it owns no +// timer. +func (application *Application) PostAfter(d time.Duration, fn func()) (stop func()) { + if application == nil || application.host == nil || fn == nil { + return func() {} + } + if d < 0 { + d = 0 + } + var stopped atomic.Bool + timer := time.AfterFunc(d, func() { + application.Post(func() { + if !stopped.Load() { + fn() + } + }) + }) + return func() { + stopped.Store(true) + timer.Stop() + } +} + // Window is one independently retained native window. Close is idempotent and // may be called from a window callback or another goroutine; the platform // adapter performs the actual close on its native event-loop thread. diff --git a/app/application_native.go b/app/application_native.go index 7abf1b4b8..7c9617420 100644 --- a/app/application_native.go +++ b/app/application_native.go @@ -14,6 +14,8 @@ import ( // RunApplication starts the native application loop. start runs once on the // locked native event-loop thread and must open at least one window. The call // blocks until the final window closes or a platform error terminates the loop. +// On macOS, call runtime.LockOSThread in an init function in package main and +// start the native application from main to satisfy AppKit's main-thread requirement. func RunApplication(start func(*Application) error) error { attendFaults() if applicationRunner != nil { diff --git a/app/application_test.go b/app/application_test.go index 9127b2284..e86cfbc33 100644 --- a/app/application_test.go +++ b/app/application_test.go @@ -6,6 +6,7 @@ import ( "errors" "runtime" "testing" + "time" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/keymap" @@ -577,3 +578,46 @@ func TestPostDelegatesToTheHost(t *testing.T) { var nilApplication *Application nilApplication.Post(func() { t.Fatal("a nil application ran work") }) } + +// PostAfter hands the work to the host's loop once the delay has passed, not on +// the caller's goroutine. +func TestPostAfterRunsTheWorkOnTheHost(t *testing.T) { + host := &fakeHost{} + application := &Application{host: host} + ran := make(chan struct{}, 1) + stop := application.PostAfter(time.Millisecond, func() { ran <- struct{}{} }) + select { + case <-ran: + case <-time.After(time.Second): + t.Fatal("the host did not run the delayed work") + } + stop() // idempotent + stop() +} + +// Stop takes back a call that has not started: the loop never runs it. +func TestPostAfterStopPreventsTheWork(t *testing.T) { + host := &fakeHost{} + application := &Application{host: host} + ran := make(chan struct{}, 1) + stop := application.PostAfter(50*time.Millisecond, func() { ran <- struct{}{} }) + stop() + select { + case <-ran: + t.Fatal("stopped work ran") + case <-time.After(150 * time.Millisecond): + } + + var nilApplication *Application + stop = nilApplication.PostAfter(time.Millisecond, func() { t.Fatal("a nil application ran work") }) + stop() +} + +func BenchmarkPostAfterStop(b *testing.B) { + application := &Application{host: &fakeHost{}} + b.ReportAllocs() + for b.Loop() { + stop := application.PostAfter(time.Hour, func() {}) + stop() + } +} diff --git a/app/backend_darwin.go b/app/backend_darwin.go index 372b0c627..a0f5cfd23 100644 --- a/app/backend_darwin.go +++ b/app/backend_darwin.go @@ -11,3 +11,5 @@ func runNative(config platform.Config) error { return darwin.Run(config) } func runNativeApplication(start platform.ApplicationStart) error { return darwin.RunApplication(start) } + +func checkNativeApplicationThread() error { return darwin.CheckApplicationThread() } diff --git a/app/capabilities.go b/app/capabilities.go index 50e83c66a..1a10a39ae 100644 --- a/app/capabilities.go +++ b/app/capabilities.go @@ -51,6 +51,13 @@ const ( // picture on the clipboard, completing before the call returns on a desktop // and on the event loop in a browser. CapabilityClipboardImageWriteAsync + // CapabilityFileDrag means files can be taken out of a window, by path + // (StartFileDrag) or by produced content (StartFilePromiseDrag). A platform + // without it can still copy files to the clipboard. + CapabilityFileDrag + // CapabilityTransparentWindow means Config.Transparent can composite a + // window over the desktop; without it the window is opaque. + CapabilityTransparentWindow ) // Capabilities is a set of platform integrations. diff --git a/app/capabilities_native.go b/app/capabilities_native.go index 8746dd9b7..8090c1188 100644 --- a/app/capabilities_native.go +++ b/app/capabilities_native.go @@ -34,11 +34,13 @@ func nativeCapabilities() Capabilities { CapabilityWindowMinimize | CapabilityReduceMotion | CapabilityPreventSleep | - CapabilitySystemProxy + CapabilitySystemProxy | + capabilityFileDrag if runtime.GOOS == "darwin" { capabilities |= CapabilityNativeAppearance } else { capabilities |= CapabilityWindowMaximize } + capabilities |= capabilityTransparentWindow return Capabilities(capabilities) } diff --git a/app/capability_file_drag_native.go b/app/capability_file_drag_native.go new file mode 100644 index 000000000..58c7746dc --- /dev/null +++ b/app/capability_file_drag_native.go @@ -0,0 +1,10 @@ +//go:build (darwin && !ios) || windows || (linux && !android && !vivagtk) + +package app + +// capabilityFileDrag reports that this build can take files out of a window: +// an NSDraggingSession on macOS, an OLE drag on Windows, and the XDND source of +// the X11 shell on Linux. The GTK shell speaks Wayland, whose drag source this +// adapter does not bind, and the mobile targets have no file manager to take +// them. +const capabilityFileDrag = CapabilityFileDrag diff --git a/app/capability_file_drag_other.go b/app/capability_file_drag_other.go new file mode 100644 index 000000000..17482904b --- /dev/null +++ b/app/capability_file_drag_other.go @@ -0,0 +1,7 @@ +//go:build !((darwin && !ios) || windows || (linux && !android && !vivagtk)) + +package app + +// capabilityFileDrag is absent on a target that cannot take files out of a +// window; see capability_file_drag_native.go. +const capabilityFileDrag Capability = 0 diff --git a/app/capability_transparent_native.go b/app/capability_transparent_native.go new file mode 100644 index 000000000..0002cdcf1 --- /dev/null +++ b/app/capability_transparent_native.go @@ -0,0 +1,9 @@ +//go:build darwin || windows || (linux && !android && !vivagtk) + +package app + +// capabilityTransparentWindow reports that this build can composite a window +// over the desktop: Metal layers on macOS, DirectComposition on Windows, and an +// ARGB frame window on the X11 shell of Linux, where OnTransparentChange says +// whether a compositing manager is there. The GTK shell does not draw one. +const capabilityTransparentWindow = CapabilityTransparentWindow diff --git a/app/capability_transparent_other.go b/app/capability_transparent_other.go new file mode 100644 index 000000000..4de0eb78a --- /dev/null +++ b/app/capability_transparent_other.go @@ -0,0 +1,7 @@ +//go:build !(darwin || windows || (linux && !android && !vivagtk)) + +package app + +// capabilityTransparentWindow is absent on a target that cannot composite a +// window over the desktop; see capability_transparent_native.go. +const capabilityTransparentWindow Capability = 0 diff --git a/app/content_window.go b/app/content_window.go index 4801f49f9..740a43678 100644 --- a/app/content_window.go +++ b/app/content_window.go @@ -11,9 +11,11 @@ import ( // content and close policy; the helper owns UI-thread delivery and lifetime. // It is suitable for document viewers, inspectors and detached tool panels. type ContentWindow struct { - window *Window - invalidator Invalidator - closeRequest func(func()) + window *Window + invalidator Invalidator + closeRequest func(func()) + concealed bool + restoreVisible bool } // OpenContentWindow opens a resizable system window. Call it on the application @@ -53,7 +55,24 @@ func (content *ContentWindow) Invalidate() { } } func (content *ContentWindow) Show() { - if content != nil { + if content != nil && !content.concealed { + content.window.Show() + } +} + +// SetConcealed temporarily hides the native window and suppresses Show requests. +// Restoring visibility preserves closed windows and unsaved editor contents. +// Call on the UI thread, for example when locking all of an application's windows. +func (content *ContentWindow) SetConcealed(conceal bool) { + if content.Closed() || content.concealed == conceal { + return + } + content.concealed = conceal + if conceal { + content.restoreVisible = !content.window.Hidden() + content.window.Hide() + } else if content.restoreVisible { + content.restoreVisible = false content.window.Show() } } diff --git a/app/content_window_test.go b/app/content_window_test.go index 42fa3ba8f..99c8275dc 100644 --- a/app/content_window_test.go +++ b/app/content_window_test.go @@ -85,6 +85,15 @@ func TestContentWindowReportsFrameAndMinimizeState(t *testing.T) { if content.Minimized() { t.Fatal("a new content window reports minimized") } + content.SetConcealed(true) + content.Show() + if !content.window.Hidden() || content.Closed() { + t.Fatal("a concealed document must stay open and hidden") + } + content.SetConcealed(false) + if content.window.Hidden() { + t.Fatal("previously visible document remained hidden") + } host.windows[0].config.OnMinimize(true) if !content.Minimized() { t.Fatal("minimize state did not follow the window") diff --git a/app/drag_files.go b/app/drag_files.go index 06342f77f..1755cb8a9 100644 --- a/app/drag_files.go +++ b/app/drag_files.go @@ -17,8 +17,8 @@ import ( type FileDragEffect = platform.DragEffect const ( - // FileDragNone is what a drag that ended nowhere, or that the user - // cancelled, reports. + // FileDragNone names no effect: a target told it may take nothing takes + // nothing. FileDragNone FileDragEffect = platform.DragEffectNone // FileDragCopy copies the files; the ones dragged out stay where they are. FileDragCopy FileDragEffect = platform.DragEffectCopy @@ -33,18 +33,29 @@ const ( // the same reason: it limits what a huge selection can make an application hold. const MaxDragFiles = platform.MaxClipboardFiles +// FilePromise is one item of a drag whose content the application produces when +// the target asks for it, instead of a path that already exists on this +// computer. Dragging a file off a remote server is this: the file is downloaded +// where the user lets go, while the target copies, so nothing is fetched when +// the drag starts. +// +// Name is one path component, unique among its siblings. A file's Open returns +// its bytes when the target reads them; a directory's List returns its children +// on demand, each named relative to it. Both callbacks may run on a goroutine +// other than the one that started the drag, and may run more than once. +type FilePromise = platform.FilePromise + // StartFileDrag takes paths out of the application's window, as dragging a file // from a file manager to another window does. The drag lasts until the pointer -// is released or the user presses Escape, and the effect the target took is -// returned — FileDragNone when it took nothing, which is also what a cancelled -// drag reports. An error wrapping ErrUnsupported means this target cannot drag -// files out of a window at all, and the application should offer them some other -// way (SetClipboardFiles tells the user something else, a copy). +// is released or the user presses Escape; the effect the target takes is the +// platform's own and is not reported. An error wrapping ErrUnsupported means +// this target cannot drag files out of a window at all, and the application +// should offer them some other way (SetClipboardFiles tells the user something +// else, a copy). // // allowed is the mask of effects the application offers: a target takes at most -// one of them, and only those. Windows reports the effect the drop performed, -// and a target that claims one the application never offered counts as taking -// nothing. +// one of them, and only those. A target that claims one the application never +// offered counts as taking nothing. // // The files are not read here, and nothing is copied when the drag starts: a // target that takes a copy or a move reads the paths while the drop happens, so @@ -55,31 +66,59 @@ const MaxDragFiles = platform.MaxClipboardFiles // called on the event-loop thread, from the handler of the pointer event that // starts the drag, and does not return until the drag has ended; the drag's own // message loop dispatches the messages that arrive meanwhile, so a handler can -// be reentered by one. macOS needs an NSDraggingSession and Linux the XDND -// protocol as a source, and neither adapter binds them yet; the Web target has -// no DOM DataTransfer behind a canvas. Those three return an error wrapping -// ErrUnsupported. -func StartFileDrag(paths []string, allowed FileDragEffect) (FileDragEffect, error) { +// be reentered by one. macOS starts an NSDraggingSession and Linux an XDND drag +// and returns once it is running; both take the pointer over from the press. The +// Web target has no DOM DataTransfer behind a canvas, and returns an error +// wrapping ErrUnsupported. +func StartFileDrag(paths []string, allowed FileDragEffect) error { if len(paths) == 0 { - return FileDragNone, fmt.Errorf("app: no files to drag out of the window") + return fmt.Errorf("app: no files to drag out of the window") } if len(paths) > MaxDragFiles { - return FileDragNone, fmt.Errorf("app: a drag takes at most %d files", MaxDragFiles) + return fmt.Errorf("app: a drag takes at most %d files", MaxDragFiles) } if allowed == FileDragNone || !platform.DragEffectKnown(allowed) { - return FileDragNone, fmt.Errorf("app: a drag of files offers FileDragCopy, FileDragMove or FileDragLink") + return fmt.Errorf("app: a drag of files offers FileDragCopy, FileDragMove or FileDragLink") } for index, path := range paths { if path == "" || strings.IndexByte(path, 0) >= 0 || !filepath.IsAbs(path) { - return FileDragNone, fmt.Errorf("app: dragged file %d is not an absolute path: %q", index, path) + return fmt.Errorf("app: dragged file %d is not an absolute path: %q", index, path) } } - if effect, err, handled := driverStartFileDrag(paths, allowed); handled { - return effect, err + if err, handled := driverStartFileDrag(paths, allowed); handled { + return err + } + err := nativeStartFileDrag(paths, allowed) + if errors.Is(err, platform.ErrDragUnsupported) { + return fmt.Errorf("%w: %v", ErrUnsupported, err) + } + return err +} + +// StartFilePromiseDrag takes files out of the application's window that do not +// exist as local paths yet: each is produced when the target asks for it, by +// Open for a file or by List for a directory, and written where the user lets +// go. A target takes a copy only, so nothing is moved or deleted at the source. +// +// It is called on the event-loop thread, from the handler of the pointer event +// that starts the drag, like StartFileDrag. Windows enumerates the whole tree +// before the drag starts and blocks until the drop ends; macOS and Linux return +// once the drag is running, and may call Open and List after it ends. An error +// wrapping ErrUnsupported means this target cannot take files out of a window. +// A tree of more than MaxDragFiles items is refused. +func StartFilePromiseDrag(files []FilePromise) error { + if len(files) == 0 { + return fmt.Errorf("app: no files to drag out of the window") + } + if err := platform.ValidateFilePromises(files); err != nil { + return err + } + if err, handled := driverStartFilePromiseDrag(files); handled { + return err } - effect, err := nativeStartFileDrag(paths, allowed) + err := nativeStartFilePromiseDrag(files) if errors.Is(err, platform.ErrDragUnsupported) { - return FileDragNone, fmt.Errorf("%w: %v", ErrUnsupported, err) + return fmt.Errorf("%w: %v", ErrUnsupported, err) } - return effect, err + return err } diff --git a/app/drag_files_test.go b/app/drag_files_test.go index 660660a0a..428477b25 100644 --- a/app/drag_files_test.go +++ b/app/drag_files_test.go @@ -3,23 +3,21 @@ package app import ( + "io" "path/filepath" "slices" + "strings" "testing" ) func TestStartFileDragOfADriverRun(t *testing.T) { driver := newFilesDriver(t) want := []string{filepath.Join(t.TempDir(), "report.pdf"), filepath.Join(t.TempDir(), "文件夹")} - effect, err := StartFileDrag(want, FileDragCopy|FileDragMove) - if err != nil { + if err := StartFileDrag(want, FileDragCopy|FileDragMove); err != nil { t.Fatal(err) } // A folder window that may copy takes the copy, as DropEffect prefers, and // the driver's target does the same. - if effect != FileDragCopy { - t.Fatalf("the drag took effect %d, want a copy", effect) - } got, taken := driver.DraggedFiles() if !slices.Equal(got, want) || taken != FileDragCopy { t.Fatalf("the driver's drag = %q taking %d, want %q taking a copy", got, taken, want) @@ -30,27 +28,33 @@ func TestStartFileDragOfADriverRun(t *testing.T) { } // An application that offers no copy is taken at its word. - if effect, err := StartFileDrag(got, FileDragMove|FileDragLink); err != nil || effect != FileDragLink { - t.Fatalf("a drag offering a link and a move took %d, %v", effect, err) + if err := StartFileDrag(got, FileDragMove|FileDragLink); err != nil { + t.Fatal(err) + } + if _, taken := driver.DraggedFiles(); taken != FileDragLink { + t.Fatalf("a drag offering a link and a move took %d", taken) + } + if err := StartFileDrag(got, FileDragMove); err != nil { + t.Fatal(err) } - if effect, err := StartFileDrag(got, FileDragMove); err != nil || effect != FileDragMove { - t.Fatalf("a drag offering only a move took %d, %v", effect, err) + if _, taken := driver.DraggedFiles(); taken != FileDragMove { + t.Fatalf("a drag offering only a move took %d", taken) } } func TestStartFileDragRefusesWhatItCannotDrag(t *testing.T) { newFilesDriver(t) - if _, err := StartFileDrag(nil, FileDragCopy); err == nil { + if err := StartFileDrag(nil, FileDragCopy); err == nil { t.Fatal("a drag of no files was accepted") } - if _, err := StartFileDrag([]string{"relative.txt"}, FileDragCopy); err == nil { + if err := StartFileDrag([]string{"relative.txt"}, FileDragCopy); err == nil { t.Fatal("a relative path was accepted") } // A drag that offers no effect cannot end anywhere. - if _, err := StartFileDrag([]string{filepath.Join(t.TempDir(), "one.txt")}, FileDragNone); err == nil { + if err := StartFileDrag([]string{filepath.Join(t.TempDir(), "one.txt")}, FileDragNone); err == nil { t.Fatal("a drag offering no effect was accepted") } - if _, err := StartFileDrag([]string{filepath.Join(t.TempDir(), "one.txt")}, FileDragEffect(8)); err == nil { + if err := StartFileDrag([]string{filepath.Join(t.TempDir(), "one.txt")}, FileDragEffect(8)); err == nil { t.Fatal("a drag offering an effect this platform does not name was accepted") } dir := t.TempDir() @@ -58,7 +62,74 @@ func TestStartFileDragRefusesWhatItCannotDrag(t *testing.T) { for index := range paths { paths[index] = filepath.Join(dir, "f") } - if _, err := StartFileDrag(paths, FileDragCopy); err == nil { + if err := StartFileDrag(paths, FileDragCopy); err == nil { t.Fatal("a drag of more files than it takes was accepted") } } + +func promiseFixture(t *testing.T) (files []FilePromise, contents map[string]string) { + t.Helper() + contents = map[string]string{"notes.txt": "hello", "inner/second.txt": "second"} + file := func(name, value string) FilePromise { + return FilePromise{Name: name, Size: int64(len(value)), Open: func() (io.ReadCloser, error) { + return io.NopCloser(strings.NewReader(value)), nil + }} + } + directory := FilePromise{Name: "docs", Directory: true, List: func() ([]FilePromise, error) { + return []FilePromise{ + file("inner/second.txt", contents["inner/second.txt"]), + file("guide.md", "guide"), + }, nil + }} + return []FilePromise{file("notes.txt", contents["notes.txt"]), directory}, contents +} + +func TestStartFilePromiseDragOfADriverRun(t *testing.T) { + driver := newFilesDriver(t) + files, _ := promiseFixture(t) + if err := StartFilePromiseDrag(files); err != nil { + t.Fatal(err) + } + recorded := driver.DraggedPromises() + if len(recorded) != len(files) || recorded[0].Name != files[0].Name || recorded[1].Name != files[1].Name { + t.Fatalf("the driver recorded %+v, want %+v", recorded, files) + } + // The content is still the application's: the driver's target asks through + // the same callbacks a real one would. + reader, err := recorded[0].Open() + if err != nil { + t.Fatal(err) + } + body, err := io.ReadAll(reader) + reader.Close() + if err != nil || string(body) != "hello" { + t.Fatalf("the promised file read %q, %v", body, err) + } + children, err := recorded[1].List() + if err != nil || len(children) != 2 { + t.Fatalf("the promised folder listed %d children, %v", len(children), err) + } +} + +func TestStartFilePromiseDragRefusesWhatItCannotPromise(t *testing.T) { + newFilesDriver(t) + open := func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader("")), nil } + list := func() ([]FilePromise, error) { return nil, nil } + for name, files := range map[string][]FilePromise{ + "no files": nil, + "no name": {{Open: open}}, + "dot": {{Name: ".", Open: open}}, + "component": {{Name: "a/b", Open: open}}, + "backslash": {{Name: `a\b`, Open: open}}, + "no content": {{Name: "a"}}, + "directory without list": {{Name: "d", Directory: true}}, + "directory with content": {{Name: "d", Directory: true, Open: open, List: list}}, + "file with list": {{Name: "a", Open: open, List: list}}, + "size below -1": {{Name: "a", Size: -2, Open: open}}, + "duplicate names": {{Name: "a", Open: open}, {Name: "a", Open: open}}, + } { + if err := StartFilePromiseDrag(files); err == nil { + t.Fatalf("%s was accepted as a drag", name) + } + } +} diff --git a/app/driver.go b/app/driver.go index 0d03a9953..97d7b5ba5 100644 --- a/app/driver.go +++ b/app/driver.go @@ -39,9 +39,11 @@ var ErrNoTerminal = errors.New("app: no focused terminal") // through Config.Invalidator, exactly as with a window; the wake is applied the // next time the driver is called (or by Pump). type Driver struct { - config Config - canvas *gfx.Canvas - painter *painter + // textMenu is the system text menu the last press opened, until it is chosen from or dismissed. + textMenu *platform.TextMenuRequest + config Config + canvas *gfx.Canvas + painter *painter // origin is where Config.Origin put the content area; MoveWindow changes it // as a window manager would. @@ -154,6 +156,10 @@ func NewDriver(config Config, canvas *gfx.Canvas) (*Driver, error) { driver.painter.setClipboardText = func(value string) { driver.SetClipboard(value) } + driver.painter.clipboardReader = func() (string, error) { return driver.clipboard, nil } + // The driver stands for a platform with the system's text menu, so a test + // sees what an application asking for one gets; it shows the menu itself. + driver.painter.enableTextMenu(true) driver.painter.setCursor = func(Cursor) error { return nil } driver.painter.setCursorImage = func(*gfx.CursorImage) error { return nil } driver.painter.scheduleFrame = func(delay time.Duration) { @@ -301,6 +307,11 @@ func (driver *Driver) pointer(kind platform.PointerEventKind, x, y float32, butt _, err := driver.painter.pointerEvent(platform.PointerEvent{ Kind: kind, Button: button, Modifiers: driver.heldModifiers(), X: x, Y: y, ScreenX: origin.X + x, ScreenY: origin.Y + y, ClickCount: clicks, }) + if err == nil && driver.painter.textMenuNative { + if request, ok := driver.painter.takeTextMenu(); ok { + driver.textMenu = &request + } + } return err } diff --git a/app/driver_system.go b/app/driver_system.go index 21289fc27..526847f48 100644 --- a/app/driver_system.go +++ b/app/driver_system.go @@ -35,10 +35,12 @@ type driverSystem struct { sleep map[string]int // sleep-prevention reasons this run holds, with their counts // dragFiles and dragAllowed are what the application last asked to drag out // of a driver-backed window, and dragTaken is the effect the driver's target - // took from them; see driverStartFileDrag. - dragFiles []string - dragAllowed platform.DragEffect - dragTaken platform.DragEffect + // took from them; see driverStartFileDrag. dragPromises is the same for a + // drag whose content the application produces on demand. + dragFiles []string + dragAllowed platform.DragEffect + dragTaken platform.DragEffect + dragPromises []FilePromise } type driverSaveFileResponse struct { @@ -151,14 +153,34 @@ func driverSetClipboardImage(png []byte) (error, bool) { // driverStartFileDrag answers a drag of files out of a driver-backed run: the // driver records what the application asked and takes the effect a folder window // takes, with no native drag and no pointer to move. -func driverStartFileDrag(paths []string, allowed platform.DragEffect) (platform.DragEffect, error, bool) { +func driverStartFileDrag(paths []string, allowed platform.DragEffect) (error, bool) { system := activeDriverSystem.Load() if system == nil { - return platform.DragEffectNone, nil, false + return nil, false } taken := platform.DragEffectOf(allowed, platform.DragEffect(platform.DropEffect(true, uint32(allowed)))) system.dragFiles, system.dragAllowed, system.dragTaken = append([]string(nil), paths...), allowed, taken - return taken, nil, true + return nil, true +} + +// driverStartFilePromiseDrag answers a drag of promised files out of a +// driver-backed run: the driver records the promises and leaves each Open and +// List to the test, which plays the target and asks for what it wants. +func driverStartFilePromiseDrag(files []FilePromise) (error, bool) { + system := activeDriverSystem.Load() + if system == nil { + return nil, false + } + system.dragPromises = append([]FilePromise(nil), files...) + return nil, true +} + +// DraggedPromises is the promises the application last asked to drag out of the +// driver's window. The slice is the driver's own; do not modify it. The content +// is still the application's to produce: Open and List behave as they would for +// a real target. +func (driver *Driver) DraggedPromises() []FilePromise { + return driver.system.dragPromises } // DraggedFiles is the files the application last asked to drag out of the diff --git a/app/driver_system_test.go b/app/driver_system_test.go index 3c318f856..4334eead3 100644 --- a/app/driver_system_test.go +++ b/app/driver_system_test.go @@ -330,13 +330,13 @@ func TestDriverInterceptsOpenDirectory(t *testing.T) { if err := driver.QueueOpenDirectory("/tmp/project", nil); err != nil { t.Fatal(err) } - options := OpenDirectoryOptions{Title: "Choose project"} + options := OpenDirectoryOptions{Title: "Choose project", InitialDirectory: "/tmp/projects"} path, err := OpenDirectory(options) if err != nil || path != "/tmp/project" { t.Fatalf("OpenDirectory = %q, %v", path, err) } request, ok := driver.LastOpenDirectoryRequest() - if !ok || request.Title != options.Title { + if !ok || request != options { t.Fatalf("request = %#v, %t", request, ok) } diff --git a/app/driver_system_unsupported.go b/app/driver_system_unsupported.go index 9f578cfcf..812d859f5 100644 --- a/app/driver_system_unsupported.go +++ b/app/driver_system_unsupported.go @@ -26,10 +26,12 @@ func driverSetClipboardFiles([]string) (error, bool) { return nil, false } func driverSetClipboardImage([]byte) (error, bool) { return nil, false } -func driverStartFileDrag([]string, platform.DragEffect) (platform.DragEffect, error, bool) { - return platform.DragEffectNone, nil, false +func driverStartFileDrag([]string, platform.DragEffect) (error, bool) { + return nil, false } +func driverStartFilePromiseDrag([]FilePromise) (error, bool) { return nil, false } + func driverSetClipboardHTML(string, string) (error, bool) { return nil, false } func driverSendNotification(Notification) (error, bool) { return nil, false } diff --git a/app/files.go b/app/files.go index bae8b253c..71a67fcaf 100644 --- a/app/files.go +++ b/app/files.go @@ -25,6 +25,15 @@ func (file FileRef) Name() string { return file.ref.Name() } +// Path is the file's absolute path on a native target, and empty where the +// platform grants access to the contents only, as a browser does. +func (file FileRef) Path() string { + if located, ok := file.ref.(interface{ Path() string }); ok { + return located.Path() + } + return "" +} + // Size is the file's length in bytes. func (file FileRef) Size() int64 { if file.ref == nil { diff --git a/app/files_native.go b/app/files_native.go index 167e0a3ed..24a105715 100644 --- a/app/files_native.go +++ b/app/files_native.go @@ -62,6 +62,7 @@ func nativeFileRefFromPath(path string) (platform.FileRef, bool) { return &nativeFileRef{path: path, info: info}, true } +func (file *nativeFileRef) Path() string { return file.path } func (file *nativeFileRef) Name() string { return file.info.Name() } func (file *nativeFileRef) Size() int64 { return file.info.Size() } func (file *nativeFileRef) MIME() string { return "" } diff --git a/app/painter.go b/app/painter.go index ef6b5e41a..ca46d8338 100644 --- a/app/painter.go +++ b/app/painter.go @@ -137,9 +137,17 @@ type painter struct { // presents immediately sets it; the headless driver does not. coalesceInput bool setClipboardText func(string) - clipboardText func() string - setCursor func(Cursor) error - setCursorImage func(*gfx.CursorImage) error + // clipboardReader reads the system clipboard's text, for a menu's Paste. + clipboardReader func() (string, error) + // textMenu is the words of the system's text menu; nil asks for none. + textMenu *TextMenuLabels + // textMenuNative is whether the window can show the system's text menu. + textMenuNative bool + // textMenuAt is the press that asked for the menu, until it is taken. + textMenuAt *pointToMenu + clipboardText func() string + setCursor func(Cursor) error + setCursorImage func(*gfx.CursorImage) error // cursorImage is the picture shown while cursor is CursorImage. cursorImage *gfx.CursorImage } @@ -169,6 +177,7 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D onFileDrop: config.OnFileDrop, onResize: config.OnResize, textInput: config.TextInput, + textMenu: config.TextMenu, canvas: canvas, size: gfx.Size{Width: float32(config.Width), Height: float32(config.Height)}, frame: framebuild.New(canvas), @@ -247,6 +256,20 @@ func (painter *painter) pointerEvent(event platform.PointerEvent) (platform.Fram // pointerInput is pointerEvent for a press the runtime reads as it comes: a // mouse's or a pen's, or a finger's once touchEvent decided it is a press. func (painter *painter) pointerInput(event platform.PointerEvent) (platform.Frame, error) { + handled := false + frame, err := painter.pointerInputOf(event, &handled) + if err != nil || handled { + return frame, err + } + if menuFrame, menuErr, asked := painter.requestTextMenu(event); asked { + return menuFrame, menuErr + } + return frame, err +} + +// pointerInputOf is pointerInput, and says in handled whether the application +// took the press. +func (painter *painter) pointerInputOf(event platform.PointerEvent, handled *bool) (platform.Frame, error) { if event.Kind == platform.PointerDown { painter.tap.Cancel() painter.pointerOutside = false @@ -284,6 +307,7 @@ func (painter *painter) pointerInput(event platform.PointerEvent) (platform.Fram (event.Button == gfx.PointerButtonSecondary && painter.focus.Router().PassesSecondary(event.X, event.Y) || event.Button == gfx.PointerButtonPrimary && painter.focus.Router().PassesPrimary(event.X, event.Y)) result, focusChanged, edgeChanged := painter.pointerStep(event) + *handled = result.Handled if passes { if !result.Handled && painter.deliverClick(painter.pointer.Hovered(), pointerClickInfo(event)) { result.Handled = true @@ -296,6 +320,7 @@ func (painter *painter) pointerInput(event platform.PointerEvent) (platform.Fram focusChanged, edgeChanged = focusChanged || again, edgeChanged || edgeAgain } result.Repaint = true + *handled = result.Handled } switch event.Kind { diff --git a/app/run.go b/app/run.go index 5091f62cb..783f4cd8a 100644 --- a/app/run.go +++ b/app/run.go @@ -10,6 +10,8 @@ import ( // Run starts the native application loop and blocks until the final window // closes. It must be called from the program's main goroutine. +// On macOS, call runtime.LockOSThread in an init function in package main to +// keep that goroutine on the process main thread for AppKit. func Run(config Config) error { attendFaults() normalized, err := config.normalize() @@ -21,18 +23,20 @@ func Run(config Config) error { defer runtime.UnlockOSThread() return runNative(platform.Config{ - Title: normalized.Title, - Class: normalized.Class, - Icon: normalized.Icon.platform(), - Width: normalized.Width, - Height: normalized.Height, - MinWidth: normalized.MinWidth, - MinHeight: normalized.MinHeight, - Maximized: normalized.Maximized, - WindowMode: platform.WindowMode(normalized.WindowMode), - WindowMaterials: normalized.windowMaterials(), - TitlebarHeight: normalized.TitlebarHeight, - TrafficLightScale: normalized.TrafficLightScale, + Title: normalized.Title, + Class: normalized.Class, + Icon: normalized.Icon.platform(), + Width: normalized.Width, + Height: normalized.Height, + MinWidth: normalized.MinWidth, + MinHeight: normalized.MinHeight, + Maximized: normalized.Maximized, + WindowMode: platform.WindowMode(normalized.WindowMode), + WindowMaterials: normalized.windowMaterials(), + Transparent: normalized.Transparent, + OnTransparentChange: normalized.OnTransparentChange, + TitlebarHeight: normalized.TitlebarHeight, + TrafficLightScale: normalized.TrafficLightScale, ClearColor: platform.Color{ Red: normalized.ClearColor.Red, Green: normalized.ClearColor.Green, diff --git a/app/run_canvas.go b/app/run_canvas.go index 9c77d7200..6beb89fac 100644 --- a/app/run_canvas.go +++ b/app/run_canvas.go @@ -16,6 +16,8 @@ import ( // RunCanvas presents a retained canvas and blocks until the native window // closes. When config.Paint is set the canvas is repainted on window resizes // and pointer interactions; otherwise the initial canvas stays unchanged. +// On macOS, call runtime.LockOSThread in an init function in package main and +// start the native canvas from main to satisfy AppKit's main-thread requirement. func RunCanvas(config Config, canvas *gfx.Canvas) error { if runtime.GOOS != "windows" { config.CaptureMenuKeys = nil @@ -43,6 +45,9 @@ func RunCanvas(config Config, canvas *gfx.Canvas) error { } runtime.LockOSThread() defer runtime.UnlockOSThread() + if err := checkNativeApplicationThread(); err != nil { + return err + } canvas.SetReduceMotion(nativeReduceMotion()) canvas.SetTextEngine(nativeTextEngine()) painter, err := newPainter(canvas, &normalized) @@ -50,6 +55,8 @@ func RunCanvas(config Config, canvas *gfx.Canvas) error { return err } painter.setClipboardText = func(value string) { _ = nativeSetClipboardText(value) } + painter.clipboardReader = nativeClipboardText + painter.enableTextMenu(nativeTextMenus()) painter.setCursor = nativeSetCursor painter.setCursorImage = nativeSetCursorImage native, frames := nativeWindowConfig(&normalized, painter) @@ -166,17 +173,20 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, closeHandler = platform.CloseRequestHandler(normalized.OnCloseRequest) } config := platform.Config{ - Actions: painter.windowActions(), - TextInput: painter.initialTextInput(), - Title: normalized.Title, Class: normalized.Class, Icon: normalized.Icon.platform(), Width: normalized.Width, Height: normalized.Height, + Actions: painter.windowActions(), + TextInput: painter.initialTextInput(), + TakeTextMenu: painter.textMenuTaker(), + Title: normalized.Title, Class: normalized.Class, Icon: normalized.Icon.platform(), Width: normalized.Width, Height: normalized.Height, MinWidth: normalized.MinWidth, MinHeight: normalized.MinHeight, Origin: normalized.originPoint(), HasOrigin: normalized.Origin != nil, - Maximized: normalized.Maximized, - WindowMode: platform.WindowMode(normalized.WindowMode), - WindowMaterials: normalized.windowMaterials(), - TitlebarHeight: normalized.TitlebarHeight, - TrafficLightScale: normalized.TrafficLightScale, - Anchor: normalized.Anchor.rect, HasAnchor: normalized.Anchor.set, + Maximized: normalized.Maximized, + WindowMode: platform.WindowMode(normalized.WindowMode), + WindowMaterials: normalized.windowMaterials(), + Transparent: normalized.Transparent, + OnTransparentChange: normalized.OnTransparentChange, + TitlebarHeight: normalized.TitlebarHeight, + TrafficLightScale: normalized.TrafficLightScale, + Anchor: normalized.Anchor.rect, HasAnchor: normalized.Anchor.set, ClearColor: platform.Color{ Red: normalized.ClearColor.Red, Green: normalized.ClearColor.Green, Blue: normalized.ClearColor.Blue, Alpha: normalized.ClearColor.Alpha, @@ -259,6 +269,8 @@ func prepareNativeWindow(config Config, canvas *gfx.Canvas) (platform.Config, *p return platform.Config{}, nil, nil, err } painter.setClipboardText = func(value string) { _ = nativeSetClipboardText(value) } + painter.clipboardReader = nativeClipboardText + painter.enableTextMenu(nativeTextMenus()) painter.setCursor = nativeSetCursor painter.setCursorImage = nativeSetCursorImage native, timer := nativeWindowConfig(&normalized, painter) diff --git a/app/startup_thread_darwin_test.go b/app/startup_thread_darwin_test.go new file mode 100644 index 000000000..2ec72dbfa --- /dev/null +++ b/app/startup_thread_darwin_test.go @@ -0,0 +1,62 @@ +//go:build darwin && !ios + +package app + +import ( + "context" + "errors" + "os" + "os/exec" + "runtime" + "strings" + "testing" + "time" +) + +const wrongStartupThreadSubprocess = "VIVA_TEST_WRONG_STARTUP_THREAD" + +func init() { + if os.Getenv(wrongStartupThreadSubprocess) == "1" { + // Keep the process main thread in TestMain without a Cocoa event + // loop. The test goroutine must get an error without waiting for it. + runtime.LockOSThread() + if err := checkNativeApplicationThread(); err != nil { + panic(err) + } + } +} + +func TestNativeStartupRejectsNonMainThread(t *testing.T) { + if os.Getenv(wrongStartupThreadSubprocess) != "1" { + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestNativeStartupRejectsNonMainThread$") + cmd.Env = append(os.Environ(), wrongStartupThreadSubprocess+"=1") + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("off-main startup subprocess: %v\n%s", err, output) + } + return + } + + config := Config{Title: "Main-thread startup test", Width: 320, Height: 240} + for _, tc := range []struct { + name string + run func() error + }{ + {"Run", func() error { return Run(config) }}, + {"RunCanvas", func() error { return RunCanvas(config, nil) }}, + {"RunApplication", func() error { + return RunApplication(func(*Application) error { + return errors.New("startup unexpectedly reached the application callback") + }) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + err := tc.run() + if err == nil || !strings.Contains(err.Error(), "process main thread") || + !strings.Contains(err.Error(), "runtime.LockOSThread") { + t.Fatalf("expected an actionable process main-thread error, got %v", err) + } + }) + } +} diff --git a/app/startup_thread_other.go b/app/startup_thread_other.go new file mode 100644 index 000000000..549b7e7ec --- /dev/null +++ b/app/startup_thread_other.go @@ -0,0 +1,5 @@ +//go:build ios || linux || windows + +package app + +func checkNativeApplicationThread() error { return nil } diff --git a/app/system.go b/app/system.go index 52c287e3d..82d5668c4 100644 --- a/app/system.go +++ b/app/system.go @@ -72,6 +72,8 @@ type OpenFileOptions struct { type OpenDirectoryOptions struct { Title string + // InitialDirectory is the starting folder. Empty uses the platform default. + InitialDirectory string } type SaveFileOptions struct { diff --git a/app/system_darwin.go b/app/system_darwin.go index 1e2604007..5411be10d 100644 --- a/app/system_darwin.go +++ b/app/system_darwin.go @@ -22,10 +22,14 @@ func nativeClipboardFiles() ([]string, error) { return darwinplatform.ClipboardF func nativeSetClipboardFiles(paths []string) error { return darwinplatform.SetClipboardFiles(paths) } -func nativeStartFileDrag(paths []string, allowed FileDragEffect) (FileDragEffect, error) { +func nativeStartFileDrag(paths []string, allowed FileDragEffect) error { return darwinplatform.StartFileDrag(paths, allowed) } +func nativeStartFilePromiseDrag(files []FilePromise) error { + return darwinplatform.StartFilePromiseDrag(files) +} + func nativeReduceMotion() bool { return darwinplatform.ReduceMotion() } // nativeTextEngine is the platform's text engine; nil keeps the reference metrics. @@ -64,7 +68,7 @@ func nativeOpenFiles(options OpenFileOptions) ([]string, error) { } func nativeOpenDirectory(options OpenDirectoryOptions) (string, error) { - path, canceled, err := darwinplatform.OpenDirectory(darwinplatform.OpenDirectoryOptions{Title: options.Title}) + path, canceled, err := darwinplatform.OpenDirectory(darwinplatform.OpenDirectoryOptions{Title: options.Title, InitialDirectory: options.InitialDirectory}) if canceled { return "", ErrCanceled } diff --git a/app/system_js.go b/app/system_js.go index eaf4ba3be..14650af51 100644 --- a/app/system_js.go +++ b/app/system_js.go @@ -45,10 +45,14 @@ func nativeSetClipboardImage(png []byte) error { return webSystemError("write clipboard image", webplatform.SetClipboardImage(png)) } -func nativeStartFileDrag(paths []string, allowed FileDragEffect) (FileDragEffect, error) { +func nativeStartFileDrag(paths []string, allowed FileDragEffect) error { return webplatform.StartFileDrag(paths, allowed) } +func nativeStartFilePromiseDrag(files []FilePromise) error { + return webplatform.StartFilePromiseDrag(files) +} + func nativeClipboardImagePNG() ([]byte, error) { return nil, webSystemError("read clipboard image", webplatform.ClipboardImagePNG()) } diff --git a/app/system_linux.go b/app/system_linux.go index 50c7eeb8b..b0d923f9c 100644 --- a/app/system_linux.go +++ b/app/system_linux.go @@ -44,9 +44,12 @@ func nativeSetClipboardFiles(paths []string) error { return linuxSystemError(linuxplatform.SetClipboardFiles(paths)) } -func nativeStartFileDrag(paths []string, allowed FileDragEffect) (FileDragEffect, error) { - effect, err := linuxplatform.StartFileDrag(paths, allowed) - return effect, linuxSystemError(err) +func nativeStartFileDrag(paths []string, allowed FileDragEffect) error { + return linuxSystemError(linuxplatform.StartFileDrag(paths, allowed)) +} + +func nativeStartFilePromiseDrag(files []FilePromise) error { + return linuxSystemError(linuxplatform.StartFilePromiseDrag(files)) } func nativeClipboardImagePNG() ([]byte, error) { @@ -81,7 +84,7 @@ func nativeOpenFiles(options OpenFileOptions) ([]string, error) { } func nativeOpenDirectory(options OpenDirectoryOptions) (string, error) { - path, canceled, err := linuxplatform.OpenDirectory(linuxplatform.OpenDirectoryOptions{Title: options.Title}) + path, canceled, err := linuxplatform.OpenDirectory(linuxplatform.OpenDirectoryOptions{Title: options.Title, InitialDirectory: options.InitialDirectory}) if canceled { return "", ErrCanceled } diff --git a/app/system_unsupported.go b/app/system_unsupported.go index 91c69a44a..482a1187e 100644 --- a/app/system_unsupported.go +++ b/app/system_unsupported.go @@ -52,6 +52,11 @@ func nativeSetAppearance(Appearance) {} // nativeStartFileDrag is the Web-independent fallback: a target with neither a // window the platform can drag from nor the Web's own drag has no way to take // files out of one. -func nativeStartFileDrag([]string, FileDragEffect) (FileDragEffect, error) { - return FileDragNone, ErrUnsupported +func nativeStartFileDrag([]string, FileDragEffect) error { + return ErrUnsupported +} + +// nativeStartFilePromiseDrag is the same fallback for promised content. +func nativeStartFilePromiseDrag([]FilePromise) error { + return ErrUnsupported } diff --git a/app/system_windows.go b/app/system_windows.go index 90714fa4f..4770666e0 100644 --- a/app/system_windows.go +++ b/app/system_windows.go @@ -19,10 +19,14 @@ func nativeClipboardFiles() ([]string, error) { return windowsplatform.Clipboard func nativeSetClipboardFiles(paths []string) error { return windowsplatform.SetClipboardFiles(paths) } -func nativeStartFileDrag(paths []string, allowed FileDragEffect) (FileDragEffect, error) { +func nativeStartFileDrag(paths []string, allowed FileDragEffect) error { return windowsplatform.StartFileDrag(paths, allowed) } +func nativeStartFilePromiseDrag(files []FilePromise) error { + return windowsplatform.StartFilePromiseDrag(files) +} + func nativeReduceMotion() bool { return windowsplatform.ReduceMotion() } // nativeTextEngine is the platform's text engine; nil keeps the reference metrics. @@ -55,7 +59,7 @@ func nativeOpenFiles(options OpenFileOptions) ([]string, error) { } func nativeOpenDirectory(options OpenDirectoryOptions) (string, error) { - path, canceled, err := windowsplatform.OpenDirectory(windowsplatform.OpenDirectoryOptions{Title: options.Title}) + path, canceled, err := windowsplatform.OpenDirectory(windowsplatform.OpenDirectoryOptions{Title: options.Title, InitialDirectory: options.InitialDirectory}) if canceled { return "", ErrCanceled } diff --git a/app/systemauth/README.md b/app/systemauth/README.md new file mode 100644 index 000000000..9025eafe4 --- /dev/null +++ b/app/systemauth/README.md @@ -0,0 +1,20 @@ +# System authentication + +`Method()` queries the operating system without showing a prompt. `Verify(ctx, reason)` +returns success after the OS verifies the current user. Call it from a worker +goroutine with an active application window. Callers should also discard results +that belong to a closed window or an earlier application lock. This API is for +an application UI lock. It handles no encryption or key release. + +- Windows uses UserConsentVerifier, with the HWND-owned desktop method where + available. The static WinRT method is tried only if the interop interface is + absent. Some older Windows desktop contexts cannot present that static + prompt. A missing active window, ordinary cancellation, and unavailable + authentication are reported separately. +- macOS uses LocalAuthentication and a fresh device-owner authentication + context. The OS can offer Touch ID or the system password. No Keychain + entitlement is needed for this prompt. +- On other platforms, the method is unavailable. + +References: [Windows desktop verification](https://learn.microsoft.com/windows/win32/api/userconsentverifierinterop/nf-userconsentverifierinterop-iuserconsentverifierinterop-requestverificationforwindowasync), +[Apple LocalAuthentication](https://developer.apple.com/documentation/localauthentication/lacontext/evaluatepolicy(_:localizedreason:reply:)). diff --git a/app/systemauth/native_darwin.go b/app/systemauth/native_darwin.go new file mode 100644 index 000000000..5b2ce3f36 --- /dev/null +++ b/app/systemauth/native_darwin.go @@ -0,0 +1,50 @@ +//go:build darwin && !ios && cgo + +package systemauth + +/* +#cgo LDFLAGS: -framework Foundation -framework LocalAuthentication +#include +#include "native_darwin.h" +*/ +import "C" + +import ( + "context" + "fmt" + "unsafe" +) + +func nativeMethod() VerificationMethod { return VerificationMethod(C.viva_systemauth_method()) } + +func nativeVerify(ctx context.Context, reason string) error { + if err := ctx.Err(); err != nil { + return err + } + auth := C.viva_systemauth_new() + if auth == nil { + return ErrUnavailable + } + defer C.viva_systemauth_free(auth) + prompt := C.CString(reason) + defer C.free(unsafe.Pointer(prompt)) + done := make(chan struct{}) + stop := context.AfterFunc(ctx, func() { C.viva_systemauth_cancel(auth); close(done) }) + status := int(C.viva_systemauth_verify(auth, prompt)) + if !stop() { + <-done + } + if err := ctx.Err(); err != nil { + return err + } + switch status { + case 0: + return nil + case -2, -4, -9: + return ErrCanceled // user, system or app canceled + case -3, -5, -6, -7, -8, -10: + return fmt.Errorf("%w (LocalAuthentication %d)", ErrUnavailable, status) + default: + return fmt.Errorf("%w (LocalAuthentication %d)", ErrFailed, status) + } +} diff --git a/app/systemauth/native_darwin.h b/app/systemauth/native_darwin.h new file mode 100644 index 000000000..7e42db87f --- /dev/null +++ b/app/systemauth/native_darwin.h @@ -0,0 +1,6 @@ +typedef void *viva_auth_context; +int viva_systemauth_method(void); +viva_auth_context viva_systemauth_new(void); +void viva_systemauth_cancel(viva_auth_context ctx); +void viva_systemauth_free(viva_auth_context ctx); +int viva_systemauth_verify(viva_auth_context ctx, const char *reason); diff --git a/app/systemauth/native_darwin.m b/app/systemauth/native_darwin.m new file mode 100644 index 000000000..b603ced61 --- /dev/null +++ b/app/systemauth/native_darwin.m @@ -0,0 +1,48 @@ +//go:build darwin && !ios && cgo + +#import +#import +#include "native_darwin.h" + +int viva_systemauth_method(void) { + @autoreleasepool { + LAContext *context = [[[LAContext alloc] init] autorelease]; + if (![context canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:NULL]) return 0; + if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:NULL] + && context.biometryType == LABiometryTypeTouchID) return 2; + return 3; + } +} + +viva_auth_context viva_systemauth_new(void) { + @autoreleasepool { + LAContext *context = [[LAContext alloc] init]; + context.touchIDAuthenticationAllowableReuseDuration = 0; + return context; + } +} + +void viva_systemauth_cancel(viva_auth_context ctx) { + @autoreleasepool { [(LAContext *)ctx invalidate]; } +} + +void viva_systemauth_free(viva_auth_context ctx) { + @autoreleasepool { [(LAContext *)ctx release]; } +} + +int viva_systemauth_verify(viva_auth_context ctx, const char *reason) { + @autoreleasepool { + LAContext *context = (LAContext *)ctx; + NSString *prompt = [NSString stringWithUTF8String:reason]; + if (prompt.length == 0) return LAErrorInvalidContext; + __block int result = LAErrorAuthenticationFailed; + dispatch_semaphore_t completion = dispatch_semaphore_create(0); + [context evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:prompt reply:^(BOOL success, NSError *error) { + result = success ? 0 : (error == nil ? LAErrorAuthenticationFailed : (int)error.code); + dispatch_semaphore_signal(completion); + }]; + dispatch_semaphore_wait(completion, DISPATCH_TIME_FOREVER); + dispatch_release(completion); + return result; + } +} diff --git a/app/systemauth/native_other.go b/app/systemauth/native_other.go new file mode 100644 index 000000000..11f878027 --- /dev/null +++ b/app/systemauth/native_other.go @@ -0,0 +1,8 @@ +//go:build !windows && (!darwin || ios || !cgo) + +package systemauth + +import "context" + +func nativeMethod() VerificationMethod { return VerificationUnavailable } +func nativeVerify(context.Context, string) error { return ErrUnavailable } diff --git a/app/systemauth/native_windows.go b/app/systemauth/native_windows.go new file mode 100644 index 000000000..35509c061 --- /dev/null +++ b/app/systemauth/native_windows.go @@ -0,0 +1,457 @@ +package systemauth + +import ( + "context" + "errors" + "fmt" + "runtime" + "sync" + "sync/atomic" + "syscall" + "time" + "unsafe" + + "golang.org/x/sys/windows" +) + +// IUserConsentVerifierStatics, IUserConsentVerifierInterop and IAsyncInfo from +// the Windows SDK. The verifier presents the system Hello prompt; a +// verifier does not release key material. +var ( + consentStaticsIID = windows.GUID{ + Data1: 0xaf4f3f91, Data2: 0x564c, Data3: 0x4ddc, + Data4: [8]byte{0xb8, 0xb5, 0x97, 0x34, 0x47, 0x62, 0x7c, 0x65}, + } + consentAsyncInfoIID = windows.GUID{ + Data1: 0x00000036, + Data4: [8]byte{0xc0, 0, 0, 0, 0, 0, 0, 0x46}, + } + consentVerifierInteropIID = windows.GUID{ + Data1: 0x39e050c3, Data2: 0x4e74, Data3: 0x441a, + Data4: [8]byte{0x8d, 0xc0, 0xb8, 0x11, 0x04, 0xdf, 0x94, 0x9c}, + } + // IAsyncOperation, and the completion + // handlers of the two operations this package starts. A parameterized + // interface's IID is a name-based UUID of its signature, so these three are + // derived, not looked up; native_windows_test.go derives them again. + consentAsyncResultIID = windows.GUID{ + Data1: 0xfd596ffd, Data2: 0x2318, Data3: 0x558f, + Data4: [8]byte{0x9d, 0xbe, 0xd2, 0x1d, 0xf4, 0x37, 0x64, 0xa5}, + } + consentResultHandlerIID = windows.GUID{ + Data1: 0x0cffc6c9, Data2: 0x4c2b, Data3: 0x5cd4, + Data4: [8]byte{0xb3, 0x8c, 0x7b, 0x8d, 0xf3, 0xff, 0x5a, 0xfb}, + } + consentAvailabilityHandlerIID = windows.GUID{ + Data1: 0x28988174, Data2: 0xace2, Data3: 0x5c15, + Data4: [8]byte{0xa0, 0xdf, 0x58, 0x0a, 0x26, 0xd9, 0x42, 0x94}, + } + // IAgileObject: the handler may be called from any thread of the apartment. + consentAgileIID = windows.GUID{ + Data1: 0x94ea2b94, Data2: 0xe9cc, Data3: 0x49e0, + Data4: [8]byte{0xc0, 0xff, 0xee, 0x64, 0xca, 0x8f, 0x5b, 0x90}, + } + consentUnknownIID = windows.GUID{ + Data4: [8]byte{0xc0, 0, 0, 0, 0, 0, 0, 0x46}, + } + + consentCOMBase = windows.NewLazySystemDLL("combase.dll") + consentInitialize = consentCOMBase.NewProc("RoInitialize") + consentUninitialize = consentCOMBase.NewProc("RoUninitialize") + consentCreateString = consentCOMBase.NewProc("WindowsCreateString") + consentDeleteString = consentCOMBase.NewProc("WindowsDeleteString") + consentGetFactory = consentCOMBase.NewProc("RoGetActivationFactory") + consentUser32 = windows.NewLazySystemDLL("user32.dll") + consentForeground = consentUser32.NewProc("GetForegroundWindow") + consentWindowPID = consentUser32.NewProc("GetWindowThreadProcessId") +) + +const ( + consentClass = "Windows.Security.Credentials.UI.UserConsentVerifier" + consentMTA = 1 + + // How long a canceled prompt gets to report that it has closed. + consentCancelWait = 2 * time.Second + + // AsyncStatus of IAsyncInfo, as the completion handler receives it. + asyncCompleted = 1 + asyncCanceled = 2 + + consentVerified = 0 + consentDeviceNotPresent = 1 + consentNotConfigured = 2 + consentDisabledByPolicy = 3 + consentDeviceBusy = 4 + consentRetriesExhausted = 5 + consentCanceled = 6 + + consentChangedMode = 0x80010106 // RPC_E_CHANGED_MODE +) + +type consentObject struct { + methods *[10]uintptr +} + +func (object *consentObject) release() { + syscall.SyscallN(object.methods[2], uintptr(unsafe.Pointer(object))) // IUnknown.Release +} + +func consentSucceeded(status uintptr) bool { return int32(status) >= 0 } + +var errNoWindowInterop = errors.New("window-owned Hello API is unavailable") + +func foregroundWindow() (uintptr, error) { + owner, _, _ := consentForeground.Call() + var pid uint32 + if owner != 0 { + consentWindowPID.Call(owner, uintptr(unsafe.Pointer(&pid))) + } + if pid != windows.GetCurrentProcessId() { + return 0, ErrForegroundRequired + } + return owner, nil +} + +func confirmForegroundOwner(owner uintptr) error { + current, err := foregroundWindow() + if err != nil || current != owner { + return ErrForegroundRequired + } + return nil +} + +func helloHRESULT(operation string, status uintptr) error { + if consentSucceeded(status) { + return nil + } + if uint32(status) == 0x800704c7 || uint32(status) == 0x80090036 { + return ErrCanceled + } + return fmt.Errorf("%w: Windows Hello %s (HRESULT 0x%08X)", ErrUnavailable, operation, uint32(status)) +} + +func nativeMethod() VerificationMethod { + ctx, cancel := context.WithTimeout(context.Background(), 750*time.Millisecond) + defer cancel() + result := make(chan VerificationMethod, 1) + go func() { result <- configuredMethod(ctx) }() + select { + case method := <-result: + return method + case <-ctx.Done(): + return VerificationUnavailable + } +} + +func configuredMethod(ctx context.Context) VerificationMethod { + ready := VerificationUnavailable + _ = withConsentApartment(func() error { + factory, err := consentFactory(&consentStaticsIID) + if err != nil { + return err + } + defer factory.release() + var operation *consentObject + status, _, _ := syscall.SyscallN(factory.methods[6], uintptr(unsafe.Pointer(factory)), uintptr(unsafe.Pointer(&operation))) // CheckAvailabilityAsync + if !consentSucceeded(status) || operation == nil { + return ErrUnavailable + } + defer operation.release() + var availability int32 = -1 + if err := waitHelloConsent(ctx, operation, &consentAvailabilityHandlerIID, unsafe.Pointer(&availability)); err != nil { + return err + } + if availability == 0 && ctx.Err() == nil { + ready = VerificationWindowsHello + } + return nil + }) + return ready +} +func nativeVerify(ctx context.Context, reason string) error { + owner, err := foregroundWindow() + if err != nil { + return err + } + return withConsentApartment(func() error { + message, err := consentHString(reason) + if err != nil { + return err + } + defer consentDeleteString.Call(message) + if err := ctx.Err(); err != nil { + return err + } + if err := confirmForegroundOwner(owner); err != nil { + return err + } + operation, err := startHelloConsent(owner, message) + if err != nil { + return err + } + defer operation.release() + var result int32 = -1 + if err := waitHelloConsent(ctx, operation, &consentResultHandlerIID, unsafe.Pointer(&result)); err != nil { + return err + } + return helloConsentError(result) + }) +} + +func withConsentApartment(run func() error) error { + for _, proc := range []*windows.LazyProc{consentInitialize, consentUninitialize, consentCreateString, consentDeleteString, consentGetFactory} { + if proc.Find() != nil { + return ErrUnavailable + } + } + runtime.LockOSThread() + defer runtime.UnlockOSThread() + status, _, _ := consentInitialize.Call(consentMTA) + switch { + case consentSucceeded(status): + defer consentUninitialize.Call() + case uint32(status) == consentChangedMode: + // Another part of this thread already joined an apartment. The + // verifier can still be activated, as GoIM does on the same path. + default: + return fmt.Errorf("%w: Windows Hello initialization failed (HRESULT 0x%08X)", ErrUnavailable, uint32(status)) + } + return run() +} + +func consentHString(value string) (uintptr, error) { + units, err := windows.UTF16FromString(value) + if err != nil { + return 0, fmt.Errorf("%w: %v", ErrUnavailable, err) + } + var name uintptr + status, _, _ := consentCreateString.Call(uintptr(unsafe.Pointer(&units[0])), uintptr(len(units)-1), uintptr(unsafe.Pointer(&name))) + if !consentSucceeded(status) || name == 0 { + return 0, fmt.Errorf("%w: Windows Hello message failed (HRESULT 0x%08X)", ErrUnavailable, uint32(status)) + } + return name, nil +} + +func consentFactory(iid *windows.GUID) (*consentObject, error) { + class, err := consentHString(consentClass) + if err != nil { + return nil, err + } + defer consentDeleteString.Call(class) + var factory *consentObject + status, _, _ := consentGetFactory.Call(class, uintptr(unsafe.Pointer(iid)), uintptr(unsafe.Pointer(&factory))) + runtime.KeepAlive(iid) + if uint32(status) == 0x80004002 && iid == &consentVerifierInteropIID { // E_NOINTERFACE + return nil, errNoWindowInterop + } + if !consentSucceeded(status) || factory == nil { + return nil, fmt.Errorf("%w: Windows Hello activation failed (HRESULT 0x%08X)", ErrUnavailable, uint32(status)) + } + return factory, nil +} + +func startHelloConsent(owner uintptr, message uintptr) (*consentObject, error) { + // Fall back to the older API only if the HWND interop is absent. + factory, err := consentFactory(&consentVerifierInteropIID) + if err == nil { + defer factory.release() + var operation *consentObject + status, _, _ := syscall.SyscallN(factory.methods[6], uintptr(unsafe.Pointer(factory)), owner, message, + uintptr(unsafe.Pointer(&consentAsyncResultIID)), uintptr(unsafe.Pointer(&operation))) + if ctxErr := helloHRESULT("request verification for window", status); ctxErr != nil { + return nil, ctxErr + } + if operation == nil { + return nil, ErrUnavailable + } + return operation, nil + } + if !errors.Is(err, errNoWindowInterop) { + return nil, err + } + factory, err = consentFactory(&consentStaticsIID) + if err != nil { + return nil, err + } + defer factory.release() + var operation *consentObject + // The static WinRT method has no REFIID argument. Its result type + // is fixed in the SDK; only the desktop interop entry takes a REFIID. + status, _, _ := syscall.SyscallN(factory.methods[7], uintptr(unsafe.Pointer(factory)), message, + uintptr(unsafe.Pointer(&operation))) + if err := helloHRESULT("request verification", status); err != nil { + return nil, err + } + if operation == nil { + return nil, ErrUnavailable + } + return operation, nil +} + +// waitHelloConsent waits for the operation to finish and then reads its result. +// It asks the operation to call back when it is done instead of asking it again +// and again: the wait is a channel receive, and nothing runs while the prompt is +// open. A canceled context cancels the operation and waits, for a bounded time, +// for the system to say the prompt has closed. +func waitHelloConsent(ctx context.Context, operation *consentObject, handlerIID *windows.GUID, result unsafe.Pointer) error { + var info *consentObject + status, _, _ := syscall.SyscallN(operation.methods[0], uintptr(unsafe.Pointer(operation)), + uintptr(unsafe.Pointer(&consentAsyncInfoIID)), uintptr(unsafe.Pointer(&info))) + runtime.KeepAlive(&consentAsyncInfoIID) + if !consentSucceeded(status) || info == nil { + return fmt.Errorf("%w: Windows Hello result is unavailable (HRESULT 0x%08X)", ErrUnavailable, uint32(status)) + } + defer info.release() + handler := newConsentHandler(handlerIID) + defer handler.release() + // put_Completed of IAsyncOperation: IUnknown (3) and IInspectable (3) come first. + status, _, _ = syscall.SyscallN(operation.methods[6], uintptr(unsafe.Pointer(operation)), handler.pointer()) + if !consentSucceeded(status) { + return fmt.Errorf("%w: Windows Hello completion handler failed (HRESULT 0x%08X)", ErrUnavailable, uint32(status)) + } + select { + case <-handler.done: + case <-ctx.Done(): + syscall.SyscallN(info.methods[9], uintptr(unsafe.Pointer(info))) // IAsyncInfo.Cancel + timer := time.NewTimer(consentCancelWait) + defer timer.Stop() + select { + case <-handler.done: + case <-timer.C: + } + return ctx.Err() + } + switch state := handler.state.Load(); state { + case asyncCompleted: + status, _, _ = syscall.SyscallN(operation.methods[8], uintptr(unsafe.Pointer(operation)), uintptr(result)) // GetResults + if !consentSucceeded(status) { + return helloHRESULT("verification result", status) + } + return nil + case asyncCanceled: + return ErrCanceled + default: + return fmt.Errorf("%w: Windows Hello verification ended in state %d", ErrUnavailable, state) + } +} + +// consentHandler is the COM object handed to put_Completed: an +// AsyncOperationCompletedHandler whose Invoke records the final status and +// wakes the waiter. Its first word is the vtable pointer, as COM requires. +type consentHandler struct { + vtable *[4]uintptr + refs atomic.Int32 + iid *windows.GUID + state atomic.Int32 + done chan struct{} + once sync.Once +} + +var ( + consentHandlerVtable [4]uintptr + consentHandlerCallback sync.Once + + // COM keeps the pointer it was given, and calls back with it from another + // thread: the registry holds the object up, and finds it again from that + // pointer, until the last reference is released. + consentHandlers = map[uintptr]*consentHandler{} + consentHandlersMu sync.Mutex +) + +func newConsentHandler(iid *windows.GUID) *consentHandler { + consentHandlerCallback.Do(func() { + // Callbacks are never freed, so each is made once for the process. + consentHandlerVtable = [4]uintptr{ + syscall.NewCallback(consentHandlerQueryInterface), + syscall.NewCallback(consentHandlerAddRef), + syscall.NewCallback(consentHandlerRelease), + syscall.NewCallback(consentHandlerInvoke), + } + }) + handler := &consentHandler{vtable: &consentHandlerVtable, iid: iid, done: make(chan struct{})} + handler.refs.Store(1) + consentHandlersMu.Lock() + consentHandlers[handler.pointer()] = handler + consentHandlersMu.Unlock() + return handler +} + +func (handler *consentHandler) pointer() uintptr { return uintptr(unsafe.Pointer(handler)) } + +// release drops one reference and returns how many remain. +func (handler *consentHandler) release() int32 { + remaining := handler.refs.Add(-1) + if remaining == 0 { + consentHandlersMu.Lock() + delete(consentHandlers, handler.pointer()) + consentHandlersMu.Unlock() + } + return remaining +} + +func lookupConsentHandler(this uintptr) *consentHandler { + consentHandlersMu.Lock() + defer consentHandlersMu.Unlock() + return consentHandlers[this] +} + +func consentHandlerQueryInterface(this, iid, object uintptr) uintptr { + handler := lookupConsentHandler(this) + if handler == nil || object == 0 { + return 0x80004003 // E_POINTER + } + // COM passes both as plain addresses, which go vet cannot tell from a stale + // uintptr, so they are read through a pointer to the word that holds them. + requested := *(**windows.GUID)(unsafe.Pointer(&iid)) + out := *(**uintptr)(unsafe.Pointer(&object)) + if *requested == consentUnknownIID || *requested == consentAgileIID || *requested == *handler.iid { + *out = this + handler.refs.Add(1) + return 0 + } + *out = 0 + return 0x80004002 // E_NOINTERFACE +} + +func consentHandlerAddRef(this uintptr) uintptr { + if handler := lookupConsentHandler(this); handler != nil { + return uintptr(handler.refs.Add(1)) + } + return 0 +} + +func consentHandlerRelease(this uintptr) uintptr { + if handler := lookupConsentHandler(this); handler != nil { + return uintptr(handler.release()) + } + return 0 +} + +func consentHandlerInvoke(this, _, status uintptr) uintptr { + if handler := lookupConsentHandler(this); handler != nil { + handler.once.Do(func() { + handler.state.Store(int32(status)) + close(handler.done) + }) + } + return 0 +} + +func helloConsentError(result int32) error { + switch result { + case consentVerified: + return nil + case consentCanceled: + return ErrCanceled + case consentDeviceNotPresent, consentNotConfigured: + return fmt.Errorf("%w: Windows Hello is not configured for this account", ErrUnavailable) + case consentDisabledByPolicy: + return fmt.Errorf("%w: Windows Hello is disabled by policy", ErrUnavailable) + case consentDeviceBusy: + return fmt.Errorf("%w: Windows Hello is busy", ErrFailed) + case consentRetriesExhausted: + return fmt.Errorf("%w: Windows Hello retries were exhausted", ErrFailed) + default: + return fmt.Errorf("%w: unrecognized Windows Hello result %d", ErrFailed, result) + } +} diff --git a/app/systemauth/native_windows_test.go b/app/systemauth/native_windows_test.go new file mode 100644 index 000000000..e58c5f620 --- /dev/null +++ b/app/systemauth/native_windows_test.go @@ -0,0 +1,150 @@ +package systemauth + +import ( + "context" + "crypto/sha1" + "errors" + "syscall" + "testing" + "time" + "unsafe" + + "golang.org/x/sys/windows" +) + +func TestHelloConsentRejectsEveryNonVerifiedResult(t *testing.T) { + for _, tc := range []struct { + result int32 + want error + }{ + {0, nil}, {1, ErrUnavailable}, {2, ErrUnavailable}, {3, ErrUnavailable}, + {4, ErrFailed}, {5, ErrFailed}, {6, ErrCanceled}, {-1, ErrFailed}, {15, ErrFailed}, + } { + if err := helloConsentError(tc.result); !errors.Is(err, tc.want) { + t.Errorf("native result %d returned %v, want %v", tc.result, err, tc.want) + } + } + if err := helloHRESULT("test", uintptr(0x800704c7)); !errors.Is(err, ErrCanceled) { + t.Fatal(err) + } + if err := helloHRESULT("test", uintptr(0x80004005)); !errors.Is(err, ErrUnavailable) { + t.Fatal(err) + } +} + +func TestHelloCapabilityWithoutShowingPrompt(t *testing.T) { + method := Method() + t.Logf("Windows Hello method: %v", method) + if method != VerificationUnavailable && method != VerificationWindowsHello { + t.Fatal("unexpected Windows method") + } +} + +// parameterizedIID derives the IID of a WinRT parameterized interface: a +// name-based (version 5) UUID of its signature under the WinRT namespace. +func parameterizedIID(signature string) windows.GUID { + namespace := [16]byte{0x11, 0xf4, 0x7a, 0xd5, 0x7b, 0x73, 0x42, 0xc0, 0xab, 0xae, 0x87, 0x8b, 0x1e, 0x16, 0xad, 0xee} + hash := sha1.New() + hash.Write(namespace[:]) + hash.Write([]byte(signature)) + sum := hash.Sum(nil)[:16] + sum[6] = sum[6]&0x0f | 0x50 + sum[8] = sum[8]&0x3f | 0x80 + return windows.GUID{ + Data1: uint32(sum[0])<<24 | uint32(sum[1])<<16 | uint32(sum[2])<<8 | uint32(sum[3]), + Data2: uint16(sum[4])<<8 | uint16(sum[5]), + Data3: uint16(sum[6])<<8 | uint16(sum[7]), + Data4: [8]byte(sum[8:16]), + } +} + +// A handler with a wrong IID is refused by the system at registration or never +// called, so the three IIDs are checked against their signatures. +func TestCompletionIIDsMatchTheirSignatures(t *testing.T) { + const ( + operation = "{9fc2b0bb-e446-44e2-aa61-9cab8f636af2}" + handler = "{fcdcf02c-e5d8-4478-915a-4d90b74b83a5}" + result = "enum(Windows.Security.Credentials.UI.UserConsentVerificationResult;i4)" + available = "enum(Windows.Security.Credentials.UI.UserConsentVerifierAvailability;i4)" + ) + for name, tc := range map[string]struct { + got, want windows.GUID + }{ + "IAsyncOperation": {consentAsyncResultIID, parameterizedIID("pinterface(" + operation + ";" + result + ")")}, + "completion handler": {consentResultHandlerIID, parameterizedIID("pinterface(" + handler + ";" + result + ")")}, + "completion handler": {consentAvailabilityHandlerIID, parameterizedIID("pinterface(" + handler + ";" + available + ")")}, + } { + if tc.got != tc.want { + t.Errorf("%s = %v, want %v", name, tc.got, tc.want) + } + } +} + +// startAvailability starts the availability query, which finishes without a +// prompt on any machine, whether or not Windows Hello is set up. +func startAvailability(t *testing.T) (*consentObject, func()) { + t.Helper() + factory, err := consentFactory(&consentStaticsIID) + if err != nil { + t.Skipf("Windows Hello is not activatable here: %v", err) + } + var operation *consentObject + status, _, _ := syscall.SyscallN(factory.methods[6], uintptr(unsafe.Pointer(factory)), uintptr(unsafe.Pointer(&operation))) // CheckAvailabilityAsync + if !consentSucceeded(status) || operation == nil { + factory.release() + t.Skipf("availability query failed (HRESULT 0x%08X)", uint32(status)) + } + return operation, func() { operation.release(); factory.release() } +} + +func TestWaitIsEndedByTheCompletionHandler(t *testing.T) { + err := withConsentApartment(func() error { + operation, done := startAvailability(t) + defer done() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + var availability int32 = -1 + started := time.Now() + if err := waitHelloConsent(ctx, operation, &consentAvailabilityHandlerIID, unsafe.Pointer(&availability)); err != nil { + return err + } + if availability < 0 { + t.Errorf("the wait returned before the result was read (availability %d)", availability) + } + t.Logf("availability %d after %v", availability, time.Since(started)) + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +// Whether the context ends the wait before or after the operation does, it ends +// promptly and never reports a success it did not read. +func TestWaitReturnsPromptlyWhenTheContextIsAlreadyDone(t *testing.T) { + err := withConsentApartment(func() error { + operation, done := startAvailability(t) + defer done() + ctx, cancel := context.WithCancel(context.Background()) + cancel() + var availability int32 = -1 + started := time.Now() + err := waitHelloConsent(ctx, operation, &consentAvailabilityHandlerIID, unsafe.Pointer(&availability)) + if elapsed := time.Since(started); elapsed > consentCancelWait+time.Second { + t.Errorf("the wait took %v after the context was canceled", elapsed) + } + if err != nil && !errors.Is(err, context.Canceled) { + t.Errorf("wait returned %v", err) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +func TestVerifyWithoutAnApplicationWindowIsRefused(t *testing.T) { + if err := nativeVerify(context.Background(), "Unlock"); !errors.Is(err, ErrForegroundRequired) { + t.Fatalf("verification with no foreground window of this process: %v", err) + } +} diff --git a/app/systemauth/systemauth.go b/app/systemauth/systemauth.go new file mode 100644 index 000000000..9ff913223 --- /dev/null +++ b/app/systemauth/systemauth.go @@ -0,0 +1,76 @@ +// Package systemauth asks the operating system to verify the current user. +// It returns a verification result for an application UI lock. It does not +// create, store, or release cryptographic keys. +package systemauth + +import ( + "context" + "errors" + "strings" + "time" + "unicode/utf8" +) + +var ( + // ErrUnavailable means the system cannot verify the user here: the + // platform has no such facility, or the user has not set one up, or policy + // turns it off. Retrying does not help until that changes. + ErrUnavailable = errors.New("system authentication is unavailable") + // ErrCanceled means the user, or the system on the user's behalf, dismissed + // the prompt. It is a refusal, never a success. + ErrCanceled = errors.New("system authentication was canceled") + // ErrForegroundRequired means no window of this process was in the + // foreground, so the system had nothing to attach its prompt to. Call Verify + // again once the application's window is active. + ErrForegroundRequired = errors.New("system authentication requires an active window") + // ErrFailed means the prompt ran and the user was not verified, or the + // request could not be made because another verification is already showing. + ErrFailed = errors.New("system authentication failed") +) + +// VerificationMethod is how the system verifies the current user. +type VerificationMethod uint8 + +const ( + // VerificationUnavailable is the zero value: the system offers no way to + // verify the user. + VerificationUnavailable VerificationMethod = iota + // VerificationWindowsHello is Windows Hello (face, fingerprint or PIN). + VerificationWindowsHello + // VerificationTouchID is Touch ID, with the system password as the fallback + // the system itself offers. + VerificationTouchID + // VerificationDevicePassword is the device-owner password, on a Mac without + // Touch ID. + VerificationDevicePassword +) + +// Method checks the system's authentication configuration without opening a prompt. +func Method() VerificationMethod { return nativeMethod() } + +var prompt = make(chan struct{}, 1) + +// Verify requests a fresh system prompt. Call from a worker goroutine while +// the application's window is in the foreground. Cancellation never returns +// success, even if the native prompt completed at the same time. +func Verify(ctx context.Context, reason string) error { + if err := ctx.Err(); err != nil { + return err + } + if strings.TrimSpace(reason) == "" || len(reason) > 1024 || !utf8.ValidString(reason) || strings.ContainsRune(reason, 0) { + return errors.New("system authentication requires a valid, nonempty reason") + } + select { + case prompt <- struct{}{}: + defer func() { <-prompt }() + default: + return ErrFailed + } + ctx, cancel := context.WithTimeout(ctx, 2*time.Minute) + defer cancel() + err := nativeVerify(ctx, reason) + if ctx.Err() != nil { + return ctx.Err() + } + return err +} diff --git a/app/systemauth/systemauth_test.go b/app/systemauth/systemauth_test.go new file mode 100644 index 000000000..e22c62577 --- /dev/null +++ b/app/systemauth/systemauth_test.go @@ -0,0 +1,28 @@ +package systemauth + +import ( + "context" + "errors" + "testing" +) + +func TestVerifyRejectsInvalidOrCanceledRequestBeforeNativeUI(t *testing.T) { + for _, reason := range []string{"", " ", "null\x00injected", "\xff"} { + if err := Verify(context.Background(), reason); err == nil { + t.Fatalf("accepted invalid reason %q", reason) + } + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := Verify(ctx, "Unlock application"); !errors.Is(err, context.Canceled) { + t.Fatalf("canceled request: %v", err) + } +} + +func TestVerifyRefusesConcurrentPrompts(t *testing.T) { + prompt <- struct{}{} + defer func() { <-prompt }() + if err := Verify(context.Background(), "Unlock application"); !errors.Is(err, ErrFailed) { + t.Fatalf("second prompt: %v", err) + } +} diff --git a/app/text_menu.go b/app/text_menu.go new file mode 100644 index 000000000..da5cc7156 --- /dev/null +++ b/app/text_menu.go @@ -0,0 +1,197 @@ +package app + +import ( + "errors" + "fmt" + "slices" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +// TextMenuLabels are the words of the menu a text field opens on a secondary +// press. A label left empty is English. The menu is the system's own where the +// platform has one to show (macOS and Windows) and the page's where it has none. +type TextMenuLabels = gfx.TextMenuLabels + +// TextMenuCommand is a command of a text field's menu. +type TextMenuCommand = platform.TextMenuCommand + +// The commands of a text field's menu. +const ( + TextMenuNone = platform.TextMenuNone + TextMenuCut = platform.TextMenuCut + TextMenuCopy = platform.TextMenuCopy + TextMenuPaste = platform.TextMenuPaste + TextMenuSelectAll = platform.TextMenuSelectAll +) + +// TextMenuItem is a row of a text field's menu, as a Driver shows it: the +// command, its words, and whether it is off. A zero Command is a separator. +type TextMenuItem = platform.TextMenuItem + +// pointToMenu is where a text menu opens: the press that asked for it. +type pointToMenu struct { + x, y float32 + at gfx.ID +} + +// requestTextMenu notes a secondary press that the application did not take, over +// a text field the window has an editor for, as the one the system's text menu +// opens for. The press focused the field already; the repaint it needs is done +// here and not left to the frame clock, so the editor the menu acts on is the +// one installed when the menu is taken. +func (painter *painter) requestTextMenu(event platform.PointerEvent) (platform.Frame, error, bool) { + if painter.textMenu == nil || !painter.textMenuNative || event.Kind != platform.PointerDown || + event.Button != gfx.PointerButtonSecondary || event.Device == gfx.PointerTouch { + return platform.Frame{}, nil, false + } + if painter.pointer.HoveredRole() != gfx.RoleTextField || painter.pointer.Hovered().IsZero() || + painter.pointer.Hovered() != painter.focus.Focused() { + return platform.Frame{}, nil, false + } + painter.textMenuAt = &pointToMenu{x: event.X, y: event.Y, at: painter.pointer.Hovered()} + frame, err := painter.repaint() + return frame, err, true +} + +// takeTextMenu is the menu the last press asked for, now that the frame it caused +// is painted: nil unless the field it was asked for still has the keyboard and the +// platform gave it an editor, which a read-only field has none of. +func (painter *painter) takeTextMenu() (platform.TextMenuRequest, bool) { + at := painter.textMenuAt + painter.textMenuAt = nil + if at == nil || !painter.textEnabled || painter.nativeText.Terminal || + painter.nativeText.Target != at.at || painter.focus.Focused() != at.at { + return platform.TextMenuRequest{}, false + } + return platform.TextMenuRequest{ + Items: painter.textMenuItems(), + X: at.x, + Y: at.y, + Perform: painter.performTextMenu, + }, true +} + +// textMenuItems are the rows of the menu, with the same rules the keyboard has: a +// secret never leaves through Cut or Copy, and nothing is cut or copied from an +// empty selection. +func (painter *painter) textMenuItems() []platform.TextMenuItem { + labels := painter.textMenu.WithDefaults() + input := painter.nativeText + selection := input.ClipboardState('c').Selection + selected := selection.Start != selection.End + composing := input.State.Composing + canCopy := selected && !input.Secure && !composing + return []platform.TextMenuItem{ + {Command: platform.TextMenuCut, Title: labels.Cut, Disabled: !canCopy}, + {Command: platform.TextMenuCopy, Title: labels.Copy, Disabled: !canCopy}, + {Command: platform.TextMenuPaste, Title: labels.Paste, Disabled: composing}, + {}, + {Command: platform.TextMenuSelectAll, Title: labels.SelectAll, Disabled: input.State.Value == "" || composing}, + } +} + +// performTextMenu runs a command chosen from the menu as the keyboard's chord of +// the same name would, and returns the frame it caused. +func (painter *painter) performTextMenu(command platform.TextMenuCommand) (platform.Frame, error) { + var err error + switch command { + case platform.TextMenuCut: + err = painter.clipboardEdit('x', painter.readClipboardText, painter.writeClipboardText) + case platform.TextMenuCopy: + err = painter.clipboardEdit('c', painter.readClipboardText, painter.writeClipboardText) + case platform.TextMenuPaste: + err = painter.clipboardEdit('v', painter.readClipboardText, painter.writeClipboardText) + case platform.TextMenuSelectAll: + _, err = painter.applyTextEvent(platform.TextEvent{Kind: platform.TextCommandEvent, Command: platform.TextSelectAll}) + default: + return platform.Frame{}, nil + } + if err != nil { + return platform.Frame{}, err + } + return painter.repaint() +} + +func (painter *painter) readClipboardText() (string, error) { + if painter.clipboardReader == nil { + return "", ErrUnsupported + } + return painter.clipboardReader() +} + +func (painter *painter) writeClipboardText(value string) error { + if painter.setClipboardText == nil { + return ErrUnsupported + } + painter.setClipboardText(value) + return nil +} + +// clipboardEdit is a clipboard chord of the focused text field ('c', 'x' or 'v') +// against the clipboard read and write give. +func (painter *painter) clipboardEdit(action byte, read func() (string, error), write func(string) error) error { + input := painter.nativeText + event, changed, err := platform.TextClipboardEvent(input.ClipboardState(action), input.Secure, action, read, write) + if err != nil || !changed { + return err + } + _, err = painter.applyTextEvent(event) + return err +} + +// enableTextMenu says whether the window can show the system's text menu. The +// canvas hears it too, so the page leaves its own menu undrawn when the system's +// is shown. +func (painter *painter) enableTextMenu(native bool) { + painter.textMenuNative = native && painter.textMenu != nil + painter.canvas.SetNativeTextMenu(painter.textMenuNative) +} + +// textMenuTaker is what the adapter asks for the menu after a press: nil when the +// window shows none, so an adapter without one is never asked. +func (painter *painter) textMenuTaker() func() (platform.TextMenuRequest, bool) { + if !painter.textMenuNative { + return nil + } + return painter.takeTextMenu +} + +// TextMenu is the rows of the system's text menu a secondary press on a text field +// opened (see Config.TextMenu), nil when none is open. The driver shows no window: +// a test reads the rows here and chooses one with ChooseTextMenu. +func (driver *Driver) TextMenu() []TextMenuItem { + if driver.textMenu == nil { + return nil + } + return slices.Clone(driver.textMenu.Items) +} + +// ChooseTextMenu chooses a command of the open text menu, as the user would, and +// closes it. It is an error when no menu is open or the command is not a row of +// it or is off. +func (driver *Driver) ChooseTextMenu(command TextMenuCommand) error { + if err := driver.Pump(); err != nil { + return err + } + request := driver.textMenu + if request == nil { + return errors.New("app: no text menu is open") + } + for _, item := range request.Items { + if item.Command != command || command == TextMenuNone { + continue + } + if item.Disabled { + return fmt.Errorf("app: the text menu's %q is off", item.Title) + } + driver.textMenu = nil + _, err := request.Perform(command) + return err + } + return fmt.Errorf("app: the text menu has no command %d", command) +} + +// DismissTextMenu closes the open text menu without choosing from it. +func (driver *Driver) DismissTextMenu() { driver.textMenu = nil } diff --git a/app/text_menu_native.go b/app/text_menu_native.go new file mode 100644 index 000000000..d174032ea --- /dev/null +++ b/app/text_menu_native.go @@ -0,0 +1,7 @@ +//go:build (darwin && !ios) || windows + +package app + +// nativeTextMenus reports that this platform shows the system's own menu for a +// text field. +func nativeTextMenus() bool { return true } diff --git a/app/text_menu_other.go b/app/text_menu_other.go new file mode 100644 index 000000000..34623b8c2 --- /dev/null +++ b/app/text_menu_other.go @@ -0,0 +1,7 @@ +//go:build !((darwin && !ios) || windows) + +package app + +// nativeTextMenus reports that this platform has no menu of its own to show for +// a text field outside a toolkit, so the page draws one. +func nativeTextMenus() bool { return false } diff --git a/app/text_menu_test.go b/app/text_menu_test.go new file mode 100644 index 000000000..ccafb9376 --- /dev/null +++ b/app/text_menu_test.go @@ -0,0 +1,145 @@ +package app + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" +) + +// textMenuDriver is a window with one text field (and a button apart from it) +// that asks for the system's text menu. +func textMenuDriver(t *testing.T, editor *text.Editor, secure, handled bool, labels *TextMenuLabels) *Driver { + t.Helper() + config := Config{Title: "text menu", Width: 300, Height: 120, TextMenu: labels} + config.Paint = func(canvas *gfx.Canvas, _ gfx.Size) { + canvas.HitWithOptions(gfx.Item(1), gfx.Rect{X: 10, Y: 10, Width: 220, Height: 30}, "field", gfx.HitOptions{ + Role: gfx.RoleTextField, Secure: secure, + }) + canvas.Hit(gfx.Item(2), gfx.Rect{X: 10, Y: 60, Width: 80, Height: 30}) + } + config.TextInput = func(TextInputContext) *TextInput { return &TextInput{Editor: editor} } + if handled { + config.OnPointer = func(event gfx.PointerEvent) gfx.EventResult { + return gfx.EventResult{Handled: event.Button == gfx.PointerButtonSecondary} + } + } + driver, err := NewDriver(config, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(driver.Close) + return driver +} + +func textMenuItem(items []TextMenuItem, command TextMenuCommand) (TextMenuItem, bool) { + for _, item := range items { + if item.Command == command { + return item, true + } + } + return TextMenuItem{}, false +} + +// A secondary press on a text field opens the system's menu for it, and the field +// takes the keyboard as it does under a primary press. Each command does what the +// chord of the same name does. +func TestTextMenuCommandsActOnTheField(t *testing.T) { + editor := text.NewEditor("hello world") + driver := textMenuDriver(t, editor, false, false, &TextMenuLabels{Paste: "粘贴"}) + if err := driver.Press(20, 20, gfx.PointerButtonSecondary); err != nil { + t.Fatal(err) + } + items := driver.TextMenu() + if len(items) == 0 { + t.Fatal("a secondary press on a text field opened no menu") + } + if paste, _ := textMenuItem(items, TextMenuPaste); paste.Title != "粘贴" { + t.Fatalf("Paste is %q, want the words the window gave", paste.Title) + } + if cut, _ := textMenuItem(items, TextMenuCut); cut.Title != "Cut" || !cut.Disabled { + t.Fatalf("Cut = %+v, want English and off with nothing selected", cut) + } + if err := driver.ChooseTextMenu(TextMenuCut); err == nil { + t.Fatal("Cut was chosen while it is off") + } + if err := driver.ChooseTextMenu(TextMenuSelectAll); err != nil { + t.Fatal(err) + } + if driver.TextMenu() != nil { + t.Fatal("the menu stayed open after a choice") + } + if selection := editor.Selection(); selection != (text.Range{Start: 0, End: 11}) { + t.Fatalf("selection after Select All = %v", selection) + } + if err := driver.Press(20, 20, gfx.PointerButtonSecondary); err != nil { + t.Fatal(err) + } + if err := driver.ChooseTextMenu(TextMenuCut); err != nil { + t.Fatal(err) + } + if editor.String() != "" || driver.Clipboard() != "hello world" { + t.Fatalf("after Cut: %q, clipboard %q", editor.String(), driver.Clipboard()) + } + driver.SetClipboard("a\r\nb") + if err := driver.Press(20, 20, gfx.PointerButtonSecondary); err != nil { + t.Fatal(err) + } + if err := driver.ChooseTextMenu(TextMenuPaste); err != nil { + t.Fatal(err) + } + if editor.String() != "a b" { + t.Fatalf("Paste into a single line = %q", editor.String()) + } + if driver.painter.focus.Focused() != gfx.Item(1) { + t.Fatal("the field does not have the keyboard after its menu") + } +} + +// A secret never leaves through the menu, as it does not through the keyboard. +func TestTextMenuOfASecretOffersNoWayOut(t *testing.T) { + editor := text.NewEditor("hunter2") + driver := textMenuDriver(t, editor, true, false, &TextMenuLabels{}) + if err := driver.Press(20, 20, gfx.PointerButtonSecondary); err != nil { + t.Fatal(err) + } + if handled, err := driver.Shortcut('a'); !handled || err != nil { + t.Fatalf("select all: handled=%v err=%v", handled, err) + } + if err := driver.Press(20, 20, gfx.PointerButtonSecondary); err != nil { + t.Fatal(err) + } + for _, command := range []TextMenuCommand{TextMenuCut, TextMenuCopy} { + if item, _ := textMenuItem(driver.TextMenu(), command); !item.Disabled { + t.Fatalf("command %d of a secret is on: %+v", command, item) + } + } + if item, _ := textMenuItem(driver.TextMenu(), TextMenuPaste); item.Disabled { + t.Fatal("Paste of a secret is off") + } +} + +// No menu opens off a text field, when the application took the press (its own +// menu), or when the window asked for none. +func TestTextMenuOpensOnlyWhereNobodyElseTookThePress(t *testing.T) { + for _, test := range []struct { + name string + x, y float32 + handled bool + labels *TextMenuLabels + }{ + {"away from the field", 20, 70, false, &TextMenuLabels{}}, + {"the application took the press", 20, 20, true, &TextMenuLabels{}}, + {"the window asked for none", 20, 20, false, nil}, + } { + t.Run(test.name, func(t *testing.T) { + driver := textMenuDriver(t, text.NewEditor("x"), false, test.handled, test.labels) + if err := driver.Press(test.x, test.y, gfx.PointerButtonSecondary); err != nil { + t.Fatal(err) + } + if driver.TextMenu() != nil { + t.Fatal("a text menu opened") + } + }) + } +} diff --git a/app/web.go b/app/web.go index eb02c2f5c..0d443f710 100644 --- a/app/web.go +++ b/app/web.go @@ -85,6 +85,10 @@ const WebProxyDirect = platform.WebProxyDirect // WebViewConfig describes a page to open. type WebViewConfig struct { + // UserAgentSuffix identifies this application after the system engine's default user agent. + // It is set before the first navigation, applies to child frames, and is private to this page. + // Empty preserves the engine default. Only printable ASCII is accepted. + UserAgentSuffix string // URL is loaded when the page opens, unless HTML is set. URL string // HTML is loaded instead of a URL, with BaseURL as its address. @@ -345,6 +349,9 @@ func partitionName(name string) (string, error) { // Open opens a page. It fails with ErrUnsupported when the platform cannot host pages or the system // has no web engine installed. func (host *WebHost) Open(config WebViewConfig) (*WebView, error) { + if strings.IndexFunc(config.UserAgentSuffix, func(r rune) bool { return r < 0x20 || r > 0x7e }) >= 0 { + return nil, fmt.Errorf("app: web view user agent suffix must be printable ASCII") + } if config.TopCornerRadius < 0 || math.IsNaN(float64(config.TopCornerRadius)) || math.IsInf(float64(config.TopCornerRadius), 0) { return nil, fmt.Errorf("app: invalid web view top corner radius") } @@ -363,6 +370,7 @@ func (host *WebHost) Open(config WebViewConfig) (*WebView, error) { platformConfig := platform.WebViewConfig{ ID: uint32(id), URL: config.URL, HTML: config.HTML, BaseURL: config.BaseURL, Proxy: config.Proxy, TopCornerRadius: config.TopCornerRadius, + UserAgentSuffix: config.UserAgentSuffix, Ephemeral: config.Ephemeral, Partition: partition, } diff --git a/app/web_dev_tools.go b/app/web_dev_tools.go new file mode 100644 index 000000000..36e893375 --- /dev/null +++ b/app/web_dev_tools.go @@ -0,0 +1,27 @@ +package app + +import ( + "errors" + "fmt" + + "github.com/vivaui/viva/internal/platform" +) + +// ShowDevTools opens the system engine's developer tools for this page: Web Inspector on macOS and +// Linux, the DevTools window on Windows. Developer tools are off until a page asks: nothing changes +// for a page that never calls it. It returns an error wrapping ErrUnsupported where the platform +// cannot open them. On macOS the page is still made inspectable then, so the user can reach it from +// the page's context menu or Safari's Develop menu. Call it on the event-loop thread. +func (view *WebView) ShowDevTools() error { + tools, ok := view.native.(platform.WebDevTools) + if !ok { + return fmt.Errorf("%w: web developer tools", ErrUnsupported) + } + if err := tools.ShowDevTools(); err != nil { + if errors.Is(err, platform.ErrWebViewUnsupported) { + return fmt.Errorf("%w: %w", ErrUnsupported, err) + } + return err + } + return nil +} diff --git a/app/web_dev_tools_test.go b/app/web_dev_tools_test.go new file mode 100644 index 000000000..5de7022a4 --- /dev/null +++ b/app/web_dev_tools_test.go @@ -0,0 +1,47 @@ +package app + +import ( + "errors" + "fmt" + "testing" + + "github.com/vivaui/viva/internal/platform" +) + +// devToolsWebView is a page whose platform can open developer tools, answering with err. +type devToolsWebView struct { + testWebView + shown int + err error +} + +func (view *devToolsWebView) ShowDevTools() error { + view.shown++ + return view.err +} + +func TestShowDevToolsReachesAPlatformThatHasThem(t *testing.T) { + native := &devToolsWebView{} + view := &WebView{native: native} + if err := view.ShowDevTools(); err != nil || native.shown != 1 { + t.Fatalf("ShowDevTools = %v after %d calls", err, native.shown) + } +} + +func TestShowDevToolsIsUnsupportedWithoutThem(t *testing.T) { + view := &WebView{native: &testWebView{}} + if err := view.ShowDevTools(); !errors.Is(err, ErrUnsupported) { + t.Fatalf("a platform without developer tools gave %v", err) + } + native := &devToolsWebView{err: fmt.Errorf("%w: no inspector", platform.ErrWebViewUnsupported)} + view = &WebView{native: native} + if err := view.ShowDevTools(); !errors.Is(err, ErrUnsupported) { + t.Fatalf("an engine that cannot open them gave %v", err) + } + failure := errors.New("closed") + native = &devToolsWebView{err: failure} + view = &WebView{native: native} + if err := view.ShowDevTools(); !errors.Is(err, failure) || errors.Is(err, ErrUnsupported) { + t.Fatalf("a platform failure became %v", err) + } +} diff --git a/app/web_test.go b/app/web_test.go index 6eb57bed4..0f9b17c2e 100644 --- a/app/web_test.go +++ b/app/web_test.go @@ -462,3 +462,27 @@ func TestAPageNobodyWatchesForFailureGivesThePlatformNone(t *testing.T) { t.Fatal("an application that set no OnProcessFailed got one") } } + +func TestWebViewUserAgentSuffixIsPerPageAndValidated(t *testing.T) { + var opened []platform.WebViewConfig + host := &WebHost{native: &platform.WebHost{Open: func(config platform.WebViewConfig) (platform.WebView, error) { + opened = append(opened, config) + return nil, platform.ErrWebViewUnsupported + }}} + for _, suffix := range []string{"ExampleDesktop/1.0", ""} { + if _, err := host.Open(WebViewConfig{URL: "https://example.com/", UserAgentSuffix: suffix}); !errors.Is(err, ErrUnsupported) { + t.Fatal(err) + } + } + if len(opened) != 2 || opened[0].UserAgentSuffix != "ExampleDesktop/1.0" || opened[1].UserAgentSuffix != "" { + t.Fatal("user agent suffix leaked between pages") + } + for _, suffix := range []string{"app\r\nInjected: yes", "app\x00", "app\x7f", "\u4e2d"} { + if _, err := host.Open(WebViewConfig{UserAgentSuffix: suffix}); err == nil || errors.Is(err, ErrUnsupported) { + t.Fatal("invalid user agent suffix reached the platform") + } + } + if len(opened) != 2 { + t.Fatal("invalid suffix opened a native page") + } +} diff --git a/base/accessors.go b/base/accessors.go index 93438a831..2819da67b 100644 --- a/base/accessors.go +++ b/base/accessors.go @@ -1187,6 +1187,7 @@ func (x *TableDecl) GetSpec() TableSpec { return x.spec } // GetFontSize reads the element's font size for the table being painted: the // explicit size when it has one, else the spec's. func (x *TableDecl) GetFontSize() float32 { return x.fontSize } +func (x *TableDecl) GetTitles() []string { return x.titles } // GetForeground reads the element's text color for the table being painted. func (x *TableDecl) GetForeground() gfx.Color { return x.foreground } @@ -1940,12 +1941,18 @@ func (x *toast) GetAction() string { return x.action } // GetDescription reads the description of toast for the styled painting layer. func (x *toast) GetDescription() string { return x.description } +// GetHideClose reads the hideClose of toast for the styled painting layer. +func (x *toast) GetHideClose() bool { return x.hideClose } + // GetN reads the n of toast for the styled painting layer. func (x *toast) GetN() uint32 { return x.n } // GetShown reads the shown of toast for the styled painting layer. func (x *toast) GetShown() bool { return x.shown } +// GetTimeout reads the timeout of toast for the styled painting layer. +func (x *toast) GetTimeout() time.Duration { return x.timeout } + // GetTitle reads the title of toast for the styled painting layer. func (x *toast) GetTitle() string { return x.title } @@ -2167,3 +2174,6 @@ func (x *Widgets) SetRectsCells(v []Rect) { x.rects = v } // GetButtonLook reads the look the recipe gave the themed button being painted, for the // styled painting layer that paints its content. func (x *Frame) GetButtonLook() style.ButtonLook { return x.buttonPainted } + +// GetMarks reads the marks of SliderDecl for the styled painting layer. +func (d *SliderDecl) GetMarks() []SliderMark { return d.marks } diff --git a/base/attrcheck_dev.go b/base/attrcheck_dev.go index f7bee8810..f80b00aa4 100644 --- a/base/attrcheck_dev.go +++ b/base/attrcheck_dev.go @@ -33,8 +33,8 @@ func (n *Node) markAttr(a uint8) { n.attrs |= a } func (f *Frame) checkAttributesOf(n *Node) { name := kindAttributeName(n) if n.Kind == kindTable && int(n.Aux) < len(WidgetsOf(f).tables) { - if spec := &WidgetsOf(f).tables[n.Aux].spec; len(spec.Columns) == 0 && len(spec.Headers) == 0 { - f.badAttribute(n, name, "rows without Columns or Headers", "a Table lays its cells out in its columns; give it Headers (the columns share its width) or Columns") + if spec := &WidgetsOf(f).tables[n.Aux].spec; len(spec.Columns) == 0 { + f.badAttribute(n, name, "rows without Columns", "a Table lays its cells out in its columns; give it Columns") } } if n.Flags&FlagChildren != 0 && !f.attributeChildContainer(n) { diff --git a/base/attrcheck_dev_test.go b/base/attrcheck_dev_test.go index ff575f4b8..c8a48382d 100644 --- a/base/attrcheck_dev_test.go +++ b/base/attrcheck_dev_test.go @@ -21,8 +21,7 @@ func (r *devTableRows) Len() int { return r.n } func (r *devTableRows) Cell(row, column int) string { return "r" } var devTableSpec = TableSpec{ - Columns: []style.TableColumn{{Width: 80}}, - Headers: []string{"Name"}, + Columns: titledColumns([]style.TableColumn{{Width: 80}}, []string{"Name"}, nil), Source: &devTableRows{n: 1}, } @@ -201,5 +200,5 @@ func TestAttributesThatDoNothingReport(t *testing.T) { func TestATableWithoutColumnsIsReported(t *testing.T) { expectAttributePanic(t, func(f *Frame) { f.Table(&TableState{}, TableSpec{Rows: tree.Sub(page, tree.Name("attr-table")), Source: &devTableRows{n: 1}}) - }, "Table", "rows without Columns or Headers") + }, "Table", "rows without Columns") } diff --git a/base/box.go b/base/box.go index 01df5effe..7d67fd7cb 100644 --- a/base/box.go +++ b/base/box.go @@ -81,7 +81,7 @@ func (b Box) Clicked() bool { if n.Ext != 0 && b.f.Exts[n.Ext].bind != 0 { b.f.settleFn(b.f, b.i) // a bound value is written before the caller reads it } - return b.f.Surface != nil && n.Flags&flagVeto == 0 && b.f.Surface.Clicked(n.ID) && !b.f.Disabled(n) + return b.f.Surface != nil && n.Flags&flagVeto == 0 && !n.Loading && b.f.Surface.Clicked(n.ID) && !b.f.Disabled(n) } // Hit makes the element's whole rectangle a pointer target named id, with the @@ -482,6 +482,23 @@ func (b Box) Small() Box { func (b Box) Large() Box { b.N().ButtonSize = style.SizeLarge; return b } func (b Box) IconOnly() Box { b.N().ButtonSize = style.SizeIcon; return b } +// Loading marks a Button or a Switch as busy with what pressing it started: on a button +// a spinner takes the place of its icon, or stands before its label when it has none; on +// a switch it turns on the thumb. Presses are not delivered, and a bound value is not +// flipped, while it is on, so a second press cannot start the work twice. The control +// keeps its look, unlike Disabled, which dims it. Loading(false) is the ordinary control. +// +// ui.Button(c, "Connect").Loading(m.connecting).Clicked() +// ui.Switch(c, &m.forwarding, "Forwarding").Loading(m.applying) +func (b Box) Loading(loading bool) Box { + n := b.N() + if n.Kind != KindButton && n.Kind != kindSwitch { + panic("ui: Loading is for a Button or a Switch") + } + n.Loading = loading + return b +} + // SwitchRecipe gives one Switch its own look, as ButtonRecipe does a Button, // winning over the page's Styles.Switch. Start from components.SwitchRecipe. // Other elements ignore it. diff --git a/base/color.go b/base/color.go index ab19c51e9..7a2eb5146 100644 --- a/base/color.go +++ b/base/color.go @@ -115,20 +115,17 @@ type ColorPickerLook struct { // hex field); Cancel, Escape and a press outside leave it as it was. A transparent // *color is no color, which Clear sets. The box is the 32 pixel trigger; Applied // reports a change. RoundTrigger, TriggerIcon, NoColor and PanelLabels change how it -// looks, and ShowAlpha adds an opacity bar and #RRGGBBAA input. +// looks, and ShowAlpha adds an opacity bar and #RRGGBBAA input. WithID names a +// trigger the application already names: the picker keeps its state by identity, so +// it takes the id when it is made, and a row's words can then be its LabelFor, as for +// any control the application names. A ColorSwatch, which keeps none, is named with +// Hit instead. // // ui.ColorPicker(c, &m.picker, &m.accent, "Accent") +// ui.ColorPicker(c, &m.picker, &m.accent, "Accent", ui.WithID(m.accentID)) // if m.picker.Applied() { m.save() } -func ColorPicker(c C, state *ColorPickerState, Color *Color, Label string) Box { - return colorPicker(c, gfx.ID{}, state, Color, Label) -} - -// ColorPickerID is ColorPicker for a trigger the application already names: the picker -// keeps its state by identity, so it takes the id when it is made. A row's words can then -// be its LabelFor, as for any control the application names. A ColorSwatch, which keeps -// none, is named with Hit instead. -func ColorPickerID(c C, ID gfx.ID, state *ColorPickerState, Color *Color, Label string) Box { - return colorPicker(c, ID, state, Color, Label) +func ColorPicker(c C, state *ColorPickerState, Color *Color, Label string, opts ...Option) Box { + return colorPicker(c, namedBy("ColorPicker", opts), state, Color, Label) } func colorPicker(c C, ID gfx.ID, s *ColorPickerState, Color *Color, Label string) Box { diff --git a/base/dialog.go b/base/dialog.go index f7182e52f..b7e7604b7 100644 --- a/base/dialog.go +++ b/base/dialog.go @@ -54,7 +54,7 @@ func (f *Frame) resolveDialogFocus() { // Dialog declares a dialog on a page whose targets and layer the application // names itself: DialogSpec.Scope, DismissID, CloseID and Layer keep the // identities the application dispatches, as they do for frame.Dialog. Most -// dialogs use Modal or ModalWith; use Dialog when the application owns those +// dialogs use Modal; use Dialog when the application owns those // targets and the dialog's layer. Header declares controls in the title row, // Body the content and Footer the buttons. func Dialog(c C, spec DialogSpec) Box { diff --git a/base/drag.go b/base/drag.go index b5dbe59ff..7232ebadb 100644 --- a/base/drag.go +++ b/base/drag.go @@ -37,8 +37,15 @@ import "github.com/vivaui/viva/gfx" // another, and is internal to the engine. type DragState struct { Frame *Frame - gen uint32 - epoch uint32 // the page paint this state was registered for + // OnMove receives every pointer move the state consumes once the press has + // become a drag, after the state's own position and target change. It is how + // a gesture continues past the page: a drag of files out of a window starts + // the operating system's drag when the pointer leaves the window. Keep it in + // the model and leave it nil when nothing needs it; it runs on the + // event-loop thread. + OnMove func(event gfx.PointerEvent) + gen uint32 + epoch uint32 // the page paint this state was registered for sources []dragSource targets []dragTarget @@ -339,6 +346,9 @@ func (s *DragState) pointer(event gfx.PointerEvent) (result gfx.EventResult, don } s.at = point s.target = s.targetAt(point, s.source) + if s.OnMove != nil { + s.OnMove(event) + } return gfx.EventResult{Handled: true, Repaint: true}, false case gfx.PointerUp: if !s.active { diff --git a/base/edit_menu.go b/base/edit_menu.go new file mode 100644 index 000000000..d4e724aa1 --- /dev/null +++ b/base/edit_menu.go @@ -0,0 +1,143 @@ +package base + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" +) + +// EditMenuLabels are the words of the menu a TextField or TextArea opens on a +// secondary press. A label left empty is English. +type EditMenuLabels = gfx.TextMenuLabels + +// The system text clipboard, which the styled layer installs for the page's edit +// menus. A page drawn by a host that installs neither has no Cut, Copy or Paste. +var ( + ClipboardText func() (string, error) + SetClipboardText func(string) error +) + +// editMenuEntry is a TextField or TextArea declared in the paint that has the +// standard edit menu: the menu is declared once the whole page is, when a +// ReadOnly or Disabled chained on the box is known. +type editMenuEntry struct { + box Box + field *Field + area bool + layer uint16 // the widget layer the field was declared on, so a dialog's field has its menu over the dialog +} + +// WithoutEditMenu keeps a TextField or TextArea from the standard edit menu, for +// a field whose application declares a ContextMenu of its own on it. +func WithoutEditMenu() Option { return Option{plain: true} } + +func hasEditMenu(opts []Option) bool { + for _, option := range opts { + if option.plain { + return false + } + } + return true +} + +// addEditMenu records a field declared in this paint for its edit menu. A field +// in a Memo is left out: the menu keeps its state by being declared, as any +// ContextMenu does, and a copied part would lose it. +func (p *Page) addEditMenu(c C, b Box, field *Field, area bool) { + if len(p.recording) > 0 || ClipboardText == nil || PaintMenu == nil { + return + } + p.editMenus = append(p.editMenus, editMenuEntry{box: b, field: field, area: area, layer: WidgetsOf(c.f).layer}) +} + +// declareEditMenus declares the edit menus of the fields of the paint. +func (p *Page) declareEditMenus(c C) { + if !p.editFocus.IsZero() { + if canvas := c.f.Surface; canvas != nil { + canvas.RequestFocusOnce(p.editFocus) + } + p.editFocus = gfx.ID{} + } + var labels EditMenuLabels + if p.config.EditMenu != nil { + labels = *p.config.EditMenu + } + labels = labels.WithDefaults() + for _, entry := range p.editMenus { + p.declareEditMenu(c, entry, labels) + } +} + +func (p *Page) declareEditMenu(c C, entry editMenuEntry, labels EditMenuLabels) { + if !entry.box.Valid() { + return + } + n := entry.box.N() + var readOnly, disabled bool + switch n.Kind { + case kindInput: + snapshot := &WidgetsOf(entry.box.f).inputs[n.Aux] + readOnly, disabled = snapshot.ReadOnly, snapshot.Disabled + case kindTextarea: + snapshot := &WidgetsOf(entry.box.f).textareas[n.Aux] + readOnly, disabled = snapshot.ReadOnly, snapshot.Disabled + default: + return + } + if disabled || n.Flags&flagDisabled != 0 { + return + } + if canvas := c.f.Surface; canvas != nil && canvas.NativeTextMenu() && !readOnly { + // The window shows the system's menu for a secondary press on a text field + // it has an editor for; a read-only field has none, and keeps this one. + return + } + widgets := WidgetsOf(c.f) + layer := widgets.layer + widgets.layer = entry.layer + defer func() { widgets.layer = layer }() + + field, id := entry.field, n.ID + contextMenu(c, entry.box, 0, nil, func(menu *MenuItems) { + editor := field.ensure() + // The item chosen acts on this field and leaves the keyboard on it, in the + // paint after the menu has closed: a menu in a Dialog gives the keyboard back + // to where it was only while the menu's own scope still traps it. + chosen := func() bool { + p.editFocus = id + return true + } + selection := editor.Selection() + _, composing := editor.Composition() + selected := selection.Start != selection.End && editor.SelectionCount() == 1 && !composing + editable := !readOnly && !composing + if !field.Secure { + if menu.Item(labels.Cut).Keys(Primary, "x").Disabled(!selected || !editable).Clicked() && chosen() { + if SetClipboardText != nil && SetClipboardText(selectedText(editor, selection)) == nil { + editor.Paste("") + } + } + if menu.Item(labels.Copy).Keys(Primary, "c").Disabled(!selected).Clicked() && chosen() && SetClipboardText != nil { + _ = SetClipboardText(selectedText(editor, selection)) + } + } + if menu.Item(labels.Paste).Keys(Primary, "v").Disabled(!editable).Clicked() && chosen() { + if value, err := ClipboardText(); err == nil { + if !entry.area { + value = text.SingleLine(value) + } + if value != "" { + editor.Paste(value) + } + } + } + menu.Separator() + if menu.Item(labels.SelectAll).Keys(Primary, "a").Disabled(editor.RuneCount() == 0 || composing).Clicked() && chosen() { + editor.SetSelection(text.Range{Start: 0, End: editor.RuneCount()}) + } + }) +} + +// selectedText is the text of selection, a range of runes of editor. +func selectedText(editor *text.Editor, selection text.Range) string { + return editor.String()[editor.ByteOffset(selection.Start):editor.ByteOffset(selection.End)] +} diff --git a/base/elements.go b/base/elements.go index 12e335f63..964f6a37d 100644 --- a/base/elements.go +++ b/base/elements.go @@ -46,7 +46,9 @@ func Text(c C, Value string) Box { return c.f.Text(Value) } // Textf allocates its string in every paint. func Textf(c C, format string, args ...any) Box { return c.f.Text(fmt.Sprintf(format, args...)) } func Spacer(c C) Box { return c.f.Spacer() } -func Divider(c C) Box { return c.f.Divider() } + +// Divider draws a one-pixel separator line. +func Divider(c C) Box { return c.f.Divider() } func Progress(c C, fraction float32) Box { return c.f.Progress(c.page.ControlID(pkProgress), fraction) } @@ -200,22 +202,18 @@ func Tabs[T comparable](c C, Value *T, tabs []T, Label func(T) string) Box { // Select is a drop-down over choices, *value the chosen one (Placeholder shows while // it is none of them); picking an option sets it. Whether its list is open is the // Select's own state. Invalid(true) marks the value as failing validation and -// DisabledOptions marks options unavailable. -func Select[T comparable](c C, Value *T, choices []T, Label func(T) string) Box { - return selectOf(c, Value, choices, Label, nil, false, gfx.ID{}) -} - -// SelectID is Select for a control the application already names: the trigger's -// hit is id, so a row's words can be its LabelFor and the application's key and -// focus routing can target it. The list's options keep the page's own identities. -func SelectID[T comparable](c C, ID gfx.ID, Value *T, choices []T, Label func(T) string) Box { - return selectOf(c, Value, choices, Label, nil, false, ID) +// DisabledOptions marks options unavailable. WithID names a control the application +// already names: the trigger's hit is id, so a row's words can be its LabelFor and the +// application's key and focus routing can target it. The list's options keep the +// page's own identities. +func Select[T comparable](c C, Value *T, choices []T, Label func(T) string, opts ...Option) Box { + return selectOf(c, Value, choices, Label, nil, false, namedBy("Select", opts), groupsOf(opts)) } // selectOf is Select, or SelectBase when base is set: the same control without // the theme's look. icons are indexed by option like the labels; nil is the // select without icons. -func selectOf[T comparable](c C, Value *T, choices []T, Label func(T) string, icons []gfx.Icon, Base bool, ID gfx.ID) Box { +func selectOf[T comparable](c C, Value *T, choices []T, Label func(T) string, icons []gfx.Icon, Base bool, ID gfx.ID, groups []SelectGroup) Box { p := c.page scope := p.BoundScope(pkSelect, unsafe.Pointer(Value)) state := stateIn[SelectState](p, scope, "select") // its open list follows its value @@ -227,6 +225,9 @@ func selectOf[T comparable](c C, Value *T, choices []T, Label func(T) string, ic b = c.f.Select(scope, state, labels, selected) } b.Icons(icons) + if len(groups) > 0 { + b.optionGroups(groups) + } state.trigger = ID p.selects = append(p.selects, state) if p.keyRoute == nil { @@ -258,7 +259,7 @@ func Splitter(c C, state *SplitterState) Box { // them zero. It is a whole control as declared: the page gives it the keys that // move its selection (TableState.Key), a click on a row selects that row as a // List's does, TableState.Changed reports either in the paint that delivers it, -// and a table given Headers and no Columns shares its width between them. +// and a table none of whose columns has a width shares its width between them. func Table(c C, state *TableState, spec TableSpec) Box { p := c.page if spec.Rows == 0 || spec.Header == 0 { @@ -285,17 +286,26 @@ func Table(c C, state *TableState, spec TableSpec) Box { // TextField adds a text field editing value, a string of the model or a Field; the // page gives the platform its editor. Changed is true in the paint that finds it -// edited, and the string already holds the edit then. +// edited, and the string already holds the edit then. WithID names the field, for a +// window's own input routing, an initial focus or a test; Field.Bind gives it an +// editor the application keeps and reads itself. // // ui.TextField(c, &m.name, "Name", "Your name") -func TextField[T TextValue](c C, Value T, Label, placeholder string) Box { - return textFieldOf(c, Value, Label, placeholder, false) +// ui.TextField(c, &m.query, "Search", "", ui.WithID(m.searchID)) +func TextField[T TextValue](c C, Value T, Label, placeholder string, opts ...Option) Box { + b, field := textFieldOf(c, Value, Label, placeholder, false, namedBy("TextField", opts), opts) + if hasEditMenu(opts) { + c.page.addEditMenu(c, b, field, false) + } + return b } // textFieldOf is TextField, or TextFieldBase when base is set. -func textFieldOf[T TextValue](c C, Value T, Label, placeholder string, Base bool) Box { +func textFieldOf[T TextValue](c C, Value T, Label, placeholder string, Base bool, named gfx.ID, opts []Option) (Box, *Field) { p := c.page - field, id := fieldOf(p, pkField, Value) + field, id := namedFieldOf(p, pkField, Value, named) + maxRunes, count := limitsOf(opts) + field.limit(maxRunes) var b Box if Base { b = c.f.FieldBase(field, id, Label, placeholder) @@ -303,71 +313,33 @@ func textFieldOf[T TextValue](c C, Value T, Label, placeholder string, Base bool b = c.f.Field(field, id, Label, placeholder) } c.f.bindField(b, field) + if count { + b.Addons().SetEnd(InputGroupSlot{Kind: InputGroupSlotText, Text: field.countText()}) + } p.fields = append(p.fields, fieldEntry{ID: id, field: field, box: b.i}) - return b -} - -// TextFieldID is TextField for a field the application already names: id is the -// field's identity in the page's Tree, so a window's own input routing, an -// initial focus or a test can address it. It edits value, a string of the model -// or a Field, as TextField does, and the page still gives the platform its -// editor. Field.Bind gives it an editor the application keeps and reads itself. -// -// ui.TextFieldID(c, m.searchID, &m.query, "Search", "") -func TextFieldID[T TextValue](c C, ID gfx.ID, Value T, Label, placeholder string) Box { - p := c.page - var field *Field - switch v := any(Value).(type) { - case *Field: - field = v - case *string: - // The string's editor is kept under the name its pointer is given, as - // TextField keeps it; only the element takes the application's identity. - field, _ = fieldOf(p, pkField, v) - } - if field == nil { - panic("ui: TextFieldID needs a string or a Field to edit") - } - b := c.f.Field(field, ID, Label, placeholder) - c.f.bindField(b, field) - p.fields = append(p.fields, fieldEntry{ID: ID, field: field, box: b.i}) - return b + return b, field } // TextArea adds a text field of several rows editing field: Enter starts a new // line, long lines wrap and the rows scroll to follow the caret. Give it a Height. -// The page gives the platform its editor, as for a TextField; it has no Submitted. +// The page gives the platform its editor, as for a TextField, and WithID names it +// the same way; it has no Submitted. // // ui.TextArea(c, &m.notes, "Notes", "Anything to add").Height(120) -func TextArea[T TextValue](c C, Value T, Label, placeholder string) Box { +func TextArea[T TextValue](c C, Value T, Label, placeholder string, opts ...Option) Box { p := c.page - field, id := fieldOf(p, pkArea, Value) + field, id := namedFieldOf(p, pkArea, Value, namedBy("TextArea", opts)) + maxRunes, _ := limitsOf(opts) + field.limit(maxRunes) b := c.f.FieldArea(field, id, Label, placeholder) c.f.bindField(b, field) if p.areaKey == nil { p.keyRoute, p.areaKey = (*Page).RouteKey, (*Field).Key // Up and Down by row } p.fields = append(p.fields, fieldEntry{ID: id, field: field, box: b.i}) - return b -} - -// TextAreaID is TextArea for a field the application already names, as TextFieldID is -// for TextField: id is the field's identity in the page's Tree, so an initial focus, -// a window's own routing or a test can address it. Field.Bind gives it an editor the -// application keeps and reads itself. -// -// ui.TextAreaID(c, m.commandID, &m.commandField, "Command", "").Height(120) -func TextAreaID(c C, ID gfx.ID, field *Field, Label, placeholder string) Box { - if field == nil { - panic("ui: TextAreaID needs a Field") - } - p := c.page - b := c.f.FieldArea(field, ID, Label, placeholder) - c.f.bindField(b, field) - if p.areaKey == nil { - p.keyRoute, p.areaKey = (*Page).RouteKey, (*Field).Key // Up and Down by row + if hasEditMenu(opts) { + p.addEditMenu(c, b, field, true) } - p.fields = append(p.fields, fieldEntry{ID: ID, field: field, box: b.i}) return b } @@ -377,16 +349,14 @@ func TextAreaID(c C, ID gfx.ID, field *Field, Label, placeholder string) Box { // it does not open it again. The focus goes back to where it was as it closes. It // reports the paint that closed it, so a panel that must stay open sets *open back. // +// spec gives the side, alignment, width and the rest of PopoverSpec; the Scope and +// DismissID it leaves zero are made from open. Its zero Align centers the panel on the +// anchor, and Start lines it up with the anchor's start. +// // more := ui.Button(c, "More") // if more.Clicked() { m.menu = !m.menu } -// ui.Popover(c, more, &m.menu, func() { ... }) -func Popover(c C, Anchor Box, open *bool, body func()) bool { - return PopoverWith(c, Anchor, open, PopoverSpec{Align: Start}, body) -} - -// PopoverWith is Popover with a spec: the side, alignment, width and the rest of -// PopoverSpec. The Scope and DismissID it leaves zero are made from open. -func PopoverWith(c C, Anchor Box, open *bool, spec PopoverSpec, body func()) bool { +// ui.Popover(c, more, &m.menu, ui.PopoverSpec{Align: ui.Start}, func() { ... }) +func Popover(c C, Anchor Box, open *bool, spec PopoverSpec, body func()) bool { p := c.page p.ForbidInMemo("Popover") if !*open { @@ -455,13 +425,9 @@ type ModalSpec struct { // *open to false. It keeps the keyboard while open, gives it to the first control as // it opens and back to where it was as it closes, and reports the paint that closed // it. The title is the dialog's name for assistive technology. body and footer may -// be nil. -func Modal(c C, open *bool, title string, body, footer func()) bool { - return ModalWith(c, open, title, ModalSpec{}, body, footer) -} - -// ModalWith is Modal with a description, a size, no close button or an initial focus. -func ModalWith(c C, open *bool, title string, spec ModalSpec, body, footer func()) bool { +// be nil. spec gives it a description, a size, no close button or an initial focus; the +// zero ModalSpec is the plain dialog. +func Modal(c C, open *bool, title string, spec ModalSpec, body, footer func()) bool { p := c.page p.ForbidInMemo("Modal") if !*open { diff --git a/base/field.go b/base/field.go index b589ced5e..138752df8 100644 --- a/base/field.go +++ b/base/field.go @@ -1,6 +1,7 @@ package base import ( + "strconv" "unicode/utf8" "github.com/vivaui/viva/gfx" @@ -32,6 +33,10 @@ type Field struct { // border and ring components.Input gives an invalid input. It is the application's // to set and clear, as Secure is; it changes the look only. Invalid bool + // Warning paints the field with the warning border: a value that needs a look but + // did not fail. Invalid wins over it. It is the application's to set and clear, as + // Invalid is; it changes the look only. + Warning bool // Disabled paints the field dimmed and takes it out of the Tab order and the pointer's // reach, as components.Input does for a disabled input. It is the application's to set // and clear, as Secure is. @@ -52,7 +57,16 @@ type Field struct { Alignment gfx.Alignment editor *text.Editor - ID gfx.ID + // accept and maxRunes are what Restrict last set on the editor, kept so a cap + // from MaxLength changes the one without losing the other. + accept func(rune) bool + maxRunes int + // count is the "n/max" words ShowCount shows, made when the numbers change. + count struct { + runes, max int + text string + } + ID gfx.ID // input is the stable TextInput the platform provider hands out. Returning // a fresh one on every repaint allocated once per focused frame. input window.TextInput @@ -73,6 +87,37 @@ type Field struct { rows bool } +// Restrict limits what edits may put into the field: accept reports whether a rune +// may be typed (nil accepts every rune) and maxRunes caps the length of the text +// (zero or less means no cap), as text.Editor.Restrict does. Set it where the model +// is made; a field bound to a string takes ui.MaxLength instead. +// +// m.port.Restrict(func(r rune) bool { return r >= '0' && r <= '9' }, 5) +func (field *Field) Restrict(accept func(rune) bool, maxRunes int) { + field.accept, field.maxRunes = accept, max(maxRunes, 0) + field.ensure().Restrict(field.accept, field.maxRunes) +} + +// limit sets the cap of the field from ui.MaxLength, leaving what Restrict accepts. +func (field *Field) limit(maxRunes int) { + if maxRunes != field.maxRunes { + field.Restrict(field.accept, maxRunes) + } +} + +// countText is the words of the count: the runes the field holds, and the cap. +func (field *Field) countText() string { + runes := field.ensure().RuneCount() + if field.count.text == "" || field.count.runes != runes || field.count.max != field.maxRunes { + field.count.runes, field.count.max = runes, field.maxRunes + field.count.text = strconv.Itoa(runes) + if field.maxRunes > 0 { + field.count.text += "/" + strconv.Itoa(field.maxRunes) + } + } + return field.count.text +} + func (field *Field) ensure() *text.Editor { if field.editor == nil { field.editor = text.NewEditor("") @@ -88,7 +133,7 @@ func (field *Field) ensure() *text.Editor { // made, as the field is kept there. // // m.searchField.Bind(&m.search) -// ui.TextFieldID(c, m.searchID, &m.searchField, "Search", "") +// ui.TextField(c, &m.searchField, "Search", "", ui.WithID(m.searchID)) func (field *Field) Bind(editor *text.Editor) { if editor == nil { panic("ui: Field.Bind needs an editor") @@ -117,7 +162,7 @@ func (field *Field) SetText(Value string) { // The page shows the selection in the next paint. // // m.preview.Select(0, 6) -// ui.TextFieldID(c, id, &m.preview, "Preview", "").ReadOnly(true) +// ui.TextField(c, &m.preview, "Preview", "", ui.WithID(id)).ReadOnly(true) func (field *Field) Select(start, end int) { field.ensure().SetSelection(text.Range{Start: start, End: end}) } @@ -139,6 +184,25 @@ func (f *Frame) FieldBase(field *Field, ID gfx.ID, Label, placeholder string) Bo return f.InputBase(field.Snapshot(f, ID, Label, placeholder)) } +// Warning paints a TextField or TextArea with the warning border (the theme's Warning +// color) in place of the input border, for a value that needs a look but did not fail; +// Warning(false) takes it away. A field marked Invalid keeps its destructive border +// over it. A *Field sets Field.Warning where the model is made. +// +// ui.TextField(c, &m.port, "Port", "").Warning(m.port == "22") +func (b Box) Warning(warning bool) Box { + n := b.N() + switch n.Kind { + case kindInput: + WidgetsOf(b.f).inputs[n.Aux].Warning = warning + case kindTextarea: + WidgetsOf(b.f).textareas[n.Aux].Warning = warning + default: + panic("ui: Warning is for a TextField or TextArea") + } + return b +} + // ReadOnly makes the TextField or TextArea of the box read-only: // ReadOnly(true) keeps its ordinary look and its value visible, but gives the // platform no editor, paints no caret and applies no edit, as Field.ReadOnly @@ -191,7 +255,7 @@ func (b Box) Submitted() bool { // OnKey gives the field a handler for the keys pressed while it has the // keyboard, before the page routes them anywhere else: a search field whose Up // and Down move a list below it, and whose Escape closes it. The handler is a -// chain on the TextField or TextFieldID box: +// chain on the TextField box: // // search := ui.TextField(c, &m.query, "Search", "") // search.OnKey(func(event gfx.KeyEvent) gfx.EventResult { @@ -239,7 +303,7 @@ func (b Box) OnKey(handler func(gfx.KeyEvent) gfx.EventResult) Box { return b } } - panic("ui: OnKey must be chained on a TextField or TextFieldID") + panic("ui: OnKey must be chained on a TextField") } // Fields answers Config.TextInput for the fields: the platform asks which editor @@ -270,7 +334,7 @@ func (field *Field) Snapshot(f *Frame, ID gfx.ID, Label, placeholder string) Inp focused := f.Surface != nil && f.Surface.Focused() == ID selection := editor.Selection() snapshot := InputSnapshot{ - ID: ID, Label: Label, Value: value, Placeholder: placeholder, Secure: field.Secure, Invalid: field.Invalid, Disabled: field.Disabled, ReadOnly: field.ReadOnly, Hint: field.Hint, + ID: ID, Label: Label, Value: value, Placeholder: placeholder, Secure: field.Secure, Invalid: field.Invalid, Warning: field.Warning, Disabled: field.Disabled, ReadOnly: field.ReadOnly, Hint: field.Hint, Alignment: field.Alignment, Focused: focused, // The field paints its own text, caret, selection and composition, and the @@ -313,7 +377,7 @@ func (f *Frame) FieldArea(field *Field, ID gfx.ID, Label, placeholder string) Bo field.rows = true return f.Textarea(TextareaSnapshot{ ID: input.ID, Label: input.Label, Value: input.Value, DisplayValue: input.Value, Placeholder: placeholder, - Hint: input.Hint, Disabled: input.Disabled, ReadOnly: input.ReadOnly, Invalid: input.Invalid, + Hint: input.Hint, Disabled: input.Disabled, ReadOnly: input.ReadOnly, Invalid: input.Invalid, Warning: input.Warning, Focused: input.Focused, HideEditorText: true, ShowCaret: input.ShowCaret, Layout: field.area, Caret: input.Caret, SelectionStart: input.SelectionStart, SelectionEnd: input.SelectionEnd, SelectionRanges: input.SelectionRanges, diff --git a/base/fields.go b/base/fields.go index 7b4d239a5..de3d2e477 100644 --- a/base/fields.go +++ b/base/fields.go @@ -13,14 +13,17 @@ type InputSnapshot struct { // the ordinary direction-dependent start alignment, which is left-to-right // for Latin text. AlignRight suits a numeric field. The label, caret, // selection, composition and platform editor all take the same alignment. - Alignment gfx.Alignment - Value string - DisplayValue string - Placeholder string - Hint string - Disabled bool - ReadOnly bool - Invalid bool + Alignment gfx.Alignment + Value string + DisplayValue string + Placeholder string + Hint string + Disabled bool + ReadOnly bool + Invalid bool + // Warning paints the field with the warning border: something to look at, not a + // failure. Invalid wins over it. + Warning bool Secure bool Focused bool PlatformEditing bool diff --git a/base/filedrop.go b/base/filedrop.go new file mode 100644 index 000000000..12cfba904 --- /dev/null +++ b/base/filedrop.go @@ -0,0 +1,128 @@ +package base + +import "github.com/vivaui/viva/gfx" + +// FileDropState is one area of a page that takes files dragged from the +// system: whether files are over it, and the files dropped on it. Keep one in +// the model, next to the state the drop changes, and declare the area every +// paint: +// +// ui.Column(c).FillWidth().DropFiles(&m.drop) +// // in the page, after the area: +// if m.drop.Over() { /* paint the highlight */ } +// if files, paths := m.drop.Dropped(); len(files) > 0 { /* take them */ } +// +// The engine owns the drag's position: while files are over the area, Over is +// true and the system shows the drop as accepted; leaving the area, or the +// drop, ends it. Dropped returns the files of a drop once, then nothing until +// the next drop. The areas of a page are tested from the last one declared, the +// one painted on top; an area that covers another takes the files. A drop on +// no area is left to the window's OnFileDrop. +// +// The files are the window's (gfx.FileDropEvent): Files read the same way on +// every platform, and Paths are absolute file system paths on a native target +// and empty in a browser. Do not declare an area inside a Memo: a copied area +// would not declare it again. One state is one area. +type FileDropState struct { + frame *Frame + gen uint32 + epoch uint32 // the page paint this state was registered for + + node int32 + declared bool + over bool + files []gfx.FileDropFile + paths []string +} + +// DropFiles makes the element an area for state that takes files dragged from +// the system. It does not need a Hit identity: the area is the element's +// rectangle, including HitOutset. +func (b Box) DropFiles(state *FileDropState) Box { + if state == nil { + panic("ui: DropFiles needs its FileDropState") + } + p := b.f.page + if p == nil { + panic("ui: DropFiles is for a page's element; a view surface has no window to drop on") + } + p.ForbidInMemo("DropFiles") + state.begin(b.f) + state.node, state.declared = b.i, true + return b +} + +// Over reports whether files dragged from the system are over the area. +func (s *FileDropState) Over() bool { return s.over } + +// Dropped returns the files dropped on the area, and their paths where the +// platform has them, and forgets them: it returns nothing until the next drop. +// Files that are folders have IsDir set and cannot be read. +func (s *FileDropState) Dropped() (files []gfx.FileDropFile, paths []string) { + files, paths = s.files, s.paths + s.files, s.paths = nil, nil + return files, paths +} + +// begin records the frame a paint declares the state in, and adds the state to +// the page that routes the files. The first declaration of a paint clears the +// last one's. +func (s *FileDropState) begin(f *Frame) { + if s.frame == f && s.gen == f.gen { + return + } + s.frame, s.gen, s.declared = f, f.gen, false + if p := f.page; p != nil && s.epoch != p.epoch { + s.epoch = p.epoch + p.fileDrops = append(p.fileDrops, s) + } +} + +// contains reports whether the point is over the declared area. +func (s *FileDropState) contains(x, y float32) bool { + if !s.declared || s.frame == nil || int(s.node) >= len(s.frame.Nodes) { + return false + } + n := &s.frame.Nodes[s.node] + r := n.Rect + if n.Ext != 0 { + h := s.frame.Exts[n.Ext].hitOut + r = Rect{X: r.X - h[3], Y: r.Y - h[0], Width: r.Width + h[1] + h[3], Height: r.Height + h[0] + h[2]} + } + return pointInRect(x, y, r) +} + +// onFileDrop gives one step of a drag of files to the area under the point, +// then to the host's own OnFileDrop when no area took it. +func (p *Page) onFileDrop(event gfx.FileDropEvent) gfx.EventResult { + var result gfx.EventResult + var taken *FileDropState + if event.Phase != gfx.FileDropLeave { + for i := len(p.fileDrops) - 1; i >= 0; i-- { + if s := p.fileDrops[i]; s.contains(event.X, event.Y) { + taken = s + break + } + } + } + for _, s := range p.fileDrops { + over := s == taken && event.Phase == gfx.FileDropOver + if s.over != over { + s.over, result.Repaint = over, true + } + } + if taken != nil { + result.Handled = true + if event.Phase == gfx.FileDropDrop { + taken.files, taken.paths = event.Files, event.Paths + result.Repaint = true + } + return result + } + if p.baseFileDrop != nil { + other := p.baseFileDrop(event) + other.Repaint = other.Repaint || result.Repaint + return other + } + return result +} diff --git a/base/form_field.go b/base/form_field.go index 3b9893ed7..c0db06b5b 100644 --- a/base/form_field.go +++ b/base/form_field.go @@ -205,7 +205,7 @@ func (state *FormFieldState) paintMessage(d *DrawContext) { // // email := ui.ID(c) // ui.Label(c, "Work email").Required().LabelFor(email) -// ui.TextFieldID(c, email, &m.email, "Work email", "") +// ui.TextField(c, &m.email, "Work email", "", ui.WithID(email)) // // Its width is the words' (plus the marker when Required is called); a later // Width, FillWidth or Grow may size it as any element. A disabled Label is diff --git a/base/frame.go b/base/frame.go index 45c2283f2..1f32e712c 100644 --- a/base/frame.go +++ b/base/frame.go @@ -123,8 +123,12 @@ type Node struct { Label string Variant style.Variant ButtonSize style.Size - RowSpan uint8 // the rows a Grid child covers; zero is one - OutOfFlow uint8 // absolute positioning: see absolute.go + Status style.Status // the outcome a Progress reports through its fill + Circle bool // a Progress drawn as a ring + Segments uint8 // a Progress bar drawn as this many separate segments; zero is one bar + Loading bool // a Button that is busy: a spinner in its icon slot, and presses are not delivered + RowSpan uint8 // the rows a Grid child covers; zero is one + OutOfFlow uint8 // absolute positioning: see absolute.go MaxLines int32 // a wrapped Text breaks into at most this many lines LineFirst, LineCount int32 // its lines, in frame.lines @@ -191,7 +195,16 @@ type Extra struct { ring Color // Ring: a line around the outside of the element ringWidth float32 // its width; zero is none borderDashed bool - fade float32 // 1 less the opacity, so that the zero value is opaque + fade float32 // 1 less the opacity, so that the zero value is opaque + glide gfx.Motion // Glide: how the element slides to a place the layout moves it to + glided bool + glideScroll gfx.Point + presence gfx.Presence // Presence: how the element enters and leaves + presenced bool + pose gfx.Pose // Pose: where the element sits relative to its place + poseMotion gfx.Motion + posed bool + glideID gfx.ID // the identity of a glided element that has no hit of its own, such as a list row gradient int32 // 1 + the index of the element's gradient in frame.gradients, or 0 for none States int32 // 1 + the index of the element's Hover, Pressed and Focus looks in frame.states, or 0 for none scrollState *ScrollState // the state a ScrollArea reports its extent to diff --git a/base/glide_test.go b/base/glide_test.go new file mode 100644 index 000000000..2dc1427cf --- /dev/null +++ b/base/glide_test.go @@ -0,0 +1,84 @@ +package base_test + +import ( + "testing" + "time" + + . "github.com/vivaui/viva/base" + + "github.com/vivaui/viva/gfx" +) + +// A row of keyed boxes: when the first is taken out, the second slides to the +// place the layout gives it instead of jumping there. +func TestGlideSlidesAnElementTheLayoutMoved(t *testing.T) { + var canvas gfx.Canvas + var view View + bounds := gfx.Rect{Width: 300, Height: 40} + now := time.Duration(0) + canvas.SetClock(func() time.Duration { return now }) + motion := gfx.Motion{Duration: 100 * time.Millisecond, Easing: gfx.EaseLinear} + green := gfx.Color{Green: 1, Alpha: 1} + frame := func(at time.Duration, first bool) float32 { + now = at + canvas.Reset() + canvas.BeginFrame() + view.Draw(&canvas, gfx.LightTheme(), bounds, func(f *Frame) { + f.Row().Children(func() { + if first { + f.Column().Size(50, 20).Background(gfx.Color{Red: 1, Alpha: 1}).Glide(motion, gfx.Point{}).Hit(gfx.Item(1), "a") + } + f.Column().Size(50, 20).Background(green).Glide(motion, gfx.Point{}).Hit(gfx.Item(2), "b") + }) + }) + canvas.EndFrame() + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color == green { + return rectangle.Bounds.X + } + } + t.Fatal("the second box was not painted") + return 0 + } + start := frame(0, true) + if start <= 0 { + t.Fatalf("second box at %v, want it beside the first", start) + } + if got := frame(time.Second, false); got != start { + t.Fatalf("frame that closes the first = %v, want the old place %v", got, start) + } + if got := frame(time.Second+50*time.Millisecond, false); got <= 0 || got >= start || !canvas.Animating() { + t.Fatalf("halfway = %v animating=%v, want between 0 and %v", got, canvas.Animating(), start) + } + if got := frame(2*time.Second, false); got != 0 || canvas.Animating() { + t.Fatalf("arrived = %v animating=%v", got, canvas.Animating()) + } +} + +// A posed element is drawn where its pose puts it, and is hit there. +func TestBoxPoseMovesAnElementAndItsHit(t *testing.T) { + var canvas gfx.Canvas + var view View + bounds := gfx.Rect{Width: 300, Height: 100} + canvas.SetClock(func() time.Duration { return 0 }) + canvas.BeginFrame() + view.Draw(&canvas, gfx.LightTheme(), bounds, func(f *Frame) { + f.Column().Size(50, 20).Background(gfx.Color{Red: 1, Alpha: 1}).Hit(gfx.Item(3), "card"). + Pose(gfx.Pose{Offset: gfx.Point{X: 30, Y: 5}, Scale: 2}, gfx.DefaultMotion()) + }) + canvas.EndFrame() + var painted gfx.Rect + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color.Red == 1 { + painted = rectangle.Bounds + } + } + if painted.Width != 100 || painted.Height != 40 { + t.Fatalf("posed element painted %+v, want it twice as large", painted) + } + for _, hit := range canvas.Hits() { + if hit.ID == gfx.Item(3) && hit.Bounds != painted { + t.Fatalf("hit %+v, painted %+v: a press must land where it is drawn", hit.Bounds, painted) + } + } +} diff --git a/base/input_group.go b/base/input_group.go index 174dac89a..bb382c3be 100644 --- a/base/input_group.go +++ b/base/input_group.go @@ -94,6 +94,8 @@ type InputGroupSnapshot struct { Disabled bool ReadOnly bool Invalid bool + // Warning paints the group with the warning border; Invalid wins over it. + Warning bool // Secure makes a single-line control a password field, as for // InputSnapshot.Secure. Secure bool diff --git a/base/layout.go b/base/layout.go index 61132b17f..6f43979ee 100644 --- a/base/layout.go +++ b/base/layout.go @@ -249,7 +249,7 @@ func (n *Node) stretches(axis int) bool { case kindSlider: return (n.Natural > 0) == (axis == AxisY) // as long as its container, never as thick case kindProgress: - return axis == AxisX // a bar is as wide as its column, but a row does not make it tall + return axis == AxisX && !n.Circle // a bar is as wide as its column, but a row does not make it tall; a ring keeps its size case kindContainer, kindText, kindSpacer, kindSlot, kindInput, kindInputGroup, kindTextarea, kindSegmented, kindTable, kindTabs, kindSelect, kindSplitter: return true } diff --git a/base/leaves.go b/base/leaves.go index 99341ab8e..88c552d15 100644 --- a/base/leaves.go +++ b/base/leaves.go @@ -4,12 +4,15 @@ import ( "time" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/style" ) // progressHeight and progressWidth are what a Progress is when it is given neither. const ( ProgressHeight = 6 ProgressWidth = 160 + // ProgressRing is the side of a circular Progress given no size. + ProgressRing = 64 // An indeterminate bar's moving segment is this much of the track and takes // indeterminatePeriod to cross it. IndeterminateShare = 0.4 @@ -50,6 +53,50 @@ func (b Box) Indeterminate() Box { return b } +// Circle draws a Progress as a ring that fills clockwise from twelve o'clock, 64 across +// unless given a Width and Height (it is as large as the smaller of the two), and an +// Indeterminate one as an arc that keeps turning. It keeps the status color and the +// accessible progress bar of the bar. +// +// ui.Progress(c, m.done/m.total).Circle().Size(80, 80) +func (b Box) Circle() Box { + n := b.N() + if n.Kind != kindProgress { + panic("ui: Circle is for a Progress") + } + n.Circle = true + return b +} + +// Segments draws a Progress bar as n separate segments with a gap between them, the first +// ones filled for the fraction (a fraction of a segment fills it from one half), for work +// that comes in steps: "3 of 5 stages". n of one or less is the ordinary bar, and a ring +// keeps being a ring. +// +// ui.Progress(c, float32(m.stage)/float32(m.stages)).Segments(m.stages) +func (b Box) Segments(n int) Box { + node := b.N() + if node.Kind != kindProgress { + panic("ui: Segments is for a Progress") + } + node.Segments = uint8(min(max(n, 0), 255)) + return b +} + +// Status colors the fill of a Progress by the outcome it reports: success, warning or +// danger take the theme's color for it in place of the primary one, and the default +// keeps the primary. It is the same vocabulary as an alert or a tag. +// +// ui.Progress(c, m.done/m.total).Status(ui.StatusSuccess) +func (b Box) Status(status style.Status) Box { + n := b.N() + if n.Kind != kindProgress { + panic("ui: Status is for a Progress") + } + n.Status = status + return b +} + // Spinner adds the theme's 16 pixel loading indicator, turning clockwise one step // every 100 ms. It asks for another frame only while it is on screen (and none when // the system asks for reduced motion, which leaves it still); a spinner inside a diff --git a/base/list.go b/base/list.go index 803a09077..10cff5e65 100644 --- a/base/list.go +++ b/base/list.go @@ -21,6 +21,11 @@ type ListState struct { // than hash them: a 32-bit hash is past 2^31-1 half the time, and a key outside // that range panics, since every such key would name the same row. Key func(i int) int + // Glide, when it has a duration, slides a row to the place the list gives it + // after rows were added, removed or moved above or among them, instead of + // letting it jump: rows must have a Key to keep their identity, and a scroll is + // not a move. The zero Motion keeps the rows where the list puts them. + Glide gfx.Motion // Label is the text of row i: typing the first letters of a row's text while // the list has the keyboard focus chooses it. It is also the row's name for // assistive technology unless Name says otherwise. Nil leaves the rows unnamed @@ -980,6 +985,16 @@ func (p *Page) ListArea(c C, state *ListState, n int, horizontal bool, row func( for i := first; i < last; i++ { box := listRowBox(c.KeyInt(state.key(i)), horizontal) row(i, box) + if state.Glide.Duration > 0 { + scrolled := gfx.Point{Y: offset} + if horizontal { + scrolled = gfx.Point{X: offset} + } + box.Glide(state.Glide, scrolled) + } + if extra := c.f.Extra(box.i); extra.glided || extra.presenced || extra.posed { + extra.glideID = state.list.rows.At(state.key(i)) + } if state.RowWidth > 0 { box.MinWidth(state.RowWidth) box.N().Margin[3] = -scrollX diff --git a/base/list_glide_test.go b/base/list_glide_test.go new file mode 100644 index 000000000..b9ccb0bb5 --- /dev/null +++ b/base/list_glide_test.go @@ -0,0 +1,68 @@ +package base_test + +import ( + "testing" + "time" + + . "github.com/vivaui/viva/base" + "github.com/vivaui/viva/gfx" +) + +// Taking a row out of a list slides the rows below it up instead of letting them +// jump, and a row's place is measured without the scroll. +func TestListGlideSlidesRowsAfterOneIsRemoved(t *testing.T) { + theme := gfx.LightTheme() + page := NewPage(PageConfig{Theme: &theme}) + canvas := testCanvas() + now := time.Duration(0) + canvas.SetClock(func() time.Duration { return now }) + var list ListState + list.Key = func(i int) int { return i + 1 } + list.Glide = gfx.Motion{Duration: 100 * time.Millisecond, Easing: gfx.EaseLinear} + rows := 3 + var second float32 + var secondID gfx.ID + draw := func(c C) { + Column(c).Fill().Children(func() { + List(c, &list, rows, func(row ListRow) { + row.Element.Height(40).Background(gfx.Color{Red: 1, Alpha: 1}) + if row.Key == 2 { + secondID = row.ID + } + }).Grow(1).MinHeight(0) + }) + } + bounds := gfx.Rect{Width: 200, Height: 300} + frame := func(at time.Duration) float32 { + now = at + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, bounds, draw) + canvas.EndFrame() + second = 0 + for _, hit := range canvas.Hits() { + if hit.ID == secondID { + second = hit.Bounds.Y + } + } + return second + } + frame(0) + start := frame(10 * time.Millisecond) + if start != 40 { + t.Fatalf("second row at %v, want 40", start) + } + // Remove the first row: the old second row is now the first and the layout + // puts it at 0, but the eye still sees it at 40. + rows = 2 + list.Key = func(i int) int { return i + 2 } + if got := frame(time.Second); got != 40 { + t.Fatalf("frame after removal = %v, want the old place 40", got) + } + if got := frame(time.Second + 50*time.Millisecond); got <= 0 || got >= 40 || !canvas.Animating() { + t.Fatalf("halfway = %v animating=%v, want between 0 and 40", got, canvas.Animating()) + } + if got := frame(2 * time.Second); got != 0 || canvas.Animating() { + t.Fatalf("arrived = %v animating=%v", got, canvas.Animating()) + } +} diff --git a/base/menu.go b/base/menu.go index b01c9f58f..c8a44ea97 100644 --- a/base/menu.go +++ b/base/menu.go @@ -593,6 +593,14 @@ func (item MenuItem) Clicked() bool { return true } +// Toggled is Clicked for a setting that stays on screen: the menu stays open, so +// several checkboxes can be changed before it is dismissed. +func (item MenuItem) Toggled() bool { + m := item.menu + canvas := m.f.Surface + return canvas != nil && !m.Items[item.i].disabled && !m.Items[item.i].submenu && canvas.Clicked(m.scope.At(MenuRowsPart+item.i)) +} + // draw paints the open menu in the popup the page placed for it. func (m *MenuItems) draw(d *DrawContext) { m.paintAt(d.Canvas, d.Theme, d.Rect, max(m.layer, m.f.popupLayer)) diff --git a/base/option.go b/base/option.go new file mode 100644 index 000000000..c28e1a289 --- /dev/null +++ b/base/option.go @@ -0,0 +1,96 @@ +package base + +import "github.com/vivaui/viva/gfx" + +// Option is a setting a control takes after its fixed arguments, written at the +// call. It is a small value, not a function, so passing one costs no allocation. +type Option struct { + id gfx.ID + maxRunes int + count bool + plain bool // WithoutEditMenu + groups []SelectGroup +} + +// WithID names the control with an identity the application already holds, so the +// page's input routing, an initial focus or a test can address it. A control given +// no WithID takes the name its bound value or its place gives it. +// +// ui.TextField(c, &m.query, "Search", "", ui.WithID(m.searchID)) +func WithID(id gfx.ID) Option { return Option{id: id} } + +// SelectGroups puts a heading row in a Select's list before the first option of each +// group, for options that belong in sets ("Recent", "All hosts"). The choices must be in +// group order; a group whose From is past the last option is left out. A heading is not an +// option: it takes no focus, no click and no type-ahead, and the indexes DisabledOptions, +// Icons and Part use stay the choices' own. The slice is the caller's, read until the +// paint ends; keep it in the model. +// +// ui.Select(c, &m.host, hosts, hostName, ui.SelectGroups(m.groups)) +func SelectGroups(groups []SelectGroup) Option { return Option{groups: groups} } + +// groupsOf is the groups opts give a Select. +func groupsOf(opts []Option) []SelectGroup { + for _, o := range opts { + if len(o.groups) > 0 { + return o.groups + } + } + return nil +} + +// MaxLength caps a TextField or TextArea at n runes: what is typed, pasted or +// composed beyond it is cut off the end, and text already longer is left alone, +// as text.Editor.Restrict does. Zero or less is no cap. +// +// ui.TextField(c, &m.name, "Name", "", ui.MaxLength(32)) +func MaxLength(n int) Option { return Option{maxRunes: n} } + +// ShowCount shows how many runes a TextField or TextArea holds, and of how many +// when MaxLength caps it ("12/32"), at the end of the field. It takes the place of +// an Action. +// +// ui.TextField(c, &m.title, "Title", "", ui.MaxLength(80), ui.ShowCount()) +func ShowCount() Option { return Option{count: true} } + +// limitsOf is the cap and the count opts ask a text control for. +func limitsOf(opts []Option) (maxRunes int, count bool) { + for _, o := range opts { + if o.maxRunes != 0 { + maxRunes = o.maxRunes + } + count = count || o.count + } + return max(maxRunes, 0), count +} + +// namedBy is the identity opts give a control, zero when they give none. A control +// has one name, so a second WithID is a mistake in the call. +func namedBy(control string, opts []Option) gfx.ID { + var id gfx.ID + for _, o := range opts { + if o.id.IsZero() { + continue + } + if !id.IsZero() { + panic("ui: " + control + " takes one WithID") + } + id = o.id + } + return id +} + +// namedFieldOf is fieldOf for a field that may carry the application's name. A +// named field keeps its editor under the name its value is given, as fieldOf keeps +// it; only the element takes the application's identity. A *Field is the editor +// itself, so naming it declares nothing for it in the page. +func namedFieldOf[T TextValue](p *Page, Kind uint8, Value T, named gfx.ID) (*Field, gfx.ID) { + if named.IsZero() { + return fieldOf(p, Kind, Value) + } + if v, ok := any(Value).(*Field); ok { + return v, named + } + field, _ := fieldOf(p, Kind, Value) + return field, named +} diff --git a/base/page.go b/base/page.go index 9c39f58fd..f3611b3ed 100644 --- a/base/page.go +++ b/base/page.go @@ -241,6 +241,13 @@ type PageConfig struct { // that keeps using Button, Checkbox, Switch, Input and Textarea rather than // their Bases, and it does not affect a control given a look of its own. Styles *Styles + // EditMenu points at the words of the menu a TextField or TextArea opens on a + // secondary press, as Theme points at the colors: the application changes them + // when its language does. Nil, and a label left empty, are English. + EditMenu *EditMenuLabels + // CanvasMenus keeps the menu of a TextField or TextArea the page's own, drawn + // in the window, where the platform would show the system's. + CanvasMenus bool } // Page is a window's declaration: one tree for the whole window. A Page lives @@ -292,10 +299,13 @@ type Page struct { groupIDs []gfx.ID // their members, in order groupStops map[gfx.ID]groupStop // the member each group has the Tab stop on contexts []contextTarget // the ContextMenus of the last paint, which Shift+F10 opens + editMenus []editMenuEntry // the fields of the last paint that have the standard edit menu + editFocus gfx.ID // the field whose edit menu item was chosen, which takes the keyboard in the next paint combos []*ComboState // the Comboboxes of the last paint trees []*TreeState // the Trees of the last paint drags []*DragState // the DragStates of the last paint drag *DragState // the one following a press, if any + fileDrops []*FileDropState // the areas of the last paint that take files from the system listStates []*ListState // the Lists of the last paint splitters []*SplitterState // the Splitters of the last paint tables []tableRoute // the Tables of the last paint, for the wheel and keys under the pointer @@ -325,6 +335,7 @@ type Page struct { baseKey func(gfx.KeyEvent) gfx.EventResult basePointer func(gfx.PointerEvent) gfx.EventResult baseShortcut func(gfx.KeyEvent) gfx.EventResult + baseFileDrop func(gfx.FileDropEvent) gfx.EventResult // keyRoute, pointerRoute, areaKey and shortcutRoute are set by the first // Control, TextArea or Shortcut a page declares, so a page without them does // not link what routes their input. @@ -716,6 +727,7 @@ type Host struct { OnKey func(gfx.KeyEvent) gfx.EventResult OnShortcut func(gfx.KeyEvent) gfx.EventResult OnPointer func(gfx.PointerEvent) gfx.EventResult + OnFileDrop func(gfx.FileDropEvent) gfx.EventResult } // Attach wires the page into a host: the page adopts or keeps the tree, paints @@ -728,6 +740,7 @@ func (p *Page) Attach(h *Host) { p.basePointer, h.OnPointer = h.OnPointer, p.onPointer p.baseShortcut, h.OnShortcut = h.OnShortcut, p.onShortcut p.baseScroll, h.OnScroll = h.OnScroll, p.Wheel + p.baseFileDrop, h.OnFileDrop = h.OnFileDrop, p.onFileDrop } // Init prepares the page's identity tree from the host's, or a new one. @@ -831,12 +844,16 @@ func (p *Page) paintOnce(Surface *gfx.Canvas, bounds Rect, View func(C)) { p.groups, p.groupIDs = p.groups[:0], p.groupIDs[:0] clear(p.contexts) p.contexts = p.contexts[:0] + clear(p.editMenus) + p.editMenus = p.editMenus[:0] clear(p.combos) p.combos = p.combos[:0] clear(p.trees) p.trees = p.trees[:0] clear(p.drags) p.drags = p.drags[:0] + clear(p.fileDrops) + p.fileDrops = p.fileDrops[:0] clear(p.listStates) p.listStates = p.listStates[:0] clear(p.tables) @@ -858,6 +875,7 @@ func (p *Page) paintOnce(Surface *gfx.Canvas, bounds Rect, View func(C)) { p.ctx.page, p.ctx.f, p.ctx.nextSet = p, f, false p.Nodes = append(p.Nodes[:0], protoNode{scope: p.root, named: true, parentNode: -1}) // node 0, the root column View(&p.ctx) + p.declareEditMenus(&p.ctx) f.End() p.hoverText = p.HoveredText() if p.settleContainers() { diff --git a/base/page_bases.go b/base/page_bases.go index d41ebb5f7..5428d0d21 100644 --- a/base/page_bases.go +++ b/base/page_bases.go @@ -128,11 +128,12 @@ func SliderBase(c C, state *SliderState) Box { // list.Draw(m.paintPanel) // option i is in sel.Part(i) // } func SelectBase[T comparable](c C, Value *T, choices []T, Label func(T) string) Box { - return selectOf(c, Value, choices, Label, nil, true, gfx.ID{}) + return selectOf(c, Value, choices, Label, nil, true, gfx.ID{}, nil) } // TextFieldBase is TextField without a look: the editable text, with no padding, // background, border or corners of its own. func TextFieldBase[T TextValue](c C, Value T, Label, placeholder string) Box { - return textFieldOf(c, Value, Label, placeholder, true) + b, _ := textFieldOf(c, Value, Label, placeholder, true, gfx.ID{}, nil) + return b } diff --git a/base/paint.go b/base/paint.go index 69b1ea845..20ea4ff09 100644 --- a/base/paint.go +++ b/base/paint.go @@ -36,6 +36,20 @@ func (f *Frame) PaintChild(i int32) { f.paintPopoverFn(f, i, n) return } + if extra := &f.Exts[n.Ext]; extra.presenced && f.Surface != nil && !extra.glideIdentity(n).IsZero() { + r := n.Rect + f.Surface.BeginPresence(extra.glideIdentity(n), elementPresenceSlot, extra.presence, gfx.Point{X: r.X + r.Width/2, Y: r.Y + r.Height/2}) + defer f.Surface.EndPresence() + } + if extra := &f.Exts[n.Ext]; extra.posed && f.Surface != nil && !extra.glideIdentity(n).IsZero() { + r := n.Rect + f.Surface.BeginPose(extra.glideIdentity(n), elementPoseSlot, extra.pose, extra.poseMotion, gfx.Point{X: r.X + r.Width/2, Y: r.Y + r.Height/2}) + defer f.Surface.EndPose() + } + if extra := &f.Exts[n.Ext]; extra.glided && f.Surface != nil && !extra.glideIdentity(n).IsZero() { + f.Surface.BeginGlide(extra.glideIdentity(n), 0, gfx.Point{X: n.Rect.X + extra.glideScroll.X, Y: n.Rect.Y + extra.glideScroll.Y}, extra.glide) + defer f.Surface.EndPose() + } if memo := f.Exts[n.Ext].memo; memo != 0 && f.memoFn != nil { if f.memoFn(f, i, true) { return @@ -412,3 +426,19 @@ func (f *Frame) paintStrike(value string, bounds Rect, style gfx.TextStyle, alig x := f.Surface.LabelOrigin(value, bounds, style, alignment) f.Surface.Fill(Rect{X: x, Y: bounds.Y + bounds.Height/2, Width: f.Surface.TextWidthStyle(value, style), Height: 1}, style.Color) } + +// elementPresenceSlot is the slot of an element's own presence among those the +// canvas keeps for its ID, apart from the parts of an overlay. +const elementPresenceSlot = 200 + +// elementPoseSlot is the slot of an element's Pose, apart from its Glide's. +const elementPoseSlot = 1 + +// glideIdentity is what a glided element is followed by: its own ID, or the one +// its list gave it when it has none. +func (x *Extra) glideIdentity(n *Node) gfx.ID { + if !n.ID.IsZero() { + return n.ID + } + return x.glideID +} diff --git a/base/presence_box_test.go b/base/presence_box_test.go new file mode 100644 index 000000000..171d9ea9c --- /dev/null +++ b/base/presence_box_test.go @@ -0,0 +1,119 @@ +package base_test + +import ( + "testing" + "time" + + . "github.com/vivaui/viva/base" + "github.com/vivaui/viva/gfx" +) + +// An element with a Presence that is no longer painted stays on screen as a +// picture that fades out, and is gone when the exit has run. +func TestBoxPresenceFadesAnElementOutAfterItIsRemoved(t *testing.T) { + theme := gfx.LightTheme() + page := NewPage(PageConfig{Theme: &theme}) + canvas := testCanvas() + now := time.Duration(0) + canvas.SetClock(func() time.Duration { return now }) + presence := gfx.Presence{Motion: gfx.Motion{Duration: 100 * time.Millisecond, Easing: gfx.EaseLinear}, Fade: true} + shown := true + draw := func(c C) { + Column(c).Fill().Children(func() { + if shown { + Column(c).Size(100, 40).Background(gfx.Color{Red: 1, Alpha: 1}).Hit(gfx.Item(7), "item").Presence(presence) + } + }) + } + bounds := gfx.Rect{Width: 200, Height: 200} + alpha := func(at time.Duration) (float32, bool) { + now = at + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, bounds, draw) + canvas.EndFrame() + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color.Red == 1 { + return rectangle.Color.Alpha, true + } + } + return 0, false + } + alpha(0) + if got, ok := alpha(time.Second); !ok || got != 1 { + t.Fatalf("shown element alpha = %v painted=%v, want opaque", got, ok) + } + shown = false + if got, ok := alpha(2 * time.Second); !ok || got < 0.99 { + t.Fatalf("frame after removal = %v painted=%v, want the element still there", got, ok) + } + if got, ok := alpha(2*time.Second + 50*time.Millisecond); !ok || got <= 0 || got >= 1 || !canvas.Animating() { + t.Fatalf("halfway = %v painted=%v animating=%v, want it fading", got, ok, canvas.Animating()) + } + if _, ok := alpha(3 * time.Second); ok || canvas.Animating() { + t.Fatalf("after the exit the element is still painted=%v animating=%v", ok, canvas.Animating()) + } + for _, hit := range canvas.Hits() { + if hit.ID == gfx.Item(7) { + t.Fatal("a leaving element declared a hit region") + } + } +} + +// A row that leaves a list with Presence is drawn fading where it was while the +// rows below it close up. +func TestListRowPresenceKeepsADeletedRowFadingOut(t *testing.T) { + theme := gfx.LightTheme() + page := NewPage(PageConfig{Theme: &theme}) + canvas := testCanvas() + now := time.Duration(0) + canvas.SetClock(func() time.Duration { return now }) + presence := gfx.Presence{Motion: gfx.Motion{Duration: 100 * time.Millisecond, Easing: gfx.EaseLinear}, Fade: true} + var list ListState + list.Key = func(i int) int { return i + 1 } + first := 1 + rows := 3 + draw := func(c C) { + list.Key = func(i int) int { return first + i } + Column(c).Fill().Children(func() { + List(c, &list, rows, func(row ListRow) { + colour := gfx.Color{Red: 0.1 * float32(row.Key), Alpha: 1} + row.Element.Height(40).Background(colour).Presence(presence) + }).Grow(1).MinHeight(0) + }) + } + bounds := gfx.Rect{Width: 200, Height: 300} + frame := func(at time.Duration) { + now = at + canvas.Reset() + canvas.BeginFrame() + page.Draw(canvas, bounds, draw) + canvas.EndFrame() + } + painted := func(key int) (float32, bool) { + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color.Red > 0.1*float32(key)-0.01 && rectangle.Color.Red < 0.1*float32(key)+0.01 { + return rectangle.Color.Alpha, true + } + } + return 0, false + } + frame(0) + frame(time.Second) + first, rows = 2, 2 // the first row is deleted + frame(2 * time.Second) + if alpha, ok := painted(1); !ok || alpha < 0.99 { + t.Fatalf("deleted row alpha = %v painted=%v, want still drawn", alpha, ok) + } + frame(2*time.Second + 50*time.Millisecond) + if alpha, ok := painted(1); !ok || alpha <= 0 || alpha >= 1 { + t.Fatalf("deleted row halfway = %v painted=%v, want fading", alpha, ok) + } + frame(3 * time.Second) + if _, ok := painted(1); ok { + t.Fatal("the deleted row is still drawn after its exit") + } + if _, ok := painted(2); !ok { + t.Fatal("the remaining row disappeared") + } +} diff --git a/base/radio.go b/base/radio.go index b0058874b..93de29661 100644 --- a/base/radio.go +++ b/base/radio.go @@ -6,21 +6,18 @@ import "github.com/vivaui/viva/gfx" // 16 pixel circle that is filled with the primary color and holds a dot while *value is // option, and the label after it. A click sets *value to option (RadioBase's rules), and // the focus moving onto it with the arrow keys of a RadioGroup chooses it, as a native -// radio group does. Name it with c.Key when the options are reordered; Hit gives it the -// application's identity. +// radio group does. Name it with c.Key when the options are reordered; WithID gives it +// an identity the application already names, so an initial focus, the application's own +// routing or a test can address it. // // ui.Radio(c, &m.plan, Monthly, "Monthly") -func Radio[T comparable](c C, Value *T, option T, Label string) Box { - return radio(c, c.page.ControlID(pkRadio), Value, option, Label) -} - -// RadioID is Radio for an option the application already names, as TextFieldID is for -// TextField: id is the option's identity in the page's Tree, so an initial focus, the -// application's own routing or a test can address it. -// -// ui.RadioID(c, hitKeepParent, &m.ungroup, false, "Keep hosts in the parent") -func RadioID[T comparable](c C, ID gfx.ID, Value *T, option T, Label string) Box { - return radio(c, ID, Value, option, Label) +// ui.Radio(c, &m.ungroup, false, "Keep hosts in the parent", ui.WithID(hitKeepParent)) +func Radio[T comparable](c C, Value *T, option T, Label string, opts ...Option) Box { + id := namedBy("Radio", opts) + if id.IsZero() { + id = c.page.ControlID(pkRadio) + } + return radio(c, id, Value, option, Label) } func radio[T comparable](c C, ID gfx.ID, Value *T, option T, Label string) Box { diff --git a/base/recipe.go b/base/recipe.go index 81799eb1a..52a76331e 100644 --- a/base/recipe.go +++ b/base/recipe.go @@ -454,10 +454,10 @@ func (f *Frame) themedDefaults(n *Node, Extra *Extra, s *resolved) { return case kindInput: snapshot := &WidgetsOf(f).inputs[n.Aux] - state = gfx.State{Focused: snapshot.Focused || f.Focused(n), Invalid: snapshot.Invalid, Disabled: snapshot.Disabled} + state = gfx.State{Focused: snapshot.Focused || f.Focused(n), Invalid: snapshot.Invalid, Warning: snapshot.Warning, Disabled: snapshot.Disabled} case kindTextarea: snapshot := &WidgetsOf(f).textareas[n.Aux] - state = gfx.State{Focused: snapshot.Focused || f.Focused(n), Invalid: snapshot.Invalid, Disabled: snapshot.Disabled} + state = gfx.State{Focused: snapshot.Focused || f.Focused(n), Invalid: snapshot.Invalid, Warning: snapshot.Warning, Disabled: snapshot.Disabled} default: return } diff --git a/base/select.go b/base/select.go index 30777fb45..3ca6873ab 100644 --- a/base/select.go +++ b/base/select.go @@ -50,6 +50,11 @@ type SelectState struct { // frame the list opens in. listMaxWidth float32 listMaxHeight float32 + + // Buffers OptionGroups builds its rows in, kept so a warm paint allocates nothing. + rowLabels []string + rowDisabled []bool + rowOption []int } // ListMaxWidth caps the width of an open Select's list: zero keeps the list's @@ -366,6 +371,13 @@ type SelectDecl struct { Visible int // how many options the list shows at once layer uint16 rects int32 // where the rows of this frame's list start in frame.widgets.rows + // grouped is true after OptionGroups: labels, selected and disabled are then rows, the + // options with a heading row before the first of each group. rowOption is the option + // each row stands for, -1 for a heading, and optDisabled the caller's DisabledOptions, + // indexed by option. + grouped bool + rowOption []int + optDisabled []bool // asked, pick and picked keep what Picked found, so asking again in the same // paint reports the same option and does not open or close the list twice. asked bool @@ -544,6 +556,11 @@ func (b Box) DisabledOptions(disabled []bool) Box { switch n.Kind { case kindSelect: d := &WidgetsOf(b.f).selects[n.Aux] + d.optDisabled = disabled + if d.grouped { + d.rowsDisabled() + return b + } d.disabled, d.state.disabled = disabled, disabled case kindSegmented: if len(disabled) == 0 { @@ -563,6 +580,110 @@ func (b Box) DisabledOptions(disabled []bool) Box { return b } +// SelectGroup is a group of a Select's options: Label heads the options from index From +// of the choices up to the next group's From (or the end); see SelectGroups. +type SelectGroup struct { + Label string + From int +} + +// optionGroups is SelectGroups' work: it rewrites the select's labels, selection and +// disabled flags as rows with a heading before each group, and keeps the mapping back to +// the options. It runs where the select is made, before Picked reads the click, since +// the rows decide which part of the list a press landed on. +func (b Box) optionGroups(groups []SelectGroup) Box { + n := b.N() + if len(groups) == 0 { + return b + } + d := &WidgetsOf(b.f).selects[n.Aux] + s := d.state + options := d.labels + s.rowLabels, s.rowOption = s.rowLabels[:0], s.rowOption[:0] + next, selectedRow := 0, -1 + for i, label := range options { + for next < len(groups) && groups[next].From <= i { + if groups[next].From == i { + s.rowLabels, s.rowOption = append(s.rowLabels, groups[next].Label), append(s.rowOption, -1) + } + next++ + } + if i == d.selected { + selectedRow = len(s.rowLabels) + } + s.rowLabels, s.rowOption = append(s.rowLabels, label), append(s.rowOption, i) + } + d.grouped, d.rowOption = true, s.rowOption + d.labels, d.selected = s.rowLabels, selectedRow + s.labels, s.selected = s.rowLabels, selectedRow + d.rowsDisabled() + b.f.resizeSelectList(d) + return b +} + +// rowsDisabled makes the rows' disabled flags from the caller's, with every heading disabled. +func (d *SelectDecl) rowsDisabled() { + s := d.state + s.rowDisabled = s.rowDisabled[:0] + for _, option := range d.rowOption { + s.rowDisabled = append(s.rowDisabled, option < 0 || OptionDisabled(d.optDisabled, option)) + } + d.disabled, s.disabled = s.rowDisabled, s.rowDisabled +} + +// optionOf is the option a row stands for: the row itself when the list has no groups. +func (d *SelectDecl) optionOf(row int) int { + if !d.grouped { + return row + } + if row < 0 || row >= len(d.rowOption) { + return -1 + } + return d.rowOption[row] +} + +// rowOf is the row of an option, or -1. +func (d *SelectDecl) rowOf(option int) int { + for row, o := range d.rowOption { + if o == option { + return row + } + } + return -1 +} + +// OptionAt is the option row stands for, and -1 for a heading, for the styled painting +// layer: the rows are what the list is made of. +func (d *SelectDecl) OptionAt(row int) int { return d.optionOf(row) } + +// IsHeading reports whether row is a group heading. +func (d *SelectDecl) IsHeading(row int) bool { return d.grouped && d.optionOf(row) < 0 } + +// resizeSelectList sets the window and the size of an open list for the rows it has now. +func (f *Frame) resizeSelectList(d *SelectDecl) { + count := len(d.labels) + d.Visible = selectRows(count, f.bounds.Height) + if d.state.listMaxHeight > 0 { + d.Visible = min(d.Visible, listRowsForHeight(count, d.state.listMaxHeight)) + } + d.state.Visible = d.Visible + if d.state.Open && count > 0 { + d.state.First = min(max(d.state.First, 0), count-d.Visible) + height := float32(selectPad + selectItem*d.Visible) + if d.Visible < count { + height += 2 * selectArrow + } + widest := d.state.WidestOption(f.Surface, d.labels, f.Palette.Metrics.FontSizeM) + width := selectListWidth(widest) + if d.state.listMaxWidth > 0 { + width = min(width, d.state.listMaxWidth) + } + if d.popup >= 0 { + Box{f: f, i: d.popup, gen: f.gen}.Size(width, height) + } + } +} + // Hint is the description assistive technology reads after a Select's name and value, for // what the value alone does not say, such as the path a chosen shell stands for. func (b Box) Hint(Text string) Box { @@ -596,7 +717,7 @@ func (b Box) Picked() (int, bool) { func (d *SelectDecl) pickIn() (int, bool) { if chosen := d.state.chosen; chosen > 0 { d.state.chosen, d.state.Open = 0, false - return chosen - 1, true + return d.optionOf(chosen - 1), true } canvas := d.Surface count := len(d.labels) @@ -614,7 +735,7 @@ func (d *SelectDecl) pickIn() (int, bool) { switch { case index < count: d.state.Open = false - return index, true + return d.optionOf(index), true case index == count: // the trigger, when it is the page's own d.state.Open = !d.state.Open if d.state.Open { @@ -686,8 +807,15 @@ func (f *Frame) SelectPart(n *Node, i int) Rect { return Rect{} } d := &WidgetsOf(f).selects[n.Aux] - if d.rects < 0 || i < 0 || i >= len(d.labels) { + if d.rects < 0 || i < 0 || i >= len(d.labels) && !d.grouped { return Rect{} } + if d.grouped { + row := d.rowOf(i) + if row < 0 { + return Rect{} + } + i = row + } return WidgetsOf(f).rows[int(d.rects)+i] } diff --git a/base/slider.go b/base/slider.go index 49a39f699..a16667b4f 100644 --- a/base/slider.go +++ b/base/slider.go @@ -69,6 +69,7 @@ func (s *SliderState) ValueText() string { } type SliderDecl struct { + marks []SliderMark state *SliderState settled bool // the pointer and the range have been dealt with in this frame changed bool // the user changed the value in this frame @@ -114,6 +115,40 @@ func (f *Frame) SliderBase(ID gfx.ID, state *SliderState) Box { return b } +// SliderMark is a value of a Slider's range that is marked on its track, with a word +// under it when Label is not empty. +type SliderMark struct { + Value float32 + Label string +} + +// markLabelRoom is the height a Slider gets below its track when a mark has a label. +const markLabelRoom = 22 + +// Marks puts a dot on the track of a Slider at each value of marks, and the word of a +// mark under it, for a range whose values mean something ("Low", "High", the stops of +// a step). A horizontal Slider with a labeled mark is taller by the room the words +// take; a vertical one is marked with dots only. Keep the slice in the model: a slice +// made in each paint allocates in each paint. +// +// ui.Slider(c, &m.quality).Range(0, 100).Step(25).Marks(m.marks) +func (b Box) Marks(marks []SliderMark) Box { + if n := b.N(); n.Kind == kindSlider { + WidgetsOf(b.f).sliders[n.Aux].marks = marks + } + return b +} + +// hasMarkLabels reports whether any mark has a word. +func hasMarkLabels(marks []SliderMark) bool { + for _, mark := range marks { + if mark.Label != "" { + return true + } + } + return false +} + // Range sets the least and the greatest value of a Slider. func (b Box) Range(least, greatest float32) Box { if n := b.N(); n.Kind == kindSlider { @@ -153,6 +188,9 @@ func (f *Frame) MeasureSlider(n *Node) { n.Pref = [2]float32{sliderThickness, sliderLength} } else { n.Pref = [2]float32{sliderLength, sliderThickness} + if hasMarkLabels(WidgetsOf(f).sliders[n.Aux].marks) { + n.Pref[1] += markLabelRoom + } } } diff --git a/base/state_types.go b/base/state_types.go index b8b06671c..0eb803ab5 100644 --- a/base/state_types.go +++ b/base/state_types.go @@ -271,27 +271,42 @@ func (hover *IconHoverState) Progress(canvas *gfx.Canvas, id gfx.ID, slot uint8, // SonnerToast is one caller-owned toast snapshot plus stable interaction IDs. // The caller owns insertion, expiry, swipe state, and removal. type SonnerToast struct { - Snapshot ToastSnapshot - Scope gfx.ID - DismissID gfx.ID - ActionID gfx.ID + // Snapshot is the toast's text, kind and placement. + Snapshot ToastSnapshot + // Scope groups the toast's identities and its focus. + Scope gfx.ID + // DismissID names the close button; zero paints none. + DismissID gfx.ID + // ActionID names the action button; zero paints none. + ActionID gfx.ID + // ActionLabel is the action button's text; empty paints none. ActionLabel string - Disabled bool + // Disabled dims the toast and disables its action and close button. + Disabled bool } // ToastSnapshot is the complete caller-owned state painted for one frame. // Timing, expiry, swipe interpretation, and stack membership live outside the // component. type ToastSnapshot struct { - Title string + // Title is the toast's first line. + Title string + // Description is the smaller line under the title; empty paints none. Description string - Type ToastKind - Index uint16 - Expanded bool - Limited bool - OffsetY float32 - SwipeX float32 - SwipeY float32 + // Type selects the icon, its color, and the spinner. + Type ToastKind + // Index is how far the toast sits behind the front of its stack. + Index uint16 + // Expanded lays a stack out with a gap instead of a peek. + Expanded bool + // Limited marks a toast beyond the visible limit; it paints nothing. + Limited bool + // OffsetY is the caller's vertical snapshot offset. + OffsetY float32 + // SwipeX is the caller's horizontal drag snapshot. + SwipeX float32 + // SwipeY is the caller's vertical drag snapshot. + SwipeY float32 } // ToastQueueEntry is one live toast as the queue sees it. @@ -310,11 +325,11 @@ type toastQueueEntry struct { paused bool } -// ToastQueue is caller-owned toast lifetime policy: Base UI's five-second -// timeout, pause on hover/focus/window blur, loading toasts that do not expire, -// and a visible limit. It never starts a timer; the caller asks Expire when -// NextDeadline comes due and pauses or resumes as the pointer and focus move. -// Painting remains PaintSonner's job. +// ToastQueue is caller-owned toast lifetime policy: a default timeout (Base UI's +// five seconds), pause on hover/focus/window blur, loading toasts that do not +// expire, and a visible limit. AddFor gives one toast its own timeout. It never +// starts a timer; the caller asks Expire when NextDeadline comes due and pauses +// or resumes as the pointer and focus move. Painting remains PaintSonner's job. type ToastQueue struct { // Timeout is the lifetime of a new non-loading toast; zero means // ToastQueueTimeout. @@ -338,10 +353,16 @@ func (queue *ToastQueue) limit() int { return ToastQueueLimit } -// Add enqueues a toast. When the limit is full it drops the oldest and returns -// its ID so the caller can paint its exit. Add reports false for a zero ID or -// one that is already queued. +// Add enqueues a toast with the queue's Timeout. When the limit is full it +// drops the oldest and returns its ID so the caller can paint its exit. Add +// reports false for a zero ID or one that is already queued. func (queue *ToastQueue) Add(id gfx.ID, now time.Time, loading bool) (evicted gfx.ID, ok bool) { + return queue.AddFor(id, now, loading, 0) +} + +// AddFor is Add with a lifetime for this toast: timeout overrides the queue's +// Timeout when positive. A loading toast never expires whatever the timeout. +func (queue *ToastQueue) AddFor(id gfx.ID, now time.Time, loading bool, timeout time.Duration) (evicted gfx.ID, ok bool) { if id.IsZero() { return gfx.ID{}, false } @@ -356,7 +377,10 @@ func (queue *ToastQueue) Add(id gfx.ID, now time.Time, loading bool) (evicted gf } entry := toastQueueEntry{id: id, loading: loading} if !loading { - entry.deadline = now.Add(queue.timeout()) + if timeout <= 0 { + timeout = queue.timeout() + } + entry.deadline = now.Add(timeout) } queue.entries = append(queue.entries, entry) return evicted, true diff --git a/base/style.go b/base/style.go index 183a0bb9d..e3bfdfa67 100644 --- a/base/style.go +++ b/base/style.go @@ -221,6 +221,57 @@ func (b Box) TransitionWith(motion gfx.Motion) Box { return b } +// Glide makes the element, with everything inside it, slide to a new place when +// the layout moves it, over motion: a tab whose neighbour closed, a row dropped +// into a list. The layout is not animated and the element is hit where it is +// painted, which the last frame's place is until it arrives. An element needs a +// stable ID to glide, as a Transition does; one painted for the first time is +// simply there, and a canvas without a frame clock, or under reduced motion, +// places it at once. An idle element schedules nothing. +// +// scrolled is how far the content around the element is scrolled by something +// the framework does not own, such as tabs the application shifts sideways: a +// scroll is not a move, so the element's place is measured less it. Pass the +// zero Point where nothing scrolls. +func (b Box) Glide(motion gfx.Motion, scrolled gfx.Point) Box { + b.N() + extra := b.f.Extra(b.i) + extra.glide, extra.glided, extra.glideScroll = motion, true, scrolled + return b +} + +// Pose moves, scales, turns and fades the element, with everything inside it, to +// pose about its centre, over motion: a card lifted by the pointer, a chevron +// turned half way round, a row set a few pixels aside. The layout is not +// changed and the frames that move it only paint; the element is hit where it is +// drawn. The zero Pose is the element as laid out. It starts at its first pose, +// so one that appears does not move in, and keeps the velocity of a pose that +// changes on the way. The element needs a stable ID (a Hit, or a Key in a List); +// a canvas without a frame clock and a session under reduced motion show the +// pose at once. See gfx.Pose for what turning does to each kind of paint. +func (b Box) Pose(pose gfx.Pose, motion gfx.Motion) Box { + b.N() + extra := b.f.Extra(b.i) + extra.pose, extra.poseMotion, extra.posed = pose, motion, true + return b +} + +// Presence gives the element an entrance and an exit, as a dialog has: it fades +// and moves in the first time it is painted, and when it is no longer painted +// the canvas keeps drawing its last frame, fading and moving it out, until it is +// gone. The leaving element is only a picture: it has no hit regions, focus or +// accessibility node, and the layout no longer gives it room, so the elements +// after it close up at once, or glide if they have Glide. The element needs a +// stable ID (a Hit, or a Key in a List); one without has no exit. A canvas +// without a frame clock and a session under reduced motion paint it and drop it +// without motion. +func (b Box) Presence(presence gfx.Presence) Box { + b.N() + extra := b.f.Extra(b.i) + extra.presence, extra.presenced = presence, true + return b +} + // Opacity draws the element and everything inside it with its colors' opacity // multiplied by v, 0 to 1: its fill, border, shadow, ring, text, icons and the // controls inside it, which are painted with a theme faded the same way. The diff --git a/base/styles_test.go b/base/styles_test.go index 27b62bd4e..90dd464fd 100644 --- a/base/styles_test.go +++ b/base/styles_test.go @@ -41,7 +41,7 @@ func TestStylesReplaceThePageRecipes(t *testing.T) { Button(c, "Save") Checkbox(c, &on, "Remember") Switch(c, &on, "Sync") - TextFieldID(c, tree.ID(tree.Feature("styles"), "field"), &field, "Name", "") + TextField(c, &field, "Name", "", WithID(tree.ID(tree.Feature("styles"), "field"))) }) }) painted := make(map[gfx.Color]bool) diff --git a/base/table.go b/base/table.go index 532fee761..74f39a681 100644 --- a/base/table.go +++ b/base/table.go @@ -31,14 +31,14 @@ func (t *TableRows) Cell(row, column int) string { // TableSpec declares a Table. type TableSpec struct { // Rows names the rows: row i is Rows.At(i). Header names the header cells of - // the columns in Sortable: column c is Header.At(c). Header may be zero when + // the Sortable columns: column c is Header.At(c). Header may be zero when // nothing is sortable. Rows, Header gfx.Scope - // Columns are the widths and alignments, as for components.Table: a column - // without a width (the last) takes what is left. + // Columns are the columns, each with its Title, Width, Alignment and Sortable: + // a column without a width (the last) takes what is left, and a table none of + // whose columns has a width shares its width equally between them. A table none + // of whose columns has a Title has no header row. Columns []style.TableColumn - // Headers are the column titles; none means no header row. - Headers []string // FitHeadings widens each fixed-width column that is narrower than its // heading to the width the heading needs, so no heading is cut or ends in an // ellipsis, the page equivalent of fitting the component's headings. A @@ -47,10 +47,21 @@ type TableSpec struct { // size and cell padding, so a heading translated longer than a hand-written // width still fits. It applies to the preferred width and to painting. FitHeadings bool - // Sortable says which columns can be sorted by clicking their header (a nil - // slice, none); the Table shows the arrow of the one TableState says is sorted. - Sortable []bool - Source TableSource + Source TableSource + // Checked, when set, gives the table a leading column of checkboxes, one for each + // row, and a checkbox in the header that checks or clears every row: the rows + // checked are the keys of the Selection, the application's to read and to change. + // It is separate from the row the user has selected (TableState.Selected), as the + // ticks of a file list are from its highlighted row. The column is not one of + // Columns: the indexes of Source.Cell, Header and TableState.SortBy stay those of + // Columns. + Checked *Selection + // SelectAllLabel and SelectRowLabel are the accessible names of the header's + // checkbox and of a row's, "Select all rows" and "Select row" when empty. + SelectAllLabel, SelectRowLabel string + // FilterLabel is the accessible name of a column's filter button, "Filter" when + // empty; the column's title is its description. + FilterLabel string // RowHeight is the height of every row, header included; zero takes the // theme's TableRowHeight and TableHeaderHeight. RowHeight float32 @@ -120,14 +131,23 @@ type TableState struct { selected int32 // 1 + the row, or 0 // changed is a selection the user made, reported by Changed in the paint // changedAt: the one a click is delivered in, or the one after a key. - changed bool - changedAt uint32 - sortColumn int32 // 1 + the column, or 0 - descending bool - reveal bool // scroll the selected row into view at the next paint - rows, page int32 // as of the last paint: how many rows, how many fit at once - rowFirst, rowEnd int32 // the declared source rows: rowFirst <= i < rowEnd - scope gfx.Scope // the rows' identities, to tell a key meant for the table + changed bool + changedAt uint32 + sortColumn int32 // 1 + the column, or 0 + descending bool + reveal bool // scroll the selected row into view at the next paint + rows, page int32 // as of the last paint: how many rows, how many fit at once + lead int32 // 1 when the last paint had a column of checkboxes in front + // checkedChanged is whether the paint being declared delivered a tick or untick: + // see CheckedChanged. + checkedChanged bool + // checkDone is the checkbox whose click this paint has already applied, so a + // table painted in two passes (frozen columns) applies it once. + checkDone gfx.ID + // headerY and headerHeight are where the header was painted last, for HeaderRect. + headerY, headerHeight float32 + rowFirst, rowEnd int32 // the declared source rows: rowFirst <= i < rowEnd + scope gfx.Scope // the rows' identities, to tell a key meant for the table // cellLefts are the painted columns' left edges and the last column's right // edge, and cellTop and cellRowHeight the first visible row's top and every // row's height, as of the last paint; see CellRect. They keep their @@ -246,9 +266,18 @@ type TableDecl struct { // and paints from. It keeps its capacity across frames, so a warm table // fits no heading into a new allocation. columns []style.TableColumn - // even is a table declared with Headers and no Columns: its columns share its + // lead is 1 when the table has a column of checkboxes in front of its Columns, + // and userColumns the Columns the application declared, which spec.Columns + // follows from with that column in front. withLead is the buffer it is built in. + lead int + userColumns []style.TableColumn + withLead []style.TableColumn + // even is a table none of whose columns has a width: its columns share its // width equally, the last taking what rounding leaves. even bool + // titles are the columns' titles, in the order of the columns, for the header + // row. It keeps its capacity across frames. + titles []string // fontSize and foreground are the element's explicit text style: what the // recipe's spec default is replaced with when the element set one. fontSize float32 @@ -276,7 +305,7 @@ type TableDecl struct { // what is left, however narrow that is. A table inside a ScrollArea is never // scrolled across by itself; the area owns its width, sideways or not. // -// tbl := f.Table(&state, ui.TableSpec{Rows: rows, Header: heads, Columns: cols, Headers: titles, Sortable: sortable, Source: &data}) +// tbl := f.Table(&state, ui.TableSpec{Rows: rows, Header: heads, Columns: cols, Source: &data}) // if row, ok := tbl.RowClicked(); ok { state.Select(row) } // if col, ok := tbl.HeaderClicked(); ok { state.SortBy(col); data.Sort(state.Sort()) } func (f *Frame) Table(state *TableState, spec TableSpec) Box { @@ -289,13 +318,22 @@ func (f *Frame) Table(state *TableState, spec TableSpec) Box { if spec.Source != nil { rows = max(spec.Source.Len(), 0) } - decl := TableDecl{spec: spec, state: state, rows: rows} - if (spec.FitHeadings || len(spec.Columns) == 0) && index < cap(*decls) { - // Reuse the fitted columns of this table from the last paint even though - // the fit itself waits for the element's FontSize in resolveTables. - decl.columns = (*decls)[:cap(*decls)][index].columns + decl := TableDecl{spec: spec, state: state, rows: rows, userColumns: spec.Columns} + state.checkedChanged, state.checkDone = false, gfx.ID{} + if index < cap(*decls) { + // Reuse the titles, and the fitted columns of a table that fits or shares, + // of this table from the last paint even though the fit itself waits for + // the element's FontSize in resolveTables. + last := &(*decls)[:cap(*decls)][index] + decl.titles, decl.withLead = last.titles, last.withLead + if spec.FitHeadings || tableColumnsShare(spec.Columns) { + decl.columns = last.columns + } } *decls = append(*decls, decl) + if spec.Checked != nil { + f.applyCheckClick(&(*decls)[index]) + } return b } @@ -309,6 +347,7 @@ func (f *Frame) resolveTables() { continue } decl := &(*decls)[n.Aux] + decl.spec.Columns = decl.userColumns decl.fontSize = decl.spec.FontSize if n.FontSet { decl.fontSize = n.FontSize @@ -316,21 +355,46 @@ func (f *Frame) resolveTables() { if n.Flags&flagHasColor != 0 { decl.foreground, decl.hasForeground = n.Color, true } - if len(decl.spec.Columns) == 0 && len(decl.spec.Headers) > 0 { + decl.titles = decl.titles[:0] + for _, column := range decl.spec.Columns { + decl.titles = append(decl.titles, column.Title) + } + if tableColumnsShare(decl.spec.Columns) { // Columns are shared out when the table's width is known (paintTable); - // until then each is one that takes what is left. - decl.columns = append(decl.columns[:0], make([]style.TableColumn, len(decl.spec.Headers))...) - clear(decl.columns) + // the declared ones are left as the application wrote them. + decl.columns = append(decl.columns[:0], decl.spec.Columns...) decl.spec.Columns, decl.even = decl.columns, true + decl.addLead() continue } if !decl.spec.FitHeadings || f.Surface == nil || len(decl.spec.Columns) == 0 { + decl.addLead() continue } decl.columns = append(decl.columns[:0], decl.spec.Columns...) - fitTableHeadings(f.Surface, f.Palette, decl.columns, decl.spec.Headers, decl.fontSize, decl.spec.CellPadding) + fitTableHeadings(f.Surface, f.Palette, decl.columns, decl.fontSize, decl.spec.CellPadding) decl.spec.Columns = decl.columns + decl.addLead() + } +} + +// tableCheckWidth is the width of the column of checkboxes. +const tableCheckWidth = 40 + +// addLead puts the column of checkboxes in front of the columns and the title +// that goes with it in front of the titles, for a table given Checked. +func (t *TableDecl) addLead() { + t.lead = 0 + if t.spec.Checked == nil { + return } + t.lead = 1 + t.withLead = append(t.withLead[:0], style.TableColumn{Width: tableCheckWidth, Alignment: style.TableAlignCenter}) + t.withLead = append(t.withLead, t.spec.Columns...) + t.spec.Columns = t.withLead + t.titles = append(t.titles, "") + copy(t.titles[1:], t.titles) + t.titles[0] = "" } // fitTableHeadings widens each fixed-width column of columns that is narrower @@ -339,7 +403,7 @@ func (f *Frame) resolveTables() { // column without a heading keep their width. The heading is measured at the // table's own font size and cell padding; a heading of a column too wide for // the room left is still ellipsized. -func fitTableHeadings(canvas *gfx.Canvas, palette Theme, columns []style.TableColumn, headings []string, fontSize, cellPadding float32) { +func fitTableHeadings(canvas *gfx.Canvas, palette Theme, columns []style.TableColumn, fontSize, cellPadding float32) { size := fontSize if size <= 0 { size = palette.Metrics.FontSizeM @@ -350,10 +414,10 @@ func fitTableHeadings(canvas *gfx.Canvas, palette Theme, columns []style.TableCo } for index := range columns { column := &columns[index] - if column.Width <= 0 || index >= len(headings) || headings[index] == "" { + if column.Width <= 0 || column.Title == "" { continue } - need := canvas.TextWidthWeight(headings[index], size, gfx.WeightMedium) + need := canvas.TextWidthWeight(column.Title, size, gfx.WeightMedium) inset := float32(0) if column.Alignment == style.TableAlignLeft { inset = max(column.Inset, 0) + max(column.EndInset, 0) @@ -382,6 +446,28 @@ func (b Box) HeaderClicked() (int, bool) { return b.f.Surface.ClickedIn(WidgetsOf(b.f).tables[n.Aux].spec.Header) } +// FilterClicked reports which column's filter button this paint is delivering a +// press on (see TableColumn.Filterable): the index in Columns. The application opens +// its choice of what to show, anchored at TableState.HeaderRect. +func (b Box) FilterClicked() (int, bool) { + n := b.N() + if n.Kind != kindTable || b.f.Surface == nil { + return 0, false + } + t := &WidgetsOf(b.f).tables[n.Aux] + for column := t.lead; column < len(t.spec.Columns); column++ { + if t.spec.Columns[column].Filterable && b.f.Surface.Clicked(FilterID(b.f.Surface, t.spec.Header, column-t.lead)) { + return column - t.lead, true + } + } + return 0, false +} + +// FilterID names the filter button of a column, in a scope inside the header's. +func FilterID(canvas *gfx.Canvas, header gfx.Scope, column int) gfx.ID { + return canvas.Tree().Sub(header, gfx.Index(1<<30)).At(column) +} + // measureTable: as wide as its fixed columns, as tall as its header and rows. func (f *Frame) measureTable(n *Node) { t := &WidgetsOf(f).tables[n.Aux] @@ -461,8 +547,10 @@ func (f *Frame) paintTable(n *Node) { // and never inside a ScrollArea, whose viewport (sideways or not) owns the // table's width; such a table is only ever clipped. if t.even { - share := float32(math.Floor(float64(r.Width / float32(len(t.spec.Columns))))) - for i := range t.spec.Columns[:len(t.spec.Columns)-1] { + // The columns after the column of checkboxes share what it leaves. + room := r.Width - tableColumnsWidth(t.spec.Columns[:t.lead]) + share := float32(math.Floor(float64(room / float32(len(t.spec.Columns)-t.lead)))) + for i := t.lead; i < len(t.spec.Columns)-1; i++ { t.spec.Columns[i].Width = share } } @@ -524,7 +612,7 @@ func (f *Frame) paintTable(n *Node) { frozenWidth := float32(0) frozenColumns := 0 if sideways { - frozenColumns = frozenColumnCount(t.spec.Columns, t.spec.FrozenColumns) + frozenColumns = frozenColumnCount(t.spec.Columns, t.spec.FrozenColumns+min(t.lead, t.spec.FrozenColumns)) frozenWidth = frozenColumnsWidth(t.spec.Columns, frozenColumns) if frozenWidth <= 0 || frozenWidth >= body.Width { frozenWidth, frozenColumns = 0, 0 @@ -546,11 +634,13 @@ func (f *Frame) paintTable(n *Node) { // A header that has scrolled above the visible area stays at its top, until the // last row would push it out. headerY := r.Y + t.state.headerHeight = headerHeight sticky := !scrolls && headerHeight > 0 && r.Y < clipTop if sticky { headerY = min(clipTop, r.Y+r.Height-headerHeight) lo = max(lo, headerY+headerHeight) } + t.state.headerY = headerY t.state.page = int32(max(int((hi-lo)/rowHeight), 1)) first, last := 0, 0 if hi > lo && t.rows > 0 { @@ -692,8 +782,32 @@ func (t *TableDecl) rowHeight(Palette Theme) float32 { return TableRowHeight(Palette) } +// hasHeader reports whether any column has a title to draw. +func (t *TableDecl) hasHeader() bool { + for _, column := range t.spec.Columns { + if column.Title != "" { + return true + } + } + return false +} + +// tableColumnsShare reports whether a table's columns share its width equally: it +// has some and none has a width of its own. +func tableColumnsShare(columns []style.TableColumn) bool { + if len(columns) == 0 { + return false + } + for _, column := range columns { + if column.Width > 0 { + return false + } + } + return true +} + func (t *TableDecl) headerHeight(Palette Theme) float32 { - if len(t.spec.Headers) == 0 { + if !t.hasHeader() { return 0 } if t.spec.RowHeight > 0 { diff --git a/base/table_check.go b/base/table_check.go new file mode 100644 index 000000000..e0ea132f5 --- /dev/null +++ b/base/table_check.go @@ -0,0 +1,90 @@ +package base + +import "github.com/vivaui/viva/gfx" + +// CheckedChanged reports whether the paint being declared delivered a tick or an +// untick in the table's column of checkboxes (TableSpec.Checked). Like Changed, it +// is true in the paint that finds the click and false in the paint after it. +func (s *TableState) CheckedChanged() bool { return s.checkedChanged } + +// GetLead is 1 when the table has a column of checkboxes in front of its columns. +func (t *TableDecl) GetLead() int { return t.lead } + +// ToggleRow ticks a row that is not ticked and unticks one that is. +func (t *TableDecl) ToggleRow(id gfx.ID, row int) { + if sel := t.spec.Checked; sel != nil && t.state.checkDone != id { + t.state.checkDone = id + if sel.Has(row) { + sel.Remove(row) + } else { + sel.Add(row) + } + t.state.checkedChanged = true + } +} + +// ToggleAll ticks every row when some are not ticked, and clears them when all are. +func (t *TableDecl) ToggleAll(id gfx.ID) { + sel := t.spec.Checked + if sel == nil || t.state.checkDone == id { + return + } + t.state.checkDone = id + if t.AllChecked() { + sel.Clear() + } else { + for row := 0; row < t.rows; row++ { + sel.Add(row) + } + } + t.state.checkedChanged = true +} + +// AllChecked reports whether the table has rows and every one is ticked: the +// Selection holds as many keys as there are rows. The keys of a table's Selection +// are its row numbers, and the application takes the ones of rows that are gone out. +func (t *TableDecl) AllChecked() bool { + return t.spec.Checked != nil && t.rows > 0 && t.spec.Checked.Len() >= t.rows +} + +// SomeChecked reports whether any row is ticked. +func (t *TableDecl) SomeChecked() bool { return t.spec.Checked != nil && t.spec.Checked.Len() > 0 } + +// checks is the scope of a table's checkboxes, inside the scope of its rows: the +// header's is item 0 and the checkbox of row r is item r+1. +func checks(canvas *gfx.Canvas, rows gfx.Scope) gfx.Scope { + return canvas.Tree().Sub(rows, gfx.Index(1<<30)) +} + +// CheckID names the checkbox of a row. +func CheckID(canvas *gfx.Canvas, rows gfx.Scope, row int) gfx.ID { + return checks(canvas, rows).At(row + 1) +} + +// HeaderCheckID names the checkbox of the header. +func HeaderCheckID(canvas *gfx.Canvas, rows gfx.Scope) gfx.ID { + return checks(canvas, rows).At(0) +} + +// applyCheckClick applies the click this paint is delivering, when it is on one of +// the table's checkboxes, as the declaration reads the click on a row. The rows +// that can have been clicked are the ones the last paint put on screen. +func (f *Frame) applyCheckClick(t *TableDecl) { + if f.Surface == nil { + return + } + id, ok := f.Surface.ClickTarget() + if !ok || id.IsZero() { + return + } + if id == HeaderCheckID(f.Surface, t.spec.Rows) { + t.ToggleAll(id) + return + } + for row := int(t.state.rowFirst); row < int(t.state.rowEnd); row++ { + if id == CheckID(f.Surface, t.spec.Rows, row) { + t.ToggleRow(id, row) + return + } + } +} diff --git a/base/table_columns_external_test.go b/base/table_columns_external_test.go new file mode 100644 index 000000000..5d15943d1 --- /dev/null +++ b/base/table_columns_external_test.go @@ -0,0 +1,18 @@ +package base_test + +import "github.com/vivaui/viva/style" + +// titledColumns is columns with the titles and the sortable flags a test keeps in +// slices of their own, one per column; a nil columns is one column of no width for +// each title. +func titledColumns(columns []style.TableColumn, titles []string, sortable []bool) []style.TableColumn { + out := make([]style.TableColumn, max(len(columns), len(titles))) + copy(out, columns) + for i, title := range titles { + out[i].Title = title + } + for i := range min(len(sortable), len(out)) { + out[i].Sortable = sortable[i] + } + return out +} diff --git a/base/table_columns_test.go b/base/table_columns_test.go new file mode 100644 index 000000000..3d480f802 --- /dev/null +++ b/base/table_columns_test.go @@ -0,0 +1,18 @@ +package base + +import "github.com/vivaui/viva/style" + +// titledColumns is columns with the titles and the sortable flags a test keeps in +// slices of their own, one per column; a nil columns is one column of no width for +// each title. +func titledColumns(columns []style.TableColumn, titles []string, sortable []bool) []style.TableColumn { + out := make([]style.TableColumn, max(len(columns), len(titles))) + copy(out, columns) + for i, title := range titles { + out[i].Title = title + } + for i := range min(len(sortable), len(out)) { + out[i].Sortable = sortable[i] + } + return out +} diff --git a/base/table_element_style_test.go b/base/table_element_style_test.go index 5f1e4c3a0..7a3cab5f0 100644 --- a/base/table_element_style_test.go +++ b/base/table_element_style_test.go @@ -14,8 +14,7 @@ func TestTableElementTextStyleReachesHeaderAndCells(t *testing.T) { theme := gfx.LightTheme() ink := gfx.Color{Red: 1, Alpha: 1} spec := TableSpec{ - Columns: []style.TableColumn{{Width: 120}}, - Headers: []string{"Name"}, + Columns: []style.TableColumn{{Title: "Name", Width: 120}}, Source: &countingRows{n: 2}, } paint := func(declare func(f *Frame) Box) ([]gfx.Text, Rect) { @@ -54,8 +53,7 @@ func TestTableElementTextStyleReachesHeaderAndCells(t *testing.T) { // The element's FontSize replaces the spec's, rather than adding to it. func TestTableElementFontSizeWinsOverTheSpec(t *testing.T) { spec := TableSpec{ - Columns: []style.TableColumn{{Width: 120}}, - Headers: []string{"Name"}, + Columns: []style.TableColumn{{Title: "Name", Width: 120}}, Source: &countingRows{n: 1}, FontSize: 12, } diff --git a/base/table_fitheadings_test.go b/base/table_fitheadings_test.go index 07545be3c..720e14520 100644 --- a/base/table_fitheadings_test.go +++ b/base/table_fitheadings_test.go @@ -25,8 +25,10 @@ func TestTableFitHeadingsGrowsFixedColumnsToTheirHeadings(t *testing.T) { view.Draw(testCanvas(), theme, gfx.Rect{Width: 500, Height: 200}, func(f *Frame) { f.Column().Fill().Children(func() { f.Table(&state, TableSpec{ - Rows: tableScope, Columns: columns, Headers: headings, - Source: &source, FitHeadings: true, + Rows: tableScope, + Columns: titledColumns(columns, headings, nil), + Source: &source, + FitHeadings: true, }) }) }) @@ -59,6 +61,7 @@ func TestTableFitHeadingsAllocatesNothingOnceWarm(t *testing.T) { theme := gfx.LightTheme() columns := []style.TableColumn{{Width: 12}, {Width: 12}, {Width: 0}} headings := []string{"Long heading", "B", "C"} + titled := titledColumns(columns, headings, nil) source := TableRows{{"a", "b", "c"}} var state TableState var view View @@ -68,8 +71,10 @@ func TestTableFitHeadingsAllocatesNothingOnceWarm(t *testing.T) { view.Draw(canvas, theme, gfx.Rect{Width: 400, Height: 200}, func(f *Frame) { f.Column().Fill().Children(func() { f.Table(&state, TableSpec{ - Rows: tableScope, Columns: columns, Headers: headings, - Source: &source, FitHeadings: true, + Rows: tableScope, + Columns: titled, + Source: &source, + FitHeadings: true, }) }) }) @@ -79,3 +84,32 @@ func TestTableFitHeadingsAllocatesNothingOnceWarm(t *testing.T) { t.Fatalf("a warm table that fits its headings allocates %v times a frame, want 0", allocs) } } + +// A table none of whose columns has a width shares its own width between them, and +// leaves the columns the application declared as it wrote them. +func TestTableSharedColumnsLeaveTheDeclaredOnesAlone(t *testing.T) { + columns := []style.TableColumn{{Title: "A"}, {Title: "B"}, {Title: "C"}} + source := TableRows{{"a", "b", "c"}} + var state TableState + var view View + canvas := testCanvas() + view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 300, Height: 200}, func(f *Frame) { + f.Column().Fill().Children(func() { + f.Table(&state, TableSpec{Rows: tableScope, Columns: columns, Source: &source}) + }) + }) + for i, column := range columns { + if column.Width != 0 { + t.Fatalf("column %d was given a width of %v in the application's slice", i, column.Width) + } + } + cells := map[float32]bool{} + for _, text := range canvas.Texts() { + if text.Value == "a" || text.Value == "b" || text.Value == "c" { + cells[text.Bounds.X] = true + } + } + if len(cells) != 3 { + t.Fatalf("the three cells of the row start at %d distinct positions, want 3", len(cells)) + } +} diff --git a/base/table_frozen_test.go b/base/table_frozen_test.go index 3a541406b..4c7ef99cc 100644 --- a/base/table_frozen_test.go +++ b/base/table_frozen_test.go @@ -10,8 +10,11 @@ import ( // first two frozen: 240 pinned at the left edge, 480 scrolling past them. func frozenSpec(state *TableState, rows TableSource) TableSpec { return TableSpec{ - Rows: tableScope, Header: headerScope, Columns: wideSixColumns, Headers: sixTitles, - Sortable: allSortableSix, Source: rows, FrozenColumns: 2, + Rows: tableScope, + Header: headerScope, + Columns: titledColumns(wideSixColumns, sixTitles, allSortableSix), + Source: rows, + FrozenColumns: 2, } } @@ -254,12 +257,12 @@ func TestFrozenTableAllocatesNothingOnceWarm(t *testing.T) { var state TableState canvas := testCanvas() var view View + spec := frozenSpec(&state, rows) + spec.Scrollbar, spec.HorizontalScrollbar = gfx.Item(900), gfx.Item(901) paint := func() { canvas.Reset() view.Draw(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { f.Column().Fill().Children(func() { - spec := frozenSpec(&state, rows) - spec.Scrollbar, spec.HorizontalScrollbar = gfx.Item(900), gfx.Item(901) f.Table(&state, spec).Fill() }) }) diff --git a/base/table_scroll_horizontal_test.go b/base/table_scroll_horizontal_test.go index 327b13d56..34ecb2ad3 100644 --- a/base/table_scroll_horizontal_test.go +++ b/base/table_scroll_horizontal_test.go @@ -39,7 +39,7 @@ func TestTableScrollsItsColumnsWhenTheyDoNotFit(t *testing.T) { paint := func() { view.Draw(canvas, theme, gfx.Rect{Width: viewport.Width, Height: viewport.Height}, func(f *Frame) { f.Column().Fill().Children(func() { - f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: wideFourColumns, Headers: fourTitles, Sortable: []bool{true, false, false, false}, Source: &rows}).Size(viewport.Width, viewport.Height) + f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: titledColumns(wideFourColumns, fourTitles, []bool{true, false, false, false}), Source: &rows}).Size(viewport.Width, viewport.Height) }) }) headerX, rowX = headerAndRowX(canvas) @@ -106,7 +106,7 @@ func TestTableWheelScrollsBothWays(t *testing.T) { canvas.Reset() view.Draw(canvas, theme, gfx.Rect{Width: viewport.Width, Height: viewport.Height}, func(f *Frame) { f.Column().Fill().Children(func() { - f.Table(&state, TableSpec{Rows: tableScope, Columns: wideFourColumns, Headers: fourTitles, Source: &rows}).Size(viewport.Width, viewport.Height) + f.Table(&state, TableSpec{Rows: tableScope, Columns: titledColumns(wideFourColumns, fourTitles, nil), Source: &rows}).Size(viewport.Width, viewport.Height) }) }) } @@ -158,7 +158,7 @@ func TestTableThatFitsDoesNotScrollAcross(t *testing.T) { canvas.Reset() view.Draw(canvas, theme, gfx.Rect{Width: viewport.Width, Height: viewport.Height}, func(f *Frame) { f.Column().Fill().Children(func() { - f.Table(&state, TableSpec{Rows: tableScope, Columns: c.columns, Headers: headers, Source: &rows}).Size(viewport.Width, viewport.Height) + f.Table(&state, TableSpec{Rows: tableScope, Columns: titledColumns(c.columns, headers, nil), Source: &rows}).Size(viewport.Width, viewport.Height) }) }) } @@ -200,7 +200,7 @@ func TestTableInAScrollAreaLeavesAcrossToTheArea(t *testing.T) { area = area.Sideways() } area.Children(func() { - f.Table(&state, TableSpec{Rows: tableScope, Columns: wideFourColumns, Headers: fourTitles, Source: &rows}) + f.Table(&state, TableSpec{Rows: tableScope, Columns: titledColumns(wideFourColumns, fourTitles, nil), Source: &rows}) }) }) }) @@ -239,8 +239,10 @@ func TestTableHorizontalScrollbarDrags(t *testing.T) { view.Draw(canvas, theme, gfx.Rect{Width: viewport.Width, Height: viewport.Height}, func(f *Frame) { f.Column().Fill().Children(func() { f.Table(&state, TableSpec{ - Rows: tableScope, Header: headerScope, Columns: wideFourColumns, - Headers: fourTitles, Sortable: []bool{true, true, true, true}, Source: &rows, + Rows: tableScope, + Header: headerScope, + Columns: titledColumns(wideFourColumns, fourTitles, []bool{true, true, true, true}), + Source: &rows, HorizontalScrollbar: gfx.Item(901), }).Size(viewport.Width, viewport.Height) }) @@ -303,11 +305,12 @@ func TestWideTableAllocatesNothingOnceWarm(t *testing.T) { var view View var state TableState canvas := testCanvas() + columns := titledColumns(wideSixColumns, sixTitles, allSortableSix) paint := func() { canvas.Reset() view.Draw(canvas, theme, gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { f.Column().Fill().Children(func() { - f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: wideSixColumns, Headers: sixTitles, Sortable: allSortableSix, Striped: true, Source: rows, Scrollbar: gfx.Item(900), HorizontalScrollbar: gfx.Item(901)}).Fill() + f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: columns, Striped: true, Source: rows, Scrollbar: gfx.Item(900), HorizontalScrollbar: gfx.Item(901)}).Fill() }) }) } @@ -335,7 +338,7 @@ func BenchmarkWideTable(b *testing.B) { canvas.Reset() view.Draw(canvas, theme, gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { f.Column().Fill().Children(func() { - f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: wideSixColumns, Headers: sixTitles, Sortable: allSortableSix, Striped: true, Source: rows, Scrollbar: gfx.Item(900), HorizontalScrollbar: gfx.Item(901)}).Fill() + f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: titledColumns(wideSixColumns, sixTitles, allSortableSix), Striped: true, Source: rows, Scrollbar: gfx.Item(900), HorizontalScrollbar: gfx.Item(901)}).Fill() }) }) } @@ -362,10 +365,14 @@ func TestTableHorizontalBarKeepsTheGutterStripAndClearRows(t *testing.T) { View.Draw(Surface, theme, gfx.Rect{Width: viewport.Width, Height: viewport.Height}, func(f *Frame) { f.Column().Fill().Children(func() { f.Table(state, TableSpec{ - Rows: tableScope, Columns: gutterColumns, Headers: []string{"A", "B", "C"}, - Source: &rows, RowHeight: 30, - Scrollbar: gfx.Item(900), HorizontalScrollbar: gfx.Item(901), - ScrollbarSize: 12, ScrollbarGutter: gutter, + Rows: tableScope, + Columns: titledColumns(gutterColumns, []string{"A", "B", "C"}, nil), + Source: &rows, + RowHeight: 30, + Scrollbar: gfx.Item(900), + HorizontalScrollbar: gfx.Item(901), + ScrollbarSize: 12, + ScrollbarGutter: gutter, }).Size(viewport.Width, viewport.Height) }) }) diff --git a/base/table_test.go b/base/table_test.go index fd497ca8d..1520f8544 100644 --- a/base/table_test.go +++ b/base/table_test.go @@ -96,7 +96,7 @@ func TestTableIsPaintedLikeTheComponent(t *testing.T) { var view View view.Draw(flexed, theme, gfx.Rect{Width: 320, Height: height}, func(f *Frame) { f.Column().Children(func() { - f.Table(&state, TableSpec{Rows: tableScope, Columns: tableColumns, Headers: titles, Source: &data}).Height(height) + f.Table(&state, TableSpec{Rows: tableScope, Columns: titledColumns(tableColumns, titles, nil), Source: &data}).Height(height) }) }) table := components.BeginTable(direct, theme, gfx.Rect{Width: 320, Height: height}, tableColumns) @@ -125,8 +125,11 @@ func TestTableSpecTypographyMatchesTheComponent(t *testing.T) { view.Draw(flexed, theme, gfx.Rect{Width: 240, Height: height}, func(f *Frame) { f.Column().Children(func() { f.Table(&state, TableSpec{ - Rows: tableScope, Columns: columns, Headers: titles, Source: &data, - FontSize: size, CellPadding: padding, + Rows: tableScope, + Columns: titledColumns(columns, titles, nil), + Source: &data, + FontSize: size, + CellPadding: padding, }).Height(height) }) }) @@ -153,8 +156,11 @@ func TestTableSpecFontSizeSizesTheSortArrow(t *testing.T) { view.Draw(canvas, theme, gfx.Rect{Width: 240, Height: 160}, func(f *Frame) { f.Column().Children(func() { f.Table(&state, TableSpec{ - Rows: tableScope, Header: headerScope, Columns: columns, Headers: cells, - Sortable: sortable, Source: &data, FontSize: size, + Rows: tableScope, + Header: headerScope, + Columns: titledColumns(columns, cells, sortable), + Source: &data, + FontSize: size, }).Height(160) }) }) @@ -197,7 +203,7 @@ func TestTableInAScrollAreaPaintsOnlyTheRowsOnScreen(t *testing.T) { view.Draw(Surface, theme, gfx.Rect{Width: 400, Height: 300}, func(f *Frame) { f.Column().Fill().Children(func() { f.ScrollArea(listID).Grow(1).Children(func() { - table = f.Table(&state, TableSpec{Rows: tableScope, Columns: tableColumns[:2], Headers: []string{"A", "B"}, Source: rows}) + table = f.Table(&state, TableSpec{Rows: tableScope, Columns: titledColumns(tableColumns[:2], []string{"A", "B"}, nil), Source: rows}) }) }) }) @@ -237,7 +243,7 @@ func TestTableWithAHeightScrollsItsRowsUnderTheHeader(t *testing.T) { var view View view.Draw(canvas, theme, gfx.Rect{Width: 300, Height: 200}, func(f *Frame) { f.Column().Children(func() { - f.Table(&state, TableSpec{Rows: tableScope, Columns: tableColumns[:2], Headers: []string{"A", "B"}, Source: rows}).Height(200) + f.Table(&state, TableSpec{Rows: tableScope, Columns: titledColumns(tableColumns[:2], []string{"A", "B"}, nil), Source: rows}).Height(200) }) }) return canvas @@ -279,7 +285,7 @@ func TestTableHeaderClicksSortAndShowTheArrow(t *testing.T) { var view View view.Draw(Surface, theme, gfx.Rect{Width: 300, Height: 200}, func(f *Frame) { f.Column().Children(func() { - tbl := f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: tableColumns[:2], Headers: []string{"Name", "N"}, Sortable: []bool{true, false}, Source: &data}) + tbl := f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: titledColumns(tableColumns[:2], []string{"Name", "N"}, []bool{true, false}), Source: &data}) if c, ok := tbl.HeaderClicked(); ok { column = c } @@ -341,12 +347,13 @@ func TestTableAllocatesNothingOnceWarm(t *testing.T) { rows := &countingRows{n: 10000} var state TableState state.SortBy(1) + columns := titledColumns(tableColumns, tableTitles, allSortable) run := func() { canvas.Reset() view.Draw(canvas, theme, gfx.Rect{Width: 500, Height: 400}, func(f *Frame) { f.Column().Fill().Children(func() { f.ScrollArea(listID).Grow(1).Children(func() { - f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: tableColumns, Headers: tableTitles, Sortable: allSortable, Striped: true, Source: rows}) + f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: columns, Striped: true, Source: rows}) }) }) }) @@ -372,7 +379,7 @@ func BenchmarkTenThousandRowTable(b *testing.B) { view.Draw(canvas, theme, gfx.Rect{Width: 800, Height: 600}, func(f *Frame) { f.Column().Fill().Children(func() { f.ScrollArea(listID).Grow(1).Children(func() { - f.Table(&state, TableSpec{Rows: tableScope, Columns: tableColumns, Headers: tableTitles, Source: rows}) + f.Table(&state, TableSpec{Rows: tableScope, Columns: titledColumns(tableColumns, tableTitles, nil), Source: rows}) }) }) }) @@ -391,7 +398,7 @@ func TestTableKeysMoveTheSelectionAndScrollItIntoView(t *testing.T) { var view View view.Draw(canvas, theme, gfx.Rect{Width: 300, Height: 200}, func(f *Frame) { f.Column().Children(func() { - f.Table(&state, TableSpec{Rows: tableScope, Columns: tableColumns[:2], Headers: []string{"A", "B"}, Source: rows}).Height(200) + f.Table(&state, TableSpec{Rows: tableScope, Columns: titledColumns(tableColumns[:2], []string{"A", "B"}, nil), Source: rows}).Height(200) }) }) return canvas @@ -451,7 +458,7 @@ func TestTableInAScrollAreaKeepsItsHeaderAndKeysScrollTheArea(t *testing.T) { f.Column().Fill().Children(func() { f.ScrollArea(listID).Grow(1).Children(func() { f.Text("above the table").Height(40) - f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: tableColumns[:2], Headers: []string{"A", "B"}, Sortable: []bool{true, true}, Source: rows}) + f.Table(&state, TableSpec{Rows: tableScope, Header: headerScope, Columns: titledColumns(tableColumns[:2], []string{"A", "B"}, []bool{true, true}), Source: rows}) }) }) }) diff --git a/base/tablecell.go b/base/tablecell.go index 16247f854..77a81f773 100644 --- a/base/tablecell.go +++ b/base/tablecell.go @@ -22,7 +22,23 @@ import ( // The header is not a cell and has no source row: it has no rectangle here. // Declaring the same state in more than one table leaves the calls describing // only the last table painted. +// HeaderRect is the rectangle of the heading of a column (an index in Columns) as +// the last paint put it, for the application to anchor a menu to. ok is false before +// the first paint, for a column that is not painted, and for a table with no header. +func (s *TableState) HeaderRect(column int) (gfx.Rect, bool) { + column += int(s.lead) + if column < 0 || column+1 >= len(s.cellLefts) || s.headerHeight <= 0 { + return gfx.Rect{}, false + } + left, right := s.cellLefts[column], s.cellLefts[column+1] + if right <= left { + return gfx.Rect{}, false + } + return gfx.Rect{X: left, Y: s.headerY, Width: right - left, Height: s.headerHeight}, true +} + func (s *TableState) CellRect(row, column int) (gfx.Rect, bool) { + column += int(s.lead) // a column of checkboxes comes before the columns the application declared if row < int(s.rowFirst) || row >= int(s.rowEnd) || column < 0 || column+1 >= len(s.cellLefts) { return gfx.Rect{}, false } @@ -45,6 +61,7 @@ func (s *TableState) CellRect(row, column int) (gfx.Rect, bool) { // the rest follow the offset the rows were painted at. func (f *Frame) RecordTableCells(t *TableDecl, body Rect, left, top, contentWidth, rowHeight float32, frozenColumns int, frozenWidth float32) { state := t.state + state.lead = int32(t.lead) state.cellLefts = state.cellLefts[:0] state.cellTop, state.cellRowHeight = top, rowHeight if len(t.spec.Columns) == 0 || rowHeight <= 0 { diff --git a/base/tablecell_test.go b/base/tablecell_test.go index 57a37843a..8b7452587 100644 --- a/base/tablecell_test.go +++ b/base/tablecell_test.go @@ -56,7 +56,8 @@ var cellColumns = []components.TableColumn{{Width: 120}, {Width: 90}, {Width: 10 func TestTableCellsAreWhereTheRowsWerePainted(t *testing.T) { const width, height = float32(400), float32(300) table := newCellTable(20, TableSpec{ - Rows: tableScope, Columns: cellColumns, Headers: []string{"A", "B", "C"}, + Rows: tableScope, + Columns: titledColumns(cellColumns, []string{"A", "B", "C"}, nil), }) table.paint(gfx.Rect{Width: width, Height: height}) rowH := components.TableRowHeight(gfx.LightTheme()) @@ -163,7 +164,7 @@ func TestTableCellsDoNotCrossTables(t *testing.T) { // A frozen column answers where the band was pinned, and a column scrolling // under it keeps its scrolled place; the frozen ones do not move with OffsetX. func TestFrozenColumnCellsStayPinned(t *testing.T) { - table := newCellTable(20, TableSpec{Rows: tableScope, Columns: wideSixColumns, Headers: sixTitles, FrozenColumns: 2}) + table := newCellTable(20, TableSpec{Rows: tableScope, Columns: titledColumns(wideSixColumns, sixTitles, nil), FrozenColumns: 2}) table.paint(gfx.Rect{Width: 400, Height: 300}) frozen, ok := table.state.CellRect(0, 0) if !ok || frozen.X != 0 || frozen.Width != 120 { @@ -187,7 +188,7 @@ func TestFrozenColumnCellsStayPinned(t *testing.T) { // the area's last paint put them, which is a window coordinate, and the header // keeps its height above them. func TestTableCellsInAScrollAreaFollowTheArea(t *testing.T) { - table := newCellTable(1000, TableSpec{Rows: tableScope, Columns: cellColumns, Headers: []string{"A", "B", "C"}}) + table := newCellTable(1000, TableSpec{Rows: tableScope, Columns: titledColumns(cellColumns, []string{"A", "B", "C"}, nil)}) rowH, headH := components.TableRowHeight(gfx.LightTheme()), components.TableHeaderHeight(gfx.LightTheme()) paint := func() { canvas := testCanvas() diff --git a/base/text_value.go b/base/text_value.go index aa70c0bad..c6778a131 100644 --- a/base/text_value.go +++ b/base/text_value.go @@ -1,9 +1,11 @@ package base import ( + "unicode/utf8" "unsafe" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" ) // TextValue is what a TextField or TextArea edits: a *string of the model, which @@ -26,8 +28,9 @@ type boundText struct { // fieldOf names the text field bound to value and returns the Field that edits it. // A string is kept in step with a Field of the page's: what the user typed since // the last paint is written to *value, and a value the program changed is put in -// the field with the caret at its end. When both changed, what the user typed is -// kept, as the newer edit. +// the field as the edit that turns the field's text into it (see Field.follow): the +// caret and selection keep to the text they were on. When both changed, what the user +// typed is kept, as the newer edit. func fieldOf[T TextValue](p *Page, Kind uint8, Value T) (*Field, gfx.ID) { switch v := any(Value).(type) { case *Field: @@ -45,7 +48,7 @@ func fieldOf[T TextValue](p *Page, Kind uint8, Value T) (*Field, gfx.ID) { case typed != bound.synced: *v, bound.synced = typed, typed case *v != bound.synced: - bound.field.SetText(*v) + bound.field.follow(*v) bound.synced = *v } return &bound.field, id @@ -53,6 +56,60 @@ func fieldOf[T TextValue](p *Page, Kind uint8, Value T) (*Field, gfx.ID) { panic("unreachable: TextValue is *string or *Field") } +// follow puts value in the field as the program's edit of the text it holds: only the +// runes between the start and the end the two share are replaced, so a long text that +// grows at its end, as a log does, costs what was added, and the caret and selection keep +// to the text they were on. A caret at the end of the text stays at its end as text is +// added there, and one inside replaced text goes to the end of what replaced it. Like +// SetText, the change is not the user's edit. A field being composed by an input method, +// or one that restricts what it takes, is set as SetText sets it. +func (field *Field) follow(value string) { + editor := field.ensure() + old := editor.String() + if _, composing := editor.Composition(); composing || old == value { + if composing { + field.SetText(value) + } + return + } + prefix := commonPrefix(old, value) + for prefix > 0 && (prefix < len(old) && !utf8.RuneStart(old[prefix]) || prefix < len(value) && !utf8.RuneStart(value[prefix])) { + prefix-- + } + suffix := commonSuffix(old[prefix:], value[prefix:]) + for suffix > 0 && !utf8.RuneStart(old[len(old)-suffix]) { + suffix-- + } + // Both ends are rune boundaries, which the editor's index turns into rune indexes + // without counting the runes before them. + start, end := editor.RuneIndex(prefix), editor.RuneIndex(len(old)-suffix) + inserted := value[prefix : len(value)-suffix] + shift := utf8.RuneCountInString(inserted) - (end - start) + last := editor.RuneCount() + place := func(at int) int { + switch { + case at < start || at == start && (at != end || at != last): + return at + case at >= end: + return at + shift + default: + return end + shift + } + } + selection, caret := editor.Selection(), editor.Caret() + anchor := selection.Start + if caret == selection.Start { + anchor = selection.End + } + after := text.Range{Start: place(anchor), End: place(caret)} + edits := [1]text.Replacement{{Range: text.Range{Start: start, End: end}, Text: inserted}} + if editor.ReplaceRangesWith(edits[:], text.ReplaceRangesOptions{AfterSelection: &after}) != nil { + field.SetText(value) + return + } + field.seen = editor.String() // the program's own change is not an edit +} + // sweepTexts forgets the fields of strings whose names the page no longer keeps: // a field a Memo copies keeps its name, and so its editor. func (p *Page) sweepTexts() { diff --git a/base/text_value_test.go b/base/text_value_test.go new file mode 100644 index 000000000..c74abf676 --- /dev/null +++ b/base/text_value_test.go @@ -0,0 +1,111 @@ +package base + +import ( + "fmt" + "strings" + "testing" + + "github.com/vivaui/viva/text" +) + +// bound is a Field holding value with the selection made from anchor to caret (rune +// indexes), as a field bound to a string holds it. +func bound(value string, anchor, caret int) *Field { + var field Field + field.SetText(value) + field.ensure().SetSelection(text.Range{Start: anchor, End: caret}) + return &field +} + +func selectionOf(field *Field) (anchor, caret int) { + editor := field.ensure() + selection := editor.Selection() + caret = editor.Caret() + anchor = selection.Start + if caret == selection.Start { + anchor = selection.End + } + return anchor, caret +} + +// A string the program changed is put in its field without taking the user's selection +// away: the selection keeps to the text it was on. +func TestAProgramChangeKeepsTheSelectionOnItsText(t *testing.T) { + for _, c := range []struct { + name string + before, after string + anchor, caret int // in before + wantAnchor, wantCaret int // in after + }{ + {"line appended after a selection", "one\ntwo\n", "one\ntwo\nthree\n", 0, 3, 0, 3}, + {"line inserted before a selection", "one\ntwo\n", "zero\none\ntwo\n", 4, 7, 9, 12}, + {"backwards selection moved", "one\ntwo\n", "zero\none\ntwo\n", 7, 4, 12, 9}, + {"caret at the end follows a log", "one\n", "one\ntwo\n", 4, 4, 8, 8}, + {"caret before inserted text stays", "ab", "aXb", 1, 1, 1, 1}, + {"caret inside replaced text goes after it", "a1234b", "aXYb", 3, 3, 3, 3}, + {"multibyte prefix", "中文a", "中文ba", 2, 3, 2, 4}, + {"text removed before the caret", "drop this keep", "keep", 12, 14, 2, 4}, + } { + field := bound(c.before, c.anchor, c.caret) + field.follow(c.after) + if got := field.Text(); got != c.after { + t.Fatalf("%s: text %q, want %q", c.name, got, c.after) + } + if anchor, caret := selectionOf(field); anchor != c.wantAnchor || caret != c.wantCaret { + t.Errorf("%s: selection %d..%d, want %d..%d", c.name, anchor, caret, c.wantAnchor, c.wantCaret) + } + } +} + +// A field that only takes some characters is set whole, as SetText sets it. +func TestAProgramChangeOfARestrictedFieldSetsItWhole(t *testing.T) { + field := bound("123", 0, 0) + field.ensure().Restrict(func(r rune) bool { return r >= '0' && r <= '9' }, 0) + field.follow("12345") + if got := field.Text(); got != "12345" { + t.Fatalf("text %q", got) + } + if _, caret := selectionOf(field); caret != 5 { + t.Fatalf("caret %d, want it at the end as SetText puts it", caret) + } +} + +// BenchmarkFieldFollowAppendedLine is a log of 20000 lines bound to a TextArea growing by +// one line: what the page does to the field for it. +func BenchmarkFieldFollowAppendedLine(b *testing.B) { + var text strings.Builder + for i := range 20000 { + fmt.Fprintf(&text, "line %d the quick brown fox jumps over the lazy dog 中文混排\n", i) + } + base := text.String() + texts := make([]string, 64) + for i := range texts { + texts[i] = base + strings.Repeat(fmt.Sprintf("appended %d\n", i), i%2+1) + } + var field Field + field.SetText(base) + b.ReportAllocs() + for i := 0; b.Loop(); i++ { + field.follow(texts[i%len(texts)]) + } +} + +// BenchmarkFieldSetTextAppendedLine is BenchmarkFieldFollowAppendedLine with the text set +// whole, as a bound string was set before. +func BenchmarkFieldSetTextAppendedLine(b *testing.B) { + var text strings.Builder + for i := range 20000 { + fmt.Fprintf(&text, "line %d the quick brown fox jumps over the lazy dog 中文混排\n", i) + } + base := text.String() + texts := make([]string, 64) + for i := range texts { + texts[i] = base + strings.Repeat(fmt.Sprintf("appended %d\n", i), i%2+1) + } + var field Field + field.SetText(base) + b.ReportAllocs() + for i := 0; b.Loop(); i++ { + field.SetText(texts[i%len(texts)]) + } +} diff --git a/base/textarea.go b/base/textarea.go index 0c9bdfb5f..656cf8ef5 100644 --- a/base/textarea.go +++ b/base/textarea.go @@ -1,7 +1,9 @@ package base import ( + "slices" "sort" + "strings" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/text" @@ -38,16 +40,18 @@ type TextareaSemantics struct { // DisplayValue starts a row; scrolling follows the caret when Layout is set. // Editing and IME state remain owned by the application/runtime. type TextareaSnapshot struct { - PaintLine func(*gfx.Canvas, string, gfx.Rect, gfx.TextStyle) - ID gfx.ID - Label string - Value string - DisplayValue string - Placeholder string - Hint string - Disabled bool - ReadOnly bool - Invalid bool + PaintLine func(*gfx.Canvas, string, gfx.Rect, gfx.TextStyle) + ID gfx.ID + Label string + Value string + DisplayValue string + Placeholder string + Hint string + Disabled bool + ReadOnly bool + Invalid bool + // Warning paints the field with the warning border; Invalid wins over it. + Warning bool Focused bool NativeEditing bool ShowCaret bool @@ -139,7 +143,12 @@ type TextareaLayout struct { wrap bool size float32 width float32 // the width rows were wrapped to - fitted bool + fonts uint32 // the canvas's FontGeneration the rows were measured in + // exact tells for each row whether the canvas wrapped it (Show) or it is still + // the estimate Fit made; estimated counts the estimated ones. + exact []bool + estimated int + fitted bool // boxWidth is the outer width the box was last laid out in, which AutoGrow // measures the next time the page lays the box out. It is zero before the // first paint. @@ -228,8 +237,12 @@ func (layout *TextareaLayout) Wheel(event gfx.ScrollEvent) bool { // after a final newline. The rows it wraps are the ones the next paint at that // width uses. func (layout *TextareaLayout) RowCount(canvas *gfx.Canvas, theme gfx.Theme, text string, width float32, noWrap bool) int { + return layout.rowCount(canvas, theme, text, width, noWrap, -1) +} + +func (layout *TextareaLayout) rowCount(canvas *gfx.Canvas, theme gfx.Theme, text string, width float32, noWrap bool, most int) int { layout.Fit(canvas, text, theme.Metrics.FontSizeM, textareaMax(0, width-2*theme.Metrics.TextInsetX()), !noWrap) - return len(layout.Rows) + return layout.realizeUpTo(most) } // ContentHeight is the height a box of outer width width needs to show text @@ -237,7 +250,16 @@ func (layout *TextareaLayout) RowCount(canvas *gfx.Canvas, theme gfx.Theme, text // `field-sizing: content` of shadcn's textarea. The application caps it where it // wants the box to start scrolling. func (layout *TextareaLayout) ContentHeight(canvas *gfx.Canvas, theme gfx.Theme, text string, width float32, noWrap bool) float32 { - rows := layout.RowCount(canvas, theme, text, width, noWrap) + return layout.ContentHeightUpTo(canvas, theme, text, width, noWrap, -1) +} + +// ContentHeightUpTo is ContentHeight for a box that grows to at most maxRows rows: the +// rows past that are not wrapped with the canvas, so a long text in an AutoGrow box costs +// the rows it can show. The height is exact while the text takes no more than maxRows +// rows, and taller than maxRows rows when it takes more. A negative maxRows is +// ContentHeight. +func (layout *TextareaLayout) ContentHeightUpTo(canvas *gfx.Canvas, theme gfx.Theme, text string, width float32, noWrap bool, maxRows int) float32 { + rows := layout.rowCount(canvas, theme, text, width, noWrap, maxRows) return textareaMax(64, float32(rows)*(theme.Metrics.FontSizeM+7)+2*textareaPadY) } @@ -350,19 +372,237 @@ func (layout *TextareaLayout) setUpstream(offset int, upstream bool) { layout.Upstream, layout.UpstreamCaret = upstream, offset } -// fit wraps text to width unless the rows already are, and keeps what it wrapped -// them with for the events that follow. +// Fit lays text out in rows at width unless they already are, and keeps what it +// laid them out with for the events that follow. +// +// The rows are estimated with the reference metrics (gfx.WrapRowEstimate), which shape +// nothing, and Show wraps the ones the box shows with the canvas: opening a long text +// costs the rows in view, not one shaped line for every row of the text. A paragraph +// wraps on its own, so when only the text changed since the last fit, only the +// paragraphs an edit touched are laid out again: the rows before them are kept and the +// rows after them move by the length the edit added or removed. Other fonts, a size or +// a width lay the whole text out again. func (layout *TextareaLayout) Fit(canvas *gfx.Canvas, text string, size, width float32, wrap bool) { + fonts := canvas.FontGeneration() + same := layout.fitted && layout.canvas == canvas && layout.fonts == fonts && layout.wrap == wrap && layout.size == size && layout.width == width layout.canvas = canvas - if layout.fitted && layout.wrap == wrap && layout.size == size && layout.width == width && layout.text == text { + if same && layout.text == text { return } - layout.fitted, layout.wrap, layout.size, layout.width, layout.text = true, wrap, size, width, text - wrapWidth := width - if !wrap { - wrapWidth = 0 + layout.size, layout.width, layout.wrap = size, width, wrap + if same { + layout.rewrap(text) + } else { + layout.Rows, layout.exact, layout.estimated = layout.Rows[:0], layout.exact[:0], 0 + layout.estimate(text, 0, len(text)+1) + } + layout.fitted, layout.fonts, layout.text = true, fonts, text +} + +// wrapWidth is the width rows wrap at, 0 for rows that never wrap. +func (layout *TextareaLayout) wrapWidth() float32 { + if !layout.wrap { + return 0 + } + return layout.width +} + +// estimate appends the estimated rows of the paragraphs of text from the one starting +// at from to the one before resume (len(text)+1 for the last). +func (layout *TextareaLayout) estimate(text string, from, resume int) { + width := layout.wrapWidth() + for at := from; at >= 0 && at < resume; { + var row gfx.TextRow + row, at = gfx.WrapRowEstimate(text, at, layout.size, gfx.WeightRegular, width) + layout.Rows = append(layout.Rows, row) + // A row that does not wrap is measured by nothing, so it is what the canvas gives. + layout.exact = append(layout.exact, width <= 0) + if width > 0 { + layout.estimated++ + } + } +} + +// rewrap lays out again the paragraphs of the last fitted text that differ in text, +// keeping the rows of the others. +func (layout *TextareaLayout) rewrap(text string) { + old := layout.text + prefix := commonPrefix(old, text) + suffix := commonSuffix(old[prefix:], text[prefix:]) + // The edit spans the paragraphs from the one the first changed byte is in to the + // one the last is in; the newline that ends that one is the first in the suffix. + from := strings.LastIndexByte(text[:prefix], '\n') + 1 + oldResume, newResume := len(old)+1, len(text)+1 // where the next untouched paragraph starts + if newline := strings.IndexByte(old[len(old)-suffix:], '\n'); newline >= 0 { + oldResume = len(old) - suffix + newline + 1 + newResume = len(text) - suffix + newline + 1 + } + rows := layout.Rows + kept := sort.Search(len(rows), func(index int) bool { return rows[index].Start >= from }) + tail := len(rows) + if oldResume <= len(old) { + tail = sort.Search(len(rows), func(index int) bool { return rows[index].Start >= oldResume }) + } + end := len(rows) + layout.estimate(text, from, newResume) + edited := len(layout.Rows) - end + layout.splice(kept, tail, end) + if delta := len(text) - len(old); delta != 0 { + for index := kept + edited; index < len(layout.Rows); index++ { + layout.Rows[index].Start += delta + layout.Rows[index].End += delta + } + } +} + +// splice replaces rows [from, to) with the rows appended after end, the length the rows +// had before: the new rows are turned to sit before the rows after to, and the old ones +// are dropped. The rows' exactness moves with them. +func (layout *TextareaLayout) splice(from, to, end int) { + for index := from; index < to; index++ { + if !layout.exact[index] { + layout.estimated-- + } + } + rows, exact := layout.Rows, layout.exact + slices.Reverse(rows[to:end]) + slices.Reverse(rows[end:]) + slices.Reverse(rows[to:]) + slices.Reverse(exact[to:end]) + slices.Reverse(exact[end:]) + slices.Reverse(exact[to:]) + layout.Rows = append(rows[:from], rows[to:]...) + layout.exact = append(exact[:from], exact[to:]...) +} + +// paragraphRows widens rows [first, last] to the whole paragraphs they are in, among +// the first count rows. +func (layout *TextareaLayout) paragraphRows(first, last, count int) (int, int) { + rows, text := layout.Rows[:count], layout.text + for first > 0 && text[rows[first].Start-1] != '\n' { + first-- + } + for last+1 < len(rows) && text[rows[last+1].Start-1] != '\n' { + last++ + } + return first, last +} + +// realize wraps with the canvas the paragraphs of rows [first, last] whose rows are +// estimated, and reports whether it changed any. The text at the top of the box stays +// there, and the row of the caret the box last followed is the row it is on now. +func (layout *TextareaLayout) realize(first, last int) bool { + if layout.estimated == 0 || len(layout.Rows) == 0 { + return false + } + first, last = max(first, 0), min(last, len(layout.Rows)-1) + if first > last { + return false + } + first, last = layout.paragraphRows(first, last, len(layout.Rows)) + if !slices.Contains(layout.exact[first:last+1], false) { + return false + } + var top int + var within float32 + if layout.LineHeight > 0 { + row := min(int(layout.Scroll/layout.LineHeight), len(layout.Rows)-1) + top, within = layout.Rows[row].Start, layout.Scroll-float32(row)*layout.LineHeight + } + // The block is laid out again on the end of the rows, a paragraph at a time: one + // that is exact is copied, an estimated one is wrapped with the canvas. + text, width, end := layout.text, layout.wrapWidth(), len(layout.Rows) + for row := first; row <= last; { + _, after := layout.paragraphRows(row, row, end) + if !slices.Contains(layout.exact[row:after+1], false) { + layout.Rows = append(layout.Rows, layout.Rows[row:after+1]...) + layout.exact = append(layout.exact, layout.exact[row:after+1]...) + } else { + resume := len(text) + 1 + if newline := strings.IndexByte(text[layout.Rows[row].Start:], '\n'); newline >= 0 { + resume = layout.Rows[row].Start + newline + 1 + } + for at := layout.Rows[row].Start; at >= 0 && at < resume; { + var wrapped gfx.TextRow + wrapped, at = layout.canvas.WrapRow(text, at, layout.size, gfx.WeightRegular, width) + layout.Rows = append(layout.Rows, wrapped) + layout.exact = append(layout.exact, true) + } + } + row = after + 1 + } + layout.splice(first, last+1, end) + if layout.LineHeight > 0 { + layout.Scroll = float32(layout.rowAt(top))*layout.LineHeight + within + } + if layout.FollowedValid { + layout.followedRow = layout.RowOf(layout.followed) + } + return true +} + +// rowAt is the row that holds offset. +func (layout *TextareaLayout) rowAt(offset int) int { + return max(sort.Search(len(layout.Rows), func(index int) bool { return layout.Rows[index].Start > offset })-1, 0) +} + +// Show settles what the box paints after Fit: the rows in view are wrapped with the +// canvas, the text at the top of the box stays where it is as they change, and a caret +// that moved since the last paint is kept in view as Follow keeps it. Content and +// LineHeight are the box's for this paint. +func (layout *TextareaLayout) Show(caret int) { + moved := !layout.FollowedValid || layout.followed != caret || layout.followedRow != layout.RowOf(caret) + for { + layout.Follow(caret, layout.RowOf(caret)) + if layout.LineHeight <= 0 { + return + } + first := int(layout.Scroll / layout.LineHeight) + last := int((layout.Scroll + layout.Content.Height) / layout.LineHeight) + if !layout.realize(first, last) { + return + } + if moved { + layout.FollowedValid = false // the rows the caret was followed to have changed + } + } +} + +// realizeUpTo wraps with the canvas the rows from the first until more than most are +// exact, or all of them for most < 0, and returns how many rows the text takes: exactly +// while that is no more than most. +func (layout *TextareaLayout) realizeUpTo(most int) int { + if most < 0 { + most = len(layout.Rows) + } + for layout.realize(0, most) { + } + return len(layout.Rows) +} + +// commonPrefix is the length of the longest prefix a and b share, compared a block +// at a time so a long text costs a memory comparison, not a loop over its bytes. +func commonPrefix(a, b string) int { + n := min(len(a), len(b)) + at := 0 + for block := 4096; at+block <= n && a[at:at+block] == b[at:at+block]; at += block { + } + for at < n && a[at] == b[at] { + at++ + } + return at +} + +// commonSuffix is the length of the longest suffix a and b share. +func commonSuffix(a, b string) int { + n := min(len(a), len(b)) + at := 0 + for block := 4096; at+block <= n && a[len(a)-at-block:len(a)-at] == b[len(b)-at-block:len(b)-at]; at += block { + } + for at < n && a[len(a)-at-1] == b[len(b)-at-1] { + at++ } - layout.Rows = canvas.WrapRows(layout.Rows[:0], text, size, gfx.WeightRegular, wrapWidth) + return at } // rowOf is the row the caret at offset is drawn on. diff --git a/base/textarea_fit_test.go b/base/textarea_fit_test.go new file mode 100644 index 000000000..ba790f8b7 --- /dev/null +++ b/base/textarea_fit_test.go @@ -0,0 +1,321 @@ +package base + +import ( + "fmt" + "math/rand/v2" + "slices" + "strings" + "testing" + + "github.com/vivaui/viva/gfx" +) + +const fitTestSize, fitTestWidth, fitTestLine = 13, 180, 20 + +// shapedCanvas measures unlike the reference metrics, as a platform text engine does, +// and records what it measured. +func shapedCanvas(measured *[]string) *gfx.Canvas { + canvas := &gfx.Canvas{} + canvas.SetMeasurer(func(value string, size, weight float32) float32 { + if measured != nil { + *measured = append(*measured, value) + } + return float32(len(value)) * size * 0.45 + }) + return canvas +} + +// paragraphs splits text at its newlines into the starts of its paragraphs. +func paragraphStarts(text string) []int { + starts := []int{0} + for at, c := range []byte(text) { + if c == '\n' { + starts = append(starts, at+1) + } + } + return starts +} + +// checkRows fails unless every paragraph's rows are the ones the canvas wraps it to +// when they are marked exact, and the estimate of them when they are not. +func checkRows(t *testing.T, canvas *gfx.Canvas, layout *TextareaLayout, text string, wrap bool) { + t.Helper() + width := float32(fitTestWidth) + if !wrap { + width = 0 + } + if len(layout.exact) != len(layout.Rows) { + t.Fatalf("%d rows but %d exactness marks", len(layout.Rows), len(layout.exact)) + } + estimated := 0 + row := 0 + for _, start := range paragraphStarts(text) { + if row >= len(layout.Rows) || layout.Rows[row].Start != start { + t.Fatalf("no row starts paragraph %d of %q: %v", start, text, layout.Rows) + } + exact := layout.exact[row] + var want []gfx.TextRow + for at := start; ; { + var r gfx.TextRow + if exact { + r, at = canvas.WrapRow(text, at, fitTestSize, gfx.WeightRegular, width) + } else { + r, at = gfx.WrapRowEstimate(text, at, fitTestSize, gfx.WeightRegular, width) + } + want = append(want, r) + if at < 0 || text[at-1] == '\n' { + break + } + } + got := layout.Rows[row : row+len(want)] + if !slices.Equal(got, want) { + t.Fatalf("paragraph at %d (exact %v) of %q:\n got %v\nwant %v", start, exact, text, got, want) + } + for index := row; index < row+len(want); index++ { + if layout.exact[index] != exact { + t.Fatalf("paragraph at %d is partly exact", start) + } + if !exact { + estimated++ + } + } + row += len(want) + } + if row != len(layout.Rows) { + t.Fatalf("%d rows past the last paragraph of %q: %v exact %v", len(layout.Rows)-row, text, layout.Rows, layout.exact) + } + if estimated != layout.estimated { + t.Fatalf("%d estimated rows counted as %d", estimated, layout.estimated) + } +} + +// However the text was edited, scrolled and shown, every paragraph is laid out either as +// the canvas wraps it or as the estimate does, and counting the rows makes them all the +// canvas's. +func TestTextareaLayoutKeepsEveryParagraphEstimatedOrExact(t *testing.T) { + pieces := []string{"a", "word ", "\n", "\r\n", " ", "中文", "the quick brown fox ", "averyveryverylongwordthatmustbreak", "é", "\n\n"} + random := rand.New(rand.NewPCG(1, 2)) + piece := func() string { + var b strings.Builder + for range random.IntN(8) { + b.WriteString(pieces[random.IntN(len(pieces))]) + } + return b.String() + } + for _, wrap := range []bool{true, false} { + canvas := shapedCanvas(nil) + var layout TextareaLayout + text := "" + for step := range 3000 { + at := random.IntN(len(text) + 1) + cut := at + random.IntN(len(text)-at+1) + if random.IntN(3) == 0 { + cut = at // a pure insertion + } + switch random.IntN(20) { + case 0: + at, cut = 0, len(text) // everything replaced + case 1: + at, cut = len(text), len(text) // appended + } + text = text[:at] + piece() + text[cut:] + layout.Fit(canvas, text, fitTestSize, fitTestWidth, wrap) + layout.Content, layout.LineHeight = gfx.Rect{Width: fitTestWidth, Height: 3 * fitTestLine}, fitTestLine + if random.IntN(2) == 0 { + layout.Scroll = layout.clampScroll(float32(random.IntN(len(layout.Rows)+1)) * fitTestLine) + layout.Show(random.IntN(len(text) + 1)) + } + checkRows(t, canvas, &layout, text, wrap) + if step%500 == 0 { + rows := layout.RowCount(canvas, gfx.LightTheme(), text, fitTestWidth+2*gfx.LightTheme().Metrics.TextInsetX(), !wrap) + width := float32(fitTestWidth) + if !wrap { + width = 0 + } + // RowCount lays the text out in the theme's size. + if want := canvas.WrapRows(nil, text, gfx.LightTheme().Metrics.FontSizeM, gfx.WeightRegular, width); rows != len(want) || !slices.Equal(layout.Rows, want) { + t.Fatalf("step %d: counted rows are not the canvas's", step) + } + } + } + } +} + +func longText(lines int) string { + var b strings.Builder + for i := range lines { + fmt.Fprintf(&b, "line %d the quick brown fox jumps over the lazy dog\n", i) + } + return b.String() +} + +// fromParagraphs fails unless every measured value is part of one of paragraphs. +func fromParagraphs(t *testing.T, what string, measured []string, paragraphs ...string) { + t.Helper() + if len(measured) == 0 { + t.Fatalf("%s: nothing was measured", what) + } + for _, value := range measured { + value = strings.TrimRight(value, " ") + if !slices.ContainsFunc(paragraphs, func(p string) bool { return strings.Contains(p, value) }) { + t.Fatalf("%s: measured %q, which is in none of %q", what, value, paragraphs) + } + } +} + +// Opening a long text shapes the rows the box shows, not every row of the text. +func TestTextareaLayoutShapesOnlyTheRowsInView(t *testing.T) { + var measured []string + canvas := shapedCanvas(&measured) + text := longText(20000) + var layout TextareaLayout + layout.Fit(canvas, text, fitTestSize, fitTestWidth, true) + layout.Content, layout.LineHeight = gfx.Rect{Width: fitTestWidth, Height: 3 * fitTestLine}, fitTestLine + layout.Show(0) + lines := strings.Split(text, "\n") + fromParagraphs(t, "at the start", measured, lines[:4]...) + + // At the end, which a caret there scrolls to. + measured = measured[:0] + layout.Show(len(text)) + if caret := layout.RowOf(len(text)); float32(caret)*fitTestLine < layout.Scroll || float32(caret+1)*fitTestLine > layout.Scroll+layout.Content.Height { + t.Fatalf("the caret's row %d is out of view at scroll %v", caret, layout.Scroll) + } + fromParagraphs(t, "at the end", measured, lines[len(lines)-5:]...) +} + +// Typing in, or appending to, a long text shapes only the paragraph it changed. +func TestTextareaLayoutShapesOnlyTheEditedParagraph(t *testing.T) { + var measured []string + canvas := shapedCanvas(&measured) + text := longText(2000) + middle := strings.Index(text, "line 1000 ") + for _, edit := range []struct { + name, text, paragraph string + caret int + }{ + {"appended", text + "a new line at the end", "a new line at the end", len(text) + 21}, + {"typed", text[:middle+10] + "x" + text[middle+10:], "line 1000 xthe quick brown fox jumps over the lazy dog", middle + 11}, + } { + var layout TextareaLayout + layout.Fit(canvas, text, fitTestSize, fitTestWidth, true) + layout.Content, layout.LineHeight = gfx.Rect{Width: fitTestWidth, Height: 3 * fitTestLine}, fitTestLine + layout.Show(edit.caret - 1) + measured = measured[:0] + layout.Fit(canvas, edit.text, fitTestSize, fitTestWidth, true) + layout.Show(edit.caret) + fromParagraphs(t, edit.name, measured, edit.paragraph) + layout.text = edit.text + checkRows(t, canvas, &layout, edit.text, true) + } +} + +// A box scrolled away from its caret stays where it was as the rows it shows are +// wrapped with the canvas: the text at its top does not move, and it is not taken back +// to the caret. +func TestTextareaLayoutKeepsItsTopTextAsRowsAreShaped(t *testing.T) { + canvas := shapedCanvas(nil) + var b strings.Builder + for i := range 400 { + fmt.Fprintf(&b, "paragraph %d %s\n", i, strings.Repeat("words that wrap differently ", 1+i%4)) + } + text := b.String() + var layout TextareaLayout + layout.Fit(canvas, text, fitTestSize, fitTestWidth, true) + layout.Content, layout.LineHeight = gfx.Rect{Width: fitTestWidth, Height: 5 * fitTestLine}, fitTestLine + layout.Show(0) + layout.Scroll = float32(len(layout.Rows)/2)*fitTestLine + 7 // a wheel took it to the middle + top := layout.Rows[int(layout.Scroll/fitTestLine)].Start + within := layout.Scroll - float32(int(layout.Scroll/fitTestLine))*fitTestLine + layout.Show(0) + row := int(layout.Scroll / fitTestLine) + if got := layout.Rows[row]; got.Start > top || got.End < top && row+1 < len(layout.Rows) && layout.Rows[row+1].Start <= top { + t.Fatalf("the row at the top is %v, which does not hold offset %d it held", got, top) + } + if got := layout.Scroll - float32(row)*fitTestLine; got != within { + t.Fatalf("the top row is %v pixels in, was %v", got, within) + } + if layout.Scroll < fitTestLine { + t.Fatal("the box went back to the caret") + } + for index := row; index <= min(row+5, len(layout.Rows)-1); index++ { + if !layout.exact[index] { + t.Fatalf("row %d in view is still estimated", index) + } + } +} + +// An AutoGrow box measures the rows it can grow to, not the whole text, and is exact +// while the text fits it. +func TestTextareaLayoutGrowsByTheRowsItCanShow(t *testing.T) { + var measured []string + canvas := shapedCanvas(&measured) + theme := gfx.LightTheme() + width := float32(fitTestWidth) + 2*theme.Metrics.TextInsetX() + text := longText(20000) + var layout TextareaLayout + height := layout.ContentHeightUpTo(canvas, theme, text, width, false, 5) + if want := float32(6)*(theme.Metrics.FontSizeM+7) + 2*TextareaPadY; height < want { + t.Fatalf("a long text is %v tall, want past five rows (%v)", height, want) + } + fromParagraphs(t, "grow", measured, strings.Split(text, "\n")[:6]...) + + short := "one line\nand a second one that is long enough to wrap in the box" + var small TextareaLayout + if got, want := small.ContentHeightUpTo(canvas, theme, short, width, false, 5), small.ContentHeight(shapedCanvas(nil), theme, short, width, false); got != want { + t.Fatalf("a short text is %v tall, want the exact %v", got, want) + } +} + +// BenchmarkTextareaLayoutOpen lays out a text of 20000 lines and shows its first rows: +// the work of the first paint. +func BenchmarkTextareaLayoutOpen(b *testing.B) { + canvas := shapedCanvas(nil) + text := longText(20000) + b.ReportAllocs() + for b.Loop() { + var layout TextareaLayout + layout.Fit(canvas, text, fitTestSize, fitTestWidth, true) + layout.Content, layout.LineHeight = gfx.Rect{Width: fitTestWidth, Height: 20 * fitTestLine}, fitTestLine + layout.Show(0) + } +} + +// BenchmarkTextareaLayoutAppendLine is a log of 20000 lines growing by one line: +// the work of the frame that shows it. +func BenchmarkTextareaLayoutAppendLine(b *testing.B) { + canvas := shapedCanvas(nil) + base := longText(20000) + texts := make([]string, 64) + for i := range texts { + texts[i] = base + fmt.Sprintf("appended %d\n", i) + } + var layout TextareaLayout + layout.Fit(canvas, base, fitTestSize, fitTestWidth, true) + layout.Content, layout.LineHeight = gfx.Rect{Width: fitTestWidth, Height: 20 * fitTestLine}, fitTestLine + layout.Show(len(base)) + b.ReportAllocs() + for i := 0; b.Loop(); i++ { + text := texts[i%len(texts)] + layout.Fit(canvas, text, fitTestSize, fitTestWidth, true) + layout.Show(len(text)) + } +} + +// BenchmarkTextareaLayoutTypeInTheMiddle is a key typed in the middle of a text of +// 20000 lines. +func BenchmarkTextareaLayoutTypeInTheMiddle(b *testing.B) { + canvas := shapedCanvas(nil) + base := longText(20000) + middle := strings.Index(base, "line 10000 ") + texts := [2]string{base, base[:middle] + "x" + base[middle:]} + var layout TextareaLayout + layout.Fit(canvas, base, fitTestSize, fitTestWidth, true) + layout.Content, layout.LineHeight = gfx.Rect{Width: fitTestWidth, Height: 20 * fitTestLine}, fitTestLine + layout.Show(middle) + b.ReportAllocs() + for i := 0; b.Loop(); i++ { + layout.Fit(canvas, texts[(i+1)%2], fitTestSize, fitTestWidth, true) + layout.Show(middle + (i+1)%2) + } +} diff --git a/base/toast.go b/base/toast.go index 3375efd69..2b5ffe775 100644 --- a/base/toast.go +++ b/base/toast.go @@ -38,9 +38,10 @@ const ToastLayer = TooltipLayer - 8 // Toaster is the toasts of a window, kept in the model, as shadcn's Sonner: Show // puts one up, and ui.Toasts, declared once in the page, paints them. A toast goes -// away five seconds after it appears, or when its close button is pressed; the -// pointer resting on the stack, or the focus in it, keeps them up. Swipe carries -// a caller's horizontal drag snapshot for one toast, and Expanded keeps the stack +// away after Timeout (five seconds when zero), or when its close button is +// pressed; the pointer resting on the stack, or the focus in it, keeps them up. +// Limit is how many are visible at once (three when zero). Swipe carries a +// caller's horizontal drag snapshot for one toast, and Expanded keeps the stack // open for a page that cannot hold the pointer on it. The zero value is empty. // // type model struct{ toaster ui.Toaster } @@ -57,10 +58,15 @@ type Toaster struct { // in it does: a caller-owned flag, for a static page whose stack cannot be // hovered. The zero value is collapsed. Expanded bool + // Timeout is the lifetime of a toast that does not name one of its own; zero + // is five seconds, as Base UI's. + Timeout time.Duration + // Limit is the most toasts visible at once; zero is three, as Base UI's. + Limit int queue ToastQueue toasts []toast // oldest first - Next uint32 + next uint32 // the number the next toast gets scope gfx.Scope stack []SonnerToast // scratch for one paint, newest first entries []ToastQueueEntry @@ -71,18 +77,34 @@ type toast struct { n uint32 // its number: ToastID, and its identity in the Toaster's scope title, description string Kind ToastKind - action string // the label of its button; none when empty + action string // the label of its button; none when empty + timeout time.Duration + hideClose bool // no close button: the toast leaves on its time or Close swipeX float32 // the caller's horizontal snapshot offset, from Swipe shown bool // painted once: in the queue, with its time running } +// ToastConfig is what one show call sets on its toast: an action button, a +// lifetime of its own, or no close button. The zero value is a toast with the +// Toaster's lifetime and its close button. +type ToastConfig struct { + // Action labels the toast's button; none when empty. + Action string + // Timeout overrides the Toaster's Timeout for this toast; zero or less uses + // the Toaster's. + Timeout time.Duration + // HideClose leaves the close button off. The toast then leaves when its time + // is up, when its action is pressed, or when the application calls Close. + HideClose bool +} + // ToastID names a toast for Close. type ToastID uint32 // Show puts up a toast: a title, and a description under it ("" for none). The // same title and description already up is not shown twice; its time starts again. func (t *Toaster) Show(title, description string, Kind ToastKind) ToastID { - return t.ShowAction(title, description, Kind, "") + return t.ShowConfig(title, description, Kind, ToastConfig{}) } // ShowAction is Show with a button labeled action, which Acted reports and which @@ -90,9 +112,16 @@ func (t *Toaster) Show(title, description string, Kind ToastKind) ToastID { // to it: what the toast offers is somewhere in the window too, for the toast goes // by itself. func (t *Toaster) ShowAction(title, description string, Kind ToastKind, action string) ToastID { + return t.ShowConfig(title, description, Kind, ToastConfig{Action: action}) +} + +// ShowConfig is Show with what this toast alone sets: an action button, its own +// lifetime, or no close button. A toast that hides its close button still goes +// by its time, by its action, or by Close. +func (t *Toaster) ShowConfig(title, description string, Kind ToastKind, config ToastConfig) ToastID { for i := range t.toasts { if item := &t.toasts[i]; item.title == title && item.description == description { - item.Kind, item.action, item.swipeX = Kind, action, 0 + item.Kind, item.action, item.timeout, item.hideClose, item.swipeX = Kind, config.Action, config.Timeout, config.HideClose, 0 if item.shown { t.queue.Remove(t.ID(item.n)) item.shown = false // the next paint queues it again, with a fresh time @@ -100,9 +129,12 @@ func (t *Toaster) ShowAction(title, description string, Kind ToastKind, action s return ToastID(item.n) } } - t.Next++ - t.toasts = append(t.toasts, toast{n: t.Next, title: title, description: description, Kind: Kind, action: action}) - return ToastID(t.Next) + t.next++ + t.toasts = append(t.toasts, toast{ + n: t.next, title: title, description: description, Kind: Kind, + action: config.Action, timeout: config.Timeout, hideClose: config.HideClose, + }) + return ToastID(t.next) } // Swipe moves toast id x pixels horizontally on this and later paints: the diff --git a/base/tree.go b/base/tree.go index b15f2d026..f957bd911 100644 --- a/base/tree.go +++ b/base/tree.go @@ -14,6 +14,10 @@ type TreeNode struct { Depth int Branch, Expanded bool Selected, Disabled bool + // Loading shows a spinner in place of the branch's chevron while the + // application fetches its children, and takes no press on it: the application + // sets it when it starts, answering Toggled, and clears it with the children. + Loading bool // Height is this row's height; zero uses TreeState.RowHeight, or the // theme's control height when that is zero too. It is read with the // description of the row, so a tree of compact and full rows needs no diff --git a/benchmarks/size.sh b/benchmarks/size.sh index 030e8c01d..f31eaf098 100755 --- a/benchmarks/size.sh +++ b/benchmarks/size.sh @@ -1,44 +1,37 @@ #!/bin/sh -# Checks the release sizes this repository promises. Run from anywhere; the +# Reports the release sizes of the example applications. Run from anywhere; the # script builds through the same viva build path a package uses, so it measures # the flags a release actually gets (trimpath, stripped link, fixed build ID, # the macOS deployment target and the Windows GUI subsystem). # # benchmarks/size.sh # -# The limits are deliberately above the current numbers: they are a regression -# alarm, not a claim that every future feature fits in the same bytes. +# It reports and does not judge: the size of a binary is a number to watch +# across changes, not a property one fixed limit can tell right from wrong. +# On GitHub Actions the table also goes to the job summary. set -eu root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT -over_limit=0 +summary=${GITHUB_STEP_SUMMARY:-/dev/null} -check() { +printf '| Binary | Bytes |\n| --- | ---: |\n' >>"$summary" + +report() { name=$1 target=$2 arch=$3 pkg=$4 - limit=$5 out="$tmp/$(basename "$pkg").$target" go run -C "$root" ./cmd/viva build --target "$target" --arch "$arch" "$pkg" -o "$out" >/dev/null size=$(wc -c <"$out" | tr -d ' ') - printf '%-28s %10d B (limit %d)\n' "$name" "$size" "$limit" - if [ "$size" -gt "$limit" ]; then - echo "size: $name is $size bytes, over the $limit-byte limit" >&2 - over_limit=1 - fi + printf '%-28s %10d B\n' "$name" "$size" + printf '| %s | %d |\n' "$name" "$size" >>"$summary" } -hello_limit=$((3750 * 1024)) # 3.75 MiB, covers all three native targets -gallery_limit=$((4 * 1024 * 1024)) -gallery_windows_limit=$((5 * 1024 * 1024)) - -check "hello darwin/arm64" darwin arm64 ./examples/guides/hello "$hello_limit" -check "hello windows/amd64" windows amd64 ./examples/guides/hello "$hello_limit" -check "hello linux/amd64" linux amd64 ./examples/guides/hello "$hello_limit" -check "showcase darwin/arm64" darwin arm64 ./cmd/showcase "$gallery_limit" -check "showcase windows/amd64" windows amd64 ./cmd/showcase "$gallery_windows_limit" - -exit "$over_limit" +report "hello darwin/arm64" darwin arm64 ./examples/guides/hello +report "hello windows/amd64" windows amd64 ./examples/guides/hello +report "hello linux/amd64" linux amd64 ./examples/guides/hello +report "showcase darwin/arm64" darwin arm64 ./cmd/showcase +report "showcase windows/amd64" windows amd64 ./cmd/showcase diff --git a/cmd/transparent-demo/main.go b/cmd/transparent-demo/main.go new file mode 100644 index 000000000..0bc1cfbfb --- /dev/null +++ b/cmd/transparent-demo/main.go @@ -0,0 +1,44 @@ +//go:build windows || linux || darwin + +// Command transparent-demo opens one window composited over the desktop, for +// looking at Config.Transparent by hand on each platform. The left band is +// painted at half alpha and the right one at full alpha, and the strip under +// them is left unpainted; the top strip is a custom titlebar. The strip's title +// says whether the capability is there and whether the desktop really shows +// through, as OnTransparentChange reported when the window opened. +package main + +import ( + "fmt" + "os" + "sync/atomic" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" +) + +func main() { + ink := gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1} + supported := app.Supports(app.CapabilityTransparentWindow) + var active atomic.Bool + config := app.Config{ + Title: "transparent demo", Width: 640, Height: 360, + WindowMode: app.WindowCustomTitlebar, + TitlebarHeight: 36, + Transparent: true, + OnTransparentChange: func(on bool) { active.Store(on); fmt.Println("transparent active:", on) }, + Paint: func(canvas *gfx.Canvas, size gfx.Size) { + canvas.MoveRegion(gfx.Rect{Width: size.Width, Height: 36}) + canvas.Fill(gfx.Rect{Width: size.Width, Height: 36}, gfx.Color{Red: 0.14, Green: 0.16, Blue: 0.22, Alpha: 1}) + canvas.Fill(gfx.Rect{Y: 36, Width: size.Width / 2, Height: size.Height - 36 - 120}, gfx.Color{Red: 0.1, Green: 0.2, Blue: 0.6, Alpha: 0.5}) + canvas.Fill(gfx.Rect{X: size.Width / 2, Y: 36, Width: size.Width / 2, Height: size.Height - 36 - 120}, gfx.Color{Red: 0.1, Green: 0.2, Blue: 0.6, Alpha: 1}) + canvas.Label(fmt.Sprintf("supported: %v active: %v", supported, active.Load()), gfx.Rect{X: 14, Y: 9, Width: 400, Height: 20}, gfx.TextStyle{Size: 13, Color: ink}) + canvas.Label("half alpha band", gfx.Rect{X: 20, Y: 80, Width: 280, Height: 24}, gfx.TextStyle{Size: 16, Color: ink}) + canvas.Label("opaque band", gfx.Rect{X: size.Width/2 + 20, Y: 80, Width: 280, Height: 24}, gfx.TextStyle{Size: 16, Color: ink}) + }, + } + if err := app.RunCanvas(config, &gfx.Canvas{}); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} diff --git a/cmd/viva/components_gen.go b/cmd/viva/components_gen.go index 1b5a834b4..5e1b47f85 100644 --- a/cmd/viva/components_gen.go +++ b/cmd/viva/components_gen.go @@ -165,7 +165,7 @@ var componentRequires = map[string][]string{ "sidebar": {"button"}, "single-select": {"checkbox", "dialog", "dropdown-menu", "hierarchy-menu", "input", "label", "popover", "tree"}, "slider": {"button", "direction"}, - "sonner": {"toast"}, + "sonner": {"dialog", "toast"}, "split-button": {"button", "button-group", "tree"}, "switch": {"button"}, "tabs": {"button", "direction", "segmented-control"}, @@ -175,4 +175,5 @@ var componentRequires = map[string][]string{ "toggle": {"button"}, "toggle-group": {"button", "button-group", "direction", "toggle"}, "tooltip": {"dialog", "popover"}, + "tree": {"spinner"}, } diff --git a/cmd/viva/feed.go b/cmd/viva/feed.go index f104d5d30..39a6cd2e3 100644 --- a/cmd/viva/feed.go +++ b/cmd/viva/feed.go @@ -16,8 +16,10 @@ import ( "os" "path/filepath" "regexp" + "runtime" "sort" "strings" + "sync" "time" "github.com/vivaui/viva/tools/manifest" @@ -60,6 +62,8 @@ func runFeed(arguments []string, output, _ io.Writer) error { patchFroms = append(patchFroms, parsed) return nil }) + var patchMaxRatio float64 + flags.Float64Var(&patchMaxRatio, "patch-max-ratio", 0, "leave out a patch larger than this fraction of its full archive, such as 0.6 (0, the default, keeps every patch)") flags.DurationVar(&validFor, "valid-for", 0, "how long clients trust the feed, such as 2160h; 0 (the default) never expires") flags.StringVar(&keyFile, "key", "", "Ed25519 private key file (default $VIVA_UPDATE_KEY)") positional, helped, err := parseFlags(c, flags, arguments, output) @@ -114,8 +118,11 @@ func runFeed(arguments []string, output, _ io.Writer) error { if err != nil { return err } + if patchMaxRatio < 0 || patchMaxRatio > 1 { + return fmt.Errorf("--patch-max-ratio %v must be between 0 and 1", patchMaxRatio) + } if len(patchFroms) > 0 { - if err := addPatches(assets, patchFroms, patchExcludes, artifactsDir, baseURL, version, app, loaded.ExecutableName()); err != nil { + if err := addPatches(assets, patchFroms, patchExcludes, patchMaxRatio, artifactsDir, baseURL, version, app, loaded.ExecutableName()); err != nil { return err } } @@ -451,8 +458,11 @@ func parsePatchFrom(value string) (patchFrom, error) { // addPatches writes a patch for every --patch-from that names a listed asset // and adds it to the asset. Every argument must match an asset, so a typo in -// the platform cannot publish a feed that silently lacks its delta. -func addPatches(assets []update.Asset, froms []patchFrom, excludes []string, dir, baseURL, version, app, executable string) error { +// the platform cannot publish a feed that silently lacks its delta. A patch +// larger than maxRatio of its full archive is left out (no file, no feed entry) +// because downloading it saves too little to be worth the apply step; a maxRatio +// of 0 keeps every patch. +func addPatches(assets []update.Asset, froms []patchFrom, excludes []string, maxRatio float64, dir, baseURL, version, app, executable string) error { base := strings.TrimRight(baseURL, "/") byTarget := make(map[string][]patchFrom, len(froms)) for _, from := range froms { @@ -472,7 +482,20 @@ func addPatches(assets []update.Asset, froms []patchFrom, excludes []string, dir } byTarget[key] = append(byTarget[key], from) } - matched := make(map[string]int, len(byTarget)) + // Every patch is cut from two archives of its own and written to a file of + // its own, so they run side by side; the feed entries are added afterwards in + // the order the arguments came, so the feed does not depend on which finished + // first. + type patchJob struct { + asset *update.Asset + key string + name string + from patchFrom + patch update.Patch + written bool + err error + } + var jobs []*patchJob for i := range assets { asset := &assets[i] key := asset.OS + "/" + asset.Arch @@ -492,31 +515,65 @@ func addPatches(assets []update.Asset, froms []patchFrom, excludes []string, dir if err != nil { return fmt.Errorf("feed: %s: %w", asset.URL, err) } - newArchive := filepath.Join(dir, name) for _, from := range froms { - var encoded bytes.Buffer - if _, err := patchgen.Write(patchgen.Request{ - App: app, FromVersion: from.version, ToVersion: version, - OS: asset.OS, Arch: asset.Arch, - OldArchive: from.archive, NewArchive: newArchive, - Executable: executable, Exclude: excludes, - Output: &encoded, - }); err != nil { - return fmt.Errorf("feed: patch %s from %s: %w", key, from.version, err) - } - patchName := name + "." + from.version + ".patch" - if err := writePatchFileBeside(filepath.Join(dir, patchName), encoded.Bytes()); err != nil { - return err + jobs = append(jobs, &patchJob{asset: asset, key: key, name: name, from: from}) + } + } + workers := min(runtime.GOMAXPROCS(0), len(jobs)) + next := make(chan *patchJob) + var running sync.WaitGroup + for range workers { + running.Add(1) + go func() { + defer running.Done() + for job := range next { + var encoded bytes.Buffer + if _, err := patchgen.Write(patchgen.Request{ + App: app, FromVersion: job.from.version, ToVersion: version, + OS: job.asset.OS, Arch: job.asset.Arch, + OldArchive: job.from.archive, NewArchive: filepath.Join(dir, job.name), + Executable: executable, Exclude: excludes, + Output: &encoded, + }); err != nil { + job.err = fmt.Errorf("feed: patch %s from %s: %w", job.key, job.from.version, err) + continue + } + if maxRatio > 0 && float64(encoded.Len()) > maxRatio*float64(job.asset.Size) { + continue + } + patchName := job.name + "." + job.from.version + ".patch" + if err := writePatchFileBeside(filepath.Join(dir, patchName), encoded.Bytes()); err != nil { + job.err = err + continue + } + sum := sha256.Sum256(encoded.Bytes()) + job.patch = update.Patch{ + FromVersion: job.from.version, + URL: base + "/" + url.PathEscape(patchName), + Size: int64(encoded.Len()), + SHA256: hex.EncodeToString(sum[:]), + } + job.written = true } - sum := sha256.Sum256(encoded.Bytes()) - asset.Patches = append(asset.Patches, update.Patch{ - FromVersion: from.version, - URL: base + "/" + url.PathEscape(patchName), - Size: int64(encoded.Len()), - SHA256: hex.EncodeToString(sum[:]), - }) - matched[key]++ + }() + } + for _, job := range jobs { + next <- job + } + close(next) + running.Wait() + matched := make(map[string]int, len(byTarget)) + for _, job := range jobs { + if job.err != nil { + return job.err + } + matched[job.key]++ + if job.written { + job.asset.Patches = append(job.asset.Patches, job.patch) } + } + for i := range assets { + asset := &assets[i] sort.Slice(asset.Patches, func(a, b int) bool { order, err := update.Compare(asset.Patches[a].FromVersion, asset.Patches[b].FromVersion) return err == nil && order < 0 diff --git a/cmd/viva/feed_test.go b/cmd/viva/feed_test.go index cb5ccc533..e9eb141b9 100644 --- a/cmd/viva/feed_test.go +++ b/cmd/viva/feed_test.go @@ -13,6 +13,7 @@ import ( "os" "path/filepath" "runtime" + "strconv" "strings" "testing" "time" @@ -596,6 +597,69 @@ version = "2.0.0" } } +func TestFeedLeavesOutAPatchOverTheMaxRatio(t *testing.T) { + t.Setenv("VIVA_UPDATE_KEY", "") + const oldTOML = `[app] +name = "Fixture Notes" +id = "dev.example.notes" +version = "2.0.0" +` + dir := t.TempDir() + oldDir, newDir := fixture(t, oldTOML), fixture(t, feedTestBasicTOML) + if err := os.WriteFile(filepath.Join(oldDir, "main.go"), []byte("package main\n\nfunc main() { extra() }\n\nfunc extra() {}\n"), 0o644); err != nil { + t.Fatal(err) + } + if output, err := runLinuxPackage(t, oldDir); err != nil { + t.Fatalf("packaging the old release: %v\n%s", err, output) + } + if output, err := runLinuxPackage(t, newDir); err != nil { + t.Fatalf("packaging the new release: %v\n%s", err, output) + } + dist := filepath.Join(dir, "dist") + oldArchive := filepath.Join(oldDir, "build", "fixture-notes-2.0.0-linux-amd64.tar.gz") + newArchive := filepath.Join(newDir, "build", "fixture-notes-2.0.1-linux-amd64.tar.gz") + copyFeedFile(t, newArchive, filepath.Join(dist, filepath.Base(newArchive))) + key, _ := feedTestKey(t, dir) + feedAsset := func(ratio string) update.Asset { + t.Helper() + feedPath := filepath.Join(dist, "latest.json") + var output bytes.Buffer + err := runCLI([]string{ + "feed", "-C", newDir, "-dir", dist, "-base-url", "https://example.com/app", + "-key", key, "-out", feedPath, + "--patch-from", "linux/amd64=2.0.0=" + oldArchive, "--patch-max-ratio", ratio, + }, &output, io.Discard) + if err != nil { + t.Fatalf("ratio %s: %v\n%s", ratio, err, output.String()) + } + data, err := os.ReadFile(feedPath) + if err != nil { + t.Fatal(err) + } + var feed update.Feed + if err := json.Unmarshal(data, &feed); err != nil { + t.Fatal(err) + } + return feed.Latest.Assets[0] + } + patchPath := filepath.Join(dist, "fixture-notes-2.0.1-linux-amd64.tar.gz.2.0.0.patch") + full := feedAsset("1") + if len(full.Patches) != 1 { + t.Fatalf("a patch under the ratio is missing (%d patches)", len(full.Patches)) + } + // A ratio just under the patch's own share of the archive must drop it. + if err := os.Remove(patchPath); err != nil { + t.Fatal(err) + } + ratio := 0.9 * float64(full.Patches[0].Size) / float64(full.Size) + if got := feedAsset(strconv.FormatFloat(ratio, 'f', -1, 64)); len(got.Patches) != 0 { + t.Errorf("a patch over the ratio is still listed (%d patches)", len(got.Patches)) + } + if _, err := os.Stat(patchPath); err == nil { + t.Error("a patch over the ratio was still written beside the archives") + } +} + func TestFeedRejectsBadPatchFrom(t *testing.T) { t.Setenv("VIVA_UPDATE_KEY", "") dir := t.TempDir() diff --git a/cmd/viva/help.go b/cmd/viva/help.go index 0aef5441e..b174a230a 100644 --- a/cmd/viva/help.go +++ b/cmd/viva/help.go @@ -78,7 +78,8 @@ func commands() []command { "as -notes must be when given. The signing key is -key, or $VIVA_UPDATE_KEY: the base64 64-byte\n" + "private key 'viva update-keygen' writes. App, version and archive directory default to viva.toml.\n" + "--patch-from os/arch=version=archive (repeatable) writes a delta update from that earlier\n" + - "release beside the archives and lists it on the asset; it works for darwin, linux and windows.", + "release beside the archives and lists it on the asset; it works for darwin, linux and windows.\n" + + "--patch-max-ratio leaves out a patch larger than that fraction of its full archive.", run: func(arguments []string, output, errorOutput io.Writer) error { return runFeed(arguments, output, errorOutput) }}, diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index 2927b5d5d..1fa5b9b95 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -43,7 +43,7 @@ The loop for every change: | A table with sortable columns | Tables | `ui.Table`, `ui.TableSpec`, `ui.TableRows`, `components.TableColumn` | | Tabs or a navigation strip | Tabs and select | `ui.Tabs`, `ui.Choice`, a `switch` on the value | | A tree, a file tree, a gallery, a calendar grid | Lists, trees and scrolling | `ui.Tree`, `ui.TreeState`, `ui.Grid`, `ui.Flow` | -| A dialog, menu, popup, drawer or dashboard | Menus, dialogs and popups | `ui.Modal`, `ui.ModalWith`, `ui.Dialog`, `ui.Menu`, `ui.PopoverWith`, `ui.Drawer` | +| A dialog, menu, popup, drawer or dashboard | Menus, dialogs and popups | `ui.Modal`, `ui.Dialog`, `ui.Menu`, `ui.Popover`, `ui.Drawer` | | Animation, a progress bar, a timer, a media player | Animation and time | `c.Canvas().Now()`, `c.Canvas().RequestFrame()`, `ui.Progress`, `ui.Spinner` | | Light/dark, a color picker, custom colors | The theme | `gfx.LightTheme()`, `gfx.DarkTheme()`, `PageConfig.Theme`, `c.Theme()` | | A split pane, a divider, drag and drop | Keys, drag and the mouse | `ui.Splitter`, `ui.DragState`, `.DragSource`, `.DropTarget` | @@ -91,8 +91,8 @@ func (m *model) page(c ui.C) { }) if ui.Button(c, "Save").Clicked() { m.save() } }) - ui.Modal(c, &m.confirm, "Delete host?", func() { /* body */ }, func() { /* footer buttons */ }) - ui.Popover(c, anchorBox, &m.menuOpen, func() { /* the panel */ }) + ui.Modal(c, &m.confirm, "Delete host?", ui.ModalSpec{}, func() { /* body */ }, func() { /* footer buttons */ }) + ui.Popover(c, anchorBox, &m.menuOpen, ui.PopoverSpec{}, func() { /* the panel */ }) } ``` @@ -131,6 +131,8 @@ func (m *model) page(c ui.C) { `ui.Row(c).Clip().Children(func() { ui.Row(c).Width(900).ScrollWith(&m.list).Children(titles) })`. - A tree: keep a `ui.TreeState` with `Node` describing each visible row, `ui.Tree(c, &m.tree, n, label, nil)`, then `m.tree.Toggled()` (open or close that branch, give the tree its new rows) and `m.tree.Chosen()`. + To load a branch's children on demand, answer `Toggled()` by fetching and set `TreeNode.Loading` on that row + until they arrive: it shows a spinner in place of the chevron and takes no second press. Typing the start of a name moves to that row. To drag rows, set `m.tree.CanDrop = func(from, to int, where ui.TreeDrop) bool` (`TreeDropBefore`, `TreeDropInside`, `TreeDropAfter`) and read `m.tree.Dropped()`; change the rows in `c.After`, since the paint that reports the drop is declaring them. @@ -169,21 +171,26 @@ func (m *model) page(c ui.C) { - A row a menu cannot say: `menu.ContentPage(40, func(c ui.C, bounds ui.Rect) { ui.ColorSwatch(c, ...) })` declares page controls in a row of their own (the keyboard passes over it); `menu.Content(height, paint)` is the canvas painter for a row the page cannot declare. -- `ui.SelectID(c, id, &m.size, choices, nil)` is `ui.Select` for a control the application names: a row's words can be its `LabelFor`, and the application's key and focus routing can target it. +- `ui.Select(c, &m.size, choices, nil, ui.WithID(id))` names a control the application holds an identity for: a row's words can be its `LabelFor`, and the application's key and focus routing can target it. +- `ui.TextField(c, &m.title, "Title", "", ui.MaxLength(80), ui.ShowCount())` caps a text control at 80 runes and shows "n/80" at the end of a `TextField` (it takes the place of an `Action`); `ui.MaxLength` also takes a `TextArea`. A model-kept `ui.Field` uses `Field.Restrict(accept, maxRunes)`. +- `.Warning(m.port == "22")` on a `TextField` or `TextArea` paints the warning border (the theme's `Warning` color) for a value that needs a look but did not fail; a field marked `Invalid` keeps its destructive border over it. A model-kept `ui.Field` sets `Field.Warning`; `inputgroup.Group.Warning(bool)` does the same for a group. +- `ui.Progress(c, m.done/m.total).Status(ui.StatusSuccess)` fills a progress bar in the theme's color for the outcome (success, warning or danger) instead of the primary one; it is the status vocabulary an alert and a tag use. `.Circle()` draws the progress as a ring that fills clockwise (64 across unless sized; `Indeterminate()` makes it a turning arc), `ui.Progress(c, m.done/m.total).Circle().Size(80, 80)`. `.Segments(5)` draws the bar as five separate segments with the first ones filled for the fraction, for work that comes in stages. +- `ui.Button(c, "Connect").Loading(m.connecting).Clicked()` marks a button busy: a spinner takes the place of its icon (or stands before its label), the button keeps its look and delivers no press while it is on, so the work cannot start twice. `ui.Switch(c, &m.forwarding, "Forwarding").Loading(m.applying)` does the same for a switch: the spinner turns on the thumb and the bound value is not flipped while it is on. +- `ui.Slider(c, &m.quality).Range(0, 100).Step(25).Marks(m.marks)` puts a dot on the track at each `ui.SliderMark{Value, Label}` and the label under it (a horizontal slider with a labelled mark is taller by the room the words take); keep the `[]ui.SliderMark` in the model. +- `ui.Select(c, &m.host, m.hosts, nil, ui.SelectGroups(m.groups))` puts a heading row before the first option of each `ui.SelectGroup{Label, From}`; the choices must be in group order. A heading is not an option (no focus, click or type-ahead), and `Picked`, `DisabledOptions` and `Icons` keep the choices' own indexes. - Color choices: `ui.ColorSwatch(c, color, chosen, "Red")` is a radio (`.Flush()` fills its border with the color, `.TabStop(chosen)` makes one swatch the Tab stop, `ColorSwatchID` keeps an application identity); `ui.ColorPicker(c, &m.picker, &m.color, "Accent")` opens a panel to pick one, `.Draft()` follows the drag before Apply and `.Applied()` says a choice was committed. - A side panel: `ui.Drawer(c, &m.open, "Title", ui.DrawerSpec{Side: ui.DrawerLeft, Size: 320}, body, footer)`; an empty title gives the body the whole panel, `NonModal` keeps the keyboard on the page, `Swipe` adds a handle that a drag toward the edge closes it by (past half its size, or thrown). -- A modal dialog: declare it while it is open, `ui.Modal(c, &m.confirm, "Delete host?", body, footer)`; the title is +- A modal dialog: declare it while it is open, `ui.Modal(c, &m.confirm, "Delete host?", ui.ModalSpec{}, body, footer)`; the title is required because it names the dialog for screen readers, and `body`/`footer` may be nil. It is centered over a scrim, keeps the keyboard while open and gives it back as it closes; a press on the scrim, the close button and Escape set - `m.confirm` to false. `ui.ModalWith(c, &m.confirm, "Delete host?", ui.ModalSpec{Description: "...", Width: 400}, body, footer)` + `m.confirm` to false. `ui.Modal(c, &m.confirm, "Delete host?", ui.ModalSpec{Description: "...", Width: 400}, body, footer)` adds a description, a size, `NoClose` or `InitialFocus`. For a dialog whose identities the application names itself, use `ui.Dialog(c, ui.DialogSpec{...})`: `Scope`, `DismissID`, `CloseID` and `InitialFocusID` are yours, `.Header(fn)`, `.Body(fn)` and `.Footer(fn)` declare it, and `.Dismissed()` reports the closing click. Do not write an Escape handler for any of these; they dismiss themselves. -- A popup of your own: `ui.Popover(c, anchor, &m.open, body)` or - `ui.PopoverWith(c, anchor, ui.PopoverSpec{Width: 220, Align: ui.Start}, &m.open, body)`; it opens off its anchor, +- A popup of your own: `ui.Popover(c, anchor, &m.open, ui.PopoverSpec{Width: 220, Align: ui.Start}, body)`; it opens off its anchor, flips when there is no room, closes on Escape or an outside press, and gives the focus back. A floating region that is none of these is `ui.Overlay(c, ui.OverlaySpec{Band: ui.LayerPaneChrome, Bounds: r})` (or `ui.LayerDrag` for a drag ghost): it takes no room, paints after the page and below Viva's menus and dialogs, and its children are page @@ -191,7 +198,7 @@ func (m *model) page(c ui.C) { `Slot` and a `Hit`; the page's overlays keep the pointer, focus and dismissal a popup needs. A component author who declares the underlying popup places it with `Beside(rect, gap, align)` or `BesideBox(box, gap, align)` to the right of an anchor (a submenu), `BesideLeft`/`BesideLeftBox` to its left, and `Within(rect)` to keep it inside a region - instead of the window; `ui.PopoverWith`'s `Side` is the application-level form of the same placement. + instead of the window; `ui.Popover`'s `Side` is the application-level form of the same placement. `Below`/`BelowBox` and `Above`/`AboveBox` place below and above. ### Choices, toasts and shortcuts @@ -226,7 +233,9 @@ func (m *model) page(c ui.C) { `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, - `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`. + `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, + `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, + `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`. - For read-only selectable output, keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`. The caller owns the lines, spans and actions; `ui/textview` owns selection and drawing without an editing model. @@ -308,6 +317,11 @@ func (m *model) page(c ui.C) { `ui.Control`'s `Draw`, a part (a card of a custom grid) is a source or target of the same state with `d.DragSource(&m.drag, part, r)` and `d.DropTarget(&m.drag, part, r, accept, drop)`, declared beside `d.Canvas.Hit(part, r)`; a target part needs no `Hit`. +- Files dragged from the system land on a box declared with `.DropFiles(&m.drop)`, a `ui.FileDropState` in the + model: `m.drop.Over()` paints the highlight while files are over it, and `m.drop.Dropped()` returns the files + (and their paths, empty in a browser) once. `ui.OpenFiles(c, options, done)` is the system's picker, answering + with files that read the same way; `ui.FilePath(file)` is a file's path where there is one. For a whole upload + area with a file list, use `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`. - For a divider between two panes, use `ui.Splitter` (see "Keys, drag and the mouse"), not a `DragState`. ## Mistakes that compile (and how each is reported) @@ -503,18 +517,19 @@ func (m *model) page(c ui.C) { from the state when the spec leaves them zero: ```go - columns := []components.TableColumn{ - {Width: 160}, - {}, // no width: the last column takes the rest + columns := []ui.TableColumn{ + {Title: "Name", Width: 160, Sortable: true}, + {Title: "Age", Sortable: true}, // no width: the last column takes the rest } - t := ui.Table(c, &m.table, ui.TableSpec{Headers: []string{"Name", "Age"}, - Sortable: []bool{true, true}, Source: &m.data, Striped: true, Columns: columns}) + t := ui.Table(c, &m.table, ui.TableSpec{Source: &m.data, Striped: true, Columns: columns}) if i, ok := t.RowClicked(); ok { m.table.Select(i) } // Selected() is the row or -1, ClearSort() unsorts if col, ok := t.HeaderClicked(); ok { m.table.SortBy(col); m.sortData() } // Sort() returns (column, descending, ok) ``` - A header cell is clickable only where `Sortable[c]` is true; `Headers` alone draws a title nobody can click. In a + A header cell is clickable only where the column is `Sortable`; a `Title` alone draws a heading nobody can click, and a table none of whose columns has a `Title` has no header row. In a `ui.Scroll` the table is as tall as its rows and only visible rows are read; with `Height`, `Fill` or `Grow` it scrolls + `Checked: &m.checked` (a `ui.Selection` of row numbers kept in the model) puts a column of checkboxes in front of the columns, with a header checkbox that ticks every row, clears them and shows mixed while some are ticked; `state.CheckedChanged()` reports a tick in the paint that delivered it. The ticks are separate from the selected row, and `Source.Cell`, `HeaderClicked` and `CellRect` keep the indexes of `Columns`. + A column with `Filterable: true` gets a funnel button at the end of its heading (`Filtered: true` paints it as on); `table.FilterClicked()` reports a press on it as the column's index, and `state.HeaderRect(column)` is where to anchor the choice of what to show, for instance a `ui.MenuAt`. The application filters its own rows. its rows under a fixed header and draws its own hover bars: `Scrollbar` names the bar's hit, `ScrollbarLabel` names it for assistive technology, `ScrollbarSize` sets its thickness (else the page's `PageConfig.ScrollbarSize`) and `ScrollbarGutter` keeps a strip beside the columns for it. An application painting its own vertical bar sets @@ -682,7 +697,7 @@ err := app.RunApplication(func(a *app.Application) error { Colors, all `gfx.Color`: `Background`, `Foreground`, `Card`, `CardForeground`, `CardElevated`, `Popover`, `PopoverForeground`, `Tooltip`, `Muted`, `MutedForeground`, `Border`, `Hover`, `Input`, `Primary`, `PrimaryForeground`, -`Selection`, `SelectionForeground`, `Secondary`, `SecondaryForeground`, `Accent`, `AccentForeground`, `Ring`, `Success`, `Danger`, `DangerForeground`, and +`Selection`, `SelectionForeground`, `Secondary`, `SecondaryForeground`, `Accent`, `AccentForeground`, `Ring`, `Success`, `Danger`, `DangerForeground`, `Warning` (the warning status color; `Theme.WarningColor` falls back to `Danger` when a hand-built theme leaves it zero), and `Chart` (an array of five). There is no `Surface`, `Text` or `Error`: use `Card`, `Foreground`, `Danger`. A `gfx.Color` is `{Red, Green, Blue, Alpha float32}` with each in 0..1 (so `gfx.Color{Alpha: 0.5}` is a black scrim); it has `Mix(other, t)`, `Over(backdrop)` and `WithAlpha(a)`, and no `R` or `A`. To write a color of your own, `gfx.RGB24(0x0a84ff)` diff --git a/cmd/viva/package_dmg_test.go b/cmd/viva/package_dmg_test.go index 8bb846da8..89417dd17 100644 --- a/cmd/viva/package_dmg_test.go +++ b/cmd/viva/package_dmg_test.go @@ -11,7 +11,7 @@ import ( ) func TestPackageMakesADiskImageHoldingTheBundleAndAnApplicationsLink(t *testing.T) { - requireMac(t) + requireDiskImages(t) dir := fixture(t, packageTOML) writeIcon(t, filepath.Join(dir, "icon.png"), 512) var output strings.Builder diff --git a/cmd/viva/package_sign_test.go b/cmd/viva/package_sign_test.go index 525f9344d..0e1efc494 100644 --- a/cmd/viva/package_sign_test.go +++ b/cmd/viva/package_sign_test.go @@ -142,7 +142,7 @@ func releaseEnvironment(t *testing.T) { } func TestADiskImageIsSignedNotarizedAndStapledOnce(t *testing.T) { - requireMac(t) + requireDiskImages(t) dir := signingFixture(t) releaseEnvironment(t) r := &recorder{} @@ -199,8 +199,8 @@ func TestADiskImageIsSignedNotarizedAndStapledOnce(t *testing.T) { // A zip is what the in-app updater downloads, so the bundle inside it has to // carry its own ticket: without one the system asks Apple at every launch, and // refuses the update wherever that lookup cannot be made. -func TestAZippedBundleIsNotarizedAndStapledBeforeTheImageIsMade(t *testing.T) { - requireMac(t) +func TestDiskImageIsMadeAfterZippedBundleNotarization(t *testing.T) { + requireDiskImages(t) dir := signingFixture(t) releaseEnvironment(t) r := &recorder{} @@ -247,8 +247,8 @@ func TestABundleWithoutADiskImageIsNotarizedByAZipAndStapledBeforeItIsZipped(t * } } -func TestARejectedNotarizationFailsThePackageWithApplesReasons(t *testing.T) { - requireMac(t) +func TestDiskImageNotarizationRejectionReportsApplesReasons(t *testing.T) { + requireDiskImages(t) dir := signingFixture(t) releaseEnvironment(t) r := &recorder{status: "Invalid"} diff --git a/cmd/viva/package_test.go b/cmd/viva/package_test.go index 9d695cc94..7b4401755 100644 --- a/cmd/viva/package_test.go +++ b/cmd/viva/package_test.go @@ -15,6 +15,18 @@ import ( "testing" ) +// requireDiskImages skips a test that makes real disk images with hdiutil unless +// VIVA_DISK_IMAGE_TESTS is set. The disk image service of a shared macOS machine fails +// now and then whatever the code does, so these run where a change can affect how an +// image is made (the disk-image CI job), not on every change. +func requireDiskImages(t *testing.T) { + t.Helper() + requireMac(t) + if os.Getenv("VIVA_DISK_IMAGE_TESTS") == "" { + t.Skip("makes real disk images with hdiutil; set VIVA_DISK_IMAGE_TESTS=1 to run") + } +} + func requireMac(t *testing.T) { t.Helper() if runtime.GOOS != "darwin" { diff --git a/cmd/viva/signing_temp_windows_test.go b/cmd/viva/signing_temp_windows_test.go index 01339b4f1..c3ac407f8 100644 --- a/cmd/viva/signing_temp_windows_test.go +++ b/cmd/viva/signing_temp_windows_test.go @@ -31,12 +31,40 @@ func signingACL(t *testing.T, path string) string { return syscall.UTF16ToString(unsafe.Slice(value, size)) } +// sddlTrustee returns how a security descriptor string names the account with +// sid. Windows writes the well-known accounts by a two-letter alias rather than +// by SID (the built-in Administrator, RID 500, is "LA"), so comparing the +// trustee of a descriptor read back from disk with the SID string fails for +// exactly the accounts that have an alias. Round-tripping a one-entry +// descriptor through the same conversion gives the form the system will use. +func sddlTrustee(t *testing.T, sid string) string { + t.Helper() + sddl, err := syscall.UTF16PtrFromString("D:(A;;FA;;;" + sid + ")") + if err != nil { + t.Fatal(err) + } + var descriptor uintptr + if ok, _, err := signingSDFromString.Call(uintptr(unsafe.Pointer(sddl)), 1, uintptr(unsafe.Pointer(&descriptor)), 0); ok == 0 { + t.Fatal(err) + } + defer syscall.LocalFree(syscall.Handle(descriptor)) + var value *uint16 + var size uint32 + if ok, _, err := signingAdvapi.NewProc("ConvertSecurityDescriptorToStringSecurityDescriptorW").Call(descriptor, 1, 4, uintptr(unsafe.Pointer(&value)), uintptr(unsafe.Pointer(&size))); ok == 0 { + t.Fatal(err) + } + defer syscall.LocalFree(syscall.Handle(uintptr(unsafe.Pointer(value)))) + entry := syscall.UTF16ToString(unsafe.Slice(value, size)) + return entry[strings.LastIndex(entry, ";")+1 : len(entry)-1] +} + func assertPrivateSigningFile(t *testing.T, path string) { t.Helper() sid, err := signingUserSID() if err != nil { t.Fatal(err) } + trustee := sddlTrustee(t, sid) for _, name := range []string{filepath.Dir(path), path} { acl := signingACL(t, name) if name == filepath.Dir(path) && !strings.HasPrefix(acl, "D:P") { @@ -48,7 +76,7 @@ func assertPrivateSigningFile(t *testing.T, path string) { } for _, entry := range entries[1:] { parts := strings.Split(strings.TrimSuffix(entry, ")"), ";") - if len(parts) != 6 || parts[0] != "A" || parts[2] != "FA" || (parts[5] != sid && parts[5] != "SY") { + if len(parts) != 6 || parts[0] != "A" || parts[2] != "FA" || (parts[5] != trustee && parts[5] != "SY") { t.Fatalf("unexpected access grant: %s", acl) } } diff --git a/cmd/viva/templates/bubble.go.txt b/cmd/viva/templates/bubble.go.txt index 4b59b187f..94e3f27c7 100644 --- a/cmd/viva/templates/bubble.go.txt +++ b/cmd/viva/templates/bubble.go.txt @@ -141,7 +141,7 @@ func bubbleTint(theme gfx.Theme) gfx.Color { // radiusXL is the corner radius of the official rounded-xl surfaces, the one // Card uses. -func radiusXL(metrics gfx.Metrics) float32 { return metrics.RadiusSurface + 4 } +func radiusXL(metrics gfx.Metrics) float32 { return gfx.RadiusOutset(metrics.RadiusSurface, 4) } // BubbleReactionSide selects whether a reaction capsule overlaps the top or // bottom edge of a bubble. diff --git a/cmd/viva/templates/button.go.txt b/cmd/viva/templates/button.go.txt index c5c749ff8..967446a24 100644 --- a/cmd/viva/templates/button.go.txt +++ b/cmd/viva/templates/button.go.txt @@ -633,8 +633,19 @@ type ButtonContent struct { IconOnly bool // Underlined underlines the label, as a hovered link is. Underlined bool + // PaintLoading, when set, paints the loading indicator in the place of the icon (or + // before the label when there is none), at Phase and in Color, with Theme. The + // button does not know what the indicator looks like: a page gives the one of + // package components' Spinner, so the recipe does not depend on its file. + PaintLoading ButtonLoadingPainter + Phase uint8 + Theme *gfx.Theme } +// ButtonLoadingPainter paints a button's loading indicator in bounds. Give it a +// function, not a closure made in each paint, which would allocate. +type ButtonLoadingPainter func(canvas *gfx.Canvas, theme *gfx.Theme, bounds gfx.Rect, color gfx.Color, phase uint8) + // PaintButtonContent paints a button's icon and label centered in area and returns the // hint an icon-only button gives assistive technology, which is its label. It is the // content half of the paint the Button does: the same placement, the same shrinking of @@ -645,7 +656,8 @@ func PaintButtonContent(canvas *gfx.Canvas, area gfx.Rect, content ButtonContent } look := buttonStyle{foreground: content.Color, underlined: content.Underlined} label := content.Label - if len(content.Icon.Commands) == 0 && len(content.Icon.Layers) == 0 { + loading := content.PaintLoading != nil + if len(content.Icon.Commands) == 0 && len(content.Icon.Layers) == 0 && !loading { paintButtonLabel(canvas, label, area, content.FontSize, content.Weight, look) return "" } @@ -655,7 +667,9 @@ func PaintButtonContent(canvas *gfx.Canvas, area gfx.Rect, content ButtonContent width = min(area.Width, width+content.Gap+canvas.TextWidthWeight(label, content.FontSize, content.Weight)) } x := area.X + (area.Width-width)/2 - if size > 0 { + if size > 0 && loading { + content.PaintLoading(canvas, content.Theme, gfx.Rect{X: x, Y: area.Y + (area.Height-size)/2, Width: size, Height: size}, content.Color, content.Phase) + } else if size > 0 { canvas.DrawIconTransformed( content.Icon, gfx.Rect{X: x, Y: area.Y + (area.Height-size)/2, Width: size, Height: size}, diff --git a/cmd/viva/templates/card.go.txt b/cmd/viva/templates/card.go.txt index c5b7bca68..0a3e1b518 100644 --- a/cmd/viva/templates/card.go.txt +++ b/cmd/viva/templates/card.go.txt @@ -42,7 +42,7 @@ func PaintCard(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, options Car if canvas == nil || bounds.Width <= 0 || bounds.Height <= 0 { return CardLayout{} } - radius := theme.Metrics.RadiusSurface + 4 + radius := gfx.RadiusOutset(theme.Metrics.RadiusSurface, 4) ring := theme.Foreground ring.Alpha *= 0.10 canvas.Elevate(bounds, radius, gfx.ShadowXS) // shadow-xs diff --git a/cmd/viva/templates/input.go.txt b/cmd/viva/templates/input.go.txt index c40795a45..cd2dc536e 100644 --- a/cmd/viva/templates/input.go.txt +++ b/cmd/viva/templates/input.go.txt @@ -37,7 +37,7 @@ func PaintInput(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, snapshot I } focused := snapshot.Focused || !snapshot.ID.IsZero() && canvas.Focused() == snapshot.ID - paintTextEntrySurface(canvas, &theme, bounds, gfx.State{Focused: focused, Invalid: snapshot.Invalid, Disabled: snapshot.Disabled}) + paintTextEntrySurface(canvas, &theme, bounds, gfx.State{Focused: focused, Invalid: snapshot.Invalid, Warning: snapshot.Warning, Disabled: snapshot.Disabled}) inset := theme.Metrics.TextInsetX() content := gfx.Rect{X: bounds.X + inset, Y: bounds.Y, Width: inputMax(0, bounds.Width-2*inset), Height: bounds.Height} paintInputContent(canvas, theme, bounds, content, snapshot, focused) @@ -350,10 +350,11 @@ func textEntryDark(theme *gfx.Theme) bool { return theme.Background.Red < 0.5 } // - border-input and a transparent fill, dark:bg-input/30 (hover input/50); // - focus: the border alone turns the accent color; there is no halo around // the control, which would wash the field and crowd its neighbors; -// - invalid: border-destructive, which also wins over the focus color; +// - invalid: border-destructive, which also wins over the focus color; warning is +// the same with the theme's warning color, and invalid wins over it; // - disabled: opacity-50 on all of it. // -// Only Hovered, Focused, Invalid and Disabled of state are read. It is a pure function: +// Only Hovered, Focused, Invalid, Warning and Disabled of state are read. It is a pure function: // the same theme and state give the same look, and nothing is painted. func TextEntryRecipe(theme gfx.Theme, state gfx.State) TextEntryLook { return textEntryRecipe(&theme, state) @@ -395,6 +396,8 @@ func textEntryTokens(theme *gfx.Theme, state gfx.State) (border, fill gfx.Color) } if state.Invalid { border = theme.Danger + } else if state.Warning { + border = theme.WarningColor() } if state.Disabled { border.Alpha *= 0.50 diff --git a/cmd/viva/templates/input_group.go.txt b/cmd/viva/templates/input_group.go.txt index ed2ef8cfa..99f98f3b9 100644 --- a/cmd/viva/templates/input_group.go.txt +++ b/cmd/viva/templates/input_group.go.txt @@ -102,7 +102,7 @@ func PaintInputGroup(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, snaps layout.Control = gfx.Rect{X: row.X + startWidth, Y: row.Y, Width: inputGroupMax(0, row.Width-startWidth-endWidth), Height: row.Height} focused := !snapshot.Disabled && (snapshot.Focused || !snapshot.ID.IsZero() && canvas.Focused() == snapshot.ID) - paintTextEntrySurface(canvas, &theme, bounds, gfx.State{Focused: focused, Invalid: snapshot.Invalid, Disabled: snapshot.Disabled}) + paintTextEntrySurface(canvas, &theme, bounds, gfx.State{Focused: focused, Invalid: snapshot.Invalid, Warning: snapshot.Warning, Disabled: snapshot.Disabled}) inputGroupPaintSlot(canvas, theme, layout.BlockStart, snapshot.BlockStart, true, false, snapshot.Disabled) inputGroupPaintSlot(canvas, theme, layout.BlockEnd, snapshot.BlockEnd, true, false, snapshot.Disabled) inputGroupPaintSlot(canvas, theme, layout.InlineStart, snapshot.InlineStart, false, true, snapshot.Disabled) diff --git a/cmd/viva/templates/item.go.txt b/cmd/viva/templates/item.go.txt index a91091cb4..6d7d600c0 100644 --- a/cmd/viva/templates/item.go.txt +++ b/cmd/viva/templates/item.go.txt @@ -153,7 +153,7 @@ func (item Item) Paint(title, description, trailing string) ItemLayout { if focused { focus := item.theme.Ring focus.Alpha *= 0.50 - item.canvas.RoundedBorder(expand(item.bounds, 3), metrics.RadiusControl+3, 3, focus, gfx.Color{}) + item.canvas.RoundedBorder(expand(item.bounds, 3), gfx.RadiusOutset(metrics.RadiusControl, 3), 3, focus, gfx.Color{}) } background := gfx.Color{} diff --git a/cmd/viva/templates/message_scroller.go.txt b/cmd/viva/templates/message_scroller.go.txt index e0a8363b2..4483a4c67 100644 --- a/cmd/viva/templates/message_scroller.go.txt +++ b/cmd/viva/templates/message_scroller.go.txt @@ -240,7 +240,7 @@ func (scroller MessageScroller) paintButton(bounds gfx.Rect, id gfx.ID, label st if scroller.canvas.FocusVisible() == id { ring := scroller.theme.Ring ring.Alpha *= 0.50 - scroller.canvas.Rounded(messageScrollerExpand(bounds, 3), scroller.theme.Metrics.RadiusControl+3, ring) + scroller.canvas.Rounded(messageScrollerExpand(bounds, 3), gfx.RadiusOutset(scroller.theme.Metrics.RadiusControl, 3), ring) } scroller.canvas.RoundedBorder(bounds, scroller.theme.Metrics.RadiusControl, 1, scroller.theme.Border, background) icon := &arrowDownIcon diff --git a/cmd/viva/templates/select.go.txt b/cmd/viva/templates/select.go.txt index 058ba044c..3d8e8af78 100644 --- a/cmd/viva/templates/select.go.txt +++ b/cmd/viva/templates/select.go.txt @@ -91,6 +91,9 @@ type SelectItem struct { Hint string Selected bool Disabled bool + // Heading paints the row as a group heading: the label muted and set small, with no + // hover, no hit and no check, in the same row height as an option. + Heading bool // Icon, when it has any geometry, is painted before the label. Icon gfx.Icon // IconImage is a full-color image in the icon slot when Icon is empty. @@ -270,6 +273,20 @@ func (selectControl *Select) AddLabel(label string) gfx.Rect { // is empty when the row is scrolled out of the popup. func (selectControl *Select) AddItem(item SelectItem) gfx.Rect { bounds := selectControl.rowBounds(32) + if item.Heading { + if !selectControl.reserve(bounds) { + return gfx.Rect{} + } + selectControl.rows.paintRow(bounds, func() { + if selectControl.options.Unpainted { + return + } + selectControl.canvas.Label(item.Label, gfx.Rect{X: bounds.X + 8, Y: bounds.Y, Width: selectMax(0, bounds.Width-16), Height: bounds.Height}, gfx.TextStyle{ + Size: selectControl.theme.Metrics.FontSizeS, Weight: gfx.WeightMedium, Color: selectControl.theme.MutedForeground, + }) + }) + return bounds + } if !selectControl.open || !selectControl.rows.takeItem(bounds, item.ID, item.Label, item.Disabled) { return gfx.Rect{} } diff --git a/cmd/viva/templates/sidebar.go.txt b/cmd/viva/templates/sidebar.go.txt index d230ef0bf..5a1aa2c71 100644 --- a/cmd/viva/templates/sidebar.go.txt +++ b/cmd/viva/templates/sidebar.go.txt @@ -182,7 +182,7 @@ func PaintSidebarInset(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, sid if card.Width <= 0 || card.Height <= 0 { return gfx.Rect{} } - canvas.Rounded(card, theme.Metrics.RadiusSurface+4, theme.Background) + canvas.Rounded(card, gfx.RadiusOutset(theme.Metrics.RadiusSurface, 4), theme.Background) return card } diff --git a/cmd/viva/templates/slider.go.txt b/cmd/viva/templates/slider.go.txt index 8fdd29fd9..750f06516 100644 --- a/cmd/viva/templates/slider.go.txt +++ b/cmd/viva/templates/slider.go.txt @@ -32,6 +32,7 @@ type SliderGeometry struct { // with ValueAt (the pointer events of the held thumb carry it, with capture while // it is dragged) and a key into one with SliderKeyDown, and passes the result back. type Slider struct { + marks []SliderMark canvas *gfx.Canvas theme gfx.Theme id gfx.ID @@ -46,6 +47,16 @@ type Slider struct { disabled bool } +// SliderMark is a value marked on the track, with a word under it when it has a label. +type SliderMark = base.SliderMark + +// Marks puts a dot on the track at each mark's value and its label under the track. +// The labels hang below bounds, so the caller leaves room for them. +func (slider Slider) Marks(marks []SliderMark) Slider { + slider.marks = marks + return slider +} + // BeginSlider starts a single-thumb 0..100 slider declaration. func BeginSlider(canvas *gfx.Canvas, theme gfx.Theme, id gfx.ID, bounds gfx.Rect, value float32) Slider { return Slider{canvas: canvas, theme: theme, id: id, bounds: bounds, maximum: 100, value: value} @@ -147,6 +158,7 @@ func (slider Slider) Paint(label string) SliderGeometry { activeRadius = geometry.Active.Width / 2 } slider.canvas.Rounded(geometry.Active, activeRadius, activeColor) + slider.paintMarks(geometry, trackColor) for index := 0; index < slider.ThumbCount(); index++ { _, id, thumbDisabled := slider.thumb(index) @@ -190,6 +202,41 @@ func (slider Slider) Paint(label string) SliderGeometry { return geometry } +// paintMarks draws a dot on the track at each mark, light over the filled part and dark +// over the rest, and the labels of the marks under the track. +func (slider Slider) paintMarks(geometry SliderGeometry, trackColor gfx.Color) { + if len(slider.marks) == 0 { + return + } + origin, extent := slider.travel() + _, end := slider.activeFractions() + const dot = float32(4) + over := slider.theme.PrimaryForeground + rest := slider.theme.MutedForeground + if slider.disabled { + over.Alpha *= 0.50 + rest.Alpha *= 0.50 + } + for _, mark := range slider.marks { + fraction := slider.fraction(mark.Value) + color := rest + if fraction <= end { + color = over + } + if slider.vertical { + y := origin + extent*(1-fraction) + slider.canvas.Rounded(gfx.Rect{X: geometry.Track.X + (geometry.Track.Width-dot)/2, Y: y - dot/2, Width: dot, Height: dot}, dot/2, color) + continue + } + x := origin + extent*fraction + slider.canvas.Rounded(gfx.Rect{X: x - dot/2, Y: geometry.Track.Y + (geometry.Track.Height-dot)/2, Width: dot, Height: dot}, dot/2, color) + if mark.Label != "" { + label := gfx.Rect{X: x - 48, Y: geometry.Bounds.Y + geometry.Bounds.Height + 2, Width: 96, Height: slider.theme.Metrics.FontSizeS + 6} + slider.canvas.LabelCenter(mark.Label, label, gfx.TextStyle{Size: slider.theme.Metrics.FontSizeS, Weight: gfx.WeightRegular, Color: rest}) + } + } +} + func (slider Slider) geometry() SliderGeometry { bounds := slider.resolvedBounds() track := slider.trackBounds() diff --git a/cmd/viva/templates/sonner.go.txt b/cmd/viva/templates/sonner.go.txt index 1e94c3545..c9f88632c 100644 --- a/cmd/viva/templates/sonner.go.txt +++ b/cmd/viva/templates/sonner.go.txt @@ -9,7 +9,9 @@ import ( // are ordered newest first. Layer is the oldest toast's layer; each newer toast // receives the next layer so collapsed cards composite correctly. type SonnerOptions struct { - Layer uint16 + // Layer is the oldest toast's layer; each newer toast receives the next. + Layer uint16 + // Expanded lays the stack out with a gap instead of a peek. Expanded bool // Limit is how many of the newest toasts show; the zero value is Base UI's 3. // Older ones are not painted. @@ -37,32 +39,39 @@ func PaintSonner(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, toasts limit = 3 } top := options.Position >= ToastTopRight + visible := min(limit, len(toasts)) + // A stack shares one width, the widest card in it, so the cards that peek + // behind the front one line up instead of showing ragged edges. + var stackWidth float32 + for index := 0; index < visible; index++ { + toast := toasts[index] + if toast.Snapshot.Limited { + continue + } + var scratch overlayLines + geometry, _ := toastMeasure(canvas, theme, viewport, toast.Snapshot, sonnerToastOptions(options, toast, 0), &scratch) + stackWidth = max(stackWidth, geometry.width) + } var stack SonnerLayout - // Where the next toast of an expanded stack goes: after the heights of the - // toasts in front of it, each with its own wrapped text. - var reach float32 - for index := len(toasts) - 1; index >= 0 && len(toasts)-1-index < limit; index-- { + // Paint from the back of the visible stack to its front, which is the + // first toast: the newest one sits at the edge and the older ones behind it. + for index := visible - 1; index >= 0; index-- { toast := toasts[index] snapshot := toast.Snapshot - snapshot.Index = sonnerIndex(len(toasts) - 1 - index) + snapshot.Index = sonnerIndex(index) snapshot.Expanded = false - toastOptions := ToastOptions{ - Layer: sonnerLayer(options.Layer, len(toasts)-index-1), - Scope: toast.Scope, - DismissID: toast.DismissID, - ActionID: toast.ActionID, - ActionLabel: toast.ActionLabel, - Disabled: toast.Disabled, - Position: options.Position, - } + toastOptions := sonnerToastOptions(options, toast, visible-1-index) + toastOptions.width = stackWidth if options.Expanded && !snapshot.Limited { + // The toast sits after the ones in front of it, each with its own + // wrapped text at the stack's width. + reach := sonnerReach(canvas, theme, viewport, toasts, options, index, stackWidth) if top { snapshot.OffsetY += reach } else { snapshot.OffsetY -= reach } snapshot.Index = 0 - reach += ToastHeight(canvas, theme, viewport, snapshot, toastOptions) + toastStackGap } layout := PaintToast(canvas, theme, viewport, snapshot, toastOptions) if layout == (ToastLayout{}) { @@ -78,6 +87,35 @@ func PaintSonner(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, toasts return stack } +// sonnerReach is how far an expanded toast at index sits from the edge: after +// the heights of the toasts in front of it, which are the smaller indexes. +func sonnerReach(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, toasts []SonnerToast, options SonnerOptions, index int, width float32) float32 { + var reach float32 + for front := 0; front < index; front++ { + if toasts[front].Snapshot.Limited { + continue + } + toastOptions := sonnerToastOptions(options, toasts[front], 0) + toastOptions.width = width + reach += ToastHeight(canvas, theme, viewport, toasts[front].Snapshot, toastOptions) + toastStackGap + } + return reach +} + +// sonnerToastOptions is the options of one toast of a stack, before the stack's +// shared width is known. +func sonnerToastOptions(options SonnerOptions, toast SonnerToast, layerOffset int) ToastOptions { + return ToastOptions{ + Layer: sonnerLayer(options.Layer, layerOffset), + Scope: toast.Scope, + DismissID: toast.DismissID, + ActionID: toast.ActionID, + ActionLabel: toast.ActionLabel, + Disabled: toast.Disabled, + Position: options.Position, + } +} + func sonnerIndex(index int) uint16 { if index > int(^uint16(0)) { return ^uint16(0) diff --git a/cmd/viva/templates/split_button.go.txt b/cmd/viva/templates/split_button.go.txt index 47109a219..48bff2aa1 100644 --- a/cmd/viva/templates/split_button.go.txt +++ b/cmd/viva/templates/split_button.go.txt @@ -151,7 +151,7 @@ func (button SplitButton) paintFocus(bounds gfx.Rect, variant ButtonVariant, id return } ring, _ := buttonRing(&button.theme, variant, false) - button.canvas.Rounded(expand(bounds, 3), button.theme.Metrics.RadiusControl+3, ring) + button.canvas.Rounded(expand(bounds, 3), gfx.RadiusOutset(button.theme.Metrics.RadiusControl, 3), ring) } func (button SplitButton) paintHalf(bounds gfx.Rect, index int, variant ButtonVariant, id gfx.ID, framed bool, radius float32) { diff --git a/cmd/viva/templates/switch.go.txt b/cmd/viva/templates/switch.go.txt index 29c2a332c..472f0eca2 100644 --- a/cmd/viva/templates/switch.go.txt +++ b/cmd/viva/templates/switch.go.txt @@ -101,6 +101,8 @@ func (switchControl Switch) Disabled() Switch { type SwitchResult struct { canvas *gfx.Canvas id gfx.ID + // Thumb is where the thumb was painted, for a caller that draws on it. + Thumb gfx.Rect } // Clicked reports whether this paint is delivering a click on the control. @@ -200,9 +202,8 @@ func (switchControl Switch) Paint() SwitchResult { inset := 1 * scale thumbX := gfx.Lerp(switchControl.bounds.X+inset, switchControl.bounds.X+switchControl.bounds.Width-thumbSize-inset, progress) thumbY := switchControl.bounds.Y + (switchControl.bounds.Height-thumbSize)/2 - switchControl.canvas.Rounded(gfx.Rect{ - X: thumbX, Y: thumbY, Width: thumbSize, Height: thumbSize, - }, thumbSize/2, thumb) + result.Thumb = gfx.Rect{X: thumbX, Y: thumbY, Width: thumbSize, Height: thumbSize} + switchControl.canvas.Rounded(result.Thumb, thumbSize/2, thumb) if !switchControl.id.IsZero() { hitBounds := gfx.Rect{ diff --git a/cmd/viva/templates/textarea.go.txt b/cmd/viva/templates/textarea.go.txt index b3ebc979f..9def89928 100644 --- a/cmd/viva/templates/textarea.go.txt +++ b/cmd/viva/templates/textarea.go.txt @@ -28,7 +28,7 @@ func PaintTextarea(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, snapsho return bounds } focused := !snapshot.Disabled && (snapshot.Focused || !snapshot.ID.IsZero() && canvas.Focused() == snapshot.ID) - paintTextEntrySurface(canvas, &theme, bounds, gfx.State{Focused: focused, Invalid: snapshot.Invalid, Disabled: snapshot.Disabled}) + paintTextEntrySurface(canvas, &theme, bounds, gfx.State{Focused: focused, Invalid: snapshot.Invalid, Warning: snapshot.Warning, Disabled: snapshot.Disabled}) inset := theme.Metrics.TextInsetX() area := gfx.Rect{X: bounds.X + inset, Y: bounds.Y + textareaPadY, Width: textareaMax(0, bounds.Width-2*inset), Height: textareaMax(0, bounds.Height-2*textareaPadY)} paintTextareaContent(canvas, theme, bounds, area, snapshot, focused) @@ -170,7 +170,7 @@ func textareaPaintRows(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, val layout.Fit(canvas, snapshot.LayoutText(), fontSize, bounds.Width, !snapshot.NoWrap) layout.Content, layout.LineHeight = bounds, lineHeight if !placeholderShown { - layout.Follow(caret, layout.RowOf(caret)) + layout.Show(caret) rows.layout, rows.index = layout, int(layout.Scroll/lineHeight) scroll = layout.Scroll } else { @@ -274,7 +274,12 @@ func textareaPaintRows(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, val if snapshot.Disabled { selectedColor.Alpha *= 0.50 } - canvas.Label(line, labelBounds, gfx.TextStyle{Size: fontSize, Weight: weight, Color: selectedColor}) + selectedStyle := gfx.TextStyle{Size: fontSize, Weight: weight, Color: selectedColor} + if snapshot.PaintLine != nil { + snapshot.PaintLine(canvas, line, labelBounds, selectedStyle) + } else { + canvas.Label(line, labelBounds, selectedStyle) + } canvas.Unclip() } } diff --git a/cmd/viva/templates/toast.go.txt b/cmd/viva/templates/toast.go.txt index 782a5df4d..e2e4f6e90 100644 --- a/cmd/viva/templates/toast.go.txt +++ b/cmd/viva/templates/toast.go.txt @@ -17,14 +17,25 @@ const ( // ToastOptions contains stable action and overlay identities. type ToastOptions struct { - Layer uint16 - Scope gfx.ID - DismissID gfx.ID - ActionID gfx.ID + // Layer is the canvas layer the toast is painted on. + Layer uint16 + // Scope groups the toast's identities and its focus. + Scope gfx.ID + // DismissID names the close button and the Escape target. Zero paints no + // close button and leaves Escape to the page. + DismissID gfx.ID + // ActionID names the action button; zero paints none. + ActionID gfx.ID + // ActionLabel is the action button's text; empty paints none. ActionLabel string - Disabled bool + // Disabled dims the toast and disables its action and close button. + Disabled bool // Position is where the toast sits; the zero value is the bottom right. Position ToastPosition + + // width is the shared width of a stack, set by PaintSonner so its cards line + // up behind one another; zero lets the toast size itself to its content. + width float32 } // ToastLayout exposes deterministic geometry for pointer routing and tests. @@ -36,20 +47,29 @@ type ToastLayout struct { Close gfx.Rect } -// Toast geometry, from Base UI's toast: a `max-w-sm` box 16px in from the -// viewport, `p-4` around content whose parts are `gap-3` apart, a title and a -// description `gap-1` apart, and a stack that peeks 12px per toast behind the -// front one (`--peek`) or opens with 12px between toasts (`--gap`). +// Toast geometry: a compact message bar, as Arco's Message and react-hot-toast: +// 10px above and below, 16px at the ends, an icon and text 8px apart, and a +// stack that peeks 10px per toast behind the front one. The width follows the +// text up to 384px, and a description sits under the title as a smaller line. +// A small close button sits at the end of the row and keeps its room. const ( toastMaxWidth = float32(384) toastInset = float32(16) - toastPadding = float32(16) - toastItemGap = float32(12) - toastTextGap = float32(4) - toastPeek = float32(12) - toastStackGap = float32(12) - toastIconSize = float32(16) - toastCloseSize = float32(32) + toastPaddingX = float32(16) + toastPaddingY = float32(10) + toastItemGap = float32(8) + toastTextGap = float32(2) + toastPeek = float32(10) + toastStackGap = float32(10) + toastIconSize = float32(20) + toastCloseSize = float32(20) + // A string's measured width and the sum of its clusters can differ by a + // fraction; the slack keeps a line that was measured to fit from wrapping. + toastTextSlack = float32(1) + // Each card behind the front of a collapsed stack is 5% smaller, down to a + // floor so a stack deeper than the visible limit cannot vanish. + toastStackScale = float32(0.05) + toastStackMinScale = float32(0.80) ) // toastGeometry measures a toast without painting it: the width, the wrapped @@ -59,35 +79,62 @@ type toastGeometry struct { text float32 // height of the title and description lines bodyWidth float32 actionWidth float32 + actionHeight float32 hasIcon bool } func toastMeasure(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapshot ToastSnapshot, options ToastOptions, scratch *overlayLines) (toastGeometry, []string) { var geometry toastGeometry - geometry.width = min(toastMaxWidth, viewport.Width-2*toastInset) - if geometry.width <= 0 { + limit := min(toastMaxWidth, viewport.Width-2*toastInset) + if limit <= 0 { return geometry, nil } metrics := theme.Metrics geometry.hasIcon = snapshot.Type != ToastDefault - geometry.bodyWidth = geometry.width - 2*toastPadding - toastCloseSize - toastItemGap + // Everything the width has to hold besides the text: the padding, the close + // button, and the icon and action when there are any. + chrome := 2 * toastPaddingX + if !options.DismissID.IsZero() { + chrome += toastCloseSize + toastItemGap + } if geometry.hasIcon { - geometry.bodyWidth -= toastIconSize + toastItemGap + chrome += toastIconSize + toastItemGap } if !options.ActionID.IsZero() && options.ActionLabel != "" { - geometry.actionWidth = BeginButton(canvas, theme, gfx.ID{}, gfx.Rect{}).Small().SizeToFit(options.ActionLabel).BoundsWidth() - geometry.bodyWidth -= geometry.actionWidth + toastItemGap + button := BeginButton(canvas, theme, gfx.ID{}, gfx.Rect{}).Small().SizeToFit(options.ActionLabel) + geometry.actionWidth, geometry.actionHeight = button.BoundsWidth(), button.BoundsHeight() + chrome += geometry.actionWidth + toastItemGap + } + bodyLimit := max(limit-chrome, 0) + // The body takes the width its own text asks for, so a short title stays a + // compact bar, and the description wraps once that would pass the limit. A + // stack hands every card the same width instead, so its peeks line up. + var bodyWidth float32 + if options.width > 0 { + bodyWidth = options.width - chrome + } else { + var titleWidth, descriptionWidth float32 + if canvas != nil { + titleWidth = canvas.TextWidthWeight(snapshot.Title, metrics.FontSizeM, gfx.WeightMedium) + descriptionWidth = canvas.TextWidthWeight(snapshot.Description, metrics.FontSizeS, gfx.WeightRegular) + } + bodyWidth = max(titleWidth, descriptionWidth) + toastTextSlack } - geometry.bodyWidth = max(geometry.bodyWidth, 0) - lines := overlayWrap(canvas, scratch, snapshot.Description, metrics.FontSizeM, gfx.WeightRegular, geometry.bodyWidth) + geometry.bodyWidth = min(max(bodyWidth, 0), bodyLimit) + geometry.width = min(chrome+geometry.bodyWidth, limit) + lines := overlayWrap(canvas, scratch, snapshot.Description, metrics.FontSizeS, gfx.WeightRegular, geometry.bodyWidth) geometry.text = overlayLineHeight(metrics) if len(lines) > 0 { - geometry.text += toastTextGap + float32(len(lines))*overlayLineHeight(metrics) + geometry.text += toastTextGap + float32(len(lines))*toastDescriptionLineHeight(metrics) } - geometry.height = max(geometry.text, toastCloseSize) + 2*toastPadding + rowHeight := max(max(geometry.text, toastCloseSize), geometry.actionHeight) + geometry.height = rowHeight + 2*toastPaddingY return geometry, lines } +// toastDescriptionLineHeight is the leading of the smaller description line. +func toastDescriptionLineHeight(metrics gfx.Metrics) float32 { return metrics.FontSizeS + 6 } + // ToastHeight is how tall PaintToast makes the toast, for a caller that stacks // toasts itself. func ToastHeight(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapshot ToastSnapshot, options ToastOptions) float32 { @@ -97,10 +144,10 @@ func ToastHeight(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapsho } // PaintToast paints one toast snapshot at the viewport position the options -// name, bottom right by default. Its height follows its text: the description -// wraps. It schedules no work and retains no lifetime state, except that a -// loading toast asks for a frame every 100ms to turn its spinner, until it is -// no longer painted. +// name, bottom right by default. Its width follows its text, up to 384px, and +// its height follows the description, which wraps at that width. It schedules +// no work and retains no lifetime state, except that a loading toast asks for a +// frame every 100ms to turn its spinner, until it is no longer painted. func PaintToast(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapshot ToastSnapshot, options ToastOptions) ToastLayout { if canvas == nil || viewport.Width <= 0 || viewport.Height <= 0 || snapshot.Limited { return ToastLayout{} @@ -121,7 +168,7 @@ func PaintToast(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapshot default: x = viewport.X + viewport.Width - width - toastInset } - stack := float32(snapshot.Index) * toastPeek + stack := float32(0) if snapshot.Expanded { stack = float32(snapshot.Index) * (height + toastStackGap) } @@ -134,8 +181,26 @@ func PaintToast(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapshot x += snapshot.SwipeX y += snapshot.OffsetY + snapshot.SwipeY bounds := gfx.Rect{X: x, Y: y, Width: width, Height: height} + // A toast that is not the front of a collapsed stack sits back from the + // edge, smaller: the scale and lift are what make the cards behind the + // front one visible and give the stack its depth. + pose, pivot := gfx.Pose{}, gfx.Point{} + if !snapshot.Expanded && snapshot.Index > 0 { + scale := max(1-float32(snapshot.Index)*toastStackScale, toastStackMinScale) + lift := float32(snapshot.Index) * toastPeek + pivot = gfx.Point{X: bounds.X + bounds.Width/2, Y: bounds.Y} + pose = gfx.Pose{Offset: gfx.Point{Y: lift}, Scale: scale} + if !top { + pivot.Y = bounds.Y + bounds.Height + pose.Offset.Y = -lift + } + } + posed := pose != (gfx.Pose{}) layout := ToastLayout{Bounds: bounds} canvas.PushLayer(options.Layer) + if posed { + canvas.BeginPose(options.DismissID, 0, pose, theme.Transition, pivot) + } if !options.DismissID.IsZero() { // A toast may still be shown while a dialog or menu is open. Claim // Escape at the outer depth so the overlay the user is working in keeps @@ -145,14 +210,16 @@ func PaintToast(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapshot if !options.Scope.IsZero() { canvas.PushFocusScope(options.Scope) } - canvas.BeginPresence(overlayKey(options.DismissID, options.Scope), overlaySurfacePart, toastPresence(theme, options.Position, height), centerOf(bounds)) - // sonner's own shadow, 0 4px 12px rgb(0 0 0 / 10%): the pinned shadcn snapshot has none. + canvas.BeginPresence(overlayKey(options.DismissID, options.Scope), overlaySurfacePart, toastPresence(theme, options.Position), centerOf(bounds)) + // Two soft layers instead of a border: one wide and one tight, close to + // sonner's 0 4px 12px rgb(0 0 0 / 10%) with a crisper edge under it. canvas.Shadow(bounds, metrics.RadiusSurface, gfx.ShadowStyle{OffsetY: 4, Blur: 12}, gfx.Color{Alpha: 0.10}) - canvas.RoundedBorder(bounds, metrics.RadiusSurface, 1, theme.Border, theme.Popover) + canvas.Shadow(bounds, metrics.RadiusSurface, gfx.ShadowStyle{OffsetY: 2, Blur: 4}, gfx.Color{Alpha: 0.06}) + canvas.Rounded(bounds, metrics.RadiusSurface, theme.Popover) // The icon, the text, the action and the close button are centered on the row // the padding leaves. - row := gfx.Rect{X: bounds.X + toastPadding, Y: bounds.Y + toastPadding, Width: bounds.Width - 2*toastPadding, Height: bounds.Height - 2*toastPadding} + row := gfx.Rect{X: bounds.X + toastPaddingX, Y: bounds.Y + toastPaddingY, Width: bounds.Width - 2*toastPaddingX, Height: bounds.Height - 2*toastPaddingY} textX := row.X if geometry.hasIcon { layout.Icon = gfx.Rect{X: row.X, Y: row.Y + (row.Height-toastIconSize)/2, Width: toastIconSize, Height: toastIconSize} @@ -171,45 +238,86 @@ func PaintToast(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapshot button.paint(options.ActionLabel, ButtonOutline) right = layout.Action.X - toastItemGap } - closeColor := theme.MutedForeground - if options.Disabled { - closeColor.Alpha *= 0.50 - } - if !options.DismissID.IsZero() && !options.Disabled && canvas.Hovered() == options.DismissID { - canvas.Rounded(layout.Close, metrics.RadiusControl, theme.Accent) - closeColor = theme.AccentForeground - } - paintCross(canvas, layout.Close, 16, closeColor) + // The close button is always there, small and quiet, and takes the accent + // while the pointer or the focus is on it. if !options.DismissID.IsZero() { + closeColor := theme.MutedForeground + if options.Disabled { + closeColor.Alpha *= 0.50 + } + if !options.Disabled && (canvas.Hovered() == options.DismissID || canvas.Focused() == options.DismissID) { + canvas.Rounded(layout.Close, toastCloseSize/2, theme.Accent) + closeColor = theme.AccentForeground + } + paintCross(canvas, layout.Close, 14, closeColor) canvas.HitWithOptions(options.DismissID, layout.Close, "Close toast", gfx.HitOptions{Role: gfx.RoleButton, Disabled: options.Disabled}) } layout.Body = gfx.Rect{X: textX, Y: row.Y + (row.Height-geometry.text)/2, Width: max(0, right-textX), Height: geometry.text} - lineHeight := overlayLineHeight(metrics) - canvas.Label(snapshot.Title, gfx.Rect{X: layout.Body.X, Y: layout.Body.Y, Width: layout.Body.Width, Height: lineHeight}, gfx.TextStyle{Size: metrics.FontSizeM, Weight: gfx.WeightMedium, Color: theme.PopoverForeground}) - overlayParagraph(canvas, lines, gfx.Rect{X: layout.Body.X, Y: layout.Body.Y + lineHeight + toastTextGap, Width: layout.Body.Width}, lineHeight, gfx.TextStyle{ - Size: metrics.FontSizeM, Weight: gfx.WeightRegular, Color: theme.MutedForeground, + titleHeight, descriptionHeight := overlayLineHeight(metrics), toastDescriptionLineHeight(metrics) + canvas.Label(snapshot.Title, gfx.Rect{X: layout.Body.X, Y: layout.Body.Y, Width: layout.Body.Width, Height: titleHeight}, gfx.TextStyle{Size: metrics.FontSizeM, Weight: gfx.WeightMedium, Color: theme.PopoverForeground}) + overlayParagraph(canvas, lines, gfx.Rect{X: layout.Body.X, Y: layout.Body.Y + titleHeight + toastTextGap, Width: layout.Body.Width}, descriptionHeight, gfx.TextStyle{ + Size: metrics.FontSizeS, Weight: gfx.WeightRegular, Color: theme.MutedForeground, }, false) canvas.EndPresence() + if posed { + canvas.EndPose() + } if !options.Scope.IsZero() { canvas.PopFocusScope() } canvas.PopLayer() + if posed { + layout = toastPoseLayout(layout, pose, pivot) + } + return layout +} + +// toastPoseLayout places the parts of a toast where the stack's pose puts them, +// so a caller's layout and hit testing agree with what was painted. +func toastPoseLayout(layout ToastLayout, pose gfx.Pose, pivot gfx.Point) ToastLayout { + layout.Bounds = toastPoseRect(layout.Bounds, pose, pivot) + layout.Icon = toastPoseRect(layout.Icon, pose, pivot) + layout.Body = toastPoseRect(layout.Body, pose, pivot) + layout.Action = toastPoseRect(layout.Action, pose, pivot) + layout.Close = toastPoseRect(layout.Close, pose, pivot) return layout } -// toastPresence is how a toast comes and goes: it slides from and to beyond its -// edge of the window, by 150% of its height, over 500ms (Base UI's -// `translateY(150%)` with `cubic-bezier(0.22, 1, 0.36, 1)`), without fading. -func toastPresence(theme gfx.Theme, position ToastPosition, height float32) gfx.Presence { +func toastPoseRect(rect gfx.Rect, pose gfx.Pose, pivot gfx.Point) gfx.Rect { + if rect == (gfx.Rect{}) { + return rect + } + scale := pose.Scale + if scale <= 0 { + scale = 1 + } + return gfx.Rect{ + X: pivot.X + (rect.X-pivot.X)*scale + pose.Offset.X, + Y: pivot.Y + (rect.Y-pivot.Y)*scale + pose.Offset.Y, + Width: rect.Width * scale, + Height: rect.Height * scale, + } +} + +// toastPresence is how a toast comes and goes: it grows from 95% with a short +// lift from its edge of the window and fades in, over 220ms. That is a lighter +// arrival than Base UI's 150%-height slide, and the scale and fade are what make +// it read as a notification rather than a panel. +func toastPresence(theme gfx.Theme, position ToastPosition) gfx.Presence { if !moving(theme) { return gfx.Presence{} } - slide := gfx.Point{Y: height * 1.5} + slide := gfx.Point{Y: 16} if position >= ToastTopRight { slide.Y = -slide.Y } - return gfx.Presence{Motion: gfx.Motion{Duration: toastDuration, Easing: gfx.EaseEmphasized}, SlideIn: slide, SlideOut: slide} + return gfx.Presence{ + Motion: gfx.Motion{Duration: toastDuration, Easing: gfx.EaseEmphasized}, + Fade: true, + Scale: 0.95, + SlideIn: slide, SlideOut: slide, + } } // toastSpinnerStep is how long a loading toast's spinner holds each of its eight spokes. @@ -229,7 +337,7 @@ func paintToastIcon(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, kind T } PaintSpinner(canvas, theme, bounds, phase) case ToastSuccess: - canvas.DrawIcon(circleCheckIcon, bounds, theme.PopoverForeground) + canvas.DrawIcon(circleCheckIcon, bounds, theme.Success) case ToastInfo: canvas.DrawIcon(infoIcon, bounds, theme.PopoverForeground) case ToastWarning: @@ -269,8 +377,9 @@ var ( }} ) -// toastDuration is the 500ms of Base UI's toast transition. -const toastDuration = 500 * time.Millisecond +// toastDuration is how long a toast takes to arrive or leave. It is shorter than +// Base UI's 500ms so a notification settles before it is read. +const toastDuration = 220 * time.Millisecond // Aliases into the style vocabulary. type ToastQueue = base.ToastQueue diff --git a/cmd/viva/templates/tree.go.txt b/cmd/viva/templates/tree.go.txt index 2d7a335aa..3537b04da 100644 --- a/cmd/viva/templates/tree.go.txt +++ b/cmd/viva/templates/tree.go.txt @@ -127,8 +127,14 @@ func (tree *Tree) Item(item TreeItem) TreeRow { if item.Disabled { color.Alpha *= 0.50 } - tree.paintDisclosure(disclosure, item.Expanded, color) - if !item.DisclosureID.IsZero() { + if item.Loading { + spinner := tree.theme + spinner.Foreground = color + PaintSpinner(tree.canvas, spinner, disclosure, SpinnerPhase(item.Phase)) + } else { + tree.paintDisclosure(disclosure, item.Expanded, color) + } + if !item.DisclosureID.IsZero() && !item.Loading { tree.canvas.HitWithOptions(item.DisclosureID, disclosure, item.Label, gfx.HitOptions{ Role: gfx.RoleButton, Disabled: item.Disabled, Expanded: item.Expanded, Expandable: true, }) diff --git a/cmd/viva/vet_test.go b/cmd/viva/vet_test.go index 12a1dc648..24d31248d 100644 --- a/cmd/viva/vet_test.go +++ b/cmd/viva/vet_test.go @@ -42,7 +42,7 @@ func (m *model) page(c ui.C) { // viva:ignore unkeyed-button ui.Button(c, "Same") } - ui.Modal(c, &m.open, "Title", nil, nil) + ui.Modal(c, &m.open, "Title", ui.ModalSpec{}, nil, nil) } func main() { _ = (&model{}).page } diff --git a/components/bubble.go b/components/bubble.go index cf611e92f..bfd9875b9 100644 --- a/components/bubble.go +++ b/components/bubble.go @@ -141,7 +141,7 @@ func bubbleTint(theme gfx.Theme) gfx.Color { // radiusXL is the corner radius of the official rounded-xl surfaces, the one // Card uses. -func radiusXL(metrics gfx.Metrics) float32 { return metrics.RadiusSurface + 4 } +func radiusXL(metrics gfx.Metrics) float32 { return gfx.RadiusOutset(metrics.RadiusSurface, 4) } // BubbleReactionSide selects whether a reaction capsule overlaps the top or // bottom edge of a bubble. diff --git a/components/button.go b/components/button.go index 6cc6934f4..2c8c1809a 100644 --- a/components/button.go +++ b/components/button.go @@ -633,8 +633,19 @@ type ButtonContent struct { IconOnly bool // Underlined underlines the label, as a hovered link is. Underlined bool + // PaintLoading, when set, paints the loading indicator in the place of the icon (or + // before the label when there is none), at Phase and in Color, with Theme. The + // button does not know what the indicator looks like: a page gives the one of + // package components' Spinner, so the recipe does not depend on its file. + PaintLoading ButtonLoadingPainter + Phase uint8 + Theme *gfx.Theme } +// ButtonLoadingPainter paints a button's loading indicator in bounds. Give it a +// function, not a closure made in each paint, which would allocate. +type ButtonLoadingPainter func(canvas *gfx.Canvas, theme *gfx.Theme, bounds gfx.Rect, color gfx.Color, phase uint8) + // PaintButtonContent paints a button's icon and label centered in area and returns the // hint an icon-only button gives assistive technology, which is its label. It is the // content half of the paint the Button does: the same placement, the same shrinking of @@ -645,7 +656,8 @@ func PaintButtonContent(canvas *gfx.Canvas, area gfx.Rect, content ButtonContent } look := buttonStyle{foreground: content.Color, underlined: content.Underlined} label := content.Label - if len(content.Icon.Commands) == 0 && len(content.Icon.Layers) == 0 { + loading := content.PaintLoading != nil + if len(content.Icon.Commands) == 0 && len(content.Icon.Layers) == 0 && !loading { paintButtonLabel(canvas, label, area, content.FontSize, content.Weight, look) return "" } @@ -655,7 +667,9 @@ func PaintButtonContent(canvas *gfx.Canvas, area gfx.Rect, content ButtonContent width = min(area.Width, width+content.Gap+canvas.TextWidthWeight(label, content.FontSize, content.Weight)) } x := area.X + (area.Width-width)/2 - if size > 0 { + if size > 0 && loading { + content.PaintLoading(canvas, content.Theme, gfx.Rect{X: x, Y: area.Y + (area.Height-size)/2, Width: size, Height: size}, content.Color, content.Phase) + } else if size > 0 { canvas.DrawIconTransformed( content.Icon, gfx.Rect{X: x, Y: area.Y + (area.Height-size)/2, Width: size, Height: size}, diff --git a/components/card.go b/components/card.go index 8e541be6e..64ac494fb 100644 --- a/components/card.go +++ b/components/card.go @@ -42,7 +42,7 @@ func PaintCard(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, options Car if canvas == nil || bounds.Width <= 0 || bounds.Height <= 0 { return CardLayout{} } - radius := theme.Metrics.RadiusSurface + 4 + radius := gfx.RadiusOutset(theme.Metrics.RadiusSurface, 4) ring := theme.Foreground ring.Alpha *= 0.10 canvas.Elevate(bounds, radius, gfx.ShadowXS) // shadow-xs diff --git a/components/input.go b/components/input.go index cadd6490d..56734cb94 100644 --- a/components/input.go +++ b/components/input.go @@ -37,7 +37,7 @@ func PaintInput(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, snapshot I } focused := snapshot.Focused || !snapshot.ID.IsZero() && canvas.Focused() == snapshot.ID - paintTextEntrySurface(canvas, &theme, bounds, gfx.State{Focused: focused, Invalid: snapshot.Invalid, Disabled: snapshot.Disabled}) + paintTextEntrySurface(canvas, &theme, bounds, gfx.State{Focused: focused, Invalid: snapshot.Invalid, Warning: snapshot.Warning, Disabled: snapshot.Disabled}) inset := theme.Metrics.TextInsetX() content := gfx.Rect{X: bounds.X + inset, Y: bounds.Y, Width: inputMax(0, bounds.Width-2*inset), Height: bounds.Height} paintInputContent(canvas, theme, bounds, content, snapshot, focused) @@ -350,10 +350,11 @@ func textEntryDark(theme *gfx.Theme) bool { return theme.Background.Red < 0.5 } // - border-input and a transparent fill, dark:bg-input/30 (hover input/50); // - focus: the border alone turns the accent color; there is no halo around // the control, which would wash the field and crowd its neighbors; -// - invalid: border-destructive, which also wins over the focus color; +// - invalid: border-destructive, which also wins over the focus color; warning is +// the same with the theme's warning color, and invalid wins over it; // - disabled: opacity-50 on all of it. // -// Only Hovered, Focused, Invalid and Disabled of state are read. It is a pure function: +// Only Hovered, Focused, Invalid, Warning and Disabled of state are read. It is a pure function: // the same theme and state give the same look, and nothing is painted. func TextEntryRecipe(theme gfx.Theme, state gfx.State) TextEntryLook { return textEntryRecipe(&theme, state) @@ -395,6 +396,8 @@ func textEntryTokens(theme *gfx.Theme, state gfx.State) (border, fill gfx.Color) } if state.Invalid { border = theme.Danger + } else if state.Warning { + border = theme.WarningColor() } if state.Disabled { border.Alpha *= 0.50 diff --git a/components/input_group.go b/components/input_group.go index 0c7e1125c..be677a153 100644 --- a/components/input_group.go +++ b/components/input_group.go @@ -102,7 +102,7 @@ func PaintInputGroup(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, snaps layout.Control = gfx.Rect{X: row.X + startWidth, Y: row.Y, Width: inputGroupMax(0, row.Width-startWidth-endWidth), Height: row.Height} focused := !snapshot.Disabled && (snapshot.Focused || !snapshot.ID.IsZero() && canvas.Focused() == snapshot.ID) - paintTextEntrySurface(canvas, &theme, bounds, gfx.State{Focused: focused, Invalid: snapshot.Invalid, Disabled: snapshot.Disabled}) + paintTextEntrySurface(canvas, &theme, bounds, gfx.State{Focused: focused, Invalid: snapshot.Invalid, Warning: snapshot.Warning, Disabled: snapshot.Disabled}) inputGroupPaintSlot(canvas, theme, layout.BlockStart, snapshot.BlockStart, true, false, snapshot.Disabled) inputGroupPaintSlot(canvas, theme, layout.BlockEnd, snapshot.BlockEnd, true, false, snapshot.Disabled) inputGroupPaintSlot(canvas, theme, layout.InlineStart, snapshot.InlineStart, false, true, snapshot.Disabled) diff --git a/components/item.go b/components/item.go index 4b5dff9f3..a1d0f3e08 100644 --- a/components/item.go +++ b/components/item.go @@ -153,7 +153,7 @@ func (item Item) Paint(title, description, trailing string) ItemLayout { if focused { focus := item.theme.Ring focus.Alpha *= 0.50 - item.canvas.RoundedBorder(expand(item.bounds, 3), metrics.RadiusControl+3, 3, focus, gfx.Color{}) + item.canvas.RoundedBorder(expand(item.bounds, 3), gfx.RadiusOutset(metrics.RadiusControl, 3), 3, focus, gfx.Color{}) } background := gfx.Color{} diff --git a/components/message_scroller.go b/components/message_scroller.go index 73afe96c0..cfecf32af 100644 --- a/components/message_scroller.go +++ b/components/message_scroller.go @@ -240,7 +240,7 @@ func (scroller MessageScroller) paintButton(bounds gfx.Rect, id gfx.ID, label st if scroller.canvas.FocusVisible() == id { ring := scroller.theme.Ring ring.Alpha *= 0.50 - scroller.canvas.Rounded(messageScrollerExpand(bounds, 3), scroller.theme.Metrics.RadiusControl+3, ring) + scroller.canvas.Rounded(messageScrollerExpand(bounds, 3), gfx.RadiusOutset(scroller.theme.Metrics.RadiusControl, 3), ring) } scroller.canvas.RoundedBorder(bounds, scroller.theme.Metrics.RadiusControl, 1, scroller.theme.Border, background) icon := &arrowDownIcon diff --git a/components/select.go b/components/select.go index 4087e4086..0a57c8c5b 100644 --- a/components/select.go +++ b/components/select.go @@ -91,6 +91,9 @@ type SelectItem struct { Hint string Selected bool Disabled bool + // Heading paints the row as a group heading: the label muted and set small, with no + // hover, no hit and no check, in the same row height as an option. + Heading bool // Icon, when it has any geometry, is painted before the label. Icon gfx.Icon // IconImage is a full-color image in the icon slot when Icon is empty. @@ -270,6 +273,20 @@ func (selectControl *Select) AddLabel(label string) gfx.Rect { // is empty when the row is scrolled out of the popup. func (selectControl *Select) AddItem(item SelectItem) gfx.Rect { bounds := selectControl.rowBounds(32) + if item.Heading { + if !selectControl.reserve(bounds) { + return gfx.Rect{} + } + selectControl.rows.paintRow(bounds, func() { + if selectControl.options.Unpainted { + return + } + selectControl.canvas.Label(item.Label, gfx.Rect{X: bounds.X + 8, Y: bounds.Y, Width: selectMax(0, bounds.Width-16), Height: bounds.Height}, gfx.TextStyle{ + Size: selectControl.theme.Metrics.FontSizeS, Weight: gfx.WeightMedium, Color: selectControl.theme.MutedForeground, + }) + }) + return bounds + } if !selectControl.open || !selectControl.rows.takeItem(bounds, item.ID, item.Label, item.Disabled) { return gfx.Rect{} } diff --git a/components/sidebar.go b/components/sidebar.go index 460cecef6..1d6d8e327 100644 --- a/components/sidebar.go +++ b/components/sidebar.go @@ -182,7 +182,7 @@ func PaintSidebarInset(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, sid if card.Width <= 0 || card.Height <= 0 { return gfx.Rect{} } - canvas.Rounded(card, theme.Metrics.RadiusSurface+4, theme.Background) + canvas.Rounded(card, gfx.RadiusOutset(theme.Metrics.RadiusSurface, 4), theme.Background) return card } diff --git a/components/slider.go b/components/slider.go index bfd7b47e6..faff45f78 100644 --- a/components/slider.go +++ b/components/slider.go @@ -32,6 +32,7 @@ type SliderGeometry struct { // with ValueAt (the pointer events of the held thumb carry it, with capture while // it is dragged) and a key into one with SliderKeyDown, and passes the result back. type Slider struct { + marks []SliderMark canvas *gfx.Canvas theme gfx.Theme id gfx.ID @@ -46,6 +47,16 @@ type Slider struct { disabled bool } +// SliderMark is a value marked on the track, with a word under it when it has a label. +type SliderMark = base.SliderMark + +// Marks puts a dot on the track at each mark's value and its label under the track. +// The labels hang below bounds, so the caller leaves room for them. +func (slider Slider) Marks(marks []SliderMark) Slider { + slider.marks = marks + return slider +} + // BeginSlider starts a single-thumb 0..100 slider declaration. func BeginSlider(canvas *gfx.Canvas, theme gfx.Theme, id gfx.ID, bounds gfx.Rect, value float32) Slider { return Slider{canvas: canvas, theme: theme, id: id, bounds: bounds, maximum: 100, value: value} @@ -147,6 +158,7 @@ func (slider Slider) Paint(label string) SliderGeometry { activeRadius = geometry.Active.Width / 2 } slider.canvas.Rounded(geometry.Active, activeRadius, activeColor) + slider.paintMarks(geometry, trackColor) for index := 0; index < slider.ThumbCount(); index++ { _, id, thumbDisabled := slider.thumb(index) @@ -190,6 +202,41 @@ func (slider Slider) Paint(label string) SliderGeometry { return geometry } +// paintMarks draws a dot on the track at each mark, light over the filled part and dark +// over the rest, and the labels of the marks under the track. +func (slider Slider) paintMarks(geometry SliderGeometry, trackColor gfx.Color) { + if len(slider.marks) == 0 { + return + } + origin, extent := slider.travel() + _, end := slider.activeFractions() + const dot = float32(4) + over := slider.theme.PrimaryForeground + rest := slider.theme.MutedForeground + if slider.disabled { + over.Alpha *= 0.50 + rest.Alpha *= 0.50 + } + for _, mark := range slider.marks { + fraction := slider.fraction(mark.Value) + color := rest + if fraction <= end { + color = over + } + if slider.vertical { + y := origin + extent*(1-fraction) + slider.canvas.Rounded(gfx.Rect{X: geometry.Track.X + (geometry.Track.Width-dot)/2, Y: y - dot/2, Width: dot, Height: dot}, dot/2, color) + continue + } + x := origin + extent*fraction + slider.canvas.Rounded(gfx.Rect{X: x - dot/2, Y: geometry.Track.Y + (geometry.Track.Height-dot)/2, Width: dot, Height: dot}, dot/2, color) + if mark.Label != "" { + label := gfx.Rect{X: x - 48, Y: geometry.Bounds.Y + geometry.Bounds.Height + 2, Width: 96, Height: slider.theme.Metrics.FontSizeS + 6} + slider.canvas.LabelCenter(mark.Label, label, gfx.TextStyle{Size: slider.theme.Metrics.FontSizeS, Weight: gfx.WeightRegular, Color: rest}) + } + } +} + func (slider Slider) geometry() SliderGeometry { bounds := slider.resolvedBounds() track := slider.trackBounds() diff --git a/components/sonner.go b/components/sonner.go index 3f4846369..6a8d702a0 100644 --- a/components/sonner.go +++ b/components/sonner.go @@ -9,7 +9,9 @@ import ( // are ordered newest first. Layer is the oldest toast's layer; each newer toast // receives the next layer so collapsed cards composite correctly. type SonnerOptions struct { - Layer uint16 + // Layer is the oldest toast's layer; each newer toast receives the next. + Layer uint16 + // Expanded lays the stack out with a gap instead of a peek. Expanded bool // Limit is how many of the newest toasts show; the zero value is Base UI's 3. // Older ones are not painted. @@ -37,32 +39,39 @@ func PaintSonner(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, toasts limit = 3 } top := options.Position >= ToastTopRight + visible := min(limit, len(toasts)) + // A stack shares one width, the widest card in it, so the cards that peek + // behind the front one line up instead of showing ragged edges. + var stackWidth float32 + for index := 0; index < visible; index++ { + toast := toasts[index] + if toast.Snapshot.Limited { + continue + } + var scratch overlayLines + geometry, _ := toastMeasure(canvas, theme, viewport, toast.Snapshot, sonnerToastOptions(options, toast, 0), &scratch) + stackWidth = max(stackWidth, geometry.width) + } var stack SonnerLayout - // Where the next toast of an expanded stack goes: after the heights of the - // toasts in front of it, each with its own wrapped text. - var reach float32 - for index := len(toasts) - 1; index >= 0 && len(toasts)-1-index < limit; index-- { + // Paint from the back of the visible stack to its front, which is the + // first toast: the newest one sits at the edge and the older ones behind it. + for index := visible - 1; index >= 0; index-- { toast := toasts[index] snapshot := toast.Snapshot - snapshot.Index = sonnerIndex(len(toasts) - 1 - index) + snapshot.Index = sonnerIndex(index) snapshot.Expanded = false - toastOptions := ToastOptions{ - Layer: sonnerLayer(options.Layer, len(toasts)-index-1), - Scope: toast.Scope, - DismissID: toast.DismissID, - ActionID: toast.ActionID, - ActionLabel: toast.ActionLabel, - Disabled: toast.Disabled, - Position: options.Position, - } + toastOptions := sonnerToastOptions(options, toast, visible-1-index) + toastOptions.width = stackWidth if options.Expanded && !snapshot.Limited { + // The toast sits after the ones in front of it, each with its own + // wrapped text at the stack's width. + reach := sonnerReach(canvas, theme, viewport, toasts, options, index, stackWidth) if top { snapshot.OffsetY += reach } else { snapshot.OffsetY -= reach } snapshot.Index = 0 - reach += ToastHeight(canvas, theme, viewport, snapshot, toastOptions) + toastStackGap } layout := PaintToast(canvas, theme, viewport, snapshot, toastOptions) if layout == (ToastLayout{}) { @@ -78,6 +87,35 @@ func PaintSonner(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, toasts return stack } +// sonnerReach is how far an expanded toast at index sits from the edge: after +// the heights of the toasts in front of it, which are the smaller indexes. +func sonnerReach(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, toasts []SonnerToast, options SonnerOptions, index int, width float32) float32 { + var reach float32 + for front := 0; front < index; front++ { + if toasts[front].Snapshot.Limited { + continue + } + toastOptions := sonnerToastOptions(options, toasts[front], 0) + toastOptions.width = width + reach += ToastHeight(canvas, theme, viewport, toasts[front].Snapshot, toastOptions) + toastStackGap + } + return reach +} + +// sonnerToastOptions is the options of one toast of a stack, before the stack's +// shared width is known. +func sonnerToastOptions(options SonnerOptions, toast SonnerToast, layerOffset int) ToastOptions { + return ToastOptions{ + Layer: sonnerLayer(options.Layer, layerOffset), + Scope: toast.Scope, + DismissID: toast.DismissID, + ActionID: toast.ActionID, + ActionLabel: toast.ActionLabel, + Disabled: toast.Disabled, + Position: options.Position, + } +} + func sonnerIndex(index int) uint16 { if index > int(^uint16(0)) { return ^uint16(0) diff --git a/components/sonner_test.go b/components/sonner_test.go index f48684513..3f7b1aea9 100644 --- a/components/sonner_test.go +++ b/components/sonner_test.go @@ -1,6 +1,7 @@ package components import ( + "fmt" "slices" "testing" @@ -14,8 +15,16 @@ func TestSonnerPaintsCallerOwnedStackNewestOnTop(t *testing.T) { {Snapshot: ToastSnapshot{Title: "Middle", Index: 99}, Scope: gfx.Item(11), DismissID: gfx.Item(2)}, {Snapshot: ToastSnapshot{Title: "Oldest", Index: 99}, Scope: gfx.Item(12), DismissID: gfx.Item(3)}, } - layout := PaintSonner(&canvas, gfx.LightTheme(), gfx.Rect{Width: 1000, Height: 700}, toasts, SonnerOptions{Layer: 40}) - if layout != (SonnerLayout{Bounds: gfx.Rect{X: 600, Y: 596, Width: 384, Height: 88}, Painted: 3}) { + viewport := gfx.Rect{Width: 1000, Height: 700} + layout := PaintSonner(&canvas, gfx.LightTheme(), viewport, toasts, SonnerOptions{Layer: 40}) + if layout.Painted != 3 { + t.Fatalf("painted = %d", layout.Painted) + } + // The stack shares one width, so its cards line up: the union's right and + // bottom edges are the viewport's inset edges, not a sum of card widths. + if layout.Bounds.Width <= 0 || layout.Bounds.Width > toastMaxWidth || + layout.Bounds.X+layout.Bounds.Width != viewport.Width-toastInset || + layout.Bounds.Y+layout.Bounds.Height != viewport.Height-toastInset { t.Fatalf("stack layout = %+v", layout) } if canvas.EscapeTarget() != gfx.Item(1) { @@ -24,6 +33,14 @@ func TestSonnerPaintsCallerOwnedStackNewestOnTop(t *testing.T) { if len(canvas.Hits()) != 3 || canvas.Hits()[0].ID != gfx.Item(3) || canvas.Hits()[2].ID != gfx.Item(1) { t.Fatalf("stack hits = %+v", canvas.Hits()) } + // The newest toast is at the edge and the older ones are lifted behind it. + row := map[string]float32{} + for _, text := range canvas.Texts() { + row[text.Value] = text.Bounds.Y + } + if !(row["Newest"] > row["Middle"] && row["Middle"] > row["Oldest"]) { + t.Fatalf("stack rows = %v, want the newest nearest the bottom", row) + } seenLayer := [3]bool{} for _, rectangle := range canvas.Rectangles() { if rectangle.Layer < 40 || rectangle.Layer > 42 { @@ -43,7 +60,8 @@ func TestSonnerPaintsCallerOwnedStackNewestOnTop(t *testing.T) { func TestSonnerExpandedGeometryAndLimitedEntry(t *testing.T) { var canvas gfx.Canvas - layout := PaintSonner(&canvas, gfx.DarkTheme(), gfx.Rect{X: 2, Y: 3, Width: 800, Height: 600}, []SonnerToast{ + viewport := gfx.Rect{X: 2, Y: 3, Width: 800, Height: 600} + layout := PaintSonner(&canvas, gfx.DarkTheme(), viewport, []SonnerToast{ {Snapshot: ToastSnapshot{Title: "One", Description: "Details"}, DismissID: gfx.Item(1)}, {Snapshot: ToastSnapshot{Title: "Hidden", Limited: true}, DismissID: gfx.Item(2)}, {Snapshot: ToastSnapshot{Title: "Three", Description: "Details"}, DismissID: gfx.Item(3)}, @@ -51,7 +69,9 @@ func TestSonnerExpandedGeometryAndLimitedEntry(t *testing.T) { if layout.Painted != 2 { t.Fatalf("painted = %d", layout.Painted) } - if layout.Bounds != (gfx.Rect{X: 402, Y: 419, Width: 384, Height: 168}) { + if layout.Bounds.Width <= 0 || layout.Bounds.Width > toastMaxWidth || + layout.Bounds.X+layout.Bounds.Width != viewport.X+viewport.Width-toastInset || + layout.Bounds.Y+layout.Bounds.Height != viewport.Y+viewport.Height-toastInset { t.Fatalf("expanded bounds = %+v", layout.Bounds) } } @@ -83,13 +103,29 @@ func TestSonnerShowsOnlyTheNewestLimitToasts(t *testing.T) { var canvas gfx.Canvas toasts := make([]SonnerToast, 5) for index := range toasts { - toasts[index] = SonnerToast{Snapshot: ToastSnapshot{Title: "Toast"}, DismissID: gfx.Item(index + 1)} + toasts[index] = SonnerToast{Snapshot: ToastSnapshot{Title: fmt.Sprintf("Toast %d", index)}, DismissID: gfx.Item(index + 1)} } - if layout := PaintSonner(&canvas, gfx.LightTheme(), gfx.Rect{Width: 1000, Height: 700}, toasts, SonnerOptions{Layer: 1}); layout.Painted != 3 { + viewport := gfx.Rect{Width: 1000, Height: 700} + if layout := PaintSonner(&canvas, gfx.LightTheme(), viewport, toasts, SonnerOptions{Layer: 1}); layout.Painted != 3 { t.Fatalf("painted = %d, want Base UI's default limit of 3", layout.Painted) } + // The slice is newest first, so the visible three are 0, 1 and 2. + seen := map[string]bool{} + for _, text := range canvas.Texts() { + seen[text.Value] = true + } + for index := 0; index < 3; index++ { + if title := fmt.Sprintf("Toast %d", index); !seen[title] { + t.Fatalf("newest toast %q is not painted: %v", title, seen) + } + } + for index := 3; index < len(toasts); index++ { + if title := fmt.Sprintf("Toast %d", index); seen[title] { + t.Fatalf("toast %q beyond the limit is painted: %v", title, seen) + } + } canvas.Reset() - if layout := PaintSonner(&canvas, gfx.LightTheme(), gfx.Rect{Width: 1000, Height: 700}, toasts, SonnerOptions{Layer: 1, Limit: 5}); layout.Painted != 5 { + if layout := PaintSonner(&canvas, gfx.LightTheme(), viewport, toasts, SonnerOptions{Layer: 1, Limit: 5}); layout.Painted != 5 { t.Fatalf("painted = %d with Limit 5", layout.Painted) } } diff --git a/components/split_button.go b/components/split_button.go index 75c1ffbbd..53a10718e 100644 --- a/components/split_button.go +++ b/components/split_button.go @@ -151,7 +151,7 @@ func (button SplitButton) paintFocus(bounds gfx.Rect, variant ButtonVariant, id return } ring, _ := buttonRing(&button.theme, variant, false) - button.canvas.Rounded(expand(bounds, 3), button.theme.Metrics.RadiusControl+3, ring) + button.canvas.Rounded(expand(bounds, 3), gfx.RadiusOutset(button.theme.Metrics.RadiusControl, 3), ring) } func (button SplitButton) paintHalf(bounds gfx.Rect, index int, variant ButtonVariant, id gfx.ID, framed bool, radius float32) { diff --git a/components/switch.go b/components/switch.go index 73c7e6dde..907f884bb 100644 --- a/components/switch.go +++ b/components/switch.go @@ -101,6 +101,8 @@ func (switchControl Switch) Disabled() Switch { type SwitchResult struct { canvas *gfx.Canvas id gfx.ID + // Thumb is where the thumb was painted, for a caller that draws on it. + Thumb gfx.Rect } // Clicked reports whether this paint is delivering a click on the control. @@ -200,9 +202,8 @@ func (switchControl Switch) Paint() SwitchResult { inset := 1 * scale thumbX := gfx.Lerp(switchControl.bounds.X+inset, switchControl.bounds.X+switchControl.bounds.Width-thumbSize-inset, progress) thumbY := switchControl.bounds.Y + (switchControl.bounds.Height-thumbSize)/2 - switchControl.canvas.Rounded(gfx.Rect{ - X: thumbX, Y: thumbY, Width: thumbSize, Height: thumbSize, - }, thumbSize/2, thumb) + result.Thumb = gfx.Rect{X: thumbX, Y: thumbY, Width: thumbSize, Height: thumbSize} + switchControl.canvas.Rounded(result.Thumb, thumbSize/2, thumb) if !switchControl.id.IsZero() { hitBounds := gfx.Rect{ diff --git a/components/textarea.go b/components/textarea.go index 8fdff6d3c..0753a015a 100644 --- a/components/textarea.go +++ b/components/textarea.go @@ -28,7 +28,7 @@ func PaintTextarea(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, snapsho return bounds } focused := !snapshot.Disabled && (snapshot.Focused || !snapshot.ID.IsZero() && canvas.Focused() == snapshot.ID) - paintTextEntrySurface(canvas, &theme, bounds, gfx.State{Focused: focused, Invalid: snapshot.Invalid, Disabled: snapshot.Disabled}) + paintTextEntrySurface(canvas, &theme, bounds, gfx.State{Focused: focused, Invalid: snapshot.Invalid, Warning: snapshot.Warning, Disabled: snapshot.Disabled}) inset := theme.Metrics.TextInsetX() area := gfx.Rect{X: bounds.X + inset, Y: bounds.Y + textareaPadY, Width: textareaMax(0, bounds.Width-2*inset), Height: textareaMax(0, bounds.Height-2*textareaPadY)} paintTextareaContent(canvas, theme, bounds, area, snapshot, focused) @@ -170,7 +170,7 @@ func textareaPaintRows(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, val layout.Fit(canvas, snapshot.LayoutText(), fontSize, bounds.Width, !snapshot.NoWrap) layout.Content, layout.LineHeight = bounds, lineHeight if !placeholderShown { - layout.Follow(caret, layout.RowOf(caret)) + layout.Show(caret) rows.layout, rows.index = layout, int(layout.Scroll/lineHeight) scroll = layout.Scroll } else { @@ -274,7 +274,12 @@ func textareaPaintRows(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, val if snapshot.Disabled { selectedColor.Alpha *= 0.50 } - canvas.Label(line, labelBounds, gfx.TextStyle{Size: fontSize, Weight: weight, Color: selectedColor}) + selectedStyle := gfx.TextStyle{Size: fontSize, Weight: weight, Color: selectedColor} + if snapshot.PaintLine != nil { + snapshot.PaintLine(canvas, line, labelBounds, selectedStyle) + } else { + canvas.Label(line, labelBounds, selectedStyle) + } canvas.Unclip() } } diff --git a/components/textarea_selection_paint_line_test.go b/components/textarea_selection_paint_line_test.go new file mode 100644 index 000000000..c52a7d394 --- /dev/null +++ b/components/textarea_selection_paint_line_test.go @@ -0,0 +1,31 @@ +package components + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +func TestTextareaPaintLineAlsoPaintsSelectedText(t *testing.T) { + var canvas gfx.Canvas + theme := gfx.LightTheme() + calls := 0 + PaintTextarea(&canvas, theme, gfx.Rect{Width: 200, Height: 80}, TextareaSnapshot{ + Value: "hello", SelectionStart: 0, SelectionEnd: 2, + PaintLine: func(c *gfx.Canvas, value string, bounds gfx.Rect, style gfx.TextStyle) { + calls++ + c.Label("custom:"+value, bounds, style) + }, + }) + if calls != 2 { + t.Fatalf("custom painter called %d times, want normal and selected passes", calls) + } + labels := canvas.Texts() + if len(labels) != 2 || labels[0].Value != "custom:hello" || labels[1].Value != "custom:hello" { + t.Fatalf("selected text bypassed the custom painter: %+v", labels) + } + _, selectedColor := selectionColors(theme) + if labels[1].Style.Color != selectedColor || !labels[1].HasClip { + t.Fatalf("selected painter lost selection color or clip: %+v", labels[1]) + } +} diff --git a/components/toast.go b/components/toast.go index fc4b7bdf5..ccd3dd5c8 100644 --- a/components/toast.go +++ b/components/toast.go @@ -17,14 +17,25 @@ const ( // ToastOptions contains stable action and overlay identities. type ToastOptions struct { - Layer uint16 - Scope gfx.ID - DismissID gfx.ID - ActionID gfx.ID + // Layer is the canvas layer the toast is painted on. + Layer uint16 + // Scope groups the toast's identities and its focus. + Scope gfx.ID + // DismissID names the close button and the Escape target. Zero paints no + // close button and leaves Escape to the page. + DismissID gfx.ID + // ActionID names the action button; zero paints none. + ActionID gfx.ID + // ActionLabel is the action button's text; empty paints none. ActionLabel string - Disabled bool + // Disabled dims the toast and disables its action and close button. + Disabled bool // Position is where the toast sits; the zero value is the bottom right. Position ToastPosition + + // width is the shared width of a stack, set by PaintSonner so its cards line + // up behind one another; zero lets the toast size itself to its content. + width float32 } // ToastLayout exposes deterministic geometry for pointer routing and tests. @@ -36,20 +47,29 @@ type ToastLayout struct { Close gfx.Rect } -// Toast geometry, from Base UI's toast: a `max-w-sm` box 16px in from the -// viewport, `p-4` around content whose parts are `gap-3` apart, a title and a -// description `gap-1` apart, and a stack that peeks 12px per toast behind the -// front one (`--peek`) or opens with 12px between toasts (`--gap`). +// Toast geometry: a compact message bar, as Arco's Message and react-hot-toast: +// 10px above and below, 16px at the ends, an icon and text 8px apart, and a +// stack that peeks 10px per toast behind the front one. The width follows the +// text up to 384px, and a description sits under the title as a smaller line. +// A small close button sits at the end of the row and keeps its room. const ( toastMaxWidth = float32(384) toastInset = float32(16) - toastPadding = float32(16) - toastItemGap = float32(12) - toastTextGap = float32(4) - toastPeek = float32(12) - toastStackGap = float32(12) - toastIconSize = float32(16) - toastCloseSize = float32(32) + toastPaddingX = float32(16) + toastPaddingY = float32(10) + toastItemGap = float32(8) + toastTextGap = float32(2) + toastPeek = float32(10) + toastStackGap = float32(10) + toastIconSize = float32(20) + toastCloseSize = float32(20) + // A string's measured width and the sum of its clusters can differ by a + // fraction; the slack keeps a line that was measured to fit from wrapping. + toastTextSlack = float32(1) + // Each card behind the front of a collapsed stack is 5% smaller, down to a + // floor so a stack deeper than the visible limit cannot vanish. + toastStackScale = float32(0.05) + toastStackMinScale = float32(0.80) ) // toastGeometry measures a toast without painting it: the width, the wrapped @@ -59,35 +79,62 @@ type toastGeometry struct { text float32 // height of the title and description lines bodyWidth float32 actionWidth float32 + actionHeight float32 hasIcon bool } func toastMeasure(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapshot ToastSnapshot, options ToastOptions, scratch *overlayLines) (toastGeometry, []string) { var geometry toastGeometry - geometry.width = min(toastMaxWidth, viewport.Width-2*toastInset) - if geometry.width <= 0 { + limit := min(toastMaxWidth, viewport.Width-2*toastInset) + if limit <= 0 { return geometry, nil } metrics := theme.Metrics geometry.hasIcon = snapshot.Type != ToastDefault - geometry.bodyWidth = geometry.width - 2*toastPadding - toastCloseSize - toastItemGap + // Everything the width has to hold besides the text: the padding, the close + // button, and the icon and action when there are any. + chrome := 2 * toastPaddingX + if !options.DismissID.IsZero() { + chrome += toastCloseSize + toastItemGap + } if geometry.hasIcon { - geometry.bodyWidth -= toastIconSize + toastItemGap + chrome += toastIconSize + toastItemGap } if !options.ActionID.IsZero() && options.ActionLabel != "" { - geometry.actionWidth = BeginButton(canvas, theme, gfx.ID{}, gfx.Rect{}).Small().SizeToFit(options.ActionLabel).BoundsWidth() - geometry.bodyWidth -= geometry.actionWidth + toastItemGap + button := BeginButton(canvas, theme, gfx.ID{}, gfx.Rect{}).Small().SizeToFit(options.ActionLabel) + geometry.actionWidth, geometry.actionHeight = button.BoundsWidth(), button.BoundsHeight() + chrome += geometry.actionWidth + toastItemGap + } + bodyLimit := max(limit-chrome, 0) + // The body takes the width its own text asks for, so a short title stays a + // compact bar, and the description wraps once that would pass the limit. A + // stack hands every card the same width instead, so its peeks line up. + var bodyWidth float32 + if options.width > 0 { + bodyWidth = options.width - chrome + } else { + var titleWidth, descriptionWidth float32 + if canvas != nil { + titleWidth = canvas.TextWidthWeight(snapshot.Title, metrics.FontSizeM, gfx.WeightMedium) + descriptionWidth = canvas.TextWidthWeight(snapshot.Description, metrics.FontSizeS, gfx.WeightRegular) + } + bodyWidth = max(titleWidth, descriptionWidth) + toastTextSlack } - geometry.bodyWidth = max(geometry.bodyWidth, 0) - lines := overlayWrap(canvas, scratch, snapshot.Description, metrics.FontSizeM, gfx.WeightRegular, geometry.bodyWidth) + geometry.bodyWidth = min(max(bodyWidth, 0), bodyLimit) + geometry.width = min(chrome+geometry.bodyWidth, limit) + lines := overlayWrap(canvas, scratch, snapshot.Description, metrics.FontSizeS, gfx.WeightRegular, geometry.bodyWidth) geometry.text = overlayLineHeight(metrics) if len(lines) > 0 { - geometry.text += toastTextGap + float32(len(lines))*overlayLineHeight(metrics) + geometry.text += toastTextGap + float32(len(lines))*toastDescriptionLineHeight(metrics) } - geometry.height = max(geometry.text, toastCloseSize) + 2*toastPadding + rowHeight := max(max(geometry.text, toastCloseSize), geometry.actionHeight) + geometry.height = rowHeight + 2*toastPaddingY return geometry, lines } +// toastDescriptionLineHeight is the leading of the smaller description line. +func toastDescriptionLineHeight(metrics gfx.Metrics) float32 { return metrics.FontSizeS + 6 } + // ToastHeight is how tall PaintToast makes the toast, for a caller that stacks // toasts itself. func ToastHeight(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapshot ToastSnapshot, options ToastOptions) float32 { @@ -97,10 +144,10 @@ func ToastHeight(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapsho } // PaintToast paints one toast snapshot at the viewport position the options -// name, bottom right by default. Its height follows its text: the description -// wraps. It schedules no work and retains no lifetime state, except that a -// loading toast asks for a frame every 100ms to turn its spinner, until it is -// no longer painted. +// name, bottom right by default. Its width follows its text, up to 384px, and +// its height follows the description, which wraps at that width. It schedules +// no work and retains no lifetime state, except that a loading toast asks for a +// frame every 100ms to turn its spinner, until it is no longer painted. func PaintToast(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapshot ToastSnapshot, options ToastOptions) ToastLayout { if canvas == nil || viewport.Width <= 0 || viewport.Height <= 0 || snapshot.Limited { return ToastLayout{} @@ -121,7 +168,7 @@ func PaintToast(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapshot default: x = viewport.X + viewport.Width - width - toastInset } - stack := float32(snapshot.Index) * toastPeek + stack := float32(0) if snapshot.Expanded { stack = float32(snapshot.Index) * (height + toastStackGap) } @@ -134,8 +181,26 @@ func PaintToast(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapshot x += snapshot.SwipeX y += snapshot.OffsetY + snapshot.SwipeY bounds := gfx.Rect{X: x, Y: y, Width: width, Height: height} + // A toast that is not the front of a collapsed stack sits back from the + // edge, smaller: the scale and lift are what make the cards behind the + // front one visible and give the stack its depth. + pose, pivot := gfx.Pose{}, gfx.Point{} + if !snapshot.Expanded && snapshot.Index > 0 { + scale := max(1-float32(snapshot.Index)*toastStackScale, toastStackMinScale) + lift := float32(snapshot.Index) * toastPeek + pivot = gfx.Point{X: bounds.X + bounds.Width/2, Y: bounds.Y} + pose = gfx.Pose{Offset: gfx.Point{Y: lift}, Scale: scale} + if !top { + pivot.Y = bounds.Y + bounds.Height + pose.Offset.Y = -lift + } + } + posed := pose != (gfx.Pose{}) layout := ToastLayout{Bounds: bounds} canvas.PushLayer(options.Layer) + if posed { + canvas.BeginPose(options.DismissID, 0, pose, theme.Transition, pivot) + } if !options.DismissID.IsZero() { // A toast may still be shown while a dialog or menu is open. Claim // Escape at the outer depth so the overlay the user is working in keeps @@ -145,14 +210,16 @@ func PaintToast(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapshot if !options.Scope.IsZero() { canvas.PushFocusScope(options.Scope) } - canvas.BeginPresence(overlayKey(options.DismissID, options.Scope), overlaySurfacePart, toastPresence(theme, options.Position, height), centerOf(bounds)) - // sonner's own shadow, 0 4px 12px rgb(0 0 0 / 10%): the pinned shadcn snapshot has none. + canvas.BeginPresence(overlayKey(options.DismissID, options.Scope), overlaySurfacePart, toastPresence(theme, options.Position), centerOf(bounds)) + // Two soft layers instead of a border: one wide and one tight, close to + // sonner's 0 4px 12px rgb(0 0 0 / 10%) with a crisper edge under it. canvas.Shadow(bounds, metrics.RadiusSurface, gfx.ShadowStyle{OffsetY: 4, Blur: 12}, gfx.Color{Alpha: 0.10}) - canvas.RoundedBorder(bounds, metrics.RadiusSurface, 1, theme.Border, theme.Popover) + canvas.Shadow(bounds, metrics.RadiusSurface, gfx.ShadowStyle{OffsetY: 2, Blur: 4}, gfx.Color{Alpha: 0.06}) + canvas.Rounded(bounds, metrics.RadiusSurface, theme.Popover) // The icon, the text, the action and the close button are centered on the row // the padding leaves. - row := gfx.Rect{X: bounds.X + toastPadding, Y: bounds.Y + toastPadding, Width: bounds.Width - 2*toastPadding, Height: bounds.Height - 2*toastPadding} + row := gfx.Rect{X: bounds.X + toastPaddingX, Y: bounds.Y + toastPaddingY, Width: bounds.Width - 2*toastPaddingX, Height: bounds.Height - 2*toastPaddingY} textX := row.X if geometry.hasIcon { layout.Icon = gfx.Rect{X: row.X, Y: row.Y + (row.Height-toastIconSize)/2, Width: toastIconSize, Height: toastIconSize} @@ -171,45 +238,86 @@ func PaintToast(canvas *gfx.Canvas, theme gfx.Theme, viewport gfx.Rect, snapshot button.paint(options.ActionLabel, ButtonOutline) right = layout.Action.X - toastItemGap } - closeColor := theme.MutedForeground - if options.Disabled { - closeColor.Alpha *= 0.50 - } - if !options.DismissID.IsZero() && !options.Disabled && canvas.Hovered() == options.DismissID { - canvas.Rounded(layout.Close, metrics.RadiusControl, theme.Accent) - closeColor = theme.AccentForeground - } - paintCross(canvas, layout.Close, 16, closeColor) + // The close button is always there, small and quiet, and takes the accent + // while the pointer or the focus is on it. if !options.DismissID.IsZero() { + closeColor := theme.MutedForeground + if options.Disabled { + closeColor.Alpha *= 0.50 + } + if !options.Disabled && (canvas.Hovered() == options.DismissID || canvas.Focused() == options.DismissID) { + canvas.Rounded(layout.Close, toastCloseSize/2, theme.Accent) + closeColor = theme.AccentForeground + } + paintCross(canvas, layout.Close, 14, closeColor) canvas.HitWithOptions(options.DismissID, layout.Close, "Close toast", gfx.HitOptions{Role: gfx.RoleButton, Disabled: options.Disabled}) } layout.Body = gfx.Rect{X: textX, Y: row.Y + (row.Height-geometry.text)/2, Width: max(0, right-textX), Height: geometry.text} - lineHeight := overlayLineHeight(metrics) - canvas.Label(snapshot.Title, gfx.Rect{X: layout.Body.X, Y: layout.Body.Y, Width: layout.Body.Width, Height: lineHeight}, gfx.TextStyle{Size: metrics.FontSizeM, Weight: gfx.WeightMedium, Color: theme.PopoverForeground}) - overlayParagraph(canvas, lines, gfx.Rect{X: layout.Body.X, Y: layout.Body.Y + lineHeight + toastTextGap, Width: layout.Body.Width}, lineHeight, gfx.TextStyle{ - Size: metrics.FontSizeM, Weight: gfx.WeightRegular, Color: theme.MutedForeground, + titleHeight, descriptionHeight := overlayLineHeight(metrics), toastDescriptionLineHeight(metrics) + canvas.Label(snapshot.Title, gfx.Rect{X: layout.Body.X, Y: layout.Body.Y, Width: layout.Body.Width, Height: titleHeight}, gfx.TextStyle{Size: metrics.FontSizeM, Weight: gfx.WeightMedium, Color: theme.PopoverForeground}) + overlayParagraph(canvas, lines, gfx.Rect{X: layout.Body.X, Y: layout.Body.Y + titleHeight + toastTextGap, Width: layout.Body.Width}, descriptionHeight, gfx.TextStyle{ + Size: metrics.FontSizeS, Weight: gfx.WeightRegular, Color: theme.MutedForeground, }, false) canvas.EndPresence() + if posed { + canvas.EndPose() + } if !options.Scope.IsZero() { canvas.PopFocusScope() } canvas.PopLayer() + if posed { + layout = toastPoseLayout(layout, pose, pivot) + } + return layout +} + +// toastPoseLayout places the parts of a toast where the stack's pose puts them, +// so a caller's layout and hit testing agree with what was painted. +func toastPoseLayout(layout ToastLayout, pose gfx.Pose, pivot gfx.Point) ToastLayout { + layout.Bounds = toastPoseRect(layout.Bounds, pose, pivot) + layout.Icon = toastPoseRect(layout.Icon, pose, pivot) + layout.Body = toastPoseRect(layout.Body, pose, pivot) + layout.Action = toastPoseRect(layout.Action, pose, pivot) + layout.Close = toastPoseRect(layout.Close, pose, pivot) return layout } -// toastPresence is how a toast comes and goes: it slides from and to beyond its -// edge of the window, by 150% of its height, over 500ms (Base UI's -// `translateY(150%)` with `cubic-bezier(0.22, 1, 0.36, 1)`), without fading. -func toastPresence(theme gfx.Theme, position ToastPosition, height float32) gfx.Presence { +func toastPoseRect(rect gfx.Rect, pose gfx.Pose, pivot gfx.Point) gfx.Rect { + if rect == (gfx.Rect{}) { + return rect + } + scale := pose.Scale + if scale <= 0 { + scale = 1 + } + return gfx.Rect{ + X: pivot.X + (rect.X-pivot.X)*scale + pose.Offset.X, + Y: pivot.Y + (rect.Y-pivot.Y)*scale + pose.Offset.Y, + Width: rect.Width * scale, + Height: rect.Height * scale, + } +} + +// toastPresence is how a toast comes and goes: it grows from 95% with a short +// lift from its edge of the window and fades in, over 220ms. That is a lighter +// arrival than Base UI's 150%-height slide, and the scale and fade are what make +// it read as a notification rather than a panel. +func toastPresence(theme gfx.Theme, position ToastPosition) gfx.Presence { if !moving(theme) { return gfx.Presence{} } - slide := gfx.Point{Y: height * 1.5} + slide := gfx.Point{Y: 16} if position >= ToastTopRight { slide.Y = -slide.Y } - return gfx.Presence{Motion: gfx.Motion{Duration: toastDuration, Easing: gfx.EaseEmphasized}, SlideIn: slide, SlideOut: slide} + return gfx.Presence{ + Motion: gfx.Motion{Duration: toastDuration, Easing: gfx.EaseEmphasized}, + Fade: true, + Scale: 0.95, + SlideIn: slide, SlideOut: slide, + } } // toastSpinnerStep is how long a loading toast's spinner holds each of its eight spokes. @@ -229,7 +337,7 @@ func paintToastIcon(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, kind T } PaintSpinner(canvas, theme, bounds, phase) case ToastSuccess: - canvas.DrawIcon(circleCheckIcon, bounds, theme.PopoverForeground) + canvas.DrawIcon(circleCheckIcon, bounds, theme.Success) case ToastInfo: canvas.DrawIcon(infoIcon, bounds, theme.PopoverForeground) case ToastWarning: @@ -269,8 +377,9 @@ var ( }} ) -// toastDuration is the 500ms of Base UI's toast transition. -const toastDuration = 500 * time.Millisecond +// toastDuration is how long a toast takes to arrive or leave. It is shorter than +// Base UI's 500ms so a notification settles before it is read. +const toastDuration = 220 * time.Millisecond // Aliases into the style vocabulary. type ToastQueue = base.ToastQueue diff --git a/components/toast_test.go b/components/toast_test.go index e59793018..4a0a72e05 100644 --- a/components/toast_test.go +++ b/components/toast_test.go @@ -10,10 +10,12 @@ import ( func TestToastPaintsOnlyCallerSnapshot(t *testing.T) { var canvas gfx.Canvas - layout := PaintToast(&canvas, gfx.LightTheme(), gfx.Rect{Width: 1000, Height: 700}, ToastSnapshot{ + viewport := gfx.Rect{Width: 1000, Height: 700} + layout := PaintToast(&canvas, gfx.LightTheme(), viewport, ToastSnapshot{ Title: "Deployment complete", Description: "Production is now up to date.", Type: ToastSuccess, Index: 1, Expanded: true, }, ToastOptions{Layer: 12, Scope: gfx.Item(63), DismissID: gfx.Item(7), ActionID: gfx.Item(8), ActionLabel: "View"}) - if layout.Bounds != (gfx.Rect{X: 600, Y: 516, Width: 384, Height: 78}) { + if layout.Bounds.Width <= 0 || layout.Bounds.Width > toastMaxWidth || + layout.Bounds.X+layout.Bounds.Width != viewport.Width-toastInset { t.Fatalf("toast bounds = %+v", layout.Bounds) } if canvas.EscapeTarget() != gfx.Item(7) || !canvas.TrappedFocusScope().IsZero() { @@ -77,6 +79,9 @@ func TestToastDescriptionWrapsAndTheToastGrows(t *testing.T) { if long.Bounds.Height <= short.Bounds.Height || long.Bounds.Y+long.Bounds.Height != short.Bounds.Y+short.Bounds.Height { t.Fatalf("short %+v, long %+v: want a taller toast that keeps its bottom edge", short.Bounds, long.Bounds) } + if short.Bounds.Width >= long.Bounds.Width { + t.Fatalf("short %+v, long %+v: want the width to follow the text", short.Bounds, long.Bounds) + } } func TestToastPositionPicksTheCornerAndLoadingAsksForFramesOnlyWhileShown(t *testing.T) { @@ -101,6 +106,56 @@ func TestToastPositionPicksTheCornerAndLoadingAsksForFramesOnlyWhileShown(t *tes } } +// A toast with no dismiss ID paints no close button and does not keep its room. +func TestToastWithoutDismissIDHasNoCloseButton(t *testing.T) { + var canvas gfx.Canvas + viewport := gfx.Rect{Width: 1000, Height: 700} + snapshot := ToastSnapshot{Title: "Copied", Type: ToastSuccess} + withClose := PaintToast(&canvas, gfx.LightTheme(), viewport, snapshot, ToastOptions{Layer: 1, DismissID: gfx.Item(1)}) + if len(canvas.Hits()) != 1 || canvas.Hits()[0].Label != "Close toast" { + t.Fatalf("hits = %+v", canvas.Hits()) + } + canvas.Reset() + withoutClose := PaintToast(&canvas, gfx.LightTheme(), viewport, snapshot, ToastOptions{Layer: 1}) + if len(canvas.Hits()) != 0 { + t.Fatalf("a toast without a dismiss ID has hits: %+v", canvas.Hits()) + } + if withoutClose.Bounds.Width >= withClose.Bounds.Width { + t.Fatalf("with close %+v, without %+v: want the close room gone", withClose.Bounds, withoutClose.Bounds) + } +} + +// The queue's default timeout is one policy; AddFor lets one toast carry its +// own, and a loading toast still never expires. +func TestToastQueueAddForUsesTheToastsOwnTimeout(t *testing.T) { + now := time.Unix(0, 0) + var queue ToastQueue + if evicted, ok := queue.AddFor(gfx.Item(1), now, false, 2*time.Second); !ok || !evicted.IsZero() { + t.Fatalf("AddFor = (%v, %v)", evicted, ok) + } + if evicted, ok := queue.Add(gfx.Item(2), now, false); !ok || !evicted.IsZero() { + t.Fatalf("Add = (%v, %v)", evicted, ok) + } + if _, expired := queue.Expire(now.Add(1999 * time.Millisecond)); expired { + t.Fatal("a two-second toast expired early") + } + if id, expired := queue.Expire(now.Add(2 * time.Second)); !expired || id != gfx.Item(1) { + t.Fatalf("first expiry = (%v, %v), want item 1", id, expired) + } + if _, expired := queue.Expire(now.Add(4 * time.Second)); expired { + t.Fatal("the default five-second toast expired early") + } + if id, expired := queue.Expire(now.Add(5 * time.Second)); !expired || id != gfx.Item(2) { + t.Fatalf("second expiry = (%v, %v), want item 2", id, expired) + } + if _, ok := queue.AddFor(gfx.Item(3), now, true, time.Second); !ok { + t.Fatal("a loading toast did not add") + } + if _, expired := queue.Expire(now.Add(time.Hour)); expired { + t.Fatal("a loading toast expired") + } +} + // The queue carries Base UI's lifetime: five seconds, a visible limit, loading // toasts that never expire, and pause/resume without losing the remaining time. func TestToastQueueExpiresPausesAndLimits(t *testing.T) { diff --git a/components/tree.go b/components/tree.go index 832cd2074..552f601fb 100644 --- a/components/tree.go +++ b/components/tree.go @@ -127,8 +127,14 @@ func (tree *Tree) Item(item TreeItem) TreeRow { if item.Disabled { color.Alpha *= 0.50 } - tree.paintDisclosure(disclosure, item.Expanded, color) - if !item.DisclosureID.IsZero() { + if item.Loading { + spinner := tree.theme + spinner.Foreground = color + PaintSpinner(tree.canvas, spinner, disclosure, SpinnerPhase(item.Phase)) + } else { + tree.paintDisclosure(disclosure, item.Expanded, color) + } + if !item.DisclosureID.IsZero() && !item.Loading { tree.canvas.HitWithOptions(item.DisclosureID, disclosure, item.Label, gfx.HitOptions{ Role: gfx.RoleButton, Disabled: item.Disabled, Expanded: item.Expanded, Expandable: true, }) diff --git a/components/tree_test.go b/components/tree_test.go index a41507754..0856845cf 100644 --- a/components/tree_test.go +++ b/components/tree_test.go @@ -46,6 +46,29 @@ func TestTreeDisabledDisclosureAndSteadyPaintAreAllocationFree(t *testing.T) { } } +// A branch whose children are being fetched shows a spinner in place of its +// chevron and takes no press on it, so a second press cannot start a second fetch. +func TestTreeLoadingBranchHasASpinnerAndNoDisclosureHit(t *testing.T) { + var canvas gfx.Canvas + loading := func() { + canvas.Reset() + tree := BeginTree(&canvas, gfx.LightTheme(), gfx.Rect{Width: 300, Height: 200}) + tree.Item(TreeItem{ID: gfx.Item(1), DisclosureID: gfx.Item(2), Label: "Remote", Branch: true, Loading: true, Phase: 3}) + } + loading() + for _, hit := range canvas.Hits() { + if hit.ID == gfx.Item(2) { + t.Fatalf("a loading branch declares its disclosure: %+v", hit) + } + } + if len(canvas.Rectangles()) == 0 { + t.Fatal("a loading branch paints no spinner") + } + if allocations := testing.AllocsPerRun(100, loading); allocations != 0 { + t.Fatalf("loading tree paint allocations = %v", allocations) + } +} + func BenchmarkTreePaint(b *testing.B) { var canvas gfx.Canvas theme := gfx.DarkTheme() diff --git a/docs/maintaining-controls.md b/docs/maintaining-controls.md index ba5c82e52..a429bd060 100644 --- a/docs/maintaining-controls.md +++ b/docs/maintaining-controls.md @@ -52,7 +52,8 @@ Opt-in page packages live under `ui/` (`ui/codeeditor`, `ui/textview`, `ui `ui/skeleton`, `ui/inputgroup`, `ui/inputotp`, `ui/questionnaire`, `ui/metriccard`, `ui/marker`, `ui/sidebar`, `ui/buttongroup`, `ui/togglegroup`, `ui/multiselect`, -`ui/hierarchypicker`). +`ui/hierarchypicker`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, +`ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`). They import only the public `base`, `components`, `gfx`, `ui` and `window` packages, plus the focused `text` editor for editor-like controls and the root `markdown` parser for the Markdown view. They own stable handlers, and are never diff --git a/docs/releases/0.6.7.md b/docs/releases/0.6.7.md index d1dc148d8..c42080a7a 100644 --- a/docs/releases/0.6.7.md +++ b/docs/releases/0.6.7.md @@ -19,7 +19,7 @@ v0.6.7 comes after v0.6.6: themed controls are driven by the engine, images take - `ui.ButtonGroup` 支持只有图标的动作与选中态,公开按钮组可以直接组合工具栏动作。 - `ui.Canvas.LabelHighlighted` 在成形文本后面按大小写不敏感匹配高亮搜索词,原文本和无障碍名保持不变。 - `WebView` 新增 `Title()`、`CanGoBack()`、`CanGoForward()`、`IsLoading()`,并提供分好类的加载失败原因。 -- `app.StartFileDrag` 可以把文件从窗口拖出到其他程序,X11 上同时显示跟随指针的半透明预览窗口。 +- `app.StartFileDrag` 在 Windows 上可以把文件从窗口拖出到其他程序;`app.OpenDragPreview` 提供跟随指针的半透明预览窗口(X11 上已实现)。 - `Window.SetIcon` 可以在运行时替换窗口图标,并同步 Windows 任务栏的分组资源。 - Windows 上彩色终端行的一次绘制合并为每遍一次 GDI 调用,DirectWrite 的文本格式与布局会在光栅器生命周期内复用,滚动彩色输出更顺畅。 - Windows 的实时缩放改由定时器驱动,拖动窗口边缘时画面按自己的节奏重绘,不再被每条原生消息带着走。 @@ -44,7 +44,7 @@ v0.6.7 comes after v0.6.6: themed controls are driven by the engine, images take - `ui.ButtonGroup` supports icon-only actions and a selected action, so a page composes toolbar actions with the public button group. - `ui.Canvas.LabelHighlighted` paints case-insensitive search matches behind shaped text while the original text and its accessible name stay unchanged. - `WebView` reports `Title()`, `CanGoBack()`, `CanGoForward()` and `IsLoading()`, and exposes classified load failures. -- `app.StartFileDrag` drags files out of a window to other programs, with a translucent preview following the pointer on X11. +- `app.StartFileDrag` drags files out of a window to other programs on Windows; `app.OpenDragPreview` offers a translucent preview following the pointer (implemented on X11). - `Window.SetIcon` replaces the window icon at run time and keeps Windows taskbar grouping resources in step. - On Windows a colored terminal row is drawn with one GDI call per pass and DirectWrite formats and layouts are kept for the rasterizer's lifetime, so scrolling colored output is smoother. - Windows live resize is paced by its timer, so dragging a window edge redraws at its own rate instead of once per native message. diff --git a/docs/releases/0.6.8.md b/docs/releases/0.6.8.md new file mode 100644 index 000000000..fb3eec1c5 --- /dev/null +++ b/docs/releases/0.6.8.md @@ -0,0 +1,65 @@ +v0.6.8 是 v0.6.7 之后的版本:`ui.Run` 改为接收 `PageConfig`,与 `OpenWindow` 一致;加入触摸输入、双向文本光标与 CodeEditor 装饰、只读选择文本 `textview`、关系图、响应式布局与延时投递,并有大量 Linux、Windows 与 macOS 的输入法、剪贴板和性能修复。macOS 是参考平台。 + +v0.6.8 comes after v0.6.7: `ui.Run` takes a `PageConfig` as `OpenWindow` does, and the release adds touch input, bidirectional text carets and CodeEditor decorations, a read-only selectable `textview`, a link graph, responsive layout and delayed posting, with many input-method, clipboard and performance fixes on Linux, Windows and macOS. macOS is the reference platform. + +## 拿到它 · Getting it + +`go get github.com/vivaui/viva@v0.6.8`,需要 Go 1.26 或更新;系统依赖与 v0.6.7 相同。每个 Release 附带 `viva` 命令的预编译压缩包、`SHA256SUMS`,以及 Homebrew 与 Scoop 清单(`brew install vivaui/tap/viva`,或 `scoop bucket add vivaui https://github.com/vivaui/homebrew-tap` 后 `scoop install viva`)。 + +`go get github.com/vivaui/viva@v0.6.8` needs Go 1.26 or newer; the system requirements are those of v0.6.7. Every Release carries prebuilt archives of the `viva` command, `SHA256SUMS`, and Homebrew and Scoop manifests (`brew install vivaui/tap/viva`, or `scoop bucket add vivaui https://github.com/vivaui/homebrew-tap` then `scoop install viva`). + +## 有什么 · What is in it + +- `ui.Run(config, ui.PageConfig{View: m.page})`:一个窗口的程序可以在同一个 `PageConfig` 里设置主题和样式;`ui` 重新导出了自定义控件与绘制要用的类型(`Identity`、事件与画布类型、字重、阴影层级、文本方向与对齐、`ButtonVariant`、`TableColumn`、各控件的外观)。 +- `Box.Variant` 可以在运行时选择按钮变体;`ui.Table` 现在自己完整:页面把移动选中行的按键送给它,点击选中一行,`TableState.Changed` 报告选择变化,只给 `Headers` 时各列均分宽度。 +- `ui.AlertDialog` 与 `Modal` 一样开在 `*bool` 上,并报告确认动作;`ui.MenuAt` 相对应用自绘表面的矩形打开菜单;没有指定初始焦点的 `Dialog` 把键盘交给正文的第一个控件;`FormField` 的标题像 HTML label 一样标注它的第一个控件。 +- `Box.From` 与 `Container`、`Breakpoint` 让布局随窗口或容器宽度变化,`Box.Hide`、`Box.Show` 隐藏和重新显示元素,`Box.Maxs`、`Box.Italic`、`Box.Strike`、`Box.OverflowWrap` 补全文本与尺寸属性,长单词在没有空间时可以折断。 +- `ui/textview` 是只读、可选择、可复制的文本;`ui.TextFieldID` 也能编辑模型里的字符串;输入、分割条、提示和树控件补全了几处缺口。 +- `components` 新增力导向的链接图(`PaintGraph`、`GraphState`、`GraphSim`),CodeEditor 增加行号栏、字节范围装饰与下划线,保持双向文本的成形光标位置,只重排被编辑触及的行;下拉菜单可以设置行高与最大宽度;Select 与 Combobox 的列表按弹出规则定位。 +- `app.Invalidator.Post` 让 goroutine 把结果交回窗口,`Application.PostAfter` 在事件循环上延时执行;`Config.Maximized` 以最大化打开窗口,`Config.OnDeactivate` 报告窗口失去激活,`Config.CaptureMenuKeys` 让应用先于菜单取键。 +- `app.WindowNotification` 是可点击的通知弹窗;`app.SetClipboardImage` 把图片放上剪贴板;`WebViewConfig` 增加 `Partition`、`UserAgentSuffix` 和 `OnProcessFailed`,`WebView.IsCrashed` 与 `ProcessFailure` 报告页面进程的死亡。 +- 触摸:手指读作点击、拖动、甩动与长按,滚动可以越过末端并弹回,小于 44 px 的控件也能被手指点中,`Config.OnPinch` 报告双指缩放,轻点放置光标、按住选词、按住显示提示;Windows 按触摸指针读手指,Linux X11 按 X Input 触摸事件读手指。 +- `Canvas.TitlebarInsets` 与 `ui.C.TitlebarInsets` 给出本窗口的标题栏边距:自定义标题栏时是平台的窗口按钮,全屏或系统标题栏下为零。 +- `Theme.WithTextScale` 按偏好缩放字号与行高,`Theme.TooltipDelay` 设置提示延迟,`gfx.TextHit` 返回点击所在的簇边缘,完全透明的文本不再绘制。 +- 辅助技术:Linux 上新增的无障碍控件会发出焦点通知;X11 上剪贴板变化会通知、按 TARGETS 读取并刷新过期的所有权,Fcitx 4 取消预编辑时保留选中文本,GTK 在窗口失焦时丢弃未选中的预编辑,IBus 先从 `WAYLAND_DISPLAY` 找守护进程地址。 +- Windows 上菜单捕获按键时保持输入法组合,最小化的窗口不再报告为窗口位置。 +- X11 窗口不用等输入就能绘制,重新曝光后会重绘;所有窗口共用一个 Vulkan 设备,标签图像从块里子分配,上传经保留的缓冲区,不再让 GPU 空等。 +- 编辑器的文本以 UTF-8 叶子保存,点击与选词不再扫描整行,Textarea 只排版视口内的行且只重排被编辑的段落,CodeEditor 只排版被编辑触及的行;`textarea` 跟随程序修改。 +- 通知窗口会保持在屏幕内并可以移动,`Select` 在对话框、抽屉或弹出层里不再替外层结束出现动画,面板的滚轮事件不再传给下面的页面,`Markdown` 解码行内字符引用,PAC 求值在取消时被唤醒而不是轮询。 +- 打包 `.dmg` 时等待磁盘映像服务放手、在卷已卸载或仍挂载时都能分离,映像构建过程中不会暴露可安装的应用。 + +- `ui.Run(config, ui.PageConfig{View: m.page})`: a one-window program sets its theme and styles in the same `PageConfig`; `ui` re-exports the types a custom control and a draw take (`Identity`, the event and canvas types, font weights, shadow levels, text direction and alignment, `ButtonVariant`, `TableColumn`, and the control looks). +- `Box.Variant` chooses a button's variant at run time; `ui.Table` is whole as declared: the page routes it the keys that move its selection, a click selects a row, `TableState.Changed` reports the change, and `Headers` without `Columns` share the width. +- `ui.AlertDialog` opens on a `*bool` as `Modal` does and reports the confirming action; `ui.MenuAt` opens a menu against a rectangle of the application's own surface; a `Dialog` that names no initial focus gives the keyboard to the first control of its body; a `FormField` title labels its first control as an HTML label does. +- `Box.From` with `Container` and `Breakpoint` lays out by the window's or a container's width, `Box.Hide` and `Box.Show` hide and show an element, `Box.Maxs`, `Box.Italic`, `Box.Strike` and `Box.OverflowWrap` complete the text and size attributes, and a long word breaks when the box has no room. +- `ui/textview` is read-only text that selects and copies; `ui.TextFieldID` also edits a model string; fields, the splitter, tooltips and trees close several gaps. +- `components` adds a force-directed link graph (`PaintGraph`, `GraphState`, `GraphSim`), and CodeEditor gains a gutter, byte-range decorations and underlines, keeps shaped bidirectional caret placement, and lays out only the lines an edit touched; dropdown menus take a row height and a maximum width; Select and Combobox lists are placed by the popup rule. +- `app.Invalidator.Post` hands a goroutine's result to a window and `Application.PostAfter` runs delayed work on the event loop; `Config.Maximized` opens a window maximized, `Config.OnDeactivate` reports a window losing the activation, and `Config.CaptureMenuKeys` lets an application take keys before the menu. +- `app.WindowNotification` is a clickable notification popup; `app.SetClipboardImage` puts an image on the clipboard; `WebViewConfig` adds `Partition`, `UserAgentSuffix` and `OnProcessFailed`, and `WebView.IsCrashed` and `ProcessFailure` report the death of a page's process. +- Touch: fingers read as taps, pans, flings and long presses, scrolling carries past its end and springs back, a fingertip reaches controls smaller than 44 px, `Config.OnPinch` reports two-finger pinches, a tap places the caret, a held finger selects a word or opens a tooltip; Windows reads a finger as a touch pointer and Linux X11 reads X Input touch events. +- `Canvas.TitlebarInsets` and `ui.C.TitlebarInsets` give the titlebar insets of the window being painted: the platform's buttons for a custom titlebar, none in full screen or under a system titlebar. +- `Theme.WithTextScale` scales text size and line height by a preference, `Theme.TooltipDelay` sets the tooltip delay, `gfx.TextHit` returns the cluster edge a click hits, and fully transparent text draws nothing. +- Platform input: newly added accessibility controls announce focus on Linux; on X11 clipboard changes notify and the clipboard is read by TARGETS with stale ownership refreshed, Fcitx 4 keeps selected text when its preedit is cancelled, GTK drops an unselected preedit on focus loss, and IBus finds the daemon address from `WAYLAND_DISPLAY` first. +- On Windows IME composition survives a menu that captures keys, and a minimized frame is no longer reported as the window position. +- X11 windows paint without waiting for input and after a re-expose; every window shares one Vulkan device, label image memory is sub-allocated from blocks, and uploads go through kept buffers without idling the GPU. +- The editor keeps its text as UTF-8 leaves, a click or word selection no longer scans the line, Textarea lays out only the rows in view and rewraps only the paragraphs an edit changed, CodeEditor lays out only the lines an edit touched, and a textarea follows program edits. +- The notification window stays on screen and can move, a `Select` inside a dialog, drawer or popover no longer closes the enclosing presence in its place, panel wheel events stay off the page underneath, `Markdown` decodes inline character references, and PAC evaluation wakes on cancel instead of polling. +- Packaging a `.dmg` waits until the disk image service lets go, detaches whether the volume is already unmounted or still attached, and keeps an image build from exposing an installable app. + +## 注意 · Caveats + +- `ui.Run(config, m.page)` 现在是 `ui.Run(config, ui.PageConfig{View: m.page})`。按 `main` 上 v0.6.8 之前的指南写出的程序在 v0.6.7 上无法编译,原因就是这一处;升到 v0.6.8 后指南与代码一致。 +- `app.TitlebarInsets()` 已移除,在页面里用 `c.TitlebarInsets()`,在自绘代码里用 `Canvas.TitlebarInsets`。 +- `ui.AlertDialog(c, spec)` 现在是 `ui.AlertDialog(c, &open, spec)` 并返回确认结果;`PopoverWith` 的 `*bool` 移到了 spec 之前;`base` 包同步变化。`ui.TextFieldID` 变为泛型,按值取用该函数的代码要写类型实参。 +- `Box.Variant` 选的按钮变体互不叠加:指南里的 `Ghost().Destructive()` 以前是实心红色按钮,现在是带危险色的幽灵按钮。 +- dev 构建会拒绝没有 `Columns` 也没有 `Headers` 的 `Table`,它以前什么也不画。 +- Android 与 iOS 后端不在 Viva 主分支上,它们留在 `mobile` 分支;桌面上的触摸、手指滚动、捏合与触摸提示都在本版本里。 +- 细则见 [升级指南 / Upgrading](../upgrading.md#v068---uirun-takes-a-pageconfig-and-four-more-signatures)。 + +- `ui.Run(config, m.page)` is now `ui.Run(config, ui.PageConfig{View: m.page})`. A program written from the guides on `main` before v0.6.8 does not compile against v0.6.7 for this reason alone; with v0.6.8 the guides and the code agree. +- `app.TitlebarInsets()` is removed: use `c.TitlebarInsets()` in a page and `Canvas.TitlebarInsets` in custom painting. +- `ui.AlertDialog(c, spec)` is now `ui.AlertDialog(c, &open, spec)` and returns the confirmation; `PopoverWith` takes its `*bool` before the spec; the `base` package changes alike. `ui.TextFieldID` is now generic, so code taking the function as a value must name a type argument. +- Button variants chosen with `Box.Variant` do not combine: the guide's `Ghost().Destructive()` used to be a solid red button and is now a ghost with the danger color. +- A dev build stops a `Table` with neither `Columns` nor `Headers`, which painted nothing before. +- The Android and iOS backends are not on Viva's main branch; they continue on the `mobile` branch. Desktop touch, finger scrolling, pinch and touch tooltips are in this release. +- Details are in the [upgrading guide](../upgrading.md#v068---uirun-takes-a-pageconfig-and-four-more-signatures). diff --git a/docs/skills/building-with-viva/SKILL.md b/docs/skills/building-with-viva/SKILL.md index bb1928e7b..fe48896de 100644 --- a/docs/skills/building-with-viva/SKILL.md +++ b/docs/skills/building-with-viva/SKILL.md @@ -68,15 +68,15 @@ func (m *model) page(c ui.C) { ### Lists, tables and trees - A long list is `ui.List(c, &m.list, n, func(row ui.ListRow) { ... })`: only the rows on screen are declared. The row's container is `row.Element`, its content is declared with `row.C`. `Selected()`, `Changed()`, `Submitted()`, `ListState.Label` (typeahead), `Selection` (multi-select), `ScrollTo`/`ScrollIntoView`/`Visible`, `Header` (pinned sections), `Reorder` (drag rows), `RowWidth` (sideways scrolling), `ClickModifiers()`. Key rows that hold a `Button`: `ui.Row(c.KeyInt(item.ID))`. -- A table is `ui.Table(c, &m.table, ui.TableSpec{Headers, Sortable, Source, Columns})`; the data is a `ui.TableRows` (`[][]string`) or your own `Len() int` / `Cell(row, col int) string`. `RowClicked()`, `HeaderClicked()`, `SortBy`, `Select`. -- A tree is `ui.Tree(c, &m.tree, n, label, content)` with a `TreeState.Node` per visible row; `Toggled()` and `Chosen()` report the user's action; `CanDrop` + `Dropped()` for drag and drop. `RowID(i)` is a row's identity; a part of a row is `ui.Text(c, name).LabelFor(m.tree.RowID(i))`. +- A table is `ui.Table(c, &m.table, ui.TableSpec{Columns, Source})`, where each `ui.TableColumn` has a `Title`, `Width`, `Alignment` and `Sortable`; the data is a `ui.TableRows` (`[][]string`) or your own `Len() int` / `Cell(row, col int) string`. `RowClicked()`, `HeaderClicked()`, `SortBy`, `Select`. +- A tree is `ui.Tree(c, &m.tree, n, label, content)` with a `TreeState.Node` per visible row; `Toggled()` and `Chosen()` report the user's action; a branch whose children are being fetched sets `TreeNode.Loading` (a spinner in place of its chevron); `CanDrop` + `Dropped()` for drag and drop. `RowID(i)` is a row's identity; a part of a row is `ui.Text(c, name).LabelFor(m.tree.RowID(i))`. - A part that rarely changes is `ui.Memo(c, *row, fn)`: it copies the declaration while that value compares equal. Pass the row (or what the function reads), not a counter. - Scrolling: `area := ui.Scroll(c).Grow(1)`; `area.ScrollState()` has `Offset`, `Content`, `Viewport`, `Max()`, `AtEnd()`, `Pinned()`, `ScrollTo`, `ScrollToEnd`; `.Follow(true)` keeps a log or chat at its end; `.Sideways()` and `.Scrollbars()` add horizontal movement and bars. ### Dialogs, menus and popups -- `ui.Modal(c, &m.open, "Title", body, footer)` or `ui.ModalWith(..., ui.ModalSpec{...}, ...)`. The title is required; Escape, the close button and a press on the scrim set `m.open` to false, so do not write an Escape handler. `ui.Dialog(c, ui.DialogSpec{...})` is the form whose identities you name: `Scope`, `DismissID`, `CloseID`, `InitialFocusID`, `.Header`, `.Body`, `.Footer`, `.Dismissed()`. -- `ui.Popover(c, anchor, &m.open, body)` / `ui.PopoverWith(c, anchor, &m.open, ui.PopoverSpec{...}, body)`; `ui.Menu(c, anchor, &m.open, func(menu *ui.MenuItems) { ... })` with `menu.Item("Rename").Clicked()`, `menu.Sub(label, body)`; `ui.ContextMenu(c, target, func(menu *ui.MenuItems) { ... })`; `ui.Drawer(c, &m.open, title, ui.DrawerSpec{...}, body, footer)`. +- `ui.Modal(c, &m.open, "Title", ui.ModalSpec{...}, body, footer)`. The title is required; Escape, the close button and a press on the scrim set `m.open` to false, so do not write an Escape handler. `ui.Dialog(c, ui.DialogSpec{...})` is the form whose identities you name: `Scope`, `DismissID`, `CloseID`, `InitialFocusID`, `.Header`, `.Body`, `.Footer`, `.Dismissed()`. +- `ui.Popover(c, anchor, &m.open, ui.PopoverSpec{...}, body)`; `ui.Menu(c, anchor, &m.open, func(menu *ui.MenuItems) { ... })` with `menu.Item("Rename").Clicked()`, `menu.Sub(label, body)`; `ui.ContextMenu(c, target, func(menu *ui.MenuItems) { ... })`; `ui.Drawer(c, &m.open, title, ui.DrawerSpec{...}, body, footer)`. - An application overlay is `ui.Overlay(c, ui.OverlaySpec{Band: ui.LayerPaneChrome, Bounds: r})` (or `ui.LayerDrag`): it takes no room, paints below Viva's menus and dialogs, and a `Canvas.Block` over its empty surface keeps presses from the page behind. - Toasts: keep a `ui.Toaster`, `m.toaster.Show(title, text, ui.ToastSuccess)`, paint `ui.Toasts(c, &m.toaster)` once; `ShowAction(..., "Undo")` + `Acted()`, `ToastLoading` + `Done(id, ...)`, `Toaster.Position`. @@ -89,7 +89,7 @@ func (m *model) page(c ui.C) { ### Optional page packages and custom surfaces - A heavy or stateful page control lives in an opt-in package under `ui/`; import it only when the page uses it. -- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`. +- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`. - For read-only selectable output, keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`. The caller owns lines, spans and actions; `ui/textview` owns selection and drawing without an editing model. - The package name is the capability, never a `view` suffix. Name its state type by role, not by repeating the package: `calendar.State`, `message.Row`, `attachment.Card`, `hovercard.Card`. Keep locals out of the package name (`cal`, `msg`, `pic`); a model field may keep the domain noun (`m.calendar`). - Some packages expose `pkg.View(c, label, &state)` (`calendar.View`, `markdown.View`); others expose a method on the state (`avatar.New().View(c, label)`, `questionnaire.New().View(c, label)`). `go doc github.com/vivaui/viva/ui/` shows which. @@ -107,6 +107,7 @@ func (m *model) page(c ui.C) { - A control you paint is `ui.Control(c, label, &m.handlers).Grow(1).Draw(m.draw)`. `ui.Handlers` receives keys, pointer, wheel and, with `gfx.RoleTextField` or `gfx.RoleTerminal`, typing and IME through `Text`. Its parts are declared in `Draw` with `d.Canvas.Hit(part, r)`; an event on a part reaches the same handlers with the part as its target. - Custom layout: `ui.CustomLayout(c, &m.layout).Children(...)` with `ui.Layout`'s `MeasureWidth`, `PlaceWidth`, `MeasureHeight`, `PlaceHeight`. The page keeps identity, focus and hits; the layout owns the children's geometry. - Drag and drop: a `ui.DragState` in the model, `.DragSource(&m.drag)` and `.DropTarget(&m.drag, accept, drop)` on `Hit` boxes, or `d.DragSource`/`d.DropTarget` inside a `Draw`. The page routes the pointer; `Dragging()`, `Source()`, `Target()`, `At()` paint the gesture. A press that does not move is still a click. A split pane is `ui.Splitter(c, &m.split)` with a `ui.SplitterState`, not a drag. +- Files from the system: `.DropFiles(&m.drop)` with a `ui.FileDropState` makes a box take files dragged onto it (`Over()` for the highlight, `Dropped()` for the files, once); `ui.OpenFiles(c, options, done)` is the system's picker and `ui.FilePath(file)` a file's path where it has one. `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour` is the whole area with its file list. - Painting your own thing: `ui.Slot(c).Draw(func(d *ui.DrawContext) { ... })`, with `d.Canvas.Fill`, `Rounded`, `Border`, `RoundedBorder`, `Elevate`, `DrawPath`, `Label`, `LabelCenter`, `d.Fade`, `d.DashedBorder`. A circle is a `Rounded` square. `Box.Rect()` is only valid in the paint that declared it. - A shortcut is declared where it acts: `if ui.Shortcut(c, ui.Primary, "s") { m.save() }`; `box.Shortcut(0, "delete")` acts while the focus is inside that element. Plain keys stay with a field being typed in. diff --git a/docs/system-integrations.md b/docs/system-integrations.md index e1b1ff528..41f2e5de0 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -14,7 +14,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | Rich copy (`SetClipboardHTML`, html + plain alt) | `NSPasteboard`: `public.html` beside `public.utf8-plain-text` | registered `HTML Format` (CF_HTML, with its header of byte offsets) beside `CF_UNICODETEXT` | X11 `CLIPBOARD`: `text/html` target beside `UTF8_STRING`; the GTK shell serves the same pair through `gtk_clipboard_set_with_data` | synchronous calls return `ErrAsyncRequired`; `SetClipboardHTMLAsync` writes one `ClipboardItem` with both MIME flavours and needs a user gesture | | Copied files (`ClipboardFiles`, returns `[]string`) | the pasteboard's file URLs, file reference URLs resolved to paths; promised files have no path and are not listed | the `CF_HDROP` list (UTF-16 form) | X11 `CLIPBOARD`: `x-special/gnome-copied-files` (Nautilus, Nemo, Caja, Thunar) or `text/uri-list` (Dolphin, most toolkits); the GTK shell asks GTK for `text/uri-list` | `ErrUnsupported` | | Copying a picture (`SetClipboardImage`, the write side of `ClipboardImagePNG`) | `NSPasteboard`: `public.png` beside its `public.tiff` conversion, so a reader that asks only for TIFF (Mail, TextEdit, Notes) pastes too | registered `PNG` format beside `CF_DIB` (32-bit, bottom-up); Windows synthesises `CF_DIBV5` and `CF_BITMAP` for the readers that ask for those. The bitmap is composited on white because a DIB carries no alpha | X11 `CLIPBOARD`: `image/png` target served from the window's own copy, INCR above one property; the GTK shell serves the same target through `gtk_clipboard_set_with_data`. Needs a running window (GTK does not) | synchronous calls return `ErrAsyncRequired`; `SetClipboardImageAsync` writes one `ClipboardItem` with the `image/png` flavour and needs a user gesture | -| Dragging files out (`StartFileDrag`, returns `FileDragEffect`) | `ErrUnsupported`: needs an `NSDraggingSession`, which the adapter does not bind yet | an OLE drag: an `IDataObject` offering the paths as `CF_HDROP` and an `IDropSource` that ends the drag when the pointer is released and cancels it on Escape, run by `DoDragDrop` on the window's event-loop thread. `SetClipboardFiles` is the copy a paste makes, not this | `ErrUnsupported`: needs XDND as a source, which the adapter does not speak yet | `ErrUnsupported`: a canvas has no DOM `DataTransfer` | +| Dragging files out (`StartFileDrag`, `StartFilePromiseDrag`; `CapabilityFileDrag`) | an `NSDraggingSession`: file URLs for paths, an `NSFilePromiseProvider` for content produced when the target asks, written where the drop lands; a copy only, and the session reports its end by cancelling the press | an OLE drag: an `IDataObject` offering paths as `CF_HDROP` or promised content as `FileGroupDescriptorW` plus one `FileContents` `IStream` per file, run by `DoDragDrop` on the window's event-loop thread; a promised tree is described to the shell before the drag starts. `SetClipboardFiles` is the copy a paste makes, not this | an XDND source offering `text/uri-list`: paths as they are, promised content staged in a private temporary directory while the pointer moves (a file manager copies real files), then dropped; X11 shell only | `ErrUnsupported`: a canvas has no DOM `DataTransfer` | | Primary selection (`SetPrimarySelection`, `PrimarySelection`) | `ErrUnsupported` | `ErrUnsupported` | X11 `PRIMARY`: selected text, pasted with a middle click | `ErrUnsupported` | | Cursor shape | AppKit cursor; wait unsupported, diagonal resize requires macOS 15 | Win32 system cursors; running window required | XCB cursor font; running window required | CSS cursor on `documentElement` | | Open files | `NSOpenPanel` | `IFileOpenDialog` | the desktop portal's `FileChooser` over D-Bus; installed `zenity` or `kdialog` without one | synchronous call returns `ErrAsyncRequired`; `OpenFilesAsync` returns `FileRef` values, using File System Access or an `` fallback | diff --git a/docs/updating.md b/docs/updating.md index df3681b56..f49b1f52c 100644 --- a/docs/updating.md +++ b/docs/updating.md @@ -185,6 +185,11 @@ versions, the OS, the architecture and every file with its mode, size and SHA-256. The feed's signature covers the patch's URL, size and digest, and the client checks every file it writes against the digest in `patch.json`. +A client on a version that is not listed takes the full archive, so a release +that ships often can pass `--patch-from` for several recent versions. A patch +grows with the distance between versions; `--patch-max-ratio 0.6` leaves out any +patch larger than 60% of its archive, since downloading it saves too little. + On Windows the payload is a **directory**: the program and the folders beside it from the portable zip. The same patch applies to an NSIS installation and to a portable copy, because both hold those files at the same paths. A portable @@ -361,8 +366,10 @@ warning. message; the application keeps running the old version and can offer the update again. - **Windows patches replace the application's files.** The installer's - uninstaller, shortcuts and registry entries are not changed; a release that - adds or removes files needs the full installer. A machine-wide installation + uninstaller, shortcuts and file associations are not changed, but its Add or + Remove Programs entry gets the new `DisplayVersion` and `EstimatedSize`, so a + package manager still sees the installed version; a release that adds or + removes files needs the full installer. A machine-wide installation under `Program Files` is not writable and reports `ErrNotWritable`. - **No update service.** The package checks a URL the application names. It does not host, stage, roll out or force anything. diff --git a/docs/upgrading.md b/docs/upgrading.md index 48d23332c..c392e8a70 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -14,13 +14,80 @@ with its own predecessor, not with whatever the application is on. ## Incompatible changes Newest first. This guide covers the incompatible changes documented here from -v0.2.2 through v0.6.0, including package moves as well as removed members and -changed signatures. Read every entry newer than the application's current -version, together with the corresponding [release notes](releases/). For a -target newer than v0.6.0, also check its intervening release notes; this page is -not a promise that later releases only add API. Releases before v0.2.2 are not +v0.2.2 through v0.6.0 and in v0.6.8, including package moves as well as removed +members and changed signatures. Read every entry newer than the application's +current version, together with the corresponding [release notes](releases/). For +a target between or newer than those, also check its intervening release notes; +this page is not a promise that other releases only add API. Releases before v0.2.2 are not covered: the release-note archive begins there. +### Unreleased - `ui.Configure` routes files dragged from the system + +`ui.Configure` now sets the window's `OnFileDrop`: it gives the files to the +`FileDropState` area (`Box.DropFiles`) under them, then to the `OnFileDrop` you +passed when no area is there. An application that sets its own `OnFileDrop` and +declares no area sees the same events as before. `ui.Host` has an `OnFileDrop` +field for a host that calls `Page.Attach` itself. + +### Unreleased - a `ui.Table` column carries its own title and sort flag + +`TableSpec.Headers` and `TableSpec.Sortable` are removed; each `TableColumn` has a +`Title` and a `Sortable` instead, so adding, dropping or reordering a column is one +edit rather than three slices that must stay the same length. + +- `Columns: cols, Headers: []string{"Name", "Age"}, Sortable: []bool{true, false}` + becomes `Columns: []ui.TableColumn{{Title: "Name", Width: 160, Sortable: true}, + {Title: "Age"}}`. +- A table none of whose columns has a `Title` has no header row. +- A table given `Headers` and no `Columns` shared its width between the columns. + Write one `TableColumn{Title: ...}` per column, with no `Width`: a table none of + whose columns has a width shares its own width equally, and leaves the slice you + declared as you wrote it. +- `components.Table` is unchanged: it still takes `Header(headings)` separately and + ignores `Title` and `Sortable`. + +### Unreleased - identity options and required specs + +The `...ID` and `...With` twins of a control are removed; each control has one +function. + +- `ui.TextFieldID`, `ui.TextAreaID`, `ui.RadioID`, `ui.SelectID` and + `ui.ColorPickerID` are removed. The identity goes at the end of the plain + function as an option, which is optional and costs no allocation: + `ui.TextFieldID(c, id, &m.query, "Search", "")` becomes + `ui.TextField(c, &m.query, "Search", "", ui.WithID(id))`, and the others + move `id` the same way. A `*string` given to `ui.TextArea` can now be named too. +- `ui.PopoverWith` is now `ui.Popover`, and `ui.ModalWith` is now `ui.Modal`; both + take their spec before the body, as `ui.Drawer` does. The old plain forms gain a + spec: `ui.Modal(c, &open, title, body, footer)` becomes + `ui.Modal(c, &open, title, ui.ModalSpec{}, body, footer)`, and + `ui.Popover(c, anchor, &open, body)` becomes + `ui.Popover(c, anchor, &open, ui.PopoverSpec{Align: ui.Start}, body)`. The plain + popover lined up with the anchor's start; a zero `PopoverSpec` centers it, so + write `Align: ui.Start` to keep the old look. + +### v0.6.8 - `ui.Run` takes a `PageConfig`, and four more signatures + +A program that follows the guides on `main` before v0.6.8 does not compile +against v0.6.7: the guides describe the signatures below. Moving to v0.6.8 makes +them match. + +- `ui.Run(config, m.page)` becomes `ui.Run(config, ui.PageConfig{View: m.page})`. + `Theme`, `Styles` and the rest of the page's settings now go in the same + `PageConfig`, so a one-window program no longer needs `NewPage`, `Configure` + and `RunCanvas`. +- `app.TitlebarInsets()` is removed: the insets differ per window and per moment + (none in full screen or under a system titlebar). Read them in the page with + `c.TitlebarInsets()`, or from `Canvas.TitlebarInsets` in a custom painter. +- `ui.AlertDialog(c, spec)` becomes `ui.AlertDialog(c, &open, spec)` and returns + `true` on the paint where the confirming action was chosen, as `ui.Modal` + opens on a `*bool`. `PopoverWith(c, anchor, spec, &open, onClose)` becomes + `PopoverWith(c, anchor, &open, spec, onClose)`. The same changes apply to the + `base` package. +- `ui.TextFieldID` is now generic over `*Field` and `*string`. Calls compile as + before; only code that takes the function as a value, such as + `f := ui.TextFieldID`, must name a type argument. + ### v0.6.0 - package moves and Page-only authoring There are two package moves **and** an authoring-model change. Updating imports diff --git a/examples/guides/overlay/main.go b/examples/guides/overlay/main.go index f8a529d81..9c554519c 100644 --- a/examples/guides/overlay/main.go +++ b/examples/guides/overlay/main.go @@ -24,7 +24,7 @@ func (m *model) page(c ui.C) { // A popover hangs off its anchor while menuOpen is true. A press outside it // or Escape closes it, and the press goes on to what is under the pointer; // the focus goes back to the anchor. - ui.PopoverWith(c, actions, &m.menuOpen, ui.PopoverSpec{Width: 180, Align: ui.Start}, func() { + ui.Popover(c, actions, &m.menuOpen, ui.PopoverSpec{Width: 180, Align: ui.Start}, func() { if ui.Button(c, "New file").Ghost().Clicked() { m.menuOpen, m.status = false, "Created" } @@ -35,7 +35,7 @@ func (m *model) page(c ui.C) { // A modal dims the page and keeps the keyboard while dialogOpen is true: // Escape, a press on the dim and the close button set it to false. - ui.ModalWith(c, &m.dialogOpen, "Delete file?", ui.ModalSpec{Description: "This cannot be undone.", Width: 400}, nil, func() { + ui.Modal(c, &m.dialogOpen, "Delete file?", ui.ModalSpec{Description: "This cannot be undone.", Width: 400}, nil, func() { if ui.Button(c, "Cancel").Outline().Clicked() { m.dialogOpen = false } diff --git a/examples/guides/table/main.go b/examples/guides/table/main.go index 17dc45560..7d07b5b52 100644 --- a/examples/guides/table/main.go +++ b/examples/guides/table/main.go @@ -31,11 +31,13 @@ func (m *model) page(c ui.C) { ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { ui.Text(c, "Servers").FontSize(20).Bold() table := ui.Table(c, &m.table, ui.TableSpec{ - Headers: []string{"Name", "State", "Region"}, - Sortable: []bool{true, true, true}, - Source: &m.rows, - Striped: true, - Columns: []ui.TableColumn{{Width: 200}, {Width: 120}, {}}, + Source: &m.rows, + Striped: true, + Columns: []ui.TableColumn{ + {Title: "Name", Width: 200, Sortable: true}, + {Title: "State", Width: 120, Sortable: true}, + {Title: "Region", Sortable: true}, + }, }) if column, ok := table.HeaderClicked(); ok { m.table.SortBy(column) diff --git a/examples/guides/webview/main.go b/examples/guides/webview/main.go index 0a38179ac..7aaf41a98 100644 --- a/examples/guides/webview/main.go +++ b/examples/guides/webview/main.go @@ -73,7 +73,7 @@ func (m *model) page(c ui.C) { m.menuOpen = !m.menuOpen } ui.Text(c, m.status).Muted() - ui.PopoverWith(c, menu, &m.menuOpen, ui.PopoverSpec{Width: 220, Align: ui.Start}, func() { + ui.Popover(c, menu, &m.menuOpen, ui.PopoverSpec{Width: 220, Align: ui.Start}, func() { if ui.Button(c, "Say hello to the page").Ghost().Clicked() && m.view != nil { m.view.PostMessage("hello from Viva") m.menuOpen = false diff --git a/examples/guides/windows/main.go b/examples/guides/windows/main.go index 74cedd8cc..007e15adc 100644 --- a/examples/guides/windows/main.go +++ b/examples/guides/windows/main.go @@ -30,7 +30,7 @@ func (state *notes) page(c ui.C) { ui.PageConfig{View: func(c ui.C) { ui.Text(c, "Settings").FontSize(20).Bold() }}) } }) - ui.ModalWith(c, &state.confirmClosing, "Discard changes?", ui.ModalSpec{ + ui.Modal(c, &state.confirmClosing, "Discard changes?", ui.ModalSpec{ Description: "The note has not been saved.", Width: 400, NoClose: true, }, nil, func() { if ui.Button(c, "Keep editing").Outline().Clicked() { diff --git a/gfx/canvas.go b/gfx/canvas.go index 931462d69..74a028624 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -731,10 +731,15 @@ type Canvas struct { // fillPoints is the outline of a gradient-filled rounded rectangle. fillPoints []Point // path and triangulation scratch survives Reset: reused every paint. - strokeSideA []Point - strokeSideB []Point - strokeRing []Point - ringPoints []Point + strokeSideA []Point + strokeSideB []Point + strokeRing []Point + ringPoints []Point + // poseShapes, posePoints and poseMerge are the scratch of turning a posed + // group's rectangles into vector shapes (presence.go). + poseShapes []Triangle + posePoints []Point + poseMerge []Triangle ringEnds []int32 earcut earcutScratch rings []ringCacheEntry @@ -794,9 +799,11 @@ type Canvas struct { afterPaint []func() // pointer is the pointer event the event pass is delivering; consumed records // that a control took it; listensForPointer that the last paint asked. - pointer PointerEvent - hasPointer bool - consumed bool + pointer PointerEvent + hasPointer bool + consumed bool + // nativeTextMenu is whether the window shows the system's text menu. + nativeTextMenu bool listensForPointer bool initialFocus ID // focusRequest asks the runtime to focus one hit even without a trap, as a @@ -1111,6 +1118,9 @@ func (canvas *Canvas) Trim() { canvas.strokeSideB = trimCapacity(canvas.strokeSideB) canvas.strokeRing = trimCapacity(canvas.strokeRing) canvas.ringPoints = trimCapacity(canvas.ringPoints) + canvas.poseShapes = trimCapacity(canvas.poseShapes) + canvas.posePoints = trimCapacity(canvas.posePoints) + canvas.poseMerge = trimCapacity(canvas.poseMerge) canvas.ringEnds = trimCapacity(canvas.ringEnds) canvas.parentScratch = trimCapacity(canvas.parentScratch) canvas.consumedScratch = trimCapacity(canvas.consumedScratch) @@ -2372,6 +2382,14 @@ func (canvas *Canvas) PointerIn(list Scope) (int, PointerEvent, bool) { return index, canvas.pointer, true } +// SetNativeTextMenu records that the window shows the system's own menu for a +// secondary press on a text field, so a page does not draw one too. The runtime +// sets it from the window; it is not reset between paints. +func (canvas *Canvas) SetNativeTextMenu(native bool) { canvas.nativeTextMenu = native } + +// NativeTextMenu reports whether the window shows the system's own text menu. +func (canvas *Canvas) NativeTextMenu() bool { return canvas.nativeTextMenu } + // Consume says the control took the pointer event being delivered: the runtime // does not also treat it as a click, and repaints. It does nothing outside the // event pass. diff --git a/gfx/fling.go b/gfx/fling.go new file mode 100644 index 000000000..152a1cc61 --- /dev/null +++ b/gfx/fling.go @@ -0,0 +1,163 @@ +package gfx + +import ( + "math" + "time" +) + +// A drag that is let go with some speed carries on: the value it moved comes to +// rest further along, at a point the application may choose (a page, a slot, an +// end of the range), by a spring that starts at the speed the pointer had. This +// file holds the pieces of that: VelocityTracker measures the speed, Project says +// where it would come to rest, RubberBand holds a value that is pulled past its +// range, Nearest picks where to settle, and Canvas.Throw hands the speed to the +// spring of Canvas.Animate. +// +// // while dragging, on every pointer move +// tracker.Add(event.X, canvas.Now()) +// // on release +// rest := Nearest(Project(event.X, tracker.Velocity(), DecelerationNormal), pages...) +// canvas.Throw(id, 0, event.X, tracker.Velocity()) +// offset := rest // painted with canvas.Animate(id, 0, rest, SpringMotion(...)) + +// velocitySamples is how many recent pointer positions a tracker keeps: enough +// to smooth a jittery pointer, few enough that it follows a flick. +const velocitySamples = 8 + +// velocityWindow is how far back a sample still counts toward the speed. A +// pointer that rested before it was let go has no speed left, however fast it +// moved earlier. +const velocityWindow = 100 * time.Millisecond + +// VelocityTracker measures the speed of a value dragged along one axis from its +// recent positions. The zero value is ready; it allocates nothing. +type VelocityTracker struct { + at [velocitySamples]time.Duration + value [velocitySamples]float32 + count int + next int +} + +// Reset forgets every position, for the start of a new drag. +func (tracker *VelocityTracker) Reset() { *tracker = VelocityTracker{} } + +// Add records that the dragged value was at value at time at. Times must not +// run backward; a sample at the time of the last one replaces it. +func (tracker *VelocityTracker) Add(value float32, at time.Duration) { + if tracker.count > 0 { + last := (tracker.next + velocitySamples - 1) % velocitySamples + if at < tracker.at[last] { + return + } + if at == tracker.at[last] { + tracker.value[last] = value + return + } + } + tracker.at[tracker.next], tracker.value[tracker.next] = at, value + tracker.next = (tracker.next + 1) % velocitySamples + tracker.count = min(tracker.count+1, velocitySamples) +} + +// Velocity returns the speed of the value in units per second at the last +// position added, from a least-squares line through the samples of the last +// 100ms. It is zero for fewer than two samples in that window, which is a drag +// that rested before it was let go. +func (tracker *VelocityTracker) Velocity() float32 { + if tracker.count < 2 { + return 0 + } + newest := (tracker.next + velocitySamples - 1) % velocitySamples + end := tracker.at[newest] + var n, sumT, sumV, sumTT, sumTV float64 + for index := range tracker.count { + slot := (tracker.next + velocitySamples - 1 - index) % velocitySamples + age := end - tracker.at[slot] + if age > velocityWindow { + break + } + t := -age.Seconds() + v := float64(tracker.value[slot]) + n++ + sumT, sumV, sumTT, sumTV = sumT+t, sumV+v, sumTT+t*t, sumTV+t*v + } + if n < 2 { + return 0 + } + denominator := n*sumTT - sumT*sumT + if denominator == 0 { + return 0 + } + return float32((n*sumTV - sumT*sumV) / denominator) +} + +// Deceleration is how fast a thrown value slows down: the fraction of its speed +// it keeps each millisecond. Higher slides further. +type Deceleration float32 + +const ( + // DecelerationNormal is the rate of a scroll view (0.998 per ms), which a + // flick of a page or a list carries far. + DecelerationNormal Deceleration = 0.998 + // DecelerationFast is a brisker stop (0.99 per ms), for a control that + // should not slide past its neighbour. + DecelerationFast Deceleration = 0.99 +) + +// Project returns where a value at position, thrown at velocity (units per +// second), would come to rest if nothing held it: the distance a speed that +// decays by deceleration each millisecond covers, the sum of the geometric +// series. It is what a snap point is chosen from, so that a flick goes on to +// the next page. +func Project(position, velocity float32, deceleration Deceleration) float32 { + rate := float64(min(max(float32(deceleration), 0), 0.9999)) + return position + float32(float64(velocity)/1000*rate/(1-rate)) +} + +// Nearest returns the point of points nearest to value, or value when there are +// none. +func Nearest(value float32, points ...float32) float32 { + if len(points) == 0 { + return value + } + best := points[0] + for _, point := range points[1:] { + if float32(math.Abs(float64(point-value))) < float32(math.Abs(float64(best-value))) { + best = point + } + } + return best +} + +// rubberBandStiffness is how soon the band resists; 0.55 is the constant of iOS +// scroll views. +const rubberBandStiffness = 0.55 + +// RubberBand holds a value pulled past the end of its range: an offset past the +// edge (positive) moves less and less far for the same pull, never reaching +// limit, the room the view has to give. An offset of zero or less is returned as +// it is, and the pull is continuous with it. +func RubberBand(offset, limit float32) float32 { + if offset <= 0 || limit <= 0 { + return offset + } + return (1 - 1/(offset*rubberBandStiffness/limit+1)) * limit +} + +// Throw hands the speed a value was let go with to the animation of the value +// named by id and slot, so that the next Animate toward a target starts there at +// that speed instead of from rest: a card released while moving glides on to its +// snap point, and one released at rest starts slowly. value is where it is let +// go, in the units Animate returns, and velocity its speed in units per second. +// It belongs in the handler of the release, and has to name the same id and slot +// the application animates with; it keeps nothing for an element that is not +// painted afterwards. +func (canvas *Canvas) Throw(id ID, slot uint8, value, velocity float32) { + state := &canvas.motion + if state.clock == nil || id.IsZero() || state.reduce { + return + } + now := canvas.Now() + entry := state.slotFor(id, slot, value, now) + *entry = motionSlot{id: id, slot: slot, seen: entry.seen, from: value, to: value, start: now, carry: float64(velocity)} +} diff --git a/gfx/fling_test.go b/gfx/fling_test.go new file mode 100644 index 000000000..14cc275f6 --- /dev/null +++ b/gfx/fling_test.go @@ -0,0 +1,172 @@ +package gfx + +import ( + "math" + "testing" + "time" +) + +func TestVelocityTrackerMeasuresASteadyDrag(t *testing.T) { + var tracker VelocityTracker + for step := range 6 { + tracker.Add(float32(step)*10, time.Duration(step)*10*time.Millisecond) // 1000 units/s + } + if got := tracker.Velocity(); math.Abs(float64(got-1000)) > 1 { + t.Fatalf("velocity = %v, want 1000", got) + } +} + +func TestVelocityTrackerIgnoresAPointerThatRestedBeforeRelease(t *testing.T) { + var tracker VelocityTracker + for step := range 5 { + tracker.Add(float32(step)*30, time.Duration(step)*10*time.Millisecond) + } + tracker.Add(120, 400*time.Millisecond) // rested 360ms, then a single sample + if got := tracker.Velocity(); got != 0 { + t.Fatalf("velocity after resting = %v, want 0", got) + } +} + +func TestVelocityTrackerNeedsTwoSamplesAndForgetsOnReset(t *testing.T) { + var tracker VelocityTracker + if tracker.Velocity() != 0 { + t.Fatal("empty tracker has velocity") + } + tracker.Add(5, 0) + if tracker.Velocity() != 0 { + t.Fatal("one sample has velocity") + } + tracker.Add(15, 10*time.Millisecond) + tracker.Reset() + if tracker.Velocity() != 0 { + t.Fatal("reset tracker has velocity") + } +} + +func TestVelocityTrackerKeepsTheNewestSamplesWhenItWraps(t *testing.T) { + var tracker VelocityTracker + for step := range 40 { // far more than it holds; speed doubles at step 30 + value := float32(step) * 10 + if step >= 30 { + value = 300 + float32(step-30)*20 + } + tracker.Add(value, time.Duration(step)*5*time.Millisecond) + } + if got := tracker.Velocity(); got < 3000 { + t.Fatalf("velocity = %v, want the recent 4000/s rather than the earlier 2000/s", got) + } +} + +func TestVelocityTrackerIgnoresTimeRunningBackward(t *testing.T) { + var tracker VelocityTracker + tracker.Add(0, 20*time.Millisecond) + tracker.Add(10, 30*time.Millisecond) + tracker.Add(999, 10*time.Millisecond) + if got := tracker.Velocity(); math.Abs(float64(got-1000)) > 1 { + t.Fatalf("velocity = %v, want 1000", got) + } +} + +func TestProjectIsTheDistanceAThrownValueCovers(t *testing.T) { + if got := Project(100, 0, DecelerationNormal); got != 100 { + t.Fatalf("at rest projects to %v", got) + } + slow, fast := Project(0, 1000, DecelerationNormal), Project(0, 2000, DecelerationNormal) + if math.Abs(float64(fast-2*slow)) > 1e-2 || slow <= 0 { + t.Fatalf("projections %v and %v are not proportional to speed", slow, fast) + } + if Project(0, -1000, DecelerationNormal) != -slow { + t.Fatal("a throw backward does not mirror a throw forward") + } + if Project(0, 1000, DecelerationFast) >= slow { + t.Fatal("a faster stop slides as far as a normal one") + } +} + +func TestNearestPicksTheClosestPoint(t *testing.T) { + if got := Nearest(130, 0, 100, 200); got != 100 { + t.Fatalf("nearest = %v", got) + } + if got := Nearest(150, 0, 100, 200); got != 100 { + t.Fatalf("a tie takes the first: %v", got) + } + if got := Nearest(42); got != 42 { + t.Fatalf("no points returns the value, got %v", got) + } +} + +func TestRubberBandResistsMoreTheFurtherItIsPulledAndNeverReachesTheLimit(t *testing.T) { + const limit = 100 + if RubberBand(-20, limit) != -20 || RubberBand(0, limit) != 0 { + t.Fatal("a value inside its range must pass through") + } + previous, previousStep := float32(0), float32(math.MaxFloat32) + for offset := float32(10); offset <= 1000; offset += 10 { + got := RubberBand(offset, limit) + if got <= previous || got >= limit { + t.Fatalf("band(%v) = %v: not increasing below the limit", offset, got) + } + if step := got - previous; step >= previousStep+1e-6 { + t.Fatalf("band(%v) gains %v, more than the %v before it", offset, step, previousStep) + } + previous, previousStep = got, got-previous + } +} + +func TestThrowStartsTheNextAnimationAtTheReleaseSpeed(t *testing.T) { + motion := SpringMotion(400*time.Millisecond, 0) + after30ms := func(speed float32) (got float32) { + var canvas Canvas + frames := newTestFrames(&canvas) + frames.at(0, func() { canvas.Animate(Item(1), 0, 0, motion) }) + canvas.Throw(Item(1), 0, 0, speed) + frames.at(time.Second, func() { canvas.Animate(Item(1), 0, 100, motion) }) + frames.at(time.Second+30*time.Millisecond, func() { got = canvas.Animate(Item(1), 0, 100, motion) }) + return got + } + still, thrown := after30ms(0), after30ms(2000) + if thrown <= still+1 { + t.Fatalf("after 30ms a thrown value is at %v, one released at rest at %v", thrown, still) + } +} + +func TestThrownSpeedIsUsedOnceAndNotKeptForALaterMove(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + motion := SpringMotion(400*time.Millisecond, 0) + value := func(at time.Duration, target float32) (got float32) { + frames.at(at, func() { got = canvas.Animate(Item(1), 0, target, motion) }) + return got + } + value(0, 0) + canvas.Throw(Item(1), 0, 0, 5000) + value(time.Second, 0) // released on its target: the speed is dropped + value(2*time.Second, 100) + if got := value(2*time.Second+10*time.Millisecond, 100); got > 5 { + t.Fatalf("a later move starts with the old throw's speed: %v after 10ms", got) + } +} + +func TestThrowIsIgnoredWithoutAClockAndUnderReducedMotion(t *testing.T) { + var canvas Canvas + canvas.Throw(Item(1), 0, 0, 100) // no clock: nothing to keep + frames := newTestFrames(&canvas) + canvas.SetReduceMotion(true) + canvas.Throw(Item(1), 0, 0, 100) + var got float32 + frames.at(time.Second, func() { got = canvas.Animate(Item(1), 0, 50, SpringMotion(time.Second, 0)) }) + if got != 50 { + t.Fatalf("reduced motion = %v, want the target", got) + } +} + +func BenchmarkVelocityTrackerAddAndRead(b *testing.B) { + var tracker VelocityTracker + at := time.Duration(0) + b.ReportAllocs() + for b.Loop() { + at += 8 * time.Millisecond + tracker.Add(float32(at/time.Millisecond), at) + _ = tracker.Velocity() + } +} diff --git a/gfx/motion.go b/gfx/motion.go index 630dc509b..3f7f4513f 100644 --- a/gfx/motion.go +++ b/gfx/motion.go @@ -29,9 +29,27 @@ const ( // Motion is one timed state change. A zero Duration is an instant change, so // hand-built themes that omit motion tokens stay static rather than animated. +// +// With Spring set the change is a spring instead of a timed curve: it keeps the +// velocity it has when its target changes on the way, so a control clicked +// again mid-flight turns around smoothly instead of stopping dead. type Motion struct { + // Duration is the length of a timed change and, for a spring, about how long + // it takes to arrive (the period of its oscillation). Duration time.Duration Easing Easing + // Spring replaces Easing with a spring of Bounce. + Spring bool + // Bounce runs from 0, a spring that arrives without overshooting, toward 1, + // a wide wobble. It is the parameter SwiftUI and CSS-in-motion libraries + // give a spring, and is clamped to [0, 0.95]. Ignored unless Spring is set. + Bounce float32 +} + +// SpringMotion returns a spring that takes about duration to arrive and +// overshoots by bounce (0 for none). +func SpringMotion(duration time.Duration, bounce float32) Motion { + return Motion{Duration: duration, Spring: true, Bounce: bounce} } // DefaultMotion returns the 150ms standard-curve transition shadcn components @@ -241,6 +259,16 @@ type motionSlot struct { start time.Duration duration time.Duration easing Easing + // A spring segment is solved exactly from its start: offset is from-to at + // the start, speed the velocity then (value units per second), omega the + // natural frequency (rad/s) and zeta the damping ratio. The solution is a + // function of elapsed time alone, so a slow frame does not change its path. + spring bool + omega, zeta float64 + speed float64 + // carry is the speed Canvas.Throw gave a settled value: the next segment + // starts at it, once. + carry float64 } // onceSlot is one PlayOnce timeline. Unlike motionSlot it never retargets: it @@ -259,6 +287,16 @@ type onceSlot struct { func (slot *motionSlot) value(now time.Duration) float32 { elapsed := now - slot.start + if slot.spring { + if elapsed <= 0 { + return slot.from + } + if slot.settled(now) { + return slot.to + } + x, _ := slot.springAt(elapsed) + return slot.to + float32(x) + } if slot.duration <= 0 || elapsed >= slot.duration { return slot.to } @@ -269,10 +307,92 @@ func (slot *motionSlot) value(now time.Duration) float32 { return Lerp(slot.from, slot.to, slot.easing.At(progress)) } +// Springs are at rest within these distances of the target, in value units and +// units per second: well below a pixel, or a thousandth of a 0-to-1 opacity. +const ( + springRestOffset = 5e-4 + springRestSpeed = 5e-3 + // springMaxCycles bounds how long a spring may run, in its own periods, so a + // pathological one cannot keep the application painting. + springMaxCycles = 12 +) + +// springAt returns the offset from the target and the velocity of a spring +// segment after elapsed, the closed-form solution of x” + 2*zeta*omega*x' + +// omega^2*x = 0 from (offset, speed). +func (slot *motionSlot) springAt(elapsed time.Duration) (x, v float64) { + t := elapsed.Seconds() + x0, v0, w, z := float64(slot.from-slot.to), slot.speed, slot.omega, slot.zeta + switch { + case z < 1-1e-9: + wd := w * math.Sqrt(1-z*z) + decay := math.Exp(-z * w * t) + sin, cos := math.Sincos(wd * t) + b := (v0 + z*w*x0) / wd + x = decay * (x0*cos + b*sin) + v = decay * (-z*w*(x0*cos+b*sin) + (-x0*wd*sin + b*wd*cos)) + default: + decay := math.Exp(-w * t) + b := v0 + w*x0 + x = decay * (x0 + b*t) + v = decay * (b - w*(x0+b*t)) + } + return x, v +} + +// velocity is the speed of the displayed value at now, in value units per +// second, which a spring taking over from this segment continues from. +func (slot *motionSlot) velocity(now time.Duration) float64 { + if slot.settled(now) { + return slot.carry + } + if slot.spring { + _, v := slot.springAt(now - slot.start) + return v + } + const step = time.Millisecond + lo, hi := max(now-step, slot.start), min(now+step, slot.start+slot.duration) + if hi <= lo { + return 0 + } + return float64(slot.value(hi)-slot.value(lo)) / (hi - lo).Seconds() +} + func (slot *motionSlot) settled(now time.Duration) bool { + if slot.spring { + elapsed := now - slot.start + if elapsed <= 0 { + return slot.from == slot.to && slot.speed == 0 + } + if slot.duration > 0 && elapsed >= slot.duration*springMaxCycles { + return true + } + x, v := slot.springAt(elapsed) + return math.Abs(x) < springRestOffset && math.Abs(v) < springRestSpeed + } return slot.duration <= 0 || now-slot.start >= slot.duration || slot.from == slot.to } +// retarget starts the segment that carries the value shown at now to target. +func (slot *motionSlot) retarget(now time.Duration, target float32, motion Motion) { + slot.rebase(now, 0, target, motion) +} + +// rebase carries the value shown at now, moved by shift, to target, keeping the +// velocity it has. A shift is for a value measured from an origin that moved +// under it: what the eye saw stays where it was. +func (slot *motionSlot) rebase(now time.Duration, shift, target float32, motion Motion) { + from, speed := slot.value(now)+shift, slot.velocity(now) + slot.from, slot.to, slot.start, slot.duration = from, target, now, motion.Duration + slot.easing, slot.spring, slot.speed, slot.carry = motion.Easing, motion.Spring, 0, 0 + if motion.Spring { + bounce := float64(min(max(motion.Bounce, 0), 0.95)) + slot.omega = 2 * math.Pi / motion.Duration.Seconds() + slot.zeta = 1 - bounce + slot.speed = speed + } +} + // motionState is the canvas-owned transition table. Slots live in paint order // so a stable layout resolves each Animate call with one index comparison. type motionState struct { @@ -293,7 +413,11 @@ type motionState struct { // presences are the overlays that are open or still leaving, and open the // groups the current paint pass has begun and not yet ended (presence.go). presences []presenceEntry - open []presenceOpen + // poses are the elements with a Pose, and poseAt the cursor that finds them + // in paint order (pose.go). + poses []poseEntry + poseAt int + open []presenceOpen // hitMotions keeps the placement of hits painted inside a moving presence // for this frame, so native overlays anchored to them move with the paint. hitMotions []hitMotionEntry @@ -354,6 +478,7 @@ func (state *motionState) sweep() { if cap(state.slots) > motionShrinkCapacity && len(state.slots)*motionShrinkFactor < cap(state.slots) { state.slots = append(make([]motionSlot, 0, len(state.slots)*2), state.slots...) } + state.sweepPoses() onces := state.onces[:0] for _, once := range state.onces { if once.seen == state.frame { @@ -383,6 +508,7 @@ func (canvas *Canvas) BeginFrame() { state.frame++ state.cursor = 0 state.onceAt = 0 + state.poseAt = 0 state.sampled = false state.active = state.clock != nil state.animating = false @@ -505,11 +631,9 @@ func (canvas *Canvas) Animate(id ID, slot uint8, target float32, motion Motion) return target } if entry.to != target { - entry.from = entry.value(now) - entry.to = target - entry.start = now - entry.duration = motion.Duration - entry.easing = motion.Easing + entry.retarget(now, target, motion) + } else { + entry.carry = 0 } if !entry.settled(now) { state.animating = true diff --git a/gfx/motion_test.go b/gfx/motion_test.go index 0711a57f0..b91015a14 100644 --- a/gfx/motion_test.go +++ b/gfx/motion_test.go @@ -714,3 +714,174 @@ func TestNowIsTheFramesTimeAndTheEventsBetween(t *testing.T) { t.Fatal("Now went back") } } + +func TestSpringAnimateArrivesWithoutOvershootAtZeroBounce(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + motion := SpringMotion(300*time.Millisecond, 0) + value := func(at time.Duration, target float32) float32 { + var got float32 + frames.at(at, func() { got = canvas.Animate(Item(1), 0, target, motion) }) + return got + } + value(0, 0) + previous := value(time.Second, 1) + if previous != 0 { + t.Fatalf("start = %v", previous) + } + for at := time.Second + 8*time.Millisecond; at < 4*time.Second; at += 8 * time.Millisecond { + got := value(at, 1) + if got < previous || got > 1 { + t.Fatalf("at %v: %v after %v, want monotonic within [0, 1]", at-time.Second, got, previous) + } + previous = got + } + if previous != 1 || canvas.Animating() { + t.Fatalf("rest = %v animating=%v", previous, canvas.Animating()) + } +} + +func TestSpringBounceOvershootsAndSettles(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + motion := SpringMotion(300*time.Millisecond, 0.5) + value := func(at time.Duration) float32 { + var got float32 + frames.at(at, func() { got = canvas.Animate(Item(1), 0, 1, motion) }) + return got + } + frames.at(0, func() { canvas.Animate(Item(1), 0, 0, motion) }) + peak := float32(0) + for at := time.Duration(0); at < 4*time.Second; at += 8 * time.Millisecond { + peak = max(peak, value(time.Second+at)) + } + if peak <= 1 { + t.Fatalf("peak = %v, a bouncy spring overshoots", peak) + } + if got := value(10 * time.Second); got != 1 || canvas.Animating() { + t.Fatalf("rest = %v animating=%v", got, canvas.Animating()) + } +} + +func TestSpringPathDoesNotDependOnFrameRate(t *testing.T) { + sample := func(step time.Duration) float32 { + var canvas Canvas + frames := newTestFrames(&canvas) + motion := SpringMotion(400*time.Millisecond, 0.3) + frames.at(0, func() { canvas.Animate(Item(1), 0, 0, motion) }) + frames.at(time.Millisecond, func() { canvas.Animate(Item(1), 0, 1, motion) }) // starts here + var got float32 + for at := time.Millisecond + step; at <= 201*time.Millisecond; at += step { + frames.at(at, func() { got = canvas.Animate(Item(1), 0, 1, motion) }) + } + return got + } + fast, slow := sample(5*time.Millisecond), sample(200*time.Millisecond) + if math.Abs(float64(fast-slow)) > 1e-4 || fast == 0 { + t.Fatalf("200ms in: %v at 200fps, %v in one frame", fast, slow) + } +} + +func TestSpringRetargetKeepsVelocity(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + motion := SpringMotion(400*time.Millisecond, 0) + value := func(at time.Duration, target float32) float32 { + var got float32 + frames.at(at, func() { got = canvas.Animate(Item(1), 0, target, motion) }) + return got + } + value(0, 0) + value(time.Second, 1) + const dt = time.Millisecond + a, b := value(time.Second+150*time.Millisecond, 1), value(time.Second+150*time.Millisecond+dt, 1) + speed := float64(b-a) / dt.Seconds() + if speed <= 0 { + t.Fatalf("speed = %v mid-flight", speed) + } + // Retarget halfway: the value must neither jump nor stop dead. + at := time.Second + 150*time.Millisecond + dt + if got := value(at, 0); math.Abs(float64(got-b)) > 1e-5 { + t.Fatalf("retarget jumped from %v to %v", b, got) + } + next := value(at+dt, 0) + if carried := float64(next-b) / dt.Seconds(); carried < speed*0.8 { + t.Fatalf("velocity after retarget = %v, was %v: it stopped dead", carried, speed) + } +} + +func TestSpringTakingOverATimedCurveKeepsItsVelocity(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + timed, spring := Motion{Duration: 200 * time.Millisecond, Easing: EaseLinear}, SpringMotion(300*time.Millisecond, 0) + value := func(at time.Duration, target float32, motion Motion) float32 { + var got float32 + frames.at(at, func() { got = canvas.Animate(Item(1), 0, target, motion) }) + return got + } + value(0, 0, timed) + value(time.Second, 1, timed) + at := time.Second + 100*time.Millisecond + before := value(at, 1, timed) // linear: 5 per second + if got := value(at, 2, spring); math.Abs(float64(got-before)) > 1e-5 { + t.Fatalf("takeover jumped from %v to %v", before, got) + } + next := value(at+time.Millisecond, 2, spring) + if speed := float64(next-before) / 0.001; speed < 4 { + t.Fatalf("speed after takeover = %v, the curve's was 5", speed) + } +} + +func TestSpringHonoursReducedMotion(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + canvas.SetReduceMotion(true) + motion := SpringMotion(300*time.Millisecond, 0.3) + frames.at(0, func() { canvas.Animate(Item(1), 0, 0, motion) }) + var got float32 + frames.at(time.Second, func() { got = canvas.Animate(Item(1), 0, 1, motion) }) + if got != 1 || canvas.Animating() { + t.Fatalf("reduced motion = %v animating=%v", got, canvas.Animating()) + } +} + +func TestWarmSpringAnimateDoesNotAllocate(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + motion := SpringMotion(300*time.Millisecond, 0.2) + paint := func(target float32) { + for id := 1; id <= 64; id++ { + canvas.Animate(Item(id), 0, target, motion) + } + } + frames.at(0, func() { paint(0) }) + now := time.Duration(0) + if allocations := testing.AllocsPerRun(100, func() { + now += 8 * time.Millisecond + frames.at(now, func() { paint(float32(now / (400 * time.Millisecond) % 2)) }) + }); allocations != 0 { + t.Fatalf("warm spring frames allocate %v times", allocations) + } +} + +func BenchmarkSpringAnimate(b *testing.B) { + var canvas Canvas + frames := newTestFrames(&canvas) + motion := SpringMotion(300*time.Millisecond, 0.2) + frames.at(0, func() { + for id := 1; id <= 64; id++ { + canvas.Animate(Item(id), 0, 0, motion) + } + }) + now := time.Duration(0) + b.ReportAllocs() + for b.Loop() { + now += 8 * time.Millisecond + target := float32(now / (400 * time.Millisecond) % 2) + frames.at(now, func() { + for id := 1; id <= 64; id++ { + canvas.Animate(Item(id), 0, target, motion) + } + }) + } +} diff --git a/gfx/path_arc_test.go b/gfx/path_arc_test.go new file mode 100644 index 000000000..11d85eb73 --- /dev/null +++ b/gfx/path_arc_test.go @@ -0,0 +1,53 @@ +package gfx + +import ( + "math" + "testing" +) + +// An arc starts on the circle at its start angle, ends on it at start plus sweep, and +// every point the curves pass through stays on the circle to within what a cubic +// approximation allows. +func TestPathBuilderArcFollowsTheCircle(t *testing.T) { + for _, test := range []struct{ start, sweep float32 }{{-90, 90}, {-90, 180}, {0, 270}, {30, 360}, {10, 45}} { + var builder PathBuilder + builder.Arc(50, 40, 20, test.start, test.sweep) + commands := builder.commands + if commands[0].Kind != PathCommandMove { + t.Fatalf("%+v: an arc does not begin with a move", test) + } + sx, sy := float64(commands[0].Point.X), float64(commands[0].Point.Y) + wantX := 50 + 20*math.Cos(float64(test.start)*math.Pi/180) + wantY := 40 + 20*math.Sin(float64(test.start)*math.Pi/180) + if math.Abs(sx-wantX) > 1e-3 || math.Abs(sy-wantY) > 1e-3 { + t.Fatalf("%+v: starts at (%v, %v), want (%v, %v)", test, sx, sy, wantX, wantY) + } + last := commands[len(commands)-1] + endAngle := float64(test.start+min(test.sweep, 360)) * math.Pi / 180 + if math.Abs(float64(last.Point.X)-(50+20*math.Cos(endAngle))) > 1e-3 || math.Abs(float64(last.Point.Y)-(40+20*math.Sin(endAngle))) > 1e-3 { + t.Fatalf("%+v: ends at (%v, %v), off the circle at the end angle", test, last.Point.X, last.Point.Y) + } + for _, c := range commands[1:] { + if d := math.Hypot(float64(c.Point.X)-50, float64(c.Point.Y)-40); math.Abs(d-20) > 1e-3 { + t.Fatalf("%+v: an end point is %v from the center, want 20", test, d) + } + } + } +} + +// A sweep of zero or less, or a radius of zero or less, adds nothing; and the +// builder's buffer is reused. +func TestPathBuilderArcOfNothingAddsNothing(t *testing.T) { + var builder PathBuilder + builder.Arc(0, 0, 10, 0, 0) + builder.Arc(0, 0, 0, 0, 90) + builder.Arc(0, 0, 10, 0, -5) + if builder.Len() != 0 { + t.Fatalf("%d commands for arcs of nothing, want none", builder.Len()) + } + builder.Arc(0, 0, 10, 0, 360) + builder.Reset() + if allocs := testing.AllocsPerRun(100, func() { builder.Reset(); builder.Arc(0, 0, 10, -90, 270) }); allocs != 0 { + t.Fatalf("a warm arc allocated %v times, want 0", allocs) + } +} diff --git a/gfx/path_builder.go b/gfx/path_builder.go index 98f9739b8..578d6a907 100644 --- a/gfx/path_builder.go +++ b/gfx/path_builder.go @@ -1,5 +1,7 @@ package gfx +import "math" + // PathBuilder assembles path geometry in a reusable command buffer, so a path // derived from data every frame (a chart series, a sparkline) costs no heap // allocation once the buffer has grown to its working size. The zero value is @@ -42,6 +44,37 @@ func (builder *PathBuilder) CubicTo(c1x, c1y, c2x, c2y, x, y float32) { builder.commands = append(builder.commands, CubicTo(c1x, c1y, c2x, c2y, x, y)) } +// Arc begins a contour at the start angle of the circle of radius around (cx, cy) and +// follows it clockwise (y down) by sweep degrees, as cubic curves of at most a quarter turn +// each. Angles are in degrees from the positive x axis, so -90 is twelve o'clock; a sweep of +// 360 or more makes a full circle, one of zero or less adds nothing. +func (builder *PathBuilder) Arc(cx, cy, radius, start, sweep float32) { + if radius <= 0 || sweep <= 0 { + return + } + sweep = min(sweep, 360) + const toRadians = math.Pi / 180 + segments := int(math.Ceil(float64(sweep) / 90)) + step := float64(sweep) / float64(segments) * toRadians + // The control points of a quarter-turn-or-less arc: 4/3 tan(step/4) of the radius. + k := 4.0 / 3.0 * math.Tan(step/4) * float64(radius) + angle := float64(start) * toRadians + point := func(a float64) (x, y float64) { + return float64(cx) + float64(radius)*math.Cos(a), float64(cy) + float64(radius)*math.Sin(a) + } + x0, y0 := point(angle) + builder.MoveTo(float32(x0), float32(y0)) + for range segments { + next := angle + step + x1, y1 := point(next) + builder.CubicTo( + float32(x0-k*math.Sin(angle)), float32(y0+k*math.Cos(angle)), + float32(x1+k*math.Sin(next)), float32(y1-k*math.Cos(next)), + float32(x1), float32(y1)) + angle, x0, y0 = next, x1, y1 + } +} + // Close closes the current contour. func (builder *PathBuilder) Close() { builder.commands = append(builder.commands, ClosePath()) diff --git a/gfx/pose.go b/gfx/pose.go new file mode 100644 index 000000000..23e23ea3d --- /dev/null +++ b/gfx/pose.go @@ -0,0 +1,240 @@ +package gfx + +import "time" + +// Pose is where an element sits relative to its place in the layout: moved, +// scaled about a pivot and faded. The zero Pose is the element as laid out. +// Unlike a Presence, which is an overlay's entrance and exit, a Pose is the +// state of an element that is always there: a tab lifted by the pointer, a row +// pushed aside, a panel resting a few pixels off. +type Pose struct { + // Offset moves the element, in logical pixels. + Offset Point + // Scale is its size as a fraction of its own; zero and one leave it alone. + Scale float32 + // Fade is how far it is faded out, from 0, opaque, to 1, gone. + Fade float32 + // Rotate turns it about the pivot, in radians, clockwise. Rectangles become + // vector shapes, text is drawn into a turned quad (a backend that cannot warp + // text draws the line upright where it would be), and shadows and images + // follow the element without turning. + Rotate float32 +} + +func (pose Pose) channels() [poseChannels]float32 { + scale := pose.Scale + if scale == 0 { + scale = 1 + } + return [poseChannels]float32{pose.Offset.X, pose.Offset.Y, scale, pose.Fade, pose.Rotate} +} + +const poseChannels = 5 + +// poseEntry is one posed element: a motionSlot per component of its pose, so +// each keeps its own velocity when the target changes on the way. +type poseEntry struct { + id ID + slot uint8 + seen uint32 + channels [poseChannels]motionSlot + // origin is where a glided element was painted last frame. + origin Point + placed bool +} + +// BeginPose starts the group of primitives that make up one posed element and +// moves them to pose, about pivot, with motion. id names the element and slot +// tells apart the poses of one id. Everything the canvas paints until the +// matching EndPose belongs to the element, which is moved, scaled and faded +// after it was painted: the application paints it where the layout puts it and +// the canvas finds the way to the pose, keeping the velocity of a pose that +// changes on the way. Hits painted inside move with it, as HitPresenceRect +// reports for a native overlay anchored to them. +// +// A pose that is at rest as the zero Pose costs a stack push, as does one with +// ID zero (a static preview), without a clock, outside BeginFrame and EndFrame +// and under reduced motion, which show the pose at once. An element starts at +// its first pose, so one that appears does not move in. +func (canvas *Canvas) BeginPose(id ID, slot uint8, pose Pose, motion Motion, pivot Point) { + state := &canvas.motion + open := presenceOpen{ + entry: -1, + rectangles: len(canvas.rectangles), triangles: len(canvas.triangles), images: len(canvas.images), + texts: len(canvas.texts), runs: len(canvas.runs), shadows: len(canvas.shadows), + hits: len(canvas.hits), hoverHints: len(canvas.hoverHints), order: canvas.order, + pose: poseTarget{pose: pose, pivot: pivot}, + } + if state.active && !id.IsZero() { + open.pose.entry = state.poseFor(id, slot, pose.channels(), state.frameTime()) + 1 + open.pose.motion = motion + } + state.open = append(state.open, open) +} + +// poseTarget is what BeginPose asked for, kept until EndPose. +type poseTarget struct { + pose Pose + pivot Point + motion Motion + // entry is 1 + the index in motionState.poses; zero for a group not tracked. + entry int +} + +// EndPose closes the group opened by BeginPose and places it. +func (canvas *Canvas) EndPose() { + state := &canvas.motion + if len(state.open) == 0 { + return + } + open := state.open[len(state.open)-1] + state.open = state.open[:len(state.open)-1] + target := open.pose + var values [poseChannels]float32 + switch { + case target.entry > 0 && target.entry <= len(state.poses): + values = state.poses[target.entry-1].step(state, target.pose.channels(), target.motion) + default: + values = target.pose.channels() + } + transform := presenceTransform{ + pivot: target.pivot, offset: Point{X: values[0], Y: values[1]}, + scale: values[2], alpha: 1 - min(max(values[3], 0), 1), scaleText: true, + }.turn(values[4]) + fade := values[3] > 0 + if !fade && transform.scale == 1 && transform.offset == (Point{}) && !transform.turned() { + return + } + transform.apply(canvas, open, fade, fade) + // What is seen is what is hit: a press lands on the tab where it is drawn, + // not where the layout will put it once it has arrived. + for index := open.hits; index < len(canvas.hits); index++ { + canvas.hits[index].Bounds = transform.rect(canvas.hits[index].Bounds) + } + state.recordHitMotions(canvas, open, transform.hitMotion()) +} + +// poseFor finds or creates the entry of an element, settled at its first pose. +func (state *motionState) poseFor(id ID, slot uint8, initial [poseChannels]float32, now time.Duration) int { + index := state.poseAt + if index >= len(state.poses) || state.poses[index].id != id || state.poses[index].slot != slot { + index = -1 + for candidate := range state.poses { + if state.poses[candidate].id == id && state.poses[candidate].slot == slot { + index = candidate + break + } + } + if index < 0 { + index = min(state.poseAt, len(state.poses)) + state.poses = append(state.poses, poseEntry{}) + copy(state.poses[index+1:], state.poses[index:]) + entry := poseEntry{id: id, slot: slot} + for channel, value := range initial { + entry.channels[channel] = motionSlot{from: value, to: value, start: now} + } + state.poses[index] = entry + } + } + state.poseAt = index + 1 + state.poses[index].seen = state.frame + return index +} + +// step moves every component toward its target and returns what is shown. +func (entry *poseEntry) step(state *motionState, targets [poseChannels]float32, motion Motion) (values [poseChannels]float32) { + now := state.frameTime() + for channel := range entry.channels { + slot := &entry.channels[channel] + target := targets[channel] + if state.reduce || motion.Duration <= 0 { + *slot = motionSlot{from: target, to: target, start: now} + values[channel] = target + continue + } + if slot.to != target { + slot.retarget(now, target, motion) + } + if !slot.settled(now) { + state.animating = true + } + values[channel] = slot.value(now) + } + return values +} + +// sweepPoses drops the poses of elements the finished paint pass did not paint. +func (state *motionState) sweepPoses() { + kept := state.poses[:0] + for _, entry := range state.poses { + if entry.seen == state.frame { + kept = append(kept, entry) + } + } + clear(state.poses[len(kept):]) + state.poses = kept + if cap(state.poses) > motionShrinkCapacity && len(state.poses)*motionShrinkFactor < cap(state.poses) { + state.poses = append(make([]poseEntry, 0, len(state.poses)*2), state.poses...) + } +} + +// BeginGlide starts the group of primitives of an element that slides to its +// new place when the layout moves it: a tab whose neighbour closed, a row +// dropped into a list. The application paints the element where the layout puts +// it and says where that is, as place, a point measured so that what moves the +// element with everything around it, a scrolled container, is not a move: the +// element's corner less the scroll. When place differs from where the last frame painted it the +// canvas shows it where it was and glides it to where it is, keeping the +// velocity of a glide the layout interrupts. An element that is painted for the +// first time is simply there. Close the group with EndPose. id and slot name the +// element as for BeginPose, which uses the same entry: a glided element has no +// other pose. +// +// Only the position glides; the size follows the layout at once. Motion with a +// zero duration, no clock, reduced motion and ID zero place the element at once. +func (canvas *Canvas) BeginGlide(id ID, slot uint8, place Point, motion Motion) { + state := &canvas.motion + canvas.BeginPose(id, slot, Pose{}, motion, Point{}) + open := &state.open[len(state.open)-1] + if open.pose.entry == 0 { + return + } + entry := &state.poses[open.pose.entry-1] + origin := place + if entry.placed && entry.origin != origin && !state.reduce && motion.Duration > 0 { + now := state.frameTime() + shift := Point{X: entry.origin.X - origin.X, Y: entry.origin.Y - origin.Y} + entry.channels[0].rebase(now, shift.X, 0, motion) + entry.channels[1].rebase(now, shift.Y, 0, motion) + } + entry.origin, entry.placed = origin, true +} + +// GlideFrom tells the canvas that the element named id and slot, which the +// next BeginGlide places, was last seen at from: a tab dropped where the pointer +// carried it, a row set down by a drag. The element then slides from there +// instead of from where the previous frame painted it. It has to come before the +// frame's BeginGlide of the element, and only affects the one that follows; an +// element that is not painted again, a canvas without a frame clock and reduced +// motion ignore it. +func (canvas *Canvas) GlideFrom(id ID, slot uint8, from Point) { + state := &canvas.motion + if !state.active || id.IsZero() || state.reduce { + return + } + index := -1 + for candidate := range state.poses { + if state.poses[candidate].id == id && state.poses[candidate].slot == slot { + index = candidate + break + } + } + if index < 0 { + return + } + entry := &state.poses[index] + // What the eye saw is the pose shown now, on top of the place painted. + now := state.frameTime() + entry.origin = Point{X: from.X - entry.channels[0].value(now), Y: from.Y - entry.channels[1].value(now)} + entry.placed = true +} diff --git a/gfx/pose_test.go b/gfx/pose_test.go new file mode 100644 index 000000000..02f0647ca --- /dev/null +++ b/gfx/pose_test.go @@ -0,0 +1,368 @@ +package gfx + +import ( + "math" + "testing" + "time" +) + +func paintPosed(canvas *Canvas, id ID, pose Pose, motion Motion) { + canvas.BeginPose(id, 0, pose, motion, Point{X: 50, Y: 50}) + canvas.Rounded(Rect{Width: 100, Height: 100}, 10, Color{Red: 1, Alpha: 1}) + canvas.Hit(id, Rect{Width: 100, Height: 100}) + canvas.EndPose() +} + +func TestPoseStartsAtItsFirstPoseAndMovesWhenItChanges(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + motion := Motion{Duration: 100 * time.Millisecond, Easing: EaseLinear} + id := Item(1) + bounds := func(at time.Duration, pose Pose) Rect { + canvas.Reset() + frames.at(at, func() { paintPosed(&canvas, id, pose, motion) }) + return canvas.Rectangles()[0].Bounds + } + if got := bounds(0, Pose{Offset: Point{X: 20}}); got.X != 20 || canvas.Animating() { + t.Fatalf("first pose = %+v animating=%v, want it shown at once", got, canvas.Animating()) + } + bounds(time.Second, Pose{Offset: Point{X: 20}}) + if got := bounds(2*time.Second, Pose{}); got.X != 20 { + t.Fatalf("frame that changes the pose = %v, want 20", got.X) + } + if got := bounds(2*time.Second+50*time.Millisecond, Pose{}); math.Abs(float64(got.X-10)) > 1e-4 || !canvas.Animating() { + t.Fatalf("halfway = %v animating=%v, want 10", got.X, canvas.Animating()) + } + if got := bounds(3*time.Second, Pose{}); got.X != 0 || canvas.Animating() { + t.Fatalf("rest = %v animating=%v", got.X, canvas.Animating()) + } +} + +func TestPoseScalesAboutItsPivotAndFades(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + canvas.Reset() + frames.at(0, func() { + paintPosed(&canvas, Item(1), Pose{Scale: 0.5, Fade: 0.75}, Motion{Duration: time.Second}) + }) + rectangle := canvas.Rectangles()[0] + if rectangle.Bounds != (Rect{X: 25, Y: 25, Width: 50, Height: 50}) { + t.Fatalf("bounds = %+v", rectangle.Bounds) + } + if math.Abs(float64(rectangle.Color.Alpha-0.25)) > 1e-6 { + t.Fatalf("alpha = %v, want 0.25", rectangle.Color.Alpha) + } +} + +func TestPoseMovesHitsAlongWithTheirPaint(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + canvas.Reset() + frames.at(0, func() { paintPosed(&canvas, Item(1), Pose{Offset: Point{X: 7, Y: 3}}, DefaultMotion()) }) + if hit := canvas.Hits()[0].Bounds; hit != (Rect{X: 7, Y: 3, Width: 100, Height: 100}) { + t.Fatalf("hit bounds = %+v, want the drawn place", hit) + } + got, moved := canvas.HitPresenceRect(0, Rect{Width: 100, Height: 100}) + if !moved || got != (Rect{X: 7, Y: 3, Width: 100, Height: 100}) { + t.Fatalf("hit rect = %+v moved=%v", got, moved) + } +} + +func TestPoseRetargetKeepsVelocity(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + motion := SpringMotion(400*time.Millisecond, 0) + x := func(at time.Duration, pose Pose) float32 { + canvas.Reset() + frames.at(at, func() { paintPosed(&canvas, Item(1), pose, motion) }) + return canvas.Rectangles()[0].Bounds.X + } + x(0, Pose{}) + x(time.Second, Pose{Offset: Point{X: 100}}) + at := time.Second + 120*time.Millisecond + a, b := x(at, Pose{Offset: Point{X: 100}}), x(at+time.Millisecond, Pose{Offset: Point{X: 100}}) + if got := x(at+time.Millisecond, Pose{}); math.Abs(float64(got-b)) > 1e-3 { + t.Fatalf("turning around jumped from %v to %v", b, got) + } + if next := x(at+2*time.Millisecond, Pose{}); (next-b)/0.001 < (b-a)/0.001*0.8 { + t.Fatalf("velocity %v after turning, was %v", (next-b)/0.001, (b-a)/0.001) + } +} + +func TestPoseIsFinalWithoutClockOrUnderReducedMotion(t *testing.T) { + var canvas Canvas + canvas.Reset() + paintPosed(&canvas, Item(1), Pose{Offset: Point{X: 9}}, DefaultMotion()) + if got := canvas.Rectangles()[0].Bounds.X; got != 9 { + t.Fatalf("no clock: x = %v, want the pose at once", got) + } + frames := newTestFrames(&canvas) + canvas.SetReduceMotion(true) + canvas.Reset() + frames.at(0, func() { paintPosed(&canvas, Item(2), Pose{}, DefaultMotion()) }) + canvas.Reset() + frames.at(time.Second, func() { paintPosed(&canvas, Item(2), Pose{Offset: Point{X: 9}}, DefaultMotion()) }) + if got := canvas.Rectangles()[0].Bounds.X; got != 9 || canvas.Animating() { + t.Fatalf("reduced motion: x = %v animating=%v", got, canvas.Animating()) + } +} + +func TestPoseForgetsUnpaintedElementsAndIdleAsksForNoFrame(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + canvas.Reset() + frames.at(0, func() { paintPosed(&canvas, Item(1), Pose{Offset: Point{X: 5}}, DefaultMotion()) }) + canvas.Reset() + frames.at(time.Second, func() { paintPosed(&canvas, Item(1), Pose{Offset: Point{X: 5}}, DefaultMotion()) }) + if _, ok := canvas.NextFrame(); ok { + t.Fatal("a pose at rest asks for a frame") + } + canvas.Reset() + frames.at(2*time.Second, func() {}) + if len(canvas.motion.poses) != 0 { + t.Fatalf("%d poses kept for an element no longer painted", len(canvas.motion.poses)) + } +} + +func TestWarmPoseDoesNotAllocate(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + motion := SpringMotion(300*time.Millisecond, 0.1) + paint := func(target float32) { + canvas.Reset() + for id := 1; id <= 32; id++ { + paintPosed(&canvas, Item(id), Pose{Offset: Point{X: target}}, motion) + } + } + frames.at(0, func() { paint(0) }) + now := time.Duration(0) + if allocations := testing.AllocsPerRun(100, func() { + now += 8 * time.Millisecond + frames.at(now, func() { paint(float32(now / (400 * time.Millisecond) % 2 * 30)) }) + }); allocations != 0 { + t.Fatalf("warm posed frames allocate %v times", allocations) + } +} + +func paintGlided(canvas *Canvas, id ID, x float32, motion Motion) float32 { + bounds := Rect{X: x, Width: 40, Height: 20} + canvas.BeginGlide(id, 0, Point{X: bounds.X, Y: bounds.Y}, motion) + canvas.Rounded(bounds, 4, Color{Alpha: 1}) + canvas.EndPose() + return canvas.Rectangles()[len(canvas.Rectangles())-1].Bounds.X +} + +func TestGlideSlidesFromWhereTheLastFramePaintedIt(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + motion := Motion{Duration: 100 * time.Millisecond, Easing: EaseLinear} + x := func(at time.Duration, layout float32) (got float32) { + canvas.Reset() + frames.at(at, func() { got = paintGlided(&canvas, Item(1), layout, motion) }) + return got + } + if got := x(0, 100); got != 100 || canvas.Animating() { + t.Fatalf("first paint = %v animating=%v, want it simply there", got, canvas.Animating()) + } + // The layout moves it 60 to the left: the eye still sees it at 100. + if got := x(time.Second, 40); got != 100 { + t.Fatalf("first frame after the move = %v, want 100", got) + } + if got := x(time.Second+50*time.Millisecond, 40); math.Abs(float64(got-70)) > 1e-3 || !canvas.Animating() { + t.Fatalf("halfway = %v animating=%v, want 70", got, canvas.Animating()) + } + if got := x(time.Second+200*time.Millisecond, 40); got != 40 || canvas.Animating() { + t.Fatalf("arrived = %v animating=%v", got, canvas.Animating()) + } +} + +func TestGlideInterruptedByAnotherMoveStaysContinuous(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + motion := SpringMotion(300*time.Millisecond, 0) + x := func(at time.Duration, layout float32) (got float32) { + canvas.Reset() + frames.at(at, func() { got = paintGlided(&canvas, Item(1), layout, motion) }) + return got + } + x(0, 100) + x(time.Second, 0) + at := time.Second + 100*time.Millisecond + seen := x(at, 0) + // A second move of the layout, by +40: the picture must not jump. + if got := x(at, 40); math.Abs(float64(got-seen)) > 1e-3 { + t.Fatalf("second move jumped from %v to %v", seen, got) + } +} + +func TestGlideIsInstantUnderReducedMotion(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + canvas.SetReduceMotion(true) + motion := DefaultMotion() + canvas.Reset() + frames.at(0, func() { paintGlided(&canvas, Item(1), 100, motion) }) + canvas.Reset() + var got float32 + frames.at(time.Second, func() { got = paintGlided(&canvas, Item(1), 0, motion) }) + if got != 0 || canvas.Animating() { + t.Fatalf("reduced motion = %v animating=%v", got, canvas.Animating()) + } +} + +func TestGlideFromStartsWhereTheElementWasCarried(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + motion := Motion{Duration: 100 * time.Millisecond, Easing: EaseLinear} + x := func(at time.Duration, layout float32, from *Point) (got float32) { + canvas.Reset() + frames.at(at, func() { + if from != nil { + canvas.GlideFrom(Item(1), 0, *from) + } + got = paintGlided(&canvas, Item(1), layout, motion) + }) + return got + } + x(0, 100, nil) + if got := x(time.Second, 40, &Point{X: 300}); got != 300 { + t.Fatalf("first frame = %v, want the point it was carried to", got) + } + if got := x(time.Second+50*time.Millisecond, 40, nil); math.Abs(float64(got-170)) > 1e-3 { + t.Fatalf("halfway = %v, want 170", got) + } + if got := x(2*time.Second, 40, nil); got != 40 { + t.Fatalf("arrived = %v", got) + } +} + +func paintPosedWith(canvas *Canvas, id ID, pose Pose, motion Motion, paint func()) { + canvas.BeginPose(id, 0, pose, motion, Point{X: 50, Y: 50}) + paint() + canvas.EndPose() +} + +func TestPoseRotationTurnsARectangleIntoVectorShapes(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + canvas.Reset() + frames.at(0, func() { + paintPosedWith(&canvas, Item(1), Pose{Rotate: math.Pi / 2}, Motion{Duration: time.Second}, func() { + canvas.Fill(Rect{X: 0, Y: 40, Width: 100, Height: 20}, Color{Red: 1, Alpha: 1}) + }) + }) + if len(canvas.Rectangles()) != 0 || len(canvas.Triangles()) == 0 { + t.Fatalf("%d rectangles and %d triangles: a turned rectangle must become shapes", len(canvas.Rectangles()), len(canvas.Triangles())) + } + // A quarter turn about (50, 50) stands the 100x20 bar up: 20 wide, 100 tall. + left, top, right, bottom := float32(1e9), float32(1e9), float32(-1e9), float32(-1e9) + for _, triangle := range canvas.Triangles() { + for _, point := range triangle.Points { + left, right = min(left, point.X), max(right, point.X) + top, bottom = min(top, point.Y), max(bottom, point.Y) + } + } + if math.Abs(float64(right-left-20)) > 1e-3 || math.Abs(float64(bottom-top-100)) > 1e-3 { + t.Fatalf("turned bar spans %vx%v, want 20x100", right-left, bottom-top) + } +} + +func TestPoseRotationKeepsPaintOrderAmongShapesAndTriangles(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + canvas.Reset() + frames.at(0, func() { + paintPosedWith(&canvas, Item(1), Pose{Rotate: 0.3}, Motion{Duration: time.Second}, func() { + canvas.Fill(Rect{Width: 50, Height: 50}, Color{Red: 1, Alpha: 1}) + canvas.DrawIcon(Icon{ViewBox: 24, Stroke: 2, Commands: []PathCommand{MoveTo(4, 12), LineTo(20, 12)}, Cap: CapRound}, Rect{Width: 24, Height: 24}, Color{Alpha: 1}) + canvas.Fill(Rect{X: 60, Width: 50, Height: 50}, Color{Green: 1, Alpha: 1}) + }) + }) + previous := uint32(0) + for index, triangle := range canvas.Triangles() { + if triangle.Order < previous { + t.Fatalf("triangle %d has order %d after %d: the group is out of paint order", index, triangle.Order, previous) + } + previous = triangle.Order + } +} + +func TestPoseRotationWarpsTextIntoAQuad(t *testing.T) { + var canvas Canvas + canvas.SetMeasurer(func(value string, size, weight float32) float32 { return float32(len(value)) * size / 2 }) + frames := newTestFrames(&canvas) + canvas.Reset() + frames.at(0, func() { + paintPosedWith(&canvas, Item(1), Pose{Rotate: math.Pi / 2}, Motion{Duration: time.Second}, func() { + canvas.Label("hello", Rect{X: 0, Y: 40, Width: 100, Height: 20}, TextStyle{Size: 13, Color: Color{Alpha: 1}}) + }) + }) + text := canvas.Texts()[0] + if !text.HasQuad { + t.Fatal("a turned label was not given a quad") + } + // Top-left (0,40) turned a quarter about (50,50) lands at (60, 0). + if got := text.Quad[0]; math.Abs(float64(got.X-60)) > 1e-3 || math.Abs(float64(got.Y)) > 1e-3 { + t.Fatalf("top-left corner at %+v, want (60, 0)", got) + } + if text.Tint[0].Alpha != 1 { + t.Fatalf("the quad's tint %+v hides the text", text.Tint[0]) + } +} + +func TestPoseScaleMakesTextFollowIt(t *testing.T) { + var canvas Canvas + canvas.SetMeasurer(func(value string, size, weight float32) float32 { return float32(len(value)) * size / 2 }) + frames := newTestFrames(&canvas) + canvas.Reset() + frames.at(0, func() { + paintPosedWith(&canvas, Item(1), Pose{Scale: 2}, Motion{Duration: time.Second}, func() { + canvas.Label("hi", Rect{X: 40, Y: 40, Width: 20, Height: 20}, TextStyle{Size: 13, Color: Color{Alpha: 1}}) + }) + }) + text := canvas.Texts()[0] + if !text.HasQuad || text.Quad[1].X-text.Quad[0].X != 40 { + t.Fatalf("text quad %+v is not twice its box", text.Quad) + } +} + +func TestPoseRotationFollowsClipAndHitAsBoundingBoxes(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + canvas.Reset() + frames.at(0, func() { + paintPosedWith(&canvas, Item(1), Pose{Rotate: math.Pi / 2}, Motion{Duration: time.Second}, func() { + canvas.Hit(Item(1), Rect{X: 0, Y: 40, Width: 100, Height: 20}) + }) + }) + got := canvas.Hits()[0].Bounds + if math.Abs(float64(got.Width-20)) > 1e-3 || math.Abs(float64(got.Height-100)) > 1e-3 { + t.Fatalf("turned hit %+v, want 20x100", got) + } +} + +func TestWarmRotatedPoseDoesNotAllocate(t *testing.T) { + var canvas Canvas + frames := newTestFrames(&canvas) + motion := SpringMotion(300*time.Millisecond, 0) + paint := func(angle float32) { + canvas.Reset() + for id := 1; id <= 16; id++ { + paintPosedWith(&canvas, Item(id), Pose{Rotate: angle}, motion, func() { + canvas.Rounded(Rect{Width: 60, Height: 30}, 6, Color{Red: 1, Alpha: 1}) + }) + } + } + frames.at(0, func() { paint(0) }) + now := time.Duration(0) + for range 20 { // warm the scratch lists + now += 8 * time.Millisecond + frames.at(now, func() { paint(0.5) }) + } + if allocations := testing.AllocsPerRun(50, func() { + now += 8 * time.Millisecond + frames.at(now, func() { paint(0.5) }) + }); allocations != 0 { + t.Fatalf("warm rotated frames allocate %v times", allocations) + } +} diff --git a/gfx/presence.go b/gfx/presence.go index b7df56bf0..47114972e 100644 --- a/gfx/presence.go +++ b/gfx/presence.go @@ -42,6 +42,8 @@ type presenceOpen struct { // order is the canvas's last paint order when the group opened. The // snapshot stores its primitives relative to it. order uint32 + // pose is what BeginPose asked for; unused by a presence. + pose poseTarget } // hitMotion is the placement a moving presence applies to one hit, as scale @@ -392,18 +394,67 @@ func (snapshot *presenceSnapshot) replay(canvas *Canvas, presence Presence, pivo type presenceTransform struct { pivot, offset Point scale, alpha float32 + // sin and cos turn the element about the pivot, after scaling; both zero is + // no turn, which is the zero value. + sin, cos float32 + // scaleText makes a label follow the scale, as a picture scaled with the + // element; without it a scaled element keeps its text at its own size, which + // stays sharp. A turned element always warps its text. + scaleText bool +} + +func (transform presenceTransform) turned() bool { return transform.sin != 0 } + +// turn returns transform turned by angle radians, clockwise on a y-down page. +func (transform presenceTransform) turn(angle float32) presenceTransform { + if angle != 0 { + sin, cos := math.Sincos(float64(angle)) + transform.sin, transform.cos = float32(sin), float32(cos) + } + return transform } func (transform presenceTransform) point(point Point) Point { + if !transform.turned() { + return Point{ + X: transform.pivot.X + (point.X-transform.pivot.X)*transform.scale + transform.offset.X, + Y: transform.pivot.Y + (point.Y-transform.pivot.Y)*transform.scale + transform.offset.Y, + } + } + x, y := (point.X-transform.pivot.X)*transform.scale, (point.Y-transform.pivot.Y)*transform.scale return Point{ - X: transform.pivot.X + (point.X-transform.pivot.X)*transform.scale + transform.offset.X, - Y: transform.pivot.Y + (point.Y-transform.pivot.Y)*transform.scale + transform.offset.Y, + X: transform.pivot.X + x*transform.cos - y*transform.sin + transform.offset.X, + Y: transform.pivot.Y + x*transform.sin + y*transform.cos + transform.offset.Y, } } +// rect is where rect lands: moved and scaled, and for a turned transform the +// box that holds the turned rectangle, which is what a clip or a hit region +// can be. func (transform presenceTransform) rect(rect Rect) Rect { - origin := transform.point(Point{X: rect.X, Y: rect.Y}) - return Rect{X: origin.X, Y: origin.Y, Width: rect.Width * transform.scale, Height: rect.Height * transform.scale} + if !transform.turned() { + origin := transform.point(Point{X: rect.X, Y: rect.Y}) + return Rect{X: origin.X, Y: origin.Y, Width: rect.Width * transform.scale, Height: rect.Height * transform.scale} + } + corners := [4]Point{ + transform.point(Point{X: rect.X, Y: rect.Y}), transform.point(Point{X: rect.X + rect.Width, Y: rect.Y}), + transform.point(Point{X: rect.X, Y: rect.Y + rect.Height}), transform.point(Point{X: rect.X + rect.Width, Y: rect.Y + rect.Height}), + } + left, top, right, bottom := corners[0].X, corners[0].Y, corners[0].X, corners[0].Y + for _, corner := range corners[1:] { + left, right = min(left, corner.X), max(right, corner.X) + top, bottom = min(top, corner.Y), max(bottom, corner.Y) + } + return Rect{X: left, Y: top, Width: right - left, Height: bottom - top} +} + +// centred is a rectangle of the scaled size of rect, centred where the centre of +// rect lands: how a primitive that cannot turn (a shadow, a bitmap) follows a +// turned element. +func (transform presenceTransform) centred(rect Rect) Rect { + centre := transform.point(Point{X: rect.X + rect.Width/2, Y: rect.Y + rect.Height/2}) + width, height := rect.Width*transform.scale, rect.Height*transform.scale + return Rect{X: centre.X - width/2, Y: centre.Y - height/2, Width: width, Height: height} } func (transform presenceTransform) color(color Color) Color { @@ -544,14 +595,24 @@ func reverseTriangles(triangles []Triangle) { // is not worth one per frame, so a label moves with the overlay but keeps its size. func (presence Presence) apply(canvas *Canvas, open presenceOpen, pivot Point, progress float32, leaving bool) { transform := presence.transform(pivot, progress, leaving) + transform.apply(canvas, open, presence.Fade, presence.Fade && progress < 1) +} + +// apply places and fades everything the canvas painted since open began. fade +// multiplies every colour by the transform's alpha; vectorize turns rounded +// border backings into rings first, which a fade that is not complete needs so +// the backing does not show through the fill. +func (transform presenceTransform) apply(canvas *Canvas, open presenceOpen, fade, vectorize bool) { for index := open.hoverHints; index < len(canvas.hoverHints); index++ { canvas.hoverHints[index].Bounds = transform.rect(canvas.hoverHints[index].Bounds) } moving := transform.scale != 1 || transform.offset != (Point{}) - fade := presence.Fade - if fade && progress < 1 { + if vectorize { vectorizeBorderBackings(canvas, open.rectangles) } + if transform.turned() { + transform.turnRectangles(canvas, open) + } for index := open.rectangles; index < len(canvas.rectangles); index++ { rectangle := &canvas.rectangles[index] rectangle.Bounds = transform.rect(rectangle.Bounds) @@ -565,7 +626,11 @@ func (presence Presence) apply(canvas *Canvas, open presenceOpen, pivot Point, p } for index := open.shadows; index < len(canvas.shadows); index++ { shadow := &canvas.shadows[index] - shadow.Bounds = transform.rect(shadow.Bounds) + if transform.turned() { + shadow.Bounds = transform.centred(shadow.Bounds) + } else { + shadow.Bounds = transform.rect(shadow.Bounds) + } shadow.Radius *= transform.scale shadow.Style.OffsetX *= transform.scale shadow.Style.OffsetY *= transform.scale @@ -597,7 +662,11 @@ func (presence Presence) apply(canvas *Canvas, open presenceOpen, pivot Point, p if image.Backdrop { continue } - image.Bounds = transform.rect(image.Bounds) + if transform.turned() { + image.Bounds = transform.centred(image.Bounds) + } else { + image.Bounds = transform.rect(image.Bounds) + } image.Radius *= transform.scale if fade { image.Fade = 1 - (1-image.Fade)*transform.alpha @@ -608,28 +677,32 @@ func (presence Presence) apply(canvas *Canvas, open presenceOpen, pivot Point, p } for index := open.texts; index < len(canvas.texts); index++ { text := &canvas.texts[index] - oldCenter := Point{X: text.Bounds.X + text.Bounds.Width/2, Y: text.Bounds.Y + text.Bounds.Height/2} - center := transform.point(oldCenter) - text.Bounds.X, text.Bounds.Y = center.X-text.Bounds.Width/2, center.Y-text.Bounds.Height/2 - if text.HasQuad { - // The quad places the label's picture; the text's size is not - // scaled, so move the corners by the centre's delta. Its tints stay - // as they are: the fade is already in the label's colour. - dx, dy := center.X-oldCenter.X, center.Y-oldCenter.Y - for corner := range text.Quad { - text.Quad[corner].X += dx - text.Quad[corner].Y += dy + if transform.turned() || (transform.scale != 1 && transform.scaleText) { + transform.warpText(text) + } else { + oldCenter := Point{X: text.Bounds.X + text.Bounds.Width/2, Y: text.Bounds.Y + text.Bounds.Height/2} + center := transform.point(oldCenter) + text.Bounds.X, text.Bounds.Y = center.X-text.Bounds.Width/2, center.Y-text.Bounds.Height/2 + if text.HasQuad { + // The quad places the label's picture; the text's size is not + // scaled, so move the corners by the centre's delta. Its tints stay + // as they are: the fade is already in the label's colour. + dx, dy := center.X-oldCenter.X, center.Y-oldCenter.Y + for corner := range text.Quad { + text.Quad[corner].X += dx + text.Quad[corner].Y += dy + } + } + if moving { + // A moving label's sub-pixel origin changes every frame. Native + // text backends key retained textures by it, so keeping the + // fraction would rasterize every visible label again on every + // frame. Whole-pixel motion leaves the origin at zero; the label + // still moves with its panel, and static text keeps its sub-pixel + // placement. + text.Bounds.X = float32(math.Round(float64(text.Bounds.X))) + text.Bounds.Y = float32(math.Round(float64(text.Bounds.Y))) } - } - if moving { - // A moving label's sub-pixel origin changes every frame. Native - // text backends key retained textures by it, so keeping the - // fraction would rasterize every visible label again on every - // frame. Whole-pixel motion leaves the origin at zero; the label - // still moves with its panel, and static text keeps its sub-pixel - // placement. - text.Bounds.X = float32(math.Round(float64(text.Bounds.X))) - text.Bounds.Y = float32(math.Round(float64(text.Bounds.Y))) } if fade { text.Style.Color = transform.color(text.Style.Color) @@ -644,3 +717,75 @@ func (presence Presence) apply(canvas *Canvas, open presenceOpen, pivot Point, p } } } + +// warpText places a label's picture in the quad its corners land on: scaled, +// turned and moved with the element. The box it is rasterised in keeps its size, +// so the text keeps its layout; a backend that cannot draw text into a quad +// paints the line axis-aligned where the label's centre went. +func (transform presenceTransform) warpText(text *Text) { + source := text.Quad + if !text.HasQuad { + left, top, right, bottom := text.Bounds.X, text.Bounds.Y, text.Bounds.X+text.Bounds.Width, text.Bounds.Y+text.Bounds.Height + source = [4]Point{{X: left, Y: top}, {X: right, Y: top}, {X: left, Y: bottom}, {X: right, Y: bottom}} + white := Color{Red: 1, Green: 1, Blue: 1, Alpha: 1} + text.Tint = [4]Color{white, white, white, white} + text.HasQuad = true + } + for corner := range source { + text.Quad[corner] = transform.point(source[corner]) + } + centre := transform.point(Point{X: text.Bounds.X + text.Bounds.Width/2, Y: text.Bounds.Y + text.Bounds.Height/2}) + text.Bounds.X, text.Bounds.Y = centre.X-text.Bounds.Width/2, centre.Y-text.Bounds.Height/2 +} + +// turnRectangles replaces the rectangles painted since open began with vector +// shapes: a rectangle cannot be turned, but its outline, rounded corners +// included, can, and keeps the order it was painted in among the other +// primitives. They are placed with the group's triangles afterwards. +func (transform presenceTransform) turnRectangles(canvas *Canvas, open presenceOpen) { + if open.rectangles >= len(canvas.rectangles) { + return + } + shapes := canvas.poseShapes[:0] + for _, rectangle := range canvas.rectangles[open.rectangles:] { + if rectangle.Color.Alpha <= 0 || rectangle.Bounds.Width <= 0 || rectangle.Bounds.Height <= 0 { + continue + } + canvas.posePoints = appendRoundedRectContour(canvas.posePoints[:0], rectangle.Bounds, rectangle.Radius) + centre := Point{X: rectangle.Bounds.X + rectangle.Bounds.Width/2, Y: rectangle.Bounds.Y + rectangle.Bounds.Height/2} + points := canvas.posePoints + for index := range points { + next := points[(index+1)%len(points)] + shapes = append(shapes, Triangle{ + Points: [3]Point{centre, points[index], next}, Color: rectangle.Color, Layer: rectangle.Layer, + // Only the outline feathers: the edge between the contour's two points. + EdgeMask: 2, ClipOf: rectangle.ClipOf, HasClip: rectangle.HasClip, Order: rectangle.Order, + }) + } + } + canvas.poseShapes = shapes + canvas.rectangles = canvas.rectangles[:open.rectangles] + insertTrianglesByOrder(canvas, open.triangles, shapes) +} + +// insertTrianglesByOrder merges shapes, which are in paint order, into the +// triangles of the group from first on, so that the list stays in paint order. +func insertTrianglesByOrder(canvas *Canvas, first int, shapes []Triangle) { + if len(shapes) == 0 { + return + } + existing := canvas.triangles[first:] + merged := canvas.poseMerge[:0] + left, right := 0, 0 + for left < len(existing) || right < len(shapes) { + if right >= len(shapes) || (left < len(existing) && existing[left].Order < shapes[right].Order) { + merged = append(merged, existing[left]) + left++ + } else { + merged = append(merged, shapes[right]) + right++ + } + } + canvas.poseMerge = merged + canvas.triangles = append(canvas.triangles[:first], merged...) +} diff --git a/gfx/state.go b/gfx/state.go index 9ba5dc319..3b4d07941 100644 --- a/gfx/state.go +++ b/gfx/state.go @@ -26,6 +26,8 @@ type State struct { ReadOnly bool // Invalid is a value that failed validation. Invalid bool + // Warning is a value that needs attention but did not fail. Invalid wins over it. + Warning bool // Checked is a checkbox, switch or toggle that is on. Checked bool // Mixed is a checkbox between on and off. It takes precedence over Checked. diff --git a/gfx/text_menu.go b/gfx/text_menu.go new file mode 100644 index 000000000..2128eff6c --- /dev/null +++ b/gfx/text_menu.go @@ -0,0 +1,25 @@ +package gfx + +// TextMenuLabels are the words of the menu a text field opens on a secondary +// press. A label left empty is English. A page, a window and its menu share one +// pointer to it, so a language change is seen the next time the menu opens. +type TextMenuLabels struct { + Cut, Copy, Paste, SelectAll string +} + +// WithDefaults returns labels with every empty one English. +func (labels TextMenuLabels) WithDefaults() TextMenuLabels { + if labels.Cut == "" { + labels.Cut = "Cut" + } + if labels.Copy == "" { + labels.Copy = "Copy" + } + if labels.Paste == "" { + labels.Paste = "Paste" + } + if labels.SelectAll == "" { + labels.SelectAll = "Select All" + } + return labels +} diff --git a/gfx/theme.go b/gfx/theme.go index 1d2cb80ce..619bd58f5 100644 --- a/gfx/theme.go +++ b/gfx/theme.go @@ -55,6 +55,17 @@ func (m Metrics) RadiusItem() float32 { return max(m.RadiusControl-2, 0) } // dialog or card surface (RadiusSurface). func (m Metrics) RadiusPopup() float32 { return max(m.RadiusSurface-1, 0) } +// RadiusOutset is the corner radius of a shape that stands by pixels outside one +// of radius: a focus ring, a surface with a border around it, or a card larger +// than a control. A square corner has nothing to follow and stays square, so a +// theme whose radii are zero is square throughout and not rounded by the offsets. +func RadiusOutset(radius, by float32) float32 { + if radius <= 0 { + return 0 + } + return radius + by +} + // RadiusFull is a corner radius no control is tall enough to reach: every // rounded shape clamps its radius to half its shorter side, so this makes a // pill (or a circle, on a square) of whatever it is given to. @@ -145,8 +156,12 @@ type Theme struct { Success Color Danger Color DangerForeground Color - Chart [5]Color - Metrics Metrics + // Warning is the color of something that needs attention but has not failed: + // the warning status of an alert, a tag or a field. A hand-built theme that + // leaves it zero paints a warning in Danger instead (see WarningColor). + Warning Color + Chart [5]Color + Metrics Metrics // Transition is the default state-change motion for controls. A zero // value disables animation for hand-built themes. Transition Motion @@ -158,6 +173,15 @@ type Theme struct { TooltipDelay time.Duration } +// WarningColor is Warning, or Danger for a theme that does not set one, so a +// hand-built theme never paints a warning in a transparent color. +func (theme Theme) WarningColor() Color { + if theme.Warning == (Color{}) { + return theme.Danger + } + return theme.Warning +} + // WithRadius is the theme with another corner radius for its controls // (Metrics.RadiusControl), for one control among others: // @@ -249,7 +273,7 @@ func (theme Theme) WithOpacity(opacity float32) Theme { &theme.Popover, &theme.PopoverForeground, &theme.Muted, &theme.MutedForeground, &theme.Border, &theme.Hover, &theme.Input, &theme.Primary, &theme.PrimaryForeground, &theme.Selection, &theme.SelectionForeground, &theme.Secondary, &theme.SecondaryForeground, &theme.Accent, - &theme.AccentForeground, &theme.Ring, &theme.Success, &theme.Danger, &theme.DangerForeground, + &theme.AccentForeground, &theme.Ring, &theme.Success, &theme.Danger, &theme.DangerForeground, &theme.Warning, } { color.Alpha *= opacity } @@ -288,6 +312,7 @@ func DarkTheme() Theme { Success: RGB(34, 197, 94), Danger: RGB(255, 100, 103), DangerForeground: RGB(255, 255, 255), + Warning: RGB(245, 158, 11), Chart: [5]Color{ RGB(142, 197, 255), RGB(43, 127, 255), RGB(21, 93, 252), RGB(20, 71, 230), RGB(25, 60, 184), @@ -324,6 +349,7 @@ func LightTheme() Theme { Success: RGB(22, 163, 74), Danger: RGB(231, 0, 11), DangerForeground: RGB(255, 255, 255), + Warning: RGB(217, 119, 6), Chart: [5]Color{ RGB(142, 197, 255), RGB(43, 127, 255), RGB(21, 93, 252), RGB(20, 71, 230), RGB(25, 60, 184), diff --git a/gfx/theme_test.go b/gfx/theme_test.go index 619c3b16f..ac43fe2d9 100644 --- a/gfx/theme_test.go +++ b/gfx/theme_test.go @@ -139,3 +139,34 @@ func TestTextInsetFollowsControlPadding(t *testing.T) { t.Fatalf("inset does not follow density: compact %v, large %v", compact, large) } } + +// A shape outside a square corner is square too; around a rounded one it grows +// with the distance. +func TestRadiusOutset(t *testing.T) { + if got := RadiusOutset(0, 4); got != 0 { + t.Errorf("outset of a square corner = %v, want 0", got) + } + if got := RadiusOutset(7.5, 3); got != 10.5 { + t.Errorf("outset of 7.5 by 3 = %v, want 10.5", got) + } + square := DefaultMetrics() + square.RadiusControl, square.RadiusSurface = 0, 0 + if square.RadiusItem() != 0 || square.RadiusPopup() != 0 { + t.Errorf("a square theme derives item %v and popup %v radii, want 0", square.RadiusItem(), square.RadiusPopup()) + } +} + +// A theme that does not set Warning paints a warning in Danger, never in a +// transparent color; the stock themes set their own. +func TestWarningColorFallsBackToDanger(t *testing.T) { + var bare Theme + bare.Danger = RGB(200, 0, 0) + if bare.WarningColor() != bare.Danger { + t.Fatalf("WarningColor of a theme without Warning = %+v, want Danger", bare.WarningColor()) + } + for name, theme := range map[string]Theme{"light": LightTheme(), "dark": DarkTheme()} { + if theme.Warning == (Color{}) || theme.WarningColor() != theme.Warning { + t.Fatalf("%s theme has no Warning of its own", name) + } + } +} diff --git a/gfx/wrap.go b/gfx/wrap.go index bef28ccd3..07535766e 100644 --- a/gfx/wrap.go +++ b/gfx/wrap.go @@ -7,6 +7,7 @@ import ( "github.com/vivaui/viva/internal/grapheme" "github.com/vivaui/viva/internal/linebreak" + "github.com/vivaui/viva/internal/textmetrics" "github.com/vivaui/viva/internal/uniprops" ) @@ -290,10 +291,29 @@ const wrapProbe = 64 // line costs a few times its own length (times its logarithm), not the length // of the paragraph behind it. func (canvas *Canvas) fitPrefix(line string, font lineFont, width float32) (fit int, all bool) { + return fitPrefix(canvas, line, font, width) +} + +// lineMeasure is what wrapping asks of whatever measures the lines: how wide a line is in a +// font. A canvas measures with its text engine; referenceMeasure with the reference metrics. +type lineMeasure interface { + widthIn(value string, font lineFont) float32 +} + +// referenceMeasure measures a plain line with the reference metrics, as a canvas without a +// text engine does: no shaping, so it is cheap however many lines it measures. +type referenceMeasure struct{} + +func (referenceMeasure) widthIn(value string, font lineFont) float32 { + return textmetrics.Width(value, font.size, font.weight) +} + +// fitPrefix is Canvas.fitPrefix with the lines measured by measure. +func fitPrefix(measure lineMeasure, line string, font lineFont, width float32) (fit int, all bool) { lo, hi := 0, len(line) // line[:lo] fits (the empty prefix does); line[:hi] does not once a probe failed for step := wrapProbe; ; step *= 2 { probe := runeFloor(line, lo+step) - if canvas.widthIn(trimSpaceRight(line[:probe]), font) > width { + if measure.widthIn(trimSpaceRight(line[:probe]), font) > width { hi = probe break } @@ -309,7 +329,7 @@ func (canvas *Canvas) fitPrefix(line string, font lineFont, width float32) (fit break } } - if canvas.widthIn(trimSpaceRight(line[:mid]), font) <= width { + if measure.widthIn(trimSpaceRight(line[:mid]), font) <= width { lo = mid } else { hi = mid diff --git a/gfx/wrap_rows.go b/gfx/wrap_rows.go index e05aff946..e43f6a99d 100644 --- a/gfx/wrap_rows.go +++ b/gfx/wrap_rows.go @@ -18,6 +18,21 @@ type TextRow struct{ Start, End int } // wraps, so each paragraph is a row. Nothing is allocated, so a caller that // needs only the rows in view can ask for them one at a time. func (canvas *Canvas) WrapRow(value string, from int, size, weight, width float32) (row TextRow, next int) { + return wrapRow(canvas, value, from, size, weight, width) +} + +// WrapRowEstimate is WrapRow with the widths taken from the reference metrics a canvas +// without a text engine measures with, instead of the platform's shaped text. It shapes +// nothing, so it costs a small part of WrapRow, and its rows are the platform's wherever +// the two agree on whether a line fits and near them elsewhere: what a view of a long text +// takes for the rows it does not show, wrapping the ones it shows with the canvas. +// +// row, next := gfx.WrapRowEstimate(text, from, 13, gfx.WeightRegular, width) +func WrapRowEstimate(value string, from int, size, weight, width float32) (row TextRow, next int) { + return wrapRow(referenceMeasure{}, value, from, size, weight, width) +} + +func wrapRow(measure lineMeasure, value string, from int, size, weight, width float32) (row TextRow, next int) { from = max(0, min(from, len(value))) end := len(value) if newline := strings.IndexByte(value[from:], '\n'); newline >= 0 { @@ -34,7 +49,7 @@ func (canvas *Canvas) WrapRow(value string, from int, size, weight, width float3 return TextRow{Start: from, End: end}, next } line := value[from:end] - fit, all := canvas.fitPrefix(line, lineFont{size: size, weight: weight}, width) + fit, all := fitPrefix(measure, line, lineFont{size: size, weight: weight}, width) if all { return TextRow{Start: from, End: end}, next } diff --git a/gfx/wrap_rows_estimate_test.go b/gfx/wrap_rows_estimate_test.go new file mode 100644 index 000000000..e9b4177dd --- /dev/null +++ b/gfx/wrap_rows_estimate_test.go @@ -0,0 +1,29 @@ +package gfx + +import "testing" + +// The estimate is what a canvas without a text engine wraps to: both measure with the +// reference metrics, so a view that estimates its rows before it shows them gets the rows +// it would have shown wherever the platform measures as the reference does. +func TestWrapRowEstimateIsTheReferenceWrap(t *testing.T) { + texts := []string{ + "", "\n", "a\r\nb\n", + "the quick brown fox jumps over the lazy dog and keeps running through the forest", + "中文混排的一段文字,用来检查东亚文字在行尾的断行规则。and some English words", + "averyveryverylongwordwithoutanyspacesthatmustbreakinthemiddle/of/a/path", + " leading spaces and trailing ones \n\nthen a blank line", + } + var canvas Canvas + for _, text := range texts { + for _, width := range []float32{0, 40, 120, 300} { + for from := 0; from >= 0; { + want, wantNext := canvas.WrapRow(text, from, 13, WeightRegular, width) + got, next := WrapRowEstimate(text, from, 13, WeightRegular, width) + if got != want || next != wantNext { + t.Fatalf("%q at %v from %d: estimate %v next %d, canvas %v next %d", text, width, from, got, next, want, wantNext) + } + from = next + } + } + } +} diff --git a/headless/doc.go b/headless/doc.go index 992b93347..7bc247602 100644 --- a/headless/doc.go +++ b/headless/doc.go @@ -69,4 +69,10 @@ // contain it) and start the process with VIVA_HEADLESS=1. RunCanvas then serves // the line protocol documented on Serve on standard input and output instead // of opening a window. +// +// On a dual-GPU Intel Mac, offscreen Metal can render black with the system +// default device. Set VIVA_HEADLESS_METAL_DEVICE=low-power for screenshots to +// use the integrated GPU instead; unset or "default" keeps the system device, +// and any other value is ignored with a warning. The option only affects the +// macOS headless renderer, not windows in a release build. package headless diff --git a/internal/componentdemo/alert.go b/internal/componentdemo/alert.go index ef59391e5..2bce09433 100644 --- a/internal/componentdemo/alert.go +++ b/internal/componentdemo/alert.go @@ -1,120 +1,101 @@ package componentdemo import ( - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/alert" ) var alertComponent = Component{ - ID: "alert", Title: "Alert", Category: "Feedback", Summary: "用于普通说明和破坏性提示的静态消息面板。", - paint: (*State).paintAlert, + ID: "alert", Title: "Alert", Category: "Feedback", Summary: "页面内的提示条:状态图标、标题、说明,可带操作按钮和关闭按钮。", + PageSource: "ui/alert/alert.go", paint: (*State).paintAlert, Examples: []Example{ {ID: "default", Title: "说明", Description: "展示普通通知及其补充说明。", Snippet: `data := components.AlertData{ Icon: icon, // caller-owned gfx.Icon, optional Title: "Sync complete", Description: "All local changes are safely on disk.", } -components.Alert(canvas, theme, bounds, data)`, PageSnippet: `look := c.Theme() -ui.Row(c).FillWidth().Pad(14).Gap(10).Items(ui.Start). - Background(look.Card).Border(1, look.Border). - Radius(look.Metrics.RadiusSurface).Children(func() { - ui.Icon(c, m.infoIcon).Size(16, 16).Color(look.CardForeground) - ui.Column(c).Grow(1).Gap(2).Children(func() { - ui.Text(c, "Sync complete").Weight(gfx.WeightMedium).Color(look.CardForeground) - ui.Text(c, "All local changes are safely on disk. The remote host confirmed the final write, so you can close the session safely."). - FontSize(look.Metrics.FontSizeM).Muted() - }) -})`, PageSnippetZh: `look := c.Theme() -ui.Row(c).FillWidth().Pad(14).Gap(10).Items(ui.Start). - Background(look.Card).Border(1, look.Border). - Radius(look.Metrics.RadiusSurface).Children(func() { - ui.Icon(c, m.infoIcon).Size(16, 16).Color(look.CardForeground) - ui.Column(c).Grow(1).Gap(2).Children(func() { - ui.Text(c, "同步已完成").Weight(gfx.WeightMedium).Color(look.CardForeground) - ui.Text(c, "所有本地更改都已安全写入磁盘。远端主机确认了最后一次写入,可以放心关闭会话。"). - FontSize(look.Metrics.FontSizeM).Muted() - }) -})`}, - {ID: "variants", Title: "语义变体", Description: "并列展示默认与破坏性提示。", Snippet: `plainData := components.AlertData{ - Icon: icon, Title: "Sync complete", +components.Alert(canvas, theme, bounds, data)`, PageSnippet: `m.notice = alert.New() +// in the page: +m.notice.View(c, alert.Spec{ + Title: "Sync complete", Description: "All local changes are safely on disk.", -} -dangerData := components.AlertData{ +}).FillWidth()`, PageSnippetZh: `m.notice = alert.New() +// 在页面中: +m.notice.View(c, alert.Spec{ + Title: "Sync complete", + Description: "All local changes are safely on disk.", +}).FillWidth()`}, + {ID: "variants", Title: "状态", Description: "默认、成功、警告、危险共用 ui.Status,颜色取自主题。", Snippet: `dangerData := components.AlertData{ Variant: components.AlertDestructive, Icon: icon, Title: "Unable to delete project", Description: "Remove any release configurations that still use this project first.", } -components.Alert(canvas, theme, plainBounds, plainData) -components.Alert(canvas, theme, dangerBounds, dangerData)`, PageSnippet: `look := c.Theme() -ui.Column(c).Gap(16).Children(func() { - ui.Row(c).FillWidth().Pad(14).Gap(10).Items(ui.Start). - Background(look.Card).Border(1, look.Border). - Radius(look.Metrics.RadiusSurface).Children(func() { - ui.Icon(c, m.infoIcon).Size(16, 16).Color(look.CardForeground) - ui.Column(c).Grow(1).Gap(2).Children(func() { - ui.Text(c, "Sync complete").Weight(gfx.WeightMedium).Color(look.CardForeground) - ui.Text(c, "All local changes are safely on disk. The remote host confirmed the final write, so you can close the session safely."). - FontSize(look.Metrics.FontSizeM).Muted() - }) - }) - ui.Row(c).FillWidth().Pad(14).Gap(10).Items(ui.Start). - Background(look.Card).Border(1, look.Border). - Radius(look.Metrics.RadiusSurface).Children(func() { - ui.Icon(c, m.alertIcon).Size(16, 16).Color(look.Danger) - ui.Column(c).Grow(1).Gap(2).Children(func() { - ui.Text(c, "Unable to delete project").Weight(gfx.WeightMedium).Color(look.Danger) - ui.Text(c, "Remove any release configurations that still use this project first."). - FontSize(look.Metrics.FontSizeM).Color(look.Danger) - }) - }) -})`, PageSnippetZh: `look := c.Theme() -ui.Column(c).Gap(16).Children(func() { - ui.Row(c).FillWidth().Pad(14).Gap(10).Items(ui.Start). - Background(look.Card).Border(1, look.Border). - Radius(look.Metrics.RadiusSurface).Children(func() { - ui.Icon(c, m.infoIcon).Size(16, 16).Color(look.CardForeground) - ui.Column(c).Grow(1).Gap(2).Children(func() { - ui.Text(c, "同步已完成").Weight(gfx.WeightMedium).Color(look.CardForeground) - ui.Text(c, "所有本地更改都已安全写入磁盘。远端主机确认了最后一次写入,可以放心关闭会话。"). - FontSize(look.Metrics.FontSizeM).Muted() - }) - }) - ui.Row(c).FillWidth().Pad(14).Gap(10).Items(ui.Start). - Background(look.Card).Border(1, look.Border). - Radius(look.Metrics.RadiusSurface).Children(func() { - ui.Icon(c, m.alertIcon).Size(16, 16).Color(look.Danger) - ui.Column(c).Grow(1).Gap(2).Children(func() { - ui.Text(c, "无法删除项目").Weight(gfx.WeightMedium).Color(look.Danger) - ui.Text(c, "请先移除仍在使用该项目的发布配置。"). - FontSize(look.Metrics.FontSizeM).Color(look.Danger) - }) - }) -})`}, +components.Alert(canvas, theme, bounds, dangerData)`, PageSnippet: `m.notice.View(c, alert.Spec{ + Status: ui.StatusDanger, + Title: "Unable to delete project", + Description: "Remove any release configurations that still use this project first.", +}).FillWidth()`, PageSnippetZh: `m.notice.View(c, alert.Spec{ + Status: ui.StatusDanger, + Title: "Unable to delete project", + Description: "Remove any release configurations that still use this project first.", +}).FillWidth()`}, + {ID: "actions", Title: "操作、关闭与横幅", Description: "Action 与 Closable 给提示条加按钮,关闭后保持关闭;Banner 去掉圆角与侧边框,用于页面顶部。", Snippet: `// A page control only: the canvas recipe has no buttons. +// See PageSnippet.`, PageSnippet: `m.notice.View(c, alert.Spec{ + Status: ui.StatusWarning, + Title: "Host key changed", + Action: "Review", + Closable: true, +}).FillWidth() +if m.notice.ActionClicked() { + // the user pressed Review +} +m.offline.View(c, alert.Spec{Status: ui.StatusDanger, Title: "Offline", Banner: true}).FillWidth()`, PageSnippetZh: `m.notice.View(c, alert.Spec{ + Status: ui.StatusWarning, + Title: "Host key changed", + Action: "Review", + Closable: true, +}).FillWidth() +if m.notice.ActionClicked() { + // 用户点了 Review +} +m.offline.View(c, alert.Spec{Status: ui.StatusDanger, Title: "Offline", Banner: true}).FillWidth()`}, }, } -func (state *State) paintAlert(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - plainData := components.AlertData{ - Icon: infoIcon, - Title: state.Text("同步已完成", "Sync complete"), - Description: state.Text("所有本地更改都已安全写入磁盘。远端主机确认了最后一次写入,可以放心关闭会话。", "All local changes are safely on disk. The remote host confirmed the final write, so you can close the session safely."), +type alertDemo struct { + notices [4]*alert.Alert + banner *alert.Alert +} + +var alertDemos = map[*State]*alertDemo{} + +func alertDemoFor(state *State) *alertDemo { + if demo := alertDemos[state]; demo != nil { + return demo } - dangerData := components.AlertData{ - Variant: components.AlertDestructive, Icon: alertIcon, Title: state.Text("无法删除项目", "Unable to delete project"), - Description: state.Text("请先移除仍在使用该项目的发布配置。", "Remove any release configurations that still use this project first."), + demo := &alertDemo{banner: alert.New()} + for i := range demo.notices { + demo.notices[i] = alert.New() } - var plain, destructive ui.Box - variants := state.exampleID == "variants" - // The page column is at most 560 wide inside 24 of padding. - contentWidth := min(float32(560), size.Width-48) + alertDemos[state] = demo + return demo +} + +func (state *State) paintAlert(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := alertDemoFor(state) + close := state.Text("关闭", "Close") state.drawPage(canvas, theme, size, 560, state.Text("Alert · 明确反馈", "Alert · Clear feedback"), func(c ui.C) { - plain = ui.Slot(c).FillWidth().Height(components.AlertHeight(canvas, theme, contentWidth, plainData)) - if variants { - destructive = ui.Slot(c).FillWidth().Height(components.AlertHeight(canvas, theme, contentWidth, dangerData)) + switch state.exampleID { + case "variants": + demo.notices[0].View(c, alert.Spec{Title: state.Text("同步已完成", "Sync complete"), Description: state.Text("所有本地更改都已安全写入磁盘。", "All local changes are safely on disk.")}).FillWidth() + demo.notices[1].View(c, alert.Spec{Status: ui.StatusSuccess, Title: state.Text("已保存", "Saved"), Description: state.Text("所有更改已写入主机。", "All changes were written to the host.")}).FillWidth() + demo.notices[2].View(c, alert.Spec{Status: ui.StatusWarning, Title: state.Text("主机密钥已变更", "Host key changed"), Description: state.Text("连接前请先核对。", "Review it before you connect.")}).FillWidth() + demo.notices[3].View(c, alert.Spec{Status: ui.StatusDanger, Title: state.Text("无法删除项目", "Unable to delete project"), Description: state.Text("请先移除仍在使用该项目的发布配置。", "Remove any release configurations that still use this project first.")}).FillWidth() + case "actions": + demo.notices[0].View(c, alert.Spec{Status: ui.StatusWarning, Title: state.Text("主机密钥已变更", "Host key changed"), Description: state.Text("build-01 的密钥与你信任的不一致。", "The key of build-01 differs from the one you trusted."), Action: state.Text("核对", "Review"), Closable: true, CloseLabel: close}).FillWidth() + demo.banner.View(c, alert.Spec{Status: ui.StatusDanger, Title: state.Text("已离线:更改将稍后同步", "Offline: changes will sync later"), Banner: true}).FillWidth() + default: + demo.notices[0].View(c, alert.Spec{Title: state.Text("同步已完成", "Sync complete"), Description: state.Text("所有本地更改都已安全写入磁盘。远端主机确认了最后一次写入,可以放心关闭会话。", "All local changes are safely on disk. The remote host confirmed the final write, so you can close the session safely.")}).FillWidth() } }) - components.Alert(canvas, theme, plain.Rect(), plainData) - if variants { - components.Alert(canvas, theme, destructive.Rect(), dangerData) - } } diff --git a/internal/componentdemo/anchor.go b/internal/componentdemo/anchor.go new file mode 100644 index 000000000..64959eb92 --- /dev/null +++ b/internal/componentdemo/anchor.go @@ -0,0 +1,59 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/anchor" +) + +var anchorComponent = Component{ + ID: "anchor", Title: "Anchor", Category: "Navigation", Summary: "锚点:长页面的目录,侧边竖线标出当前所在章节。", + Source: "ui/anchor/anchor.go", paint: (*State).paintAnchor, + Examples: []Example{ + {ID: "default", Title: "页内目录", Description: "点击链接由页面滚动到对应章节,并告诉控件哪一节是当前的;Level 缩进嵌套标题。", Snippet: `m.toc = anchor.New() +m.toc.View(c, "On this page", anchor.Spec{Items: m.sections, Active: m.section}) +if i, ok := m.toc.Clicked(); ok { + m.section = i + // scroll the page to m.sections[i] +}`, PageSnippet: `m.toc = anchor.New() +m.toc.View(c, "On this page", anchor.Spec{Items: m.sections, Active: m.section}) +if i, ok := m.toc.Clicked(); ok { + m.section = i + // scroll the page to m.sections[i] +}`, PageSnippetZh: `m.toc = anchor.New() +m.toc.View(c, "On this page", anchor.Spec{Items: m.sections, Active: m.section}) +if i, ok := m.toc.Clicked(); ok { + m.section = i + // 把页面滚动到 m.sections[i] +}`}, + }, +} + +type anchorDemo struct { + toc *anchor.Anchor + items []anchor.Item + active int +} + +var anchorDemos = map[*State]*anchorDemo{} + +func anchorDemoFor(state *State) *anchorDemo { + if demo := anchorDemos[state]; demo != nil { + return demo + } + demo := &anchorDemo{toc: anchor.New(), items: []anchor.Item{ + {Title: "Overview"}, {Title: "Install"}, {Title: "From source", Level: 1}, {Title: "From a package", Level: 1}, {Title: "Usage"}, {Title: "License"}, + }, active: 1} + anchorDemos[state] = demo + return demo +} + +func (state *State) paintAnchor(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := anchorDemoFor(state) + state.drawPage(canvas, theme, size, 280, state.Text("Anchor · 锚点", "Anchor"), func(c ui.C) { + demo.toc.View(c, state.Text("本页内容", "On this page"), anchor.Spec{Items: demo.items, Active: demo.active}).FillWidth() + if i, ok := demo.toc.Clicked(); ok { + demo.active = i + } + }) +} diff --git a/internal/componentdemo/breadcrumb.go b/internal/componentdemo/breadcrumb.go index 88149a3c6..1b1dadbcb 100644 --- a/internal/componentdemo/breadcrumb.go +++ b/internal/componentdemo/breadcrumb.go @@ -3,11 +3,13 @@ package componentdemo import ( "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/breadcrumb" ) var breadcrumbComponent = Component{ ID: "breadcrumb", Title: "Breadcrumb", Category: "Navigation", Summary: "带链接、省略项和当前位置的层级导航。", - paint: (*State).paintBreadcrumb, + paint: (*State).paintBreadcrumb, + PageSource: "ui/breadcrumb/breadcrumb.go", Examples: []Example{ {ID: "default", Title: "项目路径", Description: "链接动作由调用方持有,末项仅表示当前位置。", Snippet: `links := tree.Sub(page, tree.Name("link")) breadcrumb := components.BeginBreadcrumb(canvas, theme, trail.Rect()) @@ -16,148 +18,72 @@ breadcrumb.AddLink(links.At(1), "Viva") breadcrumb.AddCurrent("Preview") if index, ok := canvas.ClickedIn(links); ok { selected = int32(index + 1) -}`, PageSnippet: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - first := ui.Text(c, "Workspace").Muted().Hit(ui.ID(c), "Workspace") - if first.Clicked() { - m.parent = 0 - } - ui.Text(c, "›").Muted() - parent := ui.Text(c, "Viva").Muted().Hit(ui.ID(c), "Viva") - if parent.Clicked() { - m.parent = 1 - } - ui.Text(c, "›").Muted() - ui.Text(c, "Preview") -}) -caption := "Choose a parent path to go back." -if m.parent == 0 { - caption = "Selected: Workspace" -} -if m.parent == 1 { - caption = "Selected: Parent" -} -ui.Text(c, caption). - FontSize(c.Theme().Metrics.FontSizeS).Muted()`, PageSnippetZh: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - first := ui.Text(c, "工作区").Muted().Hit(ui.ID(c), "工作区") - if first.Clicked() { - m.parent = 0 - } - ui.Text(c, "›").Muted() - parent := ui.Text(c, "Viva").Muted().Hit(ui.ID(c), "Viva") - if parent.Clicked() { - m.parent = 1 - } - ui.Text(c, "›").Muted() - ui.Text(c, "预览") -}) -caption := "选择上级路径以返回。" -if m.parent == 0 { - caption = "已选择:工作区" -} -if m.parent == 1 { - caption = "已选择:上一级" -} -ui.Text(c, caption). - FontSize(c.Theme().Metrics.FontSizeS).Muted()`}, - {ID: "overflow", Title: "折叠路径", Description: "长层级使用省略项保持紧凑。", Snippet: `links := tree.Sub(page, tree.Name("link")) +}`, PageSnippet: `m.path = breadcrumb.New() +// m.places is a []breadcrumb.Item kept in the model. +m.path.View(c, "Location", breadcrumb.Spec{Items: m.places}) +if i, ok := m.path.Clicked(); ok { + m.goTo(i) +}`, PageSnippetZh: `m.path = breadcrumb.New() +// m.places 是保存在模型里的 []breadcrumb.Item。 +m.path.View(c, "Location", breadcrumb.Spec{Items: m.places}) +if i, ok := m.path.Clicked(); ok { + m.goTo(i) +}`}, + {ID: "overflow", Title: "折叠路径", Description: "Max 把中间的层级收进省略号,点开菜单选择。", Snippet: `links := tree.Sub(page, tree.Name("link")) breadcrumb := components.BeginBreadcrumb(canvas, theme, trail.Rect()) breadcrumb.AddLink(links.At(0), "Workspace") breadcrumb.AddEllipsis(tree.ID(page, "more")) breadcrumb.AddLink(links.At(1), "Components") -breadcrumb.AddCurrent("Breadcrumb")`, PageSnippet: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - first := ui.Text(c, "Workspace").Muted().Hit(ui.ID(c), "Workspace") - if first.Clicked() { - m.parent = 0 - } - ui.Text(c, "›").Muted() - ui.Text(c, "…").Muted() - ui.Text(c, "›").Muted() - parent := ui.Text(c, "Components").Muted().Hit(ui.ID(c), "Components") - if parent.Clicked() { - m.parent = 1 - } - ui.Text(c, "›").Muted() - ui.Text(c, "Breadcrumb") -}) -caption := "Choose a parent path to go back." -if m.parent == 0 { - caption = "Selected: Workspace" -} -if m.parent == 1 { - caption = "Selected: Parent" -} -ui.Text(c, caption). - FontSize(c.Theme().Metrics.FontSizeS).Muted()`, PageSnippetZh: `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - first := ui.Text(c, "工作区").Muted().Hit(ui.ID(c), "工作区") - if first.Clicked() { - m.parent = 0 - } - ui.Text(c, "›").Muted() - ui.Text(c, "…").Muted() - ui.Text(c, "›").Muted() - parent := ui.Text(c, "组件").Muted().Hit(ui.ID(c), "组件") - if parent.Clicked() { - m.parent = 1 - } - ui.Text(c, "›").Muted() - ui.Text(c, "Breadcrumb") -}) -caption := "选择上级路径以返回。" -if m.parent == 0 { - caption = "已选择:工作区" -} -if m.parent == 1 { - caption = "已选择:上一级" -} -ui.Text(c, caption). - FontSize(c.Theme().Metrics.FontSizeS).Muted()`}, +breadcrumb.AddCurrent("Breadcrumb")`, PageSnippet: `m.path.View(c, "Location", breadcrumb.Spec{ + Items: m.places, + Max: 3, +})`, PageSnippetZh: `m.path.View(c, "Location", breadcrumb.Spec{ + Items: m.places, + Max: 3, +})`}, }, } -var ( - breadcrumbUI = tree.Feature("breadcrumb") - // breadcrumbLink's item i is the i-th link of the path. - breadcrumbLink = tree.Sub(breadcrumbUI, tree.Name("link")) -) +type breadcrumbDemo struct { + path *breadcrumb.Breadcrumb + places []breadcrumb.Item +} + +var breadcrumbDemos = map[*State]*breadcrumbDemo{} + +func breadcrumbDemoFor(state *State) *breadcrumbDemo { + if demo := breadcrumbDemos[state]; demo != nil { + return demo + } + demo := &breadcrumbDemo{path: breadcrumb.New(), places: []breadcrumb.Item{ + {Label: state.Text("工作区", "Workspace")}, {Label: state.Text("项目", "Projects")}, {Label: state.Text("组件", "Components")}, + {Label: "Viva"}, {Label: state.Text("预览", "Preview")}, + }} + breadcrumbDemos[state] = demo + return demo +} func (state *State) paintBreadcrumb(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := breadcrumbDemoFor(state) caption := state.Text("选择上级路径以返回。", "Choose a parent path to go back.") switch state.values[0] { case 1: - caption = state.Text("已选择:工作区", "Selected: Workspace") + caption = state.Text("已选择:", "Selected: ") + demo.places[0].Label case 2: - caption = state.Text("已选择:上一级", "Selected: Parent") + caption = state.Text("已选择:", "Selected: ") + demo.places[len(demo.places)-2].Label + } + spec := breadcrumb.Spec{Items: demo.places, MoreLabel: state.Text("更多", "More")} + if state.exampleID == "overflow" { + spec.Max = 3 } - workspace := state.Text("工作区", "Workspace") - components := state.Text("组件", "Components") - viva := "Viva" - preview := state.Text("预览", "Preview") - overflow := state.exampleID == "overflow" state.drawPage(canvas, theme, size, 620, state.Text("Breadcrumb · 当前上下文", "Breadcrumb · Current context"), func(c ui.C) { - ui.Row(c).Gap(6).Items(ui.Center).Children(func() { - link := ui.Text(c, workspace).Muted().Hit(breadcrumbLink.At(0), workspace) - if link.Clicked() { + demo.path.View(c, state.Text("位置", "Location"), spec) + if i, ok := demo.path.Clicked(); ok { + state.values[0] = 2 + if i == 0 { state.values[0] = 1 } - ui.Text(c, "›").Muted() - if overflow { - ui.Text(c, "…").Muted() - ui.Text(c, "›").Muted() - link = ui.Text(c, components).Muted().Hit(breadcrumbLink.At(1), components) - if link.Clicked() { - state.values[0] = 2 - } - ui.Text(c, "›").Muted() - ui.Text(c, "Breadcrumb") - } else { - link = ui.Text(c, viva).Muted().Hit(breadcrumbLink.At(1), viva) - if link.Clicked() { - state.values[0] = 2 - } - ui.Text(c, "›").Muted() - ui.Text(c, preview) - } - }) + } ui.Text(c, caption).FontSize(theme.Metrics.FontSizeS).Muted() }) } diff --git a/internal/componentdemo/card.go b/internal/componentdemo/card.go index d499fc375..c14053834 100644 --- a/internal/componentdemo/card.go +++ b/internal/componentdemo/card.go @@ -3,11 +3,12 @@ package componentdemo import ( "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/card" ) var cardComponent = Component{ ID: "card", Title: "Card", Category: "Layout", Summary: "调用方布局内容、生产组件提供统一表面与间距。", - paint: (*State).paintCard, + PageSource: "ui/card/card.go", paint: (*State).paintCard, Examples: []Example{ {ID: "default", Title: "项目摘要", Description: "默认卡片承载标题、指标和页脚。", Snippet: `size := components.CardSizeDefault ring := theme.Foreground @@ -20,36 +21,24 @@ ui.Column(c).FillWidth().Pad(components.CardSpacing(theme, size)).Gap(8). ui.Text(c, "0").FontSize(28).Bold() ui.Divider(c) ui.Text(c, "Measured locally").FontSize(theme.Metrics.FontSizeS).Muted() - })`, PageSnippet: `look := c.Theme() -ring := look.Foreground -ring.Alpha *= 0.10 -ui.Column(c).FillWidth().Pad(24).Gap(8). - Background(look.Card).Border(1, ring). - Radius(look.Metrics.RadiusSurface + 4).Shadow(gfx.ShadowXS).Children(func() { - ui.Text(c, "Native preview").FontSize(look.Metrics.FontSizeM + 2). - Weight(gfx.WeightSemibold) - ui.Text(c, "Keeps scene nodes and repaints only when content changes."). - FontSize(look.Metrics.FontSizeS).Muted() - ui.Text(c, "0").FontSize(28).Bold() - ui.Text(c, "idle GPU submissions").FontSize(look.Metrics.FontSizeS).Muted() - ui.Divider(c) - ui.Text(c, "Measured locally").FontSize(look.Metrics.FontSizeS).Muted() - })`, PageSnippetZh: `look := c.Theme() -ring := look.Foreground -ring.Alpha *= 0.10 -ui.Column(c).FillWidth().Pad(24).Gap(8). - Background(look.Card).Border(1, ring). - Radius(look.Metrics.RadiusSurface + 4).Shadow(gfx.ShadowXS).Children(func() { - ui.Text(c, "Native preview").FontSize(look.Metrics.FontSizeM + 2). - Weight(gfx.WeightSemibold) - ui.Text(c, "保留场景节点,只在内容变化时重绘。"). - FontSize(look.Metrics.FontSizeS).Muted() - ui.Text(c, "0").FontSize(28).Bold() - ui.Text(c, "idle GPU submissions").FontSize(look.Metrics.FontSizeS).Muted() - ui.Divider(c) - ui.Text(c, "Measured locally").FontSize(look.Metrics.FontSizeS).Muted() - })`}, - {ID: "compact", Title: "紧凑卡片", Description: "小尺寸使用生产 CardSpacing 缩减内边距。", Snippet: `size := components.CardSizeSmall + })`, PageSnippet: `card.View(c, card.Spec{ + Title: "Native preview", + Description: "Keeps scene nodes and repaints only when content changes.", + FooterBorder: true, + Footer: func() { ui.Text(c, "Measured locally").Muted() }, +}, func() { + ui.Text(c, "0").FontSize(28).Bold() + ui.Text(c, "idle GPU submissions").Muted() +}).FillWidth()`, PageSnippetZh: `card.View(c, card.Spec{ + Title: "Native preview", + Description: "Keeps scene nodes and repaints only when content changes.", + FooterBorder: true, + Footer: func() { ui.Text(c, "Measured locally").Muted() }, +}, func() { + ui.Text(c, "0").FontSize(28).Bold() + ui.Text(c, "idle GPU submissions").Muted() +}).FillWidth()`}, + {ID: "compact", Title: "紧凑卡片", Description: "Size: Small 缩减内边距与间距。", Snippet: `size := components.CardSizeSmall ring := theme.Foreground ring.Alpha *= 0.10 ui.Column(c).FillWidth().Pad(components.CardSpacing(theme, size)).Gap(8). @@ -58,54 +47,65 @@ ui.Column(c).FillWidth().Pad(components.CardSpacing(theme, size)).Gap(8). ui.Text(c, "Native preview").FontSize(theme.Metrics.FontSizeM). Weight(gfx.WeightSemibold) ui.Text(c, "Measured locally").FontSize(theme.Metrics.FontSizeS).Muted() - })`, PageSnippet: `look := c.Theme() -ring := look.Foreground -ring.Alpha *= 0.10 -ui.Column(c).FillWidth().Pad(16).Gap(8). - Background(look.Card).Border(1, ring). - Radius(look.Metrics.RadiusSurface + 4).Shadow(gfx.ShadowXS).Children(func() { - ui.Text(c, "Native preview").FontSize(look.Metrics.FontSizeM). - Weight(gfx.WeightSemibold) - ui.Text(c, "Keeps scene nodes and repaints only when content changes."). - FontSize(look.Metrics.FontSizeS).Muted() - ui.Text(c, "0").FontSize(28).Bold() - ui.Text(c, "idle GPU submissions").FontSize(look.Metrics.FontSizeS).Muted() - ui.Divider(c) - ui.Text(c, "Measured locally").FontSize(look.Metrics.FontSizeS).Muted() - })`, PageSnippetZh: `look := c.Theme() -ring := look.Foreground -ring.Alpha *= 0.10 -ui.Column(c).FillWidth().Pad(16).Gap(8). - Background(look.Card).Border(1, ring). - Radius(look.Metrics.RadiusSurface + 4).Shadow(gfx.ShadowXS).Children(func() { - ui.Text(c, "Native preview").FontSize(look.Metrics.FontSizeM). - Weight(gfx.WeightSemibold) - ui.Text(c, "保留场景节点,只在内容变化时重绘。"). - FontSize(look.Metrics.FontSizeS).Muted() - ui.Text(c, "0").FontSize(28).Bold() - ui.Text(c, "idle GPU submissions").FontSize(look.Metrics.FontSizeS).Muted() - ui.Divider(c) - ui.Text(c, "Measured locally").FontSize(look.Metrics.FontSizeS).Muted() - })`}, + })`, PageSnippet: `card.View(c, card.Spec{ + Title: "Native preview", + Description: "Keeps scene nodes and repaints only when content changes.", + Size: card.Small, + FooterBorder: true, + Footer: func() { ui.Text(c, "Measured locally").Muted() }, +}, func() { + ui.Text(c, "0").FontSize(28).Bold() + ui.Text(c, "idle GPU submissions").Muted() +}).FillWidth()`, PageSnippetZh: `card.View(c, card.Spec{ + Title: "Native preview", + Description: "Keeps scene nodes and repaints only when content changes.", + Size: card.Small, + FooterBorder: true, + Footer: func() { ui.Text(c, "Measured locally").Muted() }, +}, func() { + ui.Text(c, "0").FontSize(28).Bold() + ui.Text(c, "idle GPU submissions").Muted() +}).FillWidth()`}, }, } +// cardDemo keeps the closures the card calls, made once: a closure made in each +// paint allocates in each paint. +type cardDemo struct { + c ui.C + theme *gfx.Theme + footer func() + body func() +} + +var cardDemos = map[*State]*cardDemo{} + +func cardDemoFor(state *State) *cardDemo { + if demo := cardDemos[state]; demo != nil { + return demo + } + demo := &cardDemo{} + demo.footer = func() { ui.Text(demo.c, "Measured locally").FontSize(demo.theme.Metrics.FontSizeS).Muted() } + demo.body = func() { + ui.Text(demo.c, "0").FontSize(28).Bold() + ui.Text(demo.c, "idle GPU submissions").FontSize(demo.theme.Metrics.FontSizeS).Muted() + } + cardDemos[state] = demo + return demo +} + func (state *State) paintCard(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - padding := float32(24) + demo := cardDemoFor(state) + spec := card.Spec{ + Title: "Native preview", + Description: state.Text("保留场景节点,只在内容变化时重绘。", "Keeps scene nodes and repaints only when content changes."), + FooterBorder: true, Footer: demo.footer, + } if state.exampleID == "compact" { - padding = 16 + spec.Size = card.Small } - ring := theme.Foreground - ring.Alpha *= 0.10 state.drawPage(canvas, theme, size, 520, state.Text("Card · 项目摘要", "Card · Project summary"), func(c ui.C) { - ui.Column(c).FillWidth().Pad(padding).Gap(8). - Background(theme.Card).Border(1, ring).Radius(theme.Metrics.RadiusSurface + 4).Shadow(gfx.ShadowXS).Children(func() { - ui.Text(c, "Native preview").FontSize(theme.Metrics.FontSizeM + 2).Weight(gfx.WeightSemibold) - ui.Text(c, state.Text("保留场景节点,只在内容变化时重绘。", "Keeps scene nodes and repaints only when content changes.")).FontSize(theme.Metrics.FontSizeS).Muted() - ui.Text(c, "0").FontSize(28).Bold() - ui.Text(c, "idle GPU submissions").FontSize(theme.Metrics.FontSizeS).Muted() - ui.Divider(c) - ui.Text(c, "Measured locally").FontSize(theme.Metrics.FontSizeS).Muted() - }) + demo.c, demo.theme = c, c.Theme() + card.View(c, spec, demo.body).FillWidth() }) } diff --git a/internal/componentdemo/catalog_a_test.go b/internal/componentdemo/catalog_a_test.go index 9a0f995c6..0d6e0c41a 100644 --- a/internal/componentdemo/catalog_a_test.go +++ b/internal/componentdemo/catalog_a_test.go @@ -154,7 +154,7 @@ func TestGroupAClicksChangeCallerState(t *testing.T) { {"alert-dialog", "default", alertDialogAction, "", func(s *State) bool { return !s.alertOpen }}, {"alert-dialog", "media", alertDialogCancel, "", func(s *State) bool { return !s.alertOpen }}, {"attachment", "default", attachmentItem.At(0), "", func(s *State) bool { return s.values[0] == 1 }}, - {"breadcrumb", "default", breadcrumbLink.At(0), "", func(s *State) bool { return s.values[0] == 1 }}, + {"breadcrumb", "default", gfx.ID{}, "工作区", func(s *State) bool { return s.values[0] == 1 }}, {"bubble", "conversation", bubbleReaction, "", func(s *State) bool { return s.flags == 1 }}, {"button-group", "horizontal", buttonGroupItem.At(2), "", func(s *State) bool { return s.values[0] == 2 }}, {"calendar", "month", calendarNext, "", func(s *State) bool { return s.values[0] == 1 }}, diff --git a/internal/componentdemo/catalog_d.go b/internal/componentdemo/catalog_d.go new file mode 100644 index 000000000..d804d5ed0 --- /dev/null +++ b/internal/componentdemo/catalog_d.go @@ -0,0 +1,30 @@ +package componentdemo + +// groupDComponents are the controls modeled on a component library's menu of +// forms and data displays: opt-in page packages made of the page's own +// primitives, so they have no canvas recipe in package components. +var groupDComponents = []Component{ + selectGroupsComponent, + progressRingComponent, + sliderMarksComponent, + expandableTextComponent, + labeledDividerComponent, + popconfirmComponent, + editableTabsComponent, + resultComponent, + tagComponent, + datePickerComponent, + descriptionsComponent, + inputNumberComponent, + rateComponent, + stepsComponent, + timePickerComponent, + timelineComponent, + transferComponent, + uploadComponent, + anchorComponent, + commentComponent, + imagePreviewComponent, + mentionsComponent, + tourComponent, +} diff --git a/internal/componentdemo/comment.go b/internal/componentdemo/comment.go new file mode 100644 index 000000000..5ff22e413 --- /dev/null +++ b/internal/componentdemo/comment.go @@ -0,0 +1,74 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/avatar" + "github.com/vivaui/viva/ui/comment" +) + +var commentComponent = Component{ + ID: "comment", Title: "Comment", Category: "Data Display", Summary: "评论:头像、作者与时间、正文、操作按钮和嵌套回复。", + Source: "ui/comment/comment.go", paint: (*State).paintComment, + Examples: []Example{ + {ID: "default", Title: "带回复的评论", Description: "操作是页面自己的按钮,回复是页面在 Replies 里继续声明的评论,任意深度都是同一个函数。", Snippet: `comment.View(c, comment.Spec{ + Avatar: &m.avatar, Author: "Ada", Time: "2h ago", Content: "Looks good to me.", + Actions: m.actions, // declares the Reply and Like buttons + Replies: m.replies, // declares comments in turn +}).FillWidth()`, PageSnippet: `comment.View(c, comment.Spec{ + Avatar: &m.avatar, Author: "Ada", Time: "2h ago", Content: "Looks good to me.", + Actions: m.actions, // declares the Reply and Like buttons + Replies: m.replies, // declares comments in turn +}).FillWidth()`, PageSnippetZh: `comment.View(c, comment.Spec{ + Avatar: &m.avatar, Author: "Ada", Time: "2h ago", Content: "Looks good to me.", + Actions: m.actions, // 声明“回复”“赞”按钮 + Replies: m.replies, // 继续声明回复的评论 +}).FillWidth()`}, + }, +} + +type commentDemo struct { + avatars [2]*avatar.State + liked int + c ui.C + state *State + actions func() + reply func() +} + +var commentDemos = map[*State]*commentDemo{} + +func commentDemoFor(state *State) *commentDemo { + if demo := commentDemos[state]; demo != nil { + return demo + } + demo := &commentDemo{state: state} + demo.avatars[0] = avatar.New().Initials("AL") + demo.avatars[1] = avatar.New().Initials("GH") + demo.actions = func() { + ui.Button(demo.c, state.Text("回复", "Reply")).Ghost().Small() + if ui.Button(demo.c, state.Text("赞", "Like")).Ghost().Small().Clicked() { + demo.liked++ + } + } + demo.reply = func() { + comment.View(demo.c, comment.Spec{ + Avatar: demo.avatars[1], Author: "Grace", Time: state.Text("1 小时前", "1h ago"), + Content: state.Text("同意,合并前再补一条测试就好。", "Agreed. One more test before it merges and it is good."), + }).FillWidth() + } + commentDemos[state] = demo + return demo +} + +func (state *State) paintComment(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := commentDemoFor(state) + state.drawPage(canvas, theme, size, 520, state.Text("Comment · 评论", "Comment"), func(c ui.C) { + demo.c = c + comment.View(c, comment.Spec{ + Avatar: demo.avatars[0], Author: "Ada", Time: state.Text("2 小时前", "2h ago"), + Content: state.Text("这个改动把重复的接线收进了一个组件,读起来清楚多了。", "This change folds the repeated wiring into one component, and it reads much clearer."), + Actions: demo.actions, Replies: demo.reply, + }).FillWidth() + }) +} diff --git a/internal/componentdemo/date_picker.go b/internal/componentdemo/date_picker.go new file mode 100644 index 000000000..e4da1f77f --- /dev/null +++ b/internal/componentdemo/date_picker.go @@ -0,0 +1,86 @@ +package componentdemo + +import ( + "time" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/datepicker" +) + +var datePickerComponent = Component{ + ID: "date-picker", Title: "Date Picker", Category: "Forms", Summary: "选择日期:按钮显示日期,点开月历选取,支持范围限制与键盘。", + Source: "ui/datepicker/datepicker.go", paint: (*State).paintDatePicker, + Examples: []Example{ + {ID: "default", Title: "选择日期", Description: "月历打开在已选日期(没有时是今天);方向键移动,PageUp/PageDown 换月,回车选择。", Snippet: `m.due = datepicker.New().Placeholder("Pick a date") +// in the page: +m.due.View(c, "Due date", &m.dueDate).Width(220) +if m.due.Changed() { + // m.dueDate holds the chosen day +}`, PageSnippet: `m.due = datepicker.New().Placeholder("Pick a date") +// in the page: +m.due.View(c, "Due date", &m.dueDate).Width(220) +if m.due.Changed() { + // m.dueDate holds the chosen day +}`, PageSnippetZh: `m.due = datepicker.New().Placeholder("Pick a date") +// 在页面中: +m.due.View(c, "Due date", &m.dueDate).Width(220) +if m.due.Changed() { + // m.dueDate 是选中的日期 +}`}, + {ID: "range", Title: "限制范围", Description: "Min 与 Max 之外的日期变暗且不能选;FirstWeekday 设置每周起始日。", Snippet: `m.start = datepicker.New(). + Min(time.Now()). + Max(time.Now().AddDate(0, 1, 0)). + FirstWeekday(time.Monday)`, PageSnippet: `m.start = datepicker.New(). + Min(time.Now()). + Max(time.Now().AddDate(0, 1, 0)). + FirstWeekday(time.Monday)`, PageSnippetZh: `m.start = datepicker.New(). + Min(time.Now()). + Max(time.Now().AddDate(0, 1, 0)). + FirstWeekday(time.Monday)`}, + }, +} + +type datePickerDemo struct { + due, window *datepicker.DatePicker + a, b time.Time +} + +var datePickerDemos = map[*State]*datePickerDemo{} + +func datePickerDemoFor(state *State) *datePickerDemo { + if demo := datePickerDemos[state]; demo != nil { + return demo + } + // A fixed day keeps the previews the same whenever they are looked at. + today := time.Date(2026, 11, 25, 9, 0, 0, 0, time.Local) + clock := func() time.Time { return today } + demo := &datePickerDemo{ + due: datepicker.New().Clock(clock).Placeholder(state.Text("选择日期", "Pick a date")), + window: datepicker.New().Clock(clock).Placeholder(state.Text("选择日期", "Pick a date")). + Min(today).Max(today.AddDate(0, 1, 0)).FirstWeekday(time.Monday), + a: time.Date(2026, 11, 18, 0, 0, 0, 0, time.Local), + } + if !state.english { + labels := datepicker.Labels{ + Months: [12]string{"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"}, + Weekdays: [7]string{"日", "一", "二", "三", "四", "五", "六"}, + Previous: "上个月", Next: "下个月", + } + demo.due.Labels(labels) + demo.window.Labels(labels) + } + datePickerDemos[state] = demo + return demo +} + +func (state *State) paintDatePicker(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := datePickerDemoFor(state) + state.drawPage(canvas, theme, size, 360, state.Text("Date Picker · 日期", "Date Picker"), func(c ui.C) { + if state.exampleID == "range" { + demo.window.View(c, state.Text("开始日期", "Start date"), &demo.b).Width(220) + return + } + demo.due.View(c, state.Text("截止日期", "Due date"), &demo.a).Width(220) + }) +} diff --git a/internal/componentdemo/descriptions.go b/internal/componentdemo/descriptions.go new file mode 100644 index 000000000..9388903e1 --- /dev/null +++ b/internal/componentdemo/descriptions.go @@ -0,0 +1,81 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/descriptions" +) + +var descriptionsComponent = Component{ + ID: "descriptions", Title: "Descriptions", Category: "Data Display", Summary: "带标签的键值列表:按列排布,可带边框、纵向或紧凑。", + Source: "ui/descriptions/descriptions.go", paint: (*State).paintDescriptions, + Examples: []Example{ + {ID: "default", Title: "详情列表", Description: "标签在前、值在后,每行按列数排布,跨列的条目占多列。", Snippet: `// m.details is a []descriptions.Item kept in the model. +descriptions.View(c, "Host details", descriptions.Spec{ + Title: "Host details", + Items: m.details, + LabelWidth: 72, +}).FillWidth()`, PageSnippet: `// m.details is a []descriptions.Item kept in the model. +descriptions.View(c, "Host details", descriptions.Spec{ + Title: "Host details", + Items: m.details, + LabelWidth: 72, +}).FillWidth()`, PageSnippetZh: `// m.details 是保存在模型里的 []descriptions.Item。 +descriptions.View(c, "Host details", descriptions.Spec{ + Title: "Host details", + Items: m.details, + LabelWidth: 72, +}).FillWidth()`}, + {ID: "bordered", Title: "带边框", Description: "表格样式,标签单元着色;Vertical 把标签放在值上方。", Snippet: `descriptions.View(c, "Host details", descriptions.Spec{ + Items: m.details, + Columns: 2, + Bordered: true, + LabelWidth: 96, +}).FillWidth()`, PageSnippet: `descriptions.View(c, "Host details", descriptions.Spec{ + Items: m.details, + Columns: 2, + Bordered: true, + LabelWidth: 96, +}).FillWidth()`, PageSnippetZh: `descriptions.View(c, "Host details", descriptions.Spec{ + Items: m.details, + Columns: 2, + Bordered: true, + LabelWidth: 96, +}).FillWidth()`}, + }, +} + +type descriptionsDemo struct { + items []descriptions.Item +} + +var descriptionsDemos = map[*State]*descriptionsDemo{} + +func descriptionsDemoFor(state *State) *descriptionsDemo { + if demo := descriptionsDemos[state]; demo != nil { + return demo + } + demo := &descriptionsDemo{items: []descriptions.Item{ + {Label: state.Text("主机", "Host"), Value: "build-01.example.com"}, + {Label: state.Text("端口", "Port"), Value: "22"}, + {Label: state.Text("用户", "User"), Value: "deploy"}, + {Label: state.Text("密钥", "Key"), Value: "ed25519 · SHA256:4kQ…9aZ", Span: 2}, + {Label: state.Text("跳板机", "Jump host"), Value: "bastion.example.com"}, + {Label: state.Text("备注", "Notes"), Value: state.Text("夜间构建机,02:00 窗口内请勿重启。", "Nightly build agent. Do not reboot during the 02:00 window."), Span: 3}, + }} + descriptionsDemos[state] = demo + return demo +} + +func (state *State) paintDescriptions(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := descriptionsDemoFor(state) + state.drawPage(canvas, theme, size, 680, state.Text("Descriptions · 详情", "Descriptions · Details"), func(c ui.C) { + title := state.Text("主机详情", "Host details") + if state.exampleID == "bordered" { + descriptions.View(c, title, descriptions.Spec{Items: demo.items, Columns: 2, Bordered: true, LabelWidth: 96}).FillWidth() + descriptions.View(c, title, descriptions.Spec{Items: demo.items, Vertical: true, Size: descriptions.Small}).FillWidth() + return + } + descriptions.View(c, title, descriptions.Spec{Title: title, Items: demo.items, LabelWidth: 72}).FillWidth() + }) +} diff --git a/internal/componentdemo/editable_tabs.go b/internal/componentdemo/editable_tabs.go new file mode 100644 index 000000000..72ff8b3a7 --- /dev/null +++ b/internal/componentdemo/editable_tabs.go @@ -0,0 +1,93 @@ +package componentdemo + +import ( + "strconv" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/editabletabs" +) + +var editableTabsComponent = Component{ + ID: "editable-tabs", Title: "Editable Tabs", Category: "Navigation", Summary: "可关闭、可新增、可滚动的标签条,如编辑器或终端的标签。", + Source: "ui/editabletabs/editabletabs.go", paint: (*State).paintEditableTabs, + Examples: []Example{ + {ID: "default", Title: "关闭与新增", Description: "标签宽度随标题;点 × 或中键、Delete 关闭,+ 新增。控件只报告,标签由页面持有;固定的标签没有关闭按钮。", Snippet: `m.strip = editabletabs.New() +// m.tabs is a []editabletabs.Tab kept in the model. +m.strip.View(c, "Sessions", &m.active, editabletabs.Spec{Tabs: m.tabs, Addable: true}).FillWidth() +if i, ok := m.strip.Closed(); ok { + m.closeTab(i) +} +if m.strip.Added() { + m.openTab() +}`, PageSnippet: `m.strip = editabletabs.New() +// m.tabs is a []editabletabs.Tab kept in the model. +m.strip.View(c, "Sessions", &m.active, editabletabs.Spec{Tabs: m.tabs, Addable: true}).FillWidth() +if i, ok := m.strip.Closed(); ok { + m.closeTab(i) +} +if m.strip.Added() { + m.openTab() +}`, PageSnippetZh: `m.strip = editabletabs.New() +// m.tabs 是保存在模型里的 []editabletabs.Tab。 +m.strip.View(c, "Sessions", &m.active, editabletabs.Spec{Tabs: m.tabs, Addable: true}).FillWidth() +if i, ok := m.strip.Closed(); ok { + m.closeTab(i) +} +if m.strip.Added() { + m.openTab() +}`}, + {ID: "overflow", Title: "溢出滚动", Description: "标签条比空间长时用滚轮滚动,并保持当前标签可见。", Snippet: `editabletabs.Spec{Tabs: m.tabs} // wheel scrolls; the active tab stays in view`, PageSnippet: `editabletabs.Spec{Tabs: m.tabs} // wheel scrolls; the active tab stays in view`, PageSnippetZh: `editabletabs.Spec{Tabs: m.tabs} // wheel scrolls; the active tab stays in view`}, + }, +} + +type editableTabsDemo struct { + strip *editabletabs.EditableTabs + tabs []editabletabs.Tab + active int + serial int +} + +var editableTabsDemos = map[*State]*editableTabsDemo{} + +func editableTabsDemoFor(state *State) *editableTabsDemo { + if demo := editableTabsDemos[state]; demo != nil { + return demo + } + demo := &editableTabsDemo{strip: editabletabs.New(), active: 1, serial: 3, tabs: []editabletabs.Tab{ + {Title: "build-01", Pinned: true}, {Title: "db-primary"}, {Title: "staging"}, + }} + if state.exampleID == "overflow" { + demo.tabs = append(demo.tabs, editabletabs.Tab{Title: "bastion"}, editabletabs.Tab{Title: "monitor"}, editabletabs.Tab{Title: "cache-01"}, editabletabs.Tab{Title: "queue"}) + demo.active = 6 + } + editableTabsDemos[state] = demo + return demo +} + +func (state *State) paintEditableTabs(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := editableTabsDemoFor(state) + spec := editabletabs.Spec{Tabs: demo.tabs, Addable: state.exampleID != "overflow", CloseLabel: state.Text("关闭", "Close"), AddLabel: state.Text("新增标签", "Add tab")} + state.drawPage(canvas, theme, size, 560, state.Text("Editable Tabs · 标签条", "Editable Tabs"), func(c ui.C) { + strip := demo.strip.View(c, state.Text("会话", "Sessions"), &demo.active, spec) + if state.exampleID == "overflow" { + strip.Width(320) + } else { + strip.FillWidth() + } + if i, ok := demo.strip.Closed(); ok { + demo.tabs = append(demo.tabs[:i], demo.tabs[i+1:]...) + if demo.active >= i { + demo.active = max(demo.active-1, 0) + } + } + if demo.strip.Added() { + demo.serial++ + demo.tabs = append(demo.tabs, editabletabs.Tab{Title: state.Text("会话 ", "session ") + strconv.Itoa(demo.serial)}) + demo.active = len(demo.tabs) - 1 + } + if len(demo.tabs) > 0 { + ui.Text(c, demo.tabs[min(demo.active, len(demo.tabs)-1)].Title).Muted() + } + }) +} diff --git a/internal/componentdemo/empty.go b/internal/componentdemo/empty.go index 77fbda084..d28a7930c 100644 --- a/internal/componentdemo/empty.go +++ b/internal/componentdemo/empty.go @@ -3,11 +3,12 @@ package componentdemo import ( "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/empty" ) var emptyComponent = Component{ ID: "empty", Title: "Empty", Category: "Feedback", Summary: "无数据时的居中图形、标题与说明。", - paint: (*State).paintEmpty, + PageSource: "ui/empty/empty.go", paint: (*State).paintEmpty, Examples: []Example{ {ID: "default", Title: "无项目", Description: "图标直接绘制在标题上方,下方留出放按钮的内容区。", Snippet: `data := components.EmptyData{ Icon: icon, Title: "No projects yet", @@ -15,56 +16,71 @@ var emptyComponent = Component{ } content := components.Empty(canvas, theme, bounds, data) components.BeginButton(canvas, theme, tree.ID(page, "create"), gfx.Rect{Height: content.Height}). - SizeToFit("Create project").CenterIn(content).Default("Create project")`, PageSnippet: `ui.Column(c).Fill().Center().Gap(6).Children(func() { - ui.Icon(c, m.folderIcon).Size(40, 40).Muted() - ui.Text(c, "No projects yet").FontSize(18).Bold() - ui.Text(c, "Create a project to get started.").FontSize(13).Muted() + SizeToFit("Create project").CenterIn(content).Default("Create project")`, PageSnippet: `empty.View(c, empty.Spec{ + Icon: m.folderIcon, + Title: "No projects yet", + Description: "Create a project to get started.", +}, func() { ui.Button(c, "Create project") -})`, PageSnippetZh: `ui.Column(c).Fill().Center().Gap(6).Children(func() { - ui.Icon(c, m.folderIcon).Size(40, 40).Muted() - ui.Text(c, "No projects yet").FontSize(18).Bold() - ui.Text(c, "Create a project to get started.").FontSize(13).Muted() +}).Fill()`, PageSnippetZh: `empty.View(c, empty.Spec{ + Icon: m.folderIcon, + Title: "No projects yet", + Description: "Create a project to get started.", +}, func() { ui.Button(c, "Create project") -})`}, - {ID: "icon", Title: "图标容器", Description: "带弱化图标背景的空状态。", Snippet: `data := components.EmptyData{ +}).Fill()`}, + {ID: "icon", Title: "图标容器", Description: "Boxed 把图标放进弱化的圆角方块。", Snippet: `data := components.EmptyData{ Media: components.EmptyMediaIcon, Icon: icon, Title: "No projects yet", Description: "Create a project to get started.", ContentHeight: 32, } content := components.Empty(canvas, theme, bounds, data) components.BeginButton(canvas, theme, tree.ID(page, "create"), gfx.Rect{Height: content.Height}). - SizeToFit("Create project").CenterIn(content).Default("Create project")`, PageSnippet: `ui.Column(c).Fill().Center().Gap(6).Children(func() { - ui.Column(c).Size(56, 56).Center().Radius(28).Background(c.Theme().Muted).Children(func() { - ui.Icon(c, m.folderIcon).Size(24, 24).Muted() - }) - ui.Text(c, "No projects yet").FontSize(18).Bold() - ui.Text(c, "Create a project to get started.").FontSize(13).Muted() + SizeToFit("Create project").CenterIn(content).Default("Create project")`, PageSnippet: `empty.View(c, empty.Spec{ + Icon: m.folderIcon, + Boxed: true, + Title: "No projects yet", + Description: "Create a project to get started.", +}, func() { ui.Button(c, "Create project") -})`, PageSnippetZh: `ui.Column(c).Fill().Center().Gap(6).Children(func() { - ui.Column(c).Size(56, 56).Center().Radius(28).Background(c.Theme().Muted).Children(func() { - ui.Icon(c, m.folderIcon).Size(24, 24).Muted() - }) - ui.Text(c, "No projects yet").FontSize(18).Bold() - ui.Text(c, "Create a project to get started.").FontSize(13).Muted() +}).Fill()`, PageSnippetZh: `empty.View(c, empty.Spec{ + Icon: m.folderIcon, + Boxed: true, + Title: "No projects yet", + Description: "Create a project to get started.", +}, func() { ui.Button(c, "Create project") -})`}, +}).Fill()`}, }, } +// emptyDemo keeps the closure the state calls for its actions, made once. +type emptyDemo struct { + c ui.C + actions func() +} + +var emptyDemos = map[*State]*emptyDemo{} + +func emptyDemoFor(state *State) *emptyDemo { + if demo := emptyDemos[state]; demo != nil { + return demo + } + demo := &emptyDemo{} + demo.actions = func() { ui.Button(demo.c, state.Text("创建项目", "Create project")) } + emptyDemos[state] = demo + return demo +} + func (state *State) paintEmpty(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { - icon := state.exampleID == "icon" + demo := emptyDemoFor(state) + spec := empty.Spec{ + Icon: folderIcon, Boxed: state.exampleID == "icon", + Title: state.Text("还没有项目", "No projects yet"), + Description: state.Text("创建一个项目即可开始。", "Create a project to get started."), + } state.drawStage(canvas, theme, size, func(c ui.C) { - ui.Column(c).Fill().Center().Gap(6).Children(func() { - if icon { - ui.Column(c).Size(56, 56).Center().Radius(28).Background(theme.Muted).Children(func() { - ui.Icon(c, folderIcon).Size(24, 24).Muted() - }) - } else { - ui.Icon(c, folderIcon).Size(40, 40).Muted() - } - ui.Text(c, "No projects yet").FontSize(18).Bold() - ui.Text(c, "Create a project to get started.").FontSize(13).Muted() - ui.Button(c, "Create project") - }) + demo.c = c + empty.View(c, spec, demo.actions).Fill() }) } diff --git a/internal/componentdemo/expandable_text.go b/internal/componentdemo/expandable_text.go new file mode 100644 index 000000000..8553759a8 --- /dev/null +++ b/internal/componentdemo/expandable_text.go @@ -0,0 +1,60 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/typography" +) + +var expandableTextComponent = Component{ + ID: "expandable-text", Title: "Expandable Text", Category: "Display", Summary: "裁成几行并可展开、可复制的文字。", + Source: "ui/typography/typography.go", paint: (*State).paintExpandableText, + Examples: []Example{ + {ID: "default", Title: "展开与复制", Description: "超过 Rows 行时以省略号结尾,Expandable 加“展开”按钮(Copyable 还会加一个把完整文本放进剪贴板的按钮,这里不演示);是否被裁剪由上一次绘制的宽度判断。", Snippet: `m.about = typography.New() +// in the page: +m.about.View(c, m.description, typography.Spec{Rows: 3, Expandable: true, Copyable: true}).FillWidth() +if m.about.Copied() { + // the text went to the clipboard +}`, PageSnippet: `m.about = typography.New() +// in the page: +m.about.View(c, m.description, typography.Spec{Rows: 3, Expandable: true, Copyable: true}).FillWidth() +if m.about.Copied() { + // the text went to the clipboard +}`, PageSnippetZh: `m.about = typography.New() +// 在页面中: +m.about.View(c, m.description, typography.Spec{Rows: 3, Expandable: true, Copyable: true}).FillWidth() +if m.about.Copied() { + // 文本已放进剪贴板 +}`}, + }, +} + +type expandableTextDemo struct { + text *typography.Text + content string +} + +var expandableTextDemos = map[*State]*expandableTextDemo{} + +func expandableTextDemoFor(state *State) *expandableTextDemo { + if demo := expandableTextDemos[state]; demo != nil { + return demo + } + demo := &expandableTextDemo{text: typography.New(), content: state.Text( + "Viva 保留场景节点,只在内容变化时重绘;空闲的应用不会调度帧、定时器或后台工作。组件声明与布局辅助函数在预热后不分配内存,并由签入的基准测试约束。这一段故意写得比三行更长,用来演示被裁剪的文字如何展开。", + "Viva keeps scene nodes and repaints only when content changes; an idle application schedules no frames, timers or background work. Component declarations and layout helpers allocate nothing once warm, and a checked-in benchmark holds them to it. This paragraph is longer than three lines on purpose, to show how a cut text expands.")} + expandableTextDemos[state] = demo + return demo +} + +func (state *State) paintExpandableText(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := expandableTextDemoFor(state) + // The copy button is not declared here: the demo tests press every control, and a press writes + // the system clipboard, which a test must not do. + spec := typography.Spec{Rows: 3, Expandable: true, Labels: typography.Labels{ + More: state.Text("展开", "More"), Less: state.Text("收起", "Less"), Copy: state.Text("复制", "Copy"), + }} + state.drawPage(canvas, theme, size, 480, state.Text("Text · 展开与复制", "Expandable Text"), func(c ui.C) { + demo.text.View(c, demo.content, spec).FillWidth() + }) +} diff --git a/internal/componentdemo/field.go b/internal/componentdemo/field.go index 39dc1984e..e52fbeec7 100644 --- a/internal/componentdemo/field.go +++ b/internal/componentdemo/field.go @@ -113,7 +113,7 @@ func (state *State) paintField(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Siz } } ui.FormField(c, form, "Work email").Children(func() { - ui.TextFieldID(c, fieldInput, field, "Work email", "").ReadOnly(!state.editing) + ui.TextField(c, field, "Work email", "", ui.WithID(fieldInput)).ReadOnly(!state.editing) }) }) } diff --git a/internal/componentdemo/form.go b/internal/componentdemo/form.go index f0f0b2dcd..f0baf08fa 100644 --- a/internal/componentdemo/form.go +++ b/internal/componentdemo/form.go @@ -128,7 +128,7 @@ func (state *State) paintForm(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size } } ui.FormField(c, form, "Username").Children(func() { - ui.TextFieldID(c, formInput, field, "Username", "").ReadOnly(!state.editing) + ui.TextField(c, field, "Username", "", ui.WithID(formInput)).ReadOnly(!state.editing) }) }) } diff --git a/internal/componentdemo/image_preview.go b/internal/componentdemo/image_preview.go new file mode 100644 index 000000000..0dfac641c --- /dev/null +++ b/internal/componentdemo/image_preview.go @@ -0,0 +1,62 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/image" + "github.com/vivaui/viva/ui/imagepreview" +) + +var imagePreviewComponent = Component{ + ID: "image-preview", Title: "Image Preview", Category: "Data Display", Summary: "图片预览:点缩略图打开对话框,缩放、适应、实际大小,拖动平移。", + initialize: (*State).initializeImageView, Source: "ui/imagepreview/imagepreview.go", paint: (*State).paintImagePreview, + Examples: []Example{ + {ID: "default", Title: "缩略图与预览", Description: "缩略图是页面自己的控件,按下时调用 Open;滚轮、+ 和 - 缩放,0 回到适应,拖动平移,Esc 关闭。", Snippet: `m.preview = imagepreview.New() +// when the thumbnail is pressed: +if m.thumbnail.Clicked() { + m.preview.Open() +} +m.preview.View(c, imagepreview.Spec{Bitmap: m.bitmap, Title: "Screenshot"})`, PageSnippet: `m.preview = imagepreview.New() +// when the thumbnail is pressed: +if m.thumbnail.Clicked() { + m.preview.Open() +} +m.preview.View(c, imagepreview.Spec{Bitmap: m.bitmap, Title: "Screenshot"})`, PageSnippetZh: `m.preview = imagepreview.New() +// 按下缩略图时: +if m.thumbnail.Clicked() { + m.preview.Open() +} +m.preview.View(c, imagepreview.Spec{Bitmap: m.bitmap, Title: "Screenshot"})`}, + }, +} + +type imagePreviewDemo struct { + preview *imagepreview.Preview + thumbnail image.State +} + +var imagePreviewDemos = map[*State]*imagePreviewDemo{} + +func imagePreviewDemoFor(state *State) *imagePreviewDemo { + if demo := imagePreviewDemos[state]; demo != nil { + return demo + } + demo := &imagePreviewDemo{preview: imagepreview.New()} + imagePreviewDemos[state] = demo + return demo +} + +func (state *State) paintImagePreview(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := imagePreviewDemoFor(state) + state.drawPage(canvas, theme, size, 520, state.Text("Image Preview · 图片预览", "Image Preview"), func(c ui.C) { + demo.thumbnail.Reset().Bitmap(*state.imageBitmap).Fit() + image.View(c, state.Text("缩略图", "Thumbnail"), &demo.thumbnail).Size(160, 100) + if demo.thumbnail.Clicked() { + demo.preview.Open() + } + demo.preview.View(c, imagepreview.Spec{ + Bitmap: *state.imageBitmap, Title: state.Text("图片预览", "Image preview"), Width: 440, Height: 260, + Labels: [4]string{state.Text("缩小", "Zoom out"), state.Text("放大", "Zoom in"), state.Text("适应", "Fit"), state.Text("实际大小", "Actual size")}, + }) + }) +} diff --git a/internal/componentdemo/input.go b/internal/componentdemo/input.go index cbb56f96f..6f8d36906 100644 --- a/internal/componentdemo/input.go +++ b/internal/componentdemo/input.go @@ -37,9 +37,9 @@ components.PaintInput(canvas, theme, field.Rect(), components.InputSnapshot{ Placeholder: "name@example.com", Invalid: invalid, })`, PageSnippet: `// m.email starts as "not-an-email". m.email.Invalid = !strings.Contains(m.email.Text(), "@") -ui.TextFieldID(c, ui.ID(c), &m.email, "Email", "name@example.com")`, PageSnippetZh: `// m.email 初始为 "not-an-email"。 +ui.TextField(c, &m.email, "Email", "name@example.com", ui.WithID(ui.ID(c)))`, PageSnippetZh: `// m.email 初始为 "not-an-email"。 m.email.Invalid = !strings.Contains(m.email.Text(), "@") -ui.TextFieldID(c, ui.ID(c), &m.email, "Email", "name@example.com")`}, +ui.TextField(c, &m.email, "Email", "name@example.com", ui.WithID(ui.ID(c)))`}, {ID: "states", Title: "禁用与只读", Description: "两个固定文本样本均不向平台 provider 暴露 Editor。", Snippet: `disabled := ui.Slot(c).FillWidth().Height(theme.Metrics.ControlHeight) components.PaintInput(canvas, theme, disabled.Rect(), components.InputSnapshot{ ID: disabledID, Label: "Disabled", @@ -195,7 +195,7 @@ func (state *State) paintInputPage(canvas *gfx.Canvas, theme gfx.Theme, size gfx ui.Text(c, mode).FontSize(theme.Metrics.FontSizeS).Muted() ui.Column(c).Gap(6).Children(func() { ui.Text(c, label).FontSize(theme.Metrics.FontSizeM) - ui.TextFieldID(c, inputEditable, field, label, placeholder).ReadOnly(!state.editing) + ui.TextField(c, field, label, placeholder, ui.WithID(inputEditable)).ReadOnly(!state.editing) }) ui.Text(c, captionText).FontSize(theme.Metrics.FontSizeS).Muted() }) @@ -213,11 +213,11 @@ func (state *State) paintInputStates(canvas *gfx.Canvas, theme gfx.Theme, size g ui.Text(c, mode).FontSize(theme.Metrics.FontSizeS).Muted() ui.Column(c).Gap(6).Children(func() { ui.Text(c, "Disabled").FontSize(theme.Metrics.FontSizeM) - ui.TextFieldID(c, inputDisabled, disabled, "Disabled", "") + ui.TextField(c, disabled, "Disabled", "", ui.WithID(inputDisabled)) }) ui.Column(c).Gap(6).Children(func() { ui.Text(c, "Read-only").FontSize(theme.Metrics.FontSizeM) - ui.TextFieldID(c, inputReadOnly, readOnly, "Read-only", "").ReadOnly(true) + ui.TextField(c, readOnly, "Read-only", "", ui.WithID(inputReadOnly)).ReadOnly(true) }) ui.Text(c, state.Text("禁用与只读字段均不连接编辑器。", "Disabled and read-only fields do not connect an editor.")). FontSize(theme.Metrics.FontSizeS).Muted() @@ -263,16 +263,16 @@ func (state *State) paintCustomInputs(canvas *gfx.Canvas, theme gfx.Theme, size ui.Text(c, mode).FontSize(theme.Metrics.FontSizeS).Muted() ui.Column(c).Gap(6).Children(func() { ui.Text(c, "RadiusFull · 16").FontSize(theme.Metrics.FontSizeM) - ui.TextFieldID(c, inputEditable, pill, "Pill", state.Text("输入中文或 English…", "Type in Chinese or English…")). + ui.TextField(c, pill, "Pill", state.Text("输入中文或 English…", "Type in Chinese or English…"), ui.WithID(inputEditable)). FontSize(16).Radius(gfx.RadiusFull).ReadOnly(!state.editing) }) ui.Column(c).Gap(6).Children(func() { ui.Text(c, "Radius 2 · 12").FontSize(theme.Metrics.FontSizeM) - ui.TextFieldID(c, inputSquare, square, "Square", "").FontSize(12).Radius(2).ReadOnly(true) + ui.TextField(c, square, "Square", "", ui.WithID(inputSquare)).FontSize(12).Radius(2).ReadOnly(true) }) ui.Column(c).Gap(6).Children(func() { ui.Text(c, "Theme").FontSize(theme.Metrics.FontSizeM) - ui.TextFieldID(c, inputPlain, plain, "Theme", "").ReadOnly(true) + ui.TextField(c, plain, "Theme", "", ui.WithID(inputPlain)).ReadOnly(true) }) }) } diff --git a/internal/componentdemo/input_number.go b/internal/componentdemo/input_number.go new file mode 100644 index 000000000..4e2567857 --- /dev/null +++ b/internal/componentdemo/input_number.go @@ -0,0 +1,91 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/inputnumber" +) + +var inputNumberComponent = Component{ + ID: "input-number", Title: "Input Number", Category: "Forms", Summary: "数字输入:两侧按钮与方向键步进,范围与小数位可配。", + Source: "ui/inputnumber/inputnumber.go", paint: (*State).paintInputNumber, initialize: (*State).initializeInputNumber, + editable: func(exampleID string) (editableField, bool) { + return editableField{ID: inputNumberField, Initial: inputNumberInitial(exampleID)}, true + }, + Examples: []Example{ + {ID: "default", Title: "带范围的数字", Description: "输入数字后回车或失焦生效,超出范围会被夹回;上下键步进,PageUp/PageDown 十倍。", Snippet: `m.port = inputnumber.New().Min(1).Max(65535) +// in the page: +m.port.View(c, "Port", &m.portValue).Width(180) +if m.port.Changed() { + // m.portValue holds the new number +}`, PageSnippet: `m.port = inputnumber.New().Min(1).Max(65535) +// in the page: +m.port.View(c, "Port", &m.portValue).Width(180) +if m.port.Changed() { + // m.portValue holds the new number +}`, PageSnippetZh: `m.port = inputnumber.New().Min(1).Max(65535) +// 在页面中: +m.port.View(c, "Port", &m.portValue).Width(180) +if m.port.Changed() { + // m.portValue 已经是新的数字 +}`}, + {ID: "decimals", Title: "小数与只读", Description: "小数位跟随步长;ReadOnly 只展示数字。", Snippet: `m.opacity = inputnumber.New().Step(0.1).Min(0).Max(1) +m.total = inputnumber.New().ReadOnly()`, PageSnippet: `m.opacity = inputnumber.New().Step(0.1).Min(0).Max(1) +m.total = inputnumber.New().ReadOnly()`, PageSnippetZh: `m.opacity = inputnumber.New().Step(0.1).Min(0).Max(1) +m.total = inputnumber.New().ReadOnly()`}, + }, +} + +var ( + inputNumberUI = tree.Feature("input-number") + inputNumberField = tree.ID(inputNumberUI, "field") +) + +// inputNumberInitial is the text of the example's editable field. +func inputNumberInitial(exampleID string) string { + if exampleID == "decimals" { + return "0.5" + } + return "22" +} + +type inputNumberDemo struct { + bound bool + port, opacity, total *inputnumber.InputNumber + a, b, c float64 +} + +var inputNumberDemos = map[*State]*inputNumberDemo{} + +func inputNumberDemoFor(state *State) *inputNumberDemo { + if demo := inputNumberDemos[state]; demo != nil { + return demo + } + demo := &inputNumberDemo{ + port: inputnumber.New().Min(1).Max(65535).FieldID(inputNumberField), opacity: inputnumber.New().Step(0.1).Min(0).Max(1).FieldID(inputNumberField), total: inputnumber.New().ReadOnly(), + a: 22, b: 0.5, c: 128, + } + inputNumberDemos[state] = demo + return demo +} + +func (state *State) initializeInputNumber() { inputNumberDemoFor(state) } + +func (state *State) paintInputNumber(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := inputNumberDemoFor(state) + if state.editing && state.editor != nil && !demo.bound { + // The platform edits the example's one editable field; the number field reads + // what is typed from the same editor. + demo.bound = true + demo.port.Field().Bind(state.editor) + demo.opacity.Field().Bind(state.editor) + } + state.drawPage(canvas, theme, size, 320, state.Text("Input Number · 数字输入", "Input Number"), func(c ui.C) { + if state.exampleID == "decimals" { + demo.opacity.View(c, state.Text("不透明度", "Opacity"), &demo.b).Width(200) + demo.total.View(c, state.Text("总数", "Total"), &demo.c).Width(200) + return + } + demo.port.View(c, state.Text("端口", "Port"), &demo.a).Width(200) + }) +} diff --git a/internal/componentdemo/interaction_test.go b/internal/componentdemo/interaction_test.go index 2b1197046..947027d02 100644 --- a/internal/componentdemo/interaction_test.go +++ b/internal/componentdemo/interaction_test.go @@ -196,7 +196,13 @@ func TestEditorOnlyResolvesEditablePlatformInput(t *testing.T) { continue } editor, ok := state.Editor(hit.ID) - want := (hit.Role == gfx.RoleTextField || component.editable != nil && hit.Role == gfx.RoleCombobox) && !hit.Disabled && !hit.ReadOnly + // A combobox is a text field of the example only where the example has an + // editable field; a select in an example without one is not editable. + editableExample := false + if component.editable != nil { + _, editableExample = component.editable(example.ID) + } + want := (hit.Role == gfx.RoleTextField || editableExample && hit.Role == gfx.RoleCombobox) && !hit.Disabled && !hit.ReadOnly if ok != want || (editor != nil) != want { t.Fatalf("%s/%s: incorrect editor resolution for %+v", component.ID, example.ID, hit) } diff --git a/internal/componentdemo/label.go b/internal/componentdemo/label.go index 11db5d0d9..7c2bd0b98 100644 --- a/internal/componentdemo/label.go +++ b/internal/componentdemo/label.go @@ -18,10 +18,10 @@ components.PaintInput(canvas, theme, fieldBounds, components.InputSnapshot{ })`, PageSnippet: `emailID := ui.ID(c) ui.Text(c, "Work email").LabelFor(emailID) // m.email starts as "team@viva.dev". -ui.TextFieldID(c, emailID, &m.email, "Work email", "team@viva.dev").ReadOnly(true)`, PageSnippetZh: `emailID := ui.ID(c) +ui.TextField(c, &m.email, "Work email", "team@viva.dev", ui.WithID(emailID)).ReadOnly(true)`, PageSnippetZh: `emailID := ui.ID(c) ui.Text(c, "工作邮箱").LabelFor(emailID) // m.email 初始为 "team@viva.dev"。 -ui.TextFieldID(c, emailID, &m.email, "工作邮箱", "team@viva.dev").ReadOnly(true)`}, +ui.TextField(c, &m.email, "工作邮箱", "team@viva.dev", ui.WithID(emailID)).ReadOnly(true)`}, {ID: "states", Title: "标签状态", Description: "普通、必填和禁用状态并列。", Snippet: `components.BeginLabel(canvas, theme, normalBounds).Paint("Display name") components.BeginLabel(canvas, theme, requiredBounds).Required().Paint("Organization name") components.BeginLabel(canvas, theme, disabledBounds).Required(). @@ -49,7 +49,7 @@ func (state *State) paintLabel(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Siz label := state.Text("工作邮箱", "Work email") ui.Column(c).FillWidth().Gap(8).Children(func() { ui.Text(c, label).LabelFor(labelInput) - ui.TextFieldID(c, labelInput, email, label, "team@viva.dev").ReadOnly(true) + ui.TextField(c, email, label, "team@viva.dev", ui.WithID(labelInput)).ReadOnly(true) }) }) return diff --git a/internal/componentdemo/labeled_divider.go b/internal/componentdemo/labeled_divider.go new file mode 100644 index 000000000..a74981f54 --- /dev/null +++ b/internal/componentdemo/labeled_divider.go @@ -0,0 +1,28 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/divider" +) + +var labeledDividerComponent = Component{ + ID: "labeled-divider", Title: "Labeled Divider", Category: "Layout", Summary: "带一个词的分隔线:居中,或靠近一端。", + Source: "ui/divider/divider.go", paint: (*State).paintLabeledDivider, + Examples: []Example{ + {ID: "default", Title: "带文字的分隔线", Description: "分隔线中间或靠近一端带一个词,如两种登录方式之间的“或”。", Snippet: `divider.View(c, "or", divider.Spec{}) +divider.View(c, "Advanced", divider.Spec{Align: divider.Start})`, PageSnippet: `divider.View(c, "or", divider.Spec{}) +divider.View(c, "Advanced", divider.Spec{Align: divider.Start})`, PageSnippetZh: `divider.View(c, "or", divider.Spec{}) +divider.View(c, "Advanced", divider.Spec{Align: divider.Start})`}, + }, +} + +func (state *State) paintLabeledDivider(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + state.drawPage(canvas, theme, size, 480, state.Text("Divider · 带文字", "Divider · Labeled"), func(c ui.C) { + ui.Text(c, state.Text("使用密钥登录", "Sign in with a key")).FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightMedium) + divider.View(c, state.Text("或", "or"), divider.Spec{}) + ui.Text(c, state.Text("使用密码登录", "Sign in with a password")).FontSize(theme.Metrics.FontSizeM).Weight(gfx.WeightMedium) + divider.View(c, state.Text("高级", "Advanced"), divider.Spec{Align: divider.Start}) + ui.Text(c, state.Text("端口与代理", "Port and proxy")).FontSize(theme.Metrics.FontSizeM) + }) +} diff --git a/internal/componentdemo/main_test.go b/internal/componentdemo/main_test.go new file mode 100644 index 000000000..b9ac38fd0 --- /dev/null +++ b/internal/componentdemo/main_test.go @@ -0,0 +1,23 @@ +package componentdemo + +import ( + "fmt" + "os" + "testing" + + "github.com/vivaui/viva/app" +) + +// TestMain keeps the system out of the tests: the catalog's tests press every +// control of every example, and a driver answers the system's file picker and +// the like in place of a native dialog that nobody is there to close. +func TestMain(m *testing.M) { + driver, err := app.NewDriver(app.Config{Width: 320, Height: 240}, nil) + if err != nil { + fmt.Fprintln(os.Stderr, "componentdemo tests:", err) + os.Exit(1) + } + code := m.Run() + driver.Close() + os.Exit(code) +} diff --git a/internal/componentdemo/mentions.go b/internal/componentdemo/mentions.go new file mode 100644 index 000000000..ed5aeb76d --- /dev/null +++ b/internal/componentdemo/mentions.go @@ -0,0 +1,73 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/mentions" +) + +var mentionsComponent = Component{ + ID: "mentions", Title: "Mentions", Category: "Forms", Summary: "提及:输入 @ 后弹出候选列表,选中后写入输入框。", + Source: "ui/mentions/mentions.go", paint: (*State).paintMentions, initialize: (*State).initializeMentions, + editable: func(string) (editableField, bool) { + return editableField{ID: mentionsField, Initial: ""}, true + }, + Examples: []Example{ + {ID: "default", Title: "输入 @ 提及", Description: "在词首输入 @ 与几个字母,列表按包含关系过滤;上下键移动,回车或 Tab 选中,Esc 关闭,点选项不会夺走输入框的键盘。", Snippet: `m.mentions = mentions.New() +m.mentions.View(c, &m.message, "Message", "Write a message", mentions.Spec{Options: m.people}) +if option, ok := m.mentions.Chosen(); ok { + // the field already holds "@Ada " +}`, PageSnippet: `m.mentions = mentions.New() +m.mentions.View(c, &m.message, "Message", "Write a message", mentions.Spec{Options: m.people}) +if option, ok := m.mentions.Chosen(); ok { + // the field already holds "@Ada " +}`, PageSnippetZh: `m.mentions = mentions.New() +m.mentions.View(c, &m.message, "Message", "Write a message", mentions.Spec{Options: m.people}) +if option, ok := m.mentions.Chosen(); ok { + // 输入框里已经是 "@Ada " +}`}, + }, +} + +var ( + mentionsUI = tree.Feature("mentions") + mentionsField = tree.ID(mentionsUI, "field") +) + +type mentionsDemo struct { + bound bool + m *mentions.Mentions + field ui.Field + options []mentions.Option +} + +var mentionsDemos = map[*State]*mentionsDemo{} + +func mentionsDemoFor(state *State) *mentionsDemo { + if demo := mentionsDemos[state]; demo != nil { + return demo + } + demo := &mentionsDemo{m: mentions.New().FieldID(mentionsField), options: []mentions.Option{ + {Label: "Ada", Detail: "Engineer"}, {Label: "Grace", Detail: "Admiral"}, {Label: "Alan", Detail: "Mathematician"}, + {Label: "Linus", Detail: "Maintainer"}, {Label: "Margaret", Detail: "Director"}, + }} + mentionsDemos[state] = demo + return demo +} + +func (state *State) initializeMentions() { mentionsDemoFor(state) } + +func (state *State) paintMentions(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := mentionsDemoFor(state) + if state.editing && state.editor != nil && !demo.bound { + // The platform edits the example's one editable field; the mentions read what + // is typed from the same editor. + demo.bound = true + demo.field.Bind(state.editor) + } + state.drawPage(canvas, theme, size, 420, state.Text("Mentions · 提及", "Mentions"), func(c ui.C) { + demo.m.View(c, &demo.field, state.Text("消息", "Message"), state.Text("输入 @ 提及某人", "Type @ to mention someone"), mentions.Spec{ + Options: demo.options, Empty: state.Text("没有匹配的人", "No one matches"), + }).FillWidth() + }) +} diff --git a/internal/componentdemo/page_source.go b/internal/componentdemo/page_source.go index a8215e5c4..5e19f80f0 100644 --- a/internal/componentdemo/page_source.go +++ b/internal/componentdemo/page_source.go @@ -47,9 +47,9 @@ var pageSource = map[string]string{ "tooltip": "base/tooltip.go", "kbd": "base/leaves.go", "label": "base/elements.go", - "card": "base/box.go", + "card": "ui/card/card.go", "item": "base/box.go", - "empty": "base/box.go", + "empty": "ui/empty/empty.go", "bubble": "ui/bubble.go", "accordion": "ui/disclosure.go", "collapsible": "ui/disclosure.go", @@ -69,11 +69,11 @@ var pageSource = map[string]string{ "hover-card": "ui/hovercard/hovercard.go", "avatar-editor": "ui/avatareditor/avatareditor.go", "reorder-grid": "ui/reordergrid/reordergrid.go", - "alert": "base/box.go", + "alert": "ui/alert/alert.go", "aspect-ratio": "ui/aspectratio/aspectratio.go", "attachment": "ui/attachment/attachment.go", "avatar": "ui/avatar/avatar.go", - "breadcrumb": "base/elements.go", + "breadcrumb": "ui/breadcrumb/breadcrumb.go", "button-group": "ui/buttongroup/buttongroup.go", "command": "ui/command/command.go", "icon-hover": "base/icon_motion.go", diff --git a/internal/componentdemo/page_usage.go b/internal/componentdemo/page_usage.go index 04a15eac0..ca262e22a 100644 --- a/internal/componentdemo/page_usage.go +++ b/internal/componentdemo/page_usage.go @@ -4,39 +4,61 @@ package componentdemo // documentation site shows it above the examples; a component without an entry // is a canvas recipe, used inside ui.Control/Draw or copied by viva add. var pageUsage = map[string]string{ - "toggle-group": `m.toggleGroup.View(c, "Text alignment")`, - "empty": `ui.Column(c).Fill().Center()`, - "item": `ui.Row(c).Gap(8).FillWidth()`, - "card": `ui.Column(c).Pad(16).Radius(12).Border(1, border)`, - "label": `ui.Text(c, "Name").LabelFor(fieldID)`, - "kbd": `ui.Kbd(c, "⌘", "K")`, - "tooltip": `ui.Button(c, "Hover").Hit(id, "Hover").Tooltip("Hint")`, - "button": `ui.Button(c, "Save").Clicked()`, - "badge": `ui.Badge(c, "New")`, - "checkbox": `ui.Checkbox(c, &m.accepted, "Accept")`, - "switch": `ui.Switch(c, &m.enabled, "Enabled")`, - "input": `ui.TextField(c, &m.name, "Name", "Ada")`, - "textarea": `ui.TextArea(c, &m.notes, "Notes", "")`, - "select": `ui.Select(c, &m.choice, choices, nameOf)`, - "combobox": `ui.Combobox(c, &m.choice, choices, nameOf, "Choice")`, - "slider": `ui.Slider(c, &m.volume).Range(0, 100)`, - "tabs": `ui.Tabs(c, &m.tab, tabs, tabLabel)`, - "dialog": `ui.Dialog(c, ui.DialogSpec{Title: "Edit host", Scope: scope, DismissID: dismiss})`, - "alert-dialog": `ui.AlertDialog(c, &m.confirm, ui.AlertDialogSpec{Title: "Delete?", ActionLabel: "Delete", CancelLabel: "Cancel"})`, - "drawer": `ui.Drawer(c, &m.open, "Host", ui.DrawerSpec{Side: ui.DrawerRight}, body, footer)`, - "sheet": `ui.Drawer(c, &m.open, "Details", ui.DrawerSpec{Side: ui.DrawerRight}, body, footer)`, - "popover": `ui.PopoverWith(c, anchor, &m.open, ui.PopoverSpec{Title: "Details"}, body)`, - "dropdown-menu": `ui.Menu(c, anchor, &m.open, func(menu *ui.MenuItems) { menu.Item("Rename") })`, - "context-menu": `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { menu.Item("Delete") })`, + "select-groups": `ui.Select(c, &m.host, m.hosts, nil, ui.SelectGroups(m.groups))`, + "progress-ring": `ui.Progress(c, m.done/m.total).Circle().Size(80, 80)`, + "slider-marks": `ui.Slider(c, &m.quality).Range(0, 100).Step(25).Marks(m.marks)`, + "expandable-text": `m.about.View(c, m.description, typography.Spec{Rows: 3, Expandable: true}).FillWidth()`, + "labeled-divider": `divider.View(c, "or", divider.Spec{})`, + "popconfirm": `m.remove.View(c, trigger, popconfirm.Spec{Title: "Remove build-01?", Danger: true})`, + "editable-tabs": `m.strip.View(c, "Sessions", &m.active, editabletabs.Spec{Tabs: m.tabs, Addable: true}).FillWidth()`, + "result": `result.View(c, result.Spec{Status: ui.StatusSuccess, Title: "Done"}, nil).Fill()`, + "tag": `tag.View(c, "production", tag.Spec{Status: ui.StatusSuccess, Closable: true})`, + "steps": `steps.View(c, "Checkout", &m.step, steps.Spec{Steps: m.stages, Clickable: true})`, + "descriptions": `descriptions.View(c, "Host details", descriptions.Spec{Items: m.details, Columns: 2, Bordered: true})`, + "timeline": `timeline.View(c, "History", timeline.Spec{Items: m.events, Pending: "Waiting"})`, + "rate": `m.rate.View(c, "Rating", &m.score)`, + "input-number": `m.port.View(c, "Port", &m.portValue)`, + "date-picker": `m.due.View(c, "Due date", &m.dueDate)`, + "time-picker": `m.start.View(c, "Start", &m.startAt)`, + "transfer": `m.moves.View(c, "Hosts", transfer.Spec{Items: m.hosts})`, + "anchor": `m.toc.View(c, "On this page", anchor.Spec{Items: m.sections, Active: m.section})`, + "comment": `comment.View(c, comment.Spec{Author: "Ada", Content: text}).FillWidth()`, + "image-preview": `m.preview.View(c, imagepreview.Spec{Bitmap: m.bitmap, Title: "Screenshot"})`, + "mentions": `m.mentions.View(c, &m.message, "Message", "", mentions.Spec{Options: m.people}).FillWidth()`, + "tour": `m.tour.View(c, tour.Spec{Steps: m.steps})`, + "upload": `m.upload.View(c, "Attachments", upload.Spec{Items: m.files, Multiple: true})`, + "toggle-group": `m.toggleGroup.View(c, "Text alignment")`, + "empty": `empty.View(c, empty.Spec{Title: "No projects yet"}, nil).Fill()`, + "item": `ui.Row(c).Gap(8).FillWidth()`, + "card": `card.View(c, card.Spec{Title: "Native preview", Description: "Keeps nodes."}, func() { ui.Text(c, "0").Bold() }).FillWidth()`, + "label": `ui.Text(c, "Name").LabelFor(fieldID)`, + "kbd": `ui.Kbd(c, "⌘", "K")`, + "tooltip": `ui.Button(c, "Hover").Hit(id, "Hover").Tooltip("Hint")`, + "button": `ui.Button(c, "Save").Clicked()`, + "badge": `ui.Badge(c, "New")`, + "checkbox": `ui.Checkbox(c, &m.accepted, "Accept")`, + "switch": `ui.Switch(c, &m.enabled, "Enabled")`, + "input": `ui.TextField(c, &m.name, "Name", "Ada")`, + "textarea": `ui.TextArea(c, &m.notes, "Notes", "")`, + "select": `ui.Select(c, &m.choice, choices, nameOf)`, + "combobox": `ui.Combobox(c, &m.choice, choices, nameOf, "Choice")`, + "slider": `ui.Slider(c, &m.volume).Range(0, 100)`, + "tabs": `ui.Tabs(c, &m.tab, tabs, tabLabel)`, + "dialog": `ui.Dialog(c, ui.DialogSpec{Title: "Edit host", Scope: scope, DismissID: dismiss})`, + "alert-dialog": `ui.AlertDialog(c, &m.confirm, ui.AlertDialogSpec{Title: "Delete?", ActionLabel: "Delete", CancelLabel: "Cancel"})`, + "drawer": `ui.Drawer(c, &m.open, "Host", ui.DrawerSpec{Side: ui.DrawerRight}, body, footer)`, + "sheet": `ui.Drawer(c, &m.open, "Details", ui.DrawerSpec{Side: ui.DrawerRight}, body, footer)`, + "popover": `ui.Popover(c, anchor, &m.open, ui.PopoverSpec{Title: "Details"}, body)`, + "dropdown-menu": `ui.Menu(c, anchor, &m.open, func(menu *ui.MenuItems) { menu.Item("Rename") })`, + "context-menu": `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { menu.Item("Delete") })`, "table": `bills := ui.TableRows{ {"设计系统", "已支付", "¥ 2,400"}, {"桌面构建", "处理中", "¥ 860"}, {"性能审计", "待付款", "¥ 1,280"}, } ui.Table(c, &m.table, ui.TableSpec{ - Rows: rows, Columns: columns, - Headers: []string{"项目", "状态", "金额"}, - Source: &bills, + Rows: rows, Source: &bills, + Columns: []ui.TableColumn{{Title: "项目", Width: 112}, {Title: "状态", Width: 88}, {Title: "金额"}}, })`, "list": `ui.List(c, &m.list, len(rows), func(row ui.ListRow) { _ = row })`, "tree": `ui.Tree(c, &m.tree, len(rows), func(i int) string { return rows[i] }, func(i int) {})`, @@ -79,11 +101,11 @@ ui.Table(c, &m.table, ui.TableSpec{ "hover-card": `hovercard.View(c, "@viva-framework", &m.hoverCard)`, "avatar-editor": `m.avatarEditor.View(c, "Image crop").FillWidth().MaxWidth(440)`, "reorder-grid": `m.reorderGrid.View(c, "Host order").FillWidth().Height(220)`, - "alert": `ui.Row(c).FillWidth().Pad(14).Gap(10).Background(c.Theme().Card).Border(1, c.Theme().Border).Children(func() { ui.Text(c, "Sync complete").Bold() })`, + "alert": `m.notice.View(c, alert.Spec{Status: ui.StatusWarning, Title: "Host key changed", Closable: true}).FillWidth()`, "aspect-ratio": `aspectratio.View(c, "16:9 release preview", m.media, func() { ui.Text(c, "16:9 release preview").Muted() })`, "attachment": `m.attachment.View(c, "product-demo.mov").FillWidth()`, "avatar": `m.avatar.View(c, "Skyler").Size(64, 64)`, - "breadcrumb": `ui.Row(c).Gap(6).Items(ui.Center).Children(func() { ui.Text(c, "Workspace").Muted(); ui.Text(c, "›").Muted(); ui.Text(c, "Preview") })`, + "breadcrumb": `m.path.View(c, "Location", breadcrumb.Spec{Items: m.places, Max: 4})`, "button-group": `m.buttonGroup.View(c, "Text alignment").FillWidth()`, "command": `command.View(c, "Command", &m.command).FillWidth().Height(220)`, "icon-hover": `id := ui.ID(c); ui.Icon(c, m.moreIcon).Size(24, 24).Hit(id, "More actions").BindIconHover(ui.BindIconHover(&m.iconHover, id))`, diff --git a/internal/componentdemo/pagination.go b/internal/componentdemo/pagination.go index 2634c002b..2e041f6ab 100644 --- a/internal/componentdemo/pagination.go +++ b/internal/componentdemo/pagination.go @@ -3,11 +3,15 @@ package componentdemo import ( "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/pagination" ) var paginationComponent = Component{ ID: "pagination", Title: "Pagination", Category: "Navigation", Summary: "调用方持有当前页的紧凑分页控件。", paint: (*State).paintPagination, initialize: (*State).initializePagination, + editable: func(exampleID string) (editableField, bool) { + return editableField{ID: pagerField}, exampleID == "pager" + }, Examples: []Example{ {ID: "default", Title: "分页导航", Description: "上一页、页码与下一页共同更新当前页。", Snippet: `pages := tree.Sub(page, tree.Name("page")) pagination := components.BeginPagination(canvas, theme, bounds) @@ -41,6 +45,44 @@ ui.Pagination(c, []ui.PaginationItem{ {Kind: ui.PaginationEllipsis}, {ID: ui.ID(c), Label: "8", Kind: ui.PaginationPage}, {ID: ui.ID(c), Label: "Next", Kind: ui.PaginationNext, Disabled: page == 8}, +})`}, + {ID: "pager", Title: "总数与跳页", Description: "由 Total 自动排出页码窗口,并保持页码在范围内;输入页码后回车跳转。", Snippet: `m.pager = pagination.State{PageSize: 20} +// in the page: +pagination.View(c, "Pages", &m.pager, pagination.Spec{ + Total: len(m.rows), + ShowTotal: true, + Jumper: true, +}) +if m.pager.Changed() { + // m.pager.Page or m.pager.PageSize moved: load the rows +}`, PageSnippet: `m.pager = pagination.State{PageSize: 20} +// in the page: +pagination.View(c, "Pages", &m.pager, pagination.Spec{ + Total: len(m.rows), + ShowTotal: true, + Jumper: true, +}) +if m.pager.Changed() { + // m.pager.Page or m.pager.PageSize moved: load the rows +}`, PageSnippetZh: `m.pager = pagination.State{PageSize: 20} +// in the page: +pagination.View(c, "Pages", &m.pager, pagination.Spec{ + Total: len(m.rows), + ShowTotal: true, + Jumper: true, +}) +if m.pager.Changed() { + // m.pager.Page or m.pager.PageSize moved: load the rows +}`}, + {ID: "sizes", Title: "每页条数", Description: "改变每页条数时保持当前首行可见。", Snippet: `pagination.View(c, "Pages", &m.pager, pagination.Spec{ + Total: len(m.rows), + SizeOptions: []int{10, 20, 50}, +})`, PageSnippet: `pagination.View(c, "Pages", &m.pager, pagination.Spec{ + Total: len(m.rows), + SizeOptions: []int{10, 20, 50}, +})`, PageSnippetZh: `pagination.View(c, "Pages", &m.pager, pagination.Spec{ + Total: len(m.rows), + SizeOptions: []int{10, 20, 50}, })`}, {ID: "boundaries", Title: "边界状态", Description: "第一页禁用上一页,并保留省略号。", Snippet: `pages := tree.Sub(page, tree.Name("page")) current := int32(1) @@ -92,7 +134,49 @@ func (state *State) initializePagination() { state.values[0] = 3 } +// pagerSizes are the page sizes the example offers, made once: a slice made in +// each paint allocates in each paint. +var pagerSizes = []int{10, 20, 50} + +// pagerBound says whether the platform editor was bound to the example's jump field. +var pagerBound = map[*State]bool{} + +var pagerField = tree.ID(paginationUI, "jump") + +// pagerDemos is the state of the page-assembled example, made once. +var pagerDemos = map[*State]*pagination.State{} + +func (state *State) paintPager(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + pager := pagerDemos[state] + if pager == nil { + pager = &pagination.State{PageSize: 20, Page: 6} + pagerDemos[state] = pager + } + if state.editing && state.editor != nil && !pagerBound[state] { + // The platform edits the jump field; the pager reads what is typed from the same editor. + pagerBound[state] = true + pager.Jumper().Bind(state.editor) + } + labels := pagination.Labels{ + Previous: state.Text("上一页", "Previous"), Next: state.Text("下一页", "Next"), Total: state.Text("共", "Total"), + GoTo: state.Text("跳至页", "Go to page"), PerPage: state.Text("每页条数", "Rows per page"), + } + state.drawPage(canvas, theme, size, 760, state.Text("Pagination · 分页", "Pagination"), func(c ui.C) { + spec := pagination.Spec{Total: 235, ShowTotal: true, Labels: labels} + if state.exampleID == "sizes" { + spec.SizeOptions = pagerSizes + } else { + spec.Jumper, spec.JumperID = true, pagerField + } + pagination.View(c, state.Text("页码", "Pages"), pager, spec) + }) +} + func (state *State) paintPagination(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + if state.exampleID == "pager" || state.exampleID == "sizes" { + state.paintPager(canvas, theme, size) + return + } page := state.values[0] compact := size.Width-48 < 430 state.drawPage(canvas, theme, size, 620, "Results", func(c ui.C) { diff --git a/internal/componentdemo/popconfirm.go b/internal/componentdemo/popconfirm.go new file mode 100644 index 000000000..7f12a756c --- /dev/null +++ b/internal/componentdemo/popconfirm.go @@ -0,0 +1,83 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/popconfirm" +) + +var popconfirmComponent = Component{ + ID: "popconfirm", Title: "Popconfirm", Category: "Overlay", Summary: "挨着按钮的轻量确认:一句问题、可选说明和两个答案。", + Source: "ui/popconfirm/popconfirm.go", paint: (*State).paintPopconfirm, + Examples: []Example{ + {ID: "default", Title: "确认删除", Description: "按钮打开问题;确认或取消都会关闭,Esc 与点击外部关闭但不作答。不可撤销的后果仍应使用 AlertDialog。", Snippet: `m.remove = popconfirm.New() +// in the page: +trigger := ui.Button(c, "Remove").Outline() +if trigger.Clicked() { + m.remove.Open() +} +m.remove.View(c, trigger, popconfirm.Spec{Title: "Remove build-01?", Danger: true, OkLabel: "Remove"}) +if m.remove.Confirmed() { + m.removeHost() +}`, PageSnippet: `m.remove = popconfirm.New() +// in the page: +trigger := ui.Button(c, "Remove").Outline() +if trigger.Clicked() { + m.remove.Open() +} +m.remove.View(c, trigger, popconfirm.Spec{Title: "Remove build-01?", Danger: true, OkLabel: "Remove"}) +if m.remove.Confirmed() { + m.removeHost() +}`, PageSnippetZh: `m.remove = popconfirm.New() +// 在页面中: +trigger := ui.Button(c, "Remove").Outline() +if trigger.Clicked() { + m.remove.Open() +} +m.remove.View(c, trigger, popconfirm.Spec{Title: "Remove build-01?", Danger: true, OkLabel: "Remove"}) +if m.remove.Confirmed() { + m.removeHost() +}`}, + }, +} + +type popconfirmDemo struct { + pc *popconfirm.Popconfirm +} + +var popconfirmDemos = map[*State]*popconfirmDemo{} + +func popconfirmDemoFor(state *State) *popconfirmDemo { + if demo := popconfirmDemos[state]; demo != nil { + return demo + } + demo := &popconfirmDemo{pc: popconfirm.New()} + popconfirmDemos[state] = demo + return demo +} + +func (state *State) paintPopconfirm(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := popconfirmDemoFor(state) + spec := popconfirm.Spec{ + Title: state.Text("移除 build-01?", "Remove build-01?"), Description: state.Text("主机及其保存的设置都会被删除。", "The host and its saved settings are deleted."), + OkLabel: state.Text("移除", "Remove"), CancelLabel: state.Text("取消", "Cancel"), Danger: true, + } + state.drawPage(canvas, theme, size, 420, state.Text("Popconfirm · 轻量确认", "Popconfirm"), func(c ui.C) { + trigger := ui.Button(c, state.Text("移除主机", "Remove host")).Outline() + if trigger.Clicked() { + demo.pc.Open() + } + demo.pc.View(c, trigger, spec) + if demo.pc.Confirmed() { + state.flags = 1 + } else if demo.pc.Cancelled() { + state.flags = 2 + } + switch state.flags { + case 1: + ui.Text(c, state.Text("已确认", "Confirmed")).Muted() + case 2: + ui.Text(c, state.Text("已取消", "Cancelled")).Muted() + } + }) +} diff --git a/internal/componentdemo/popover.go b/internal/componentdemo/popover.go index bb6728b54..5ef341a9f 100644 --- a/internal/componentdemo/popover.go +++ b/internal/componentdemo/popover.go @@ -24,7 +24,7 @@ trigger := ui.Button(c, "Open details").Outline().Self(ui.Start) if trigger.Clicked() { open = !open } -ui.PopoverWith(c, trigger, &open, ui.PopoverSpec{ +ui.Popover(c, trigger, &open, ui.PopoverSpec{ Title: "Native surface", Description: "Clamped to the current viewport without timers.", Scope: m.scope, DismissID: m.dismissID, @@ -33,7 +33,7 @@ trigger := ui.Button(c, "Open details").Outline().Self(ui.Start) if trigger.Clicked() { open = !open } -ui.PopoverWith(c, trigger, &open, ui.PopoverSpec{ +ui.Popover(c, trigger, &open, ui.PopoverSpec{ Title: "Native surface", Description: "Clamped to the current viewport without timers.", Scope: m.scope, DismissID: m.dismissID, @@ -55,7 +55,7 @@ if trigger.Clicked() { open = !open } enabled := false -ui.PopoverWith(c, trigger, &open, ui.PopoverSpec{ +ui.Popover(c, trigger, &open, ui.PopoverSpec{ Title: "Build status", Description: "The stable host owns this overlay state.", Scope: m.scope, DismissID: m.dismissID, @@ -73,7 +73,7 @@ if trigger.Clicked() { open = !open } enabled := false -ui.PopoverWith(c, trigger, &open, ui.PopoverSpec{ +ui.Popover(c, trigger, &open, ui.PopoverSpec{ Title: "Build status", Description: "The stable host owns this overlay state.", Scope: m.scope, DismissID: m.dismissID, @@ -112,7 +112,7 @@ func (state *State) paintPopover(canvas *gfx.Canvas, theme gfx.Theme, size gfx.S if state.exampleID == "custom-body" { title, description = "Build status", "The stable host owns this overlay state." } - ui.PopoverWith(c, trigger, &demo.open, ui.PopoverSpec{ + ui.Popover(c, trigger, &demo.open, ui.PopoverSpec{ Title: title, Description: description, Scope: popoverScope, DismissID: popoverDismiss, }, func() { diff --git a/internal/componentdemo/progress_ring.go b/internal/componentdemo/progress_ring.go new file mode 100644 index 000000000..a68c12dac --- /dev/null +++ b/internal/componentdemo/progress_ring.go @@ -0,0 +1,35 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +var progressRingComponent = Component{ + ID: "progress-ring", Title: "Progress Ring", Category: "Feedback", Summary: "环形进度:按比例顺时针填充,可着状态色,也可无限转动。", + Source: "ui/leaves_paint.go", paint: (*State).paintProgressRing, + Examples: []Example{ + {ID: "default", Title: "环形与状态色", Description: "Segments 把进度条分成几段,前几段按比例填满;Circle 把进度条画成圆环,Status 用成功、警告、危险色填充;Indeterminate 的环不断转动,系统要求减少动效时静止。", Snippet: `ui.Progress(c, m.done/m.total).Circle().Size(80, 80) +ui.Progress(c, 1).Circle().Status(ui.StatusSuccess) +ui.Progress(c, 0).Circle().Indeterminate() +ui.Progress(c, 0.6).Segments(5)`, PageSnippet: `ui.Progress(c, m.done/m.total).Circle().Size(80, 80) +ui.Progress(c, 1).Circle().Status(ui.StatusSuccess) +ui.Progress(c, 0).Circle().Indeterminate() +ui.Progress(c, 0.6).Segments(5)`, PageSnippetZh: `ui.Progress(c, m.done/m.total).Circle().Size(80, 80) +ui.Progress(c, 1).Circle().Status(ui.StatusSuccess) +ui.Progress(c, 0).Circle().Indeterminate() +ui.Progress(c, 0.6).Segments(5)`}, + }, +} + +func (state *State) paintProgressRing(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + state.drawPage(canvas, theme, size, 480, state.Text("Progress · 环形", "Progress · Ring"), func(c ui.C) { + ui.Progress(c, 0.6).Segments(5).Label(state.Text("阶段", "Stages")) + ui.Row(c).Gap(20).Items(ui.Center).Children(func() { + ui.Progress(c, 0.25).Circle().Label(state.Text("上传", "Upload")) + ui.Progress(c, 0.7).Circle().Status(ui.StatusSuccess).Size(80, 80).Label(state.Text("同步", "Sync")) + ui.Progress(c, 0.9).Circle().Status(ui.StatusWarning).Size(48, 48).Label(state.Text("磁盘", "Disk")) + ui.Progress(c, 1).Circle().Status(ui.StatusDanger).Size(48, 48).Label(state.Text("失败", "Failed")) + }) + }) +} diff --git a/internal/componentdemo/radio_group.go b/internal/componentdemo/radio_group.go index 605f604a8..f39d39f7e 100644 --- a/internal/componentdemo/radio_group.go +++ b/internal/componentdemo/radio_group.go @@ -136,7 +136,7 @@ func (state *State) paintRadioGroup(canvas *gfx.Canvas, theme gfx.Theme, size gf } radios := func() { for index, plan := range plans { - ui.RadioID(c, radioGroupItem.At(index), &page.plan, plan, plan) + ui.Radio(c, &page.plan, plan, plan, ui.WithID(radioGroupItem.At(index))) } } if horizontal { diff --git a/internal/componentdemo/rate.go b/internal/componentdemo/rate.go new file mode 100644 index 000000000..29f98a071 --- /dev/null +++ b/internal/componentdemo/rate.go @@ -0,0 +1,65 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/rate" +) + +var rateComponent = Component{ + ID: "rate", Title: "Rate", Category: "Forms", Summary: "星级评分:点击选择,可半星、可清除,只读时仅展示。", + Source: "ui/rate/rate.go", paint: (*State).paintRate, + Examples: []Example{ + {ID: "default", Title: "星级评分", Description: "点击选择,再点已选的星清除;悬停预览,方向键调整。", Snippet: `m.rate = rate.New() +// in the page: +m.rate.View(c, "Rating", &m.score) +if m.rate.Changed() { + // m.score already holds the new score +}`, PageSnippet: `m.rate = rate.New() +// in the page: +m.rate.View(c, "Rating", &m.score) +if m.rate.Changed() { + // m.score already holds the new score +}`, PageSnippetZh: `m.rate = rate.New() +// 在页面中: +m.rate.View(c, "Rating", &m.score) +if m.rate.Changed() { + // m.score 已经是新的分数 +}`}, + {ID: "half", Title: "半星与只读", Description: "AllowHalf 支持半星;ReadOnly 只展示分数。", Snippet: `m.rate = rate.New().AllowHalf().Size(28) +m.average = rate.New().ReadOnly().Count(10).Size(16)`, PageSnippet: `m.rate = rate.New().AllowHalf().Size(28) +m.average = rate.New().ReadOnly().Count(10).Size(16)`, PageSnippetZh: `m.rate = rate.New().AllowHalf().Size(28) +m.average = rate.New().ReadOnly().Count(10).Size(16)`}, + }, +} + +type rateDemo struct { + basic, half, readOnly *rate.Rate + a, b, c float32 +} + +var rateDemos = map[*State]*rateDemo{} + +func rateDemoFor(state *State) *rateDemo { + if demo := rateDemos[state]; demo != nil { + return demo + } + demo := &rateDemo{ + basic: rate.New(), half: rate.New().AllowHalf().Size(28), readOnly: rate.New().ReadOnly().Count(10).Size(16), + a: 3, b: 3.5, c: 8, + } + rateDemos[state] = demo + return demo +} + +func (state *State) paintRate(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := rateDemoFor(state) + state.drawPage(canvas, theme, size, 420, state.Text("Rate · 评分", "Rate · Rating"), func(c ui.C) { + if state.exampleID == "half" { + demo.half.View(c, state.Text("半星评分", "Half star rating"), &demo.b) + demo.readOnly.View(c, state.Text("平均分", "Average"), &demo.c) + return + } + demo.basic.View(c, state.Text("评分", "Rating"), &demo.a) + }) +} diff --git a/internal/componentdemo/result.go b/internal/componentdemo/result.go new file mode 100644 index 000000000..be2eb54d2 --- /dev/null +++ b/internal/componentdemo/result.go @@ -0,0 +1,89 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/result" +) + +var resultComponent = Component{ + ID: "result", Title: "Result", Category: "Feedback", Summary: "任务结果页:大状态图标、标题、说明与后续操作。", + Source: "ui/result/result.go", paint: (*State).paintResult, + Examples: []Example{ + {ID: "default", Title: "成功", Description: "状态决定图标与颜色;操作区放下一步按钮。", Snippet: `result.View(c, result.Spec{ + Status: ui.StatusSuccess, + Title: "Key imported", + Description: "The key is now in your vault.", +}, func() { + ui.Button(c, "Done") +}).Fill()`, PageSnippet: `result.View(c, result.Spec{ + Status: ui.StatusSuccess, + Title: "Key imported", + Description: "The key is now in your vault.", +}, func() { + ui.Button(c, "Done") +}).Fill()`, PageSnippetZh: `result.View(c, result.Spec{ + Status: ui.StatusSuccess, + Title: "Key imported", + Description: "The key is now in your vault.", +}, func() { + ui.Button(c, "Done") +}).Fill()`}, + {ID: "failure", Title: "失败与警告", Description: "危险与警告沿用同一套 ui.Status。", Snippet: `result.View(c, result.Spec{ + Status: ui.StatusDanger, + Title: "Import failed", + Description: "The file is not a private key.", +}, func() { + ui.Button(c, "Try again") +}).Fill()`, PageSnippet: `result.View(c, result.Spec{ + Status: ui.StatusDanger, + Title: "Import failed", + Description: "The file is not a private key.", +}, func() { + ui.Button(c, "Try again") +}).Fill()`, PageSnippetZh: `result.View(c, result.Spec{ + Status: ui.StatusDanger, + Title: "Import failed", + Description: "The file is not a private key.", +}, func() { + ui.Button(c, "Try again") +}).Fill()`}, + }, +} + +// resultDemo keeps the closure the result calls for its actions, made once. +type resultDemo struct { + c ui.C + label string + actions func() +} + +var resultDemos = map[*State]*resultDemo{} + +func resultDemoFor(state *State) *resultDemo { + if demo := resultDemos[state]; demo != nil { + return demo + } + demo := &resultDemo{} + demo.actions = func() { ui.Button(demo.c, demo.label) } + resultDemos[state] = demo + return demo +} + +func (state *State) paintResult(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := resultDemoFor(state) + spec := result.Spec{ + Status: ui.StatusSuccess, Title: state.Text("密钥已导入", "Key imported"), + Description: state.Text("密钥已保存在你的保险库中。", "The key is now in your vault."), + } + demo.label = state.Text("完成", "Done") + if state.exampleID == "failure" { + spec.Status = ui.StatusDanger + spec.Title, spec.Description = state.Text("导入失败", "Import failed"), state.Text("该文件不是私钥。", "The file is not a private key.") + demo.label = state.Text("重试", "Try again") + } + state.drawStage(canvas, theme, size, func(c ui.C) { + demo.c = c + result.View(c, spec, demo.actions).Fill() + }) +} diff --git a/internal/componentdemo/select_groups.go b/internal/componentdemo/select_groups.go new file mode 100644 index 000000000..087649ff4 --- /dev/null +++ b/internal/componentdemo/select_groups.go @@ -0,0 +1,48 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +var selectGroupsComponent = Component{ + ID: "select-groups", Title: "Select Groups", Category: "Forms", Summary: "下拉列表里的分组标题行。", + Source: "base/select.go", paint: (*State).paintSelectGroups, + Examples: []Example{ + {ID: "default", Title: "分组选项", Description: "SelectGroups 在每组第一个选项前加一行标题;标题不是选项,不能聚焦、点击或类型检索,Picked、DisabledOptions 和 Icons 仍用选项自己的下标。选项须按组排序。", Snippet: `// m.groups is a []ui.SelectGroup kept in the model: +// {Label: "Recent", From: 0}, {Label: "All hosts", From: 2} +ui.Select(c, &m.host, m.hosts, nil, ui.SelectGroups(m.groups))`, PageSnippet: `// m.groups is a []ui.SelectGroup kept in the model: +// {Label: "Recent", From: 0}, {Label: "All hosts", From: 2} +ui.Select(c, &m.host, m.hosts, nil, ui.SelectGroups(m.groups))`, PageSnippetZh: `// m.groups 是保存在模型里的 []ui.SelectGroup: +// {Label: "Recent", From: 0}, {Label: "All hosts", From: 2} +ui.Select(c, &m.host, m.hosts, nil, ui.SelectGroups(m.groups))`}, + }, +} + +type selectGroupsDemo struct { + hosts []string + groups []ui.SelectGroup + host string +} + +var selectGroupsDemos = map[*State]*selectGroupsDemo{} + +func selectGroupsDemoFor(state *State) *selectGroupsDemo { + if demo := selectGroupsDemos[state]; demo != nil { + return demo + } + demo := &selectGroupsDemo{ + hosts: []string{"build-01", "db-primary", "staging", "bastion", "monitor"}, + groups: []ui.SelectGroup{{Label: state.Text("最近", "Recent"), From: 0}, {Label: state.Text("全部主机", "All hosts"), From: 2}}, + host: "staging", + } + selectGroupsDemos[state] = demo + return demo +} + +func (state *State) paintSelectGroups(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := selectGroupsDemoFor(state) + state.drawPage(canvas, theme, size, 360, state.Text("Select · 分组", "Select · Groups"), func(c ui.C) { + ui.Select(c, &demo.host, demo.hosts, nil, ui.SelectGroups(demo.groups)).Placeholder(state.Text("主机", "Host")).Width(240) + }) +} diff --git a/internal/componentdemo/slider_marks.go b/internal/componentdemo/slider_marks.go new file mode 100644 index 000000000..a1ab87dec --- /dev/null +++ b/internal/componentdemo/slider_marks.go @@ -0,0 +1,46 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +var sliderMarksComponent = Component{ + ID: "slider-marks", Title: "Slider Marks", Category: "Forms", Summary: "滑块轨道上的刻度点与文字标记。", + Source: "base/slider.go", paint: (*State).paintSliderMarks, + Examples: []Example{ + {ID: "default", Title: "带标记的滑块", Description: "Marks 在轨道上给每个值画一个点,并把文字放在下面;带文字的横向滑块会相应增高。", Snippet: `// m.marks is a []ui.SliderMark kept in the model. +ui.Slider(c, &m.quality).Range(0, 100).Step(25).Marks(m.marks)`, PageSnippet: `// m.marks is a []ui.SliderMark kept in the model. +ui.Slider(c, &m.quality).Range(0, 100).Step(25).Marks(m.marks)`, PageSnippetZh: `// m.marks 是保存在模型里的 []ui.SliderMark。 +ui.Slider(c, &m.quality).Range(0, 100).Step(25).Marks(m.marks)`}, + }, +} + +type sliderMarksDemo struct { + marks []ui.SliderMark +} + +var sliderMarksDemos = map[*State]*sliderMarksDemo{} + +func sliderMarksDemoFor(state *State) *sliderMarksDemo { + if demo := sliderMarksDemos[state]; demo != nil { + return demo + } + demo := &sliderMarksDemo{marks: []ui.SliderMark{ + {Value: 0, Label: state.Text("低", "Low")}, {Value: 25}, {Value: 50, Label: state.Text("中", "Medium")}, {Value: 75}, + {Value: 100, Label: state.Text("高", "High")}, + }} + sliderMarksDemos[state] = demo + return demo +} + +func (state *State) paintSliderMarks(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := sliderMarksDemoFor(state) + state.drawPage(canvas, theme, size, 480, state.Text("Slider · 标记", "Slider · Marks"), func(c ui.C) { + quality := ui.State[ui.SliderState](c, "quality") + if quality.Value == 0 && state.flags&1 == 0 { + quality.Value, state.flags = 50, state.flags|1 + } + ui.Slider(c, quality).Range(0, 100).Step(25).Marks(demo.marks).Label(state.Text("画质", "Quality")).FillWidth() + }) +} diff --git a/internal/componentdemo/state.go b/internal/componentdemo/state.go index 4014e85d1..3c615d796 100644 --- a/internal/componentdemo/state.go +++ b/internal/componentdemo/state.go @@ -71,11 +71,12 @@ var coreComponents = []Component{ var catalog = buildCatalog() func buildCatalog() []Component { - result := make([]Component, 0, len(coreComponents)+len(groupAComponents)+len(groupBComponents)+len(groupCComponents)) + result := make([]Component, 0, len(coreComponents)+len(groupAComponents)+len(groupBComponents)+len(groupCComponents)+len(groupDComponents)) result = append(result, coreComponents...) result = append(result, groupAComponents...) result = append(result, groupBComponents...) result = append(result, groupCComponents...) + result = append(result, groupDComponents...) for index := 1; index < len(result); index++ { for current := index; current > 0 && componentLess(result[current], result[current-1]); current-- { result[current], result[current-1] = result[current-1], result[current] diff --git a/internal/componentdemo/steps.go b/internal/componentdemo/steps.go new file mode 100644 index 000000000..302b61c85 --- /dev/null +++ b/internal/componentdemo/steps.go @@ -0,0 +1,78 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/steps" +) + +var stepsComponent = Component{ + ID: "steps", Title: "Steps", Category: "Navigation", Summary: "按顺序展示任务阶段:已完成、进行中、未开始与出错。", + Source: "ui/steps/steps.go", paint: (*State).paintSteps, + Examples: []Example{ + {ID: "default", Title: "横向步骤", Description: "已完成的步骤打勾,当前步骤高亮;可点击的步骤条用点击或键盘切换当前步骤。", Snippet: `// m.stages is a []steps.Step kept in the model. +steps.View(c, "Checkout", &m.step, steps.Spec{ + Steps: m.stages, + Clickable: true, +}).FillWidth()`, PageSnippet: `// m.stages is a []steps.Step kept in the model. +steps.View(c, "Checkout", &m.step, steps.Spec{ + Steps: m.stages, + Clickable: true, +}).FillWidth()`, PageSnippetZh: `// m.stages 是保存在模型里的 []steps.Step。 +steps.View(c, "Checkout", &m.step, steps.Spec{ + Steps: m.stages, + Clickable: true, +}).FillWidth()`}, + {ID: "vertical", Title: "纵向、圆点与出错", Description: "纵向排列,圆点标记,当前步骤失败时用危险色标出。", Snippet: `steps.View(c, "Deploy", &m.step, steps.Spec{ + Steps: m.stages, + Direction: steps.Vertical, + Type: steps.Dot, + Status: steps.Error, +})`, PageSnippet: `steps.View(c, "Deploy", &m.step, steps.Spec{ + Steps: m.stages, + Direction: steps.Vertical, + Type: steps.Dot, + Status: steps.Error, +})`, PageSnippetZh: `steps.View(c, "Deploy", &m.step, steps.Spec{ + Steps: m.stages, + Direction: steps.Vertical, + Type: steps.Dot, + Status: steps.Error, +})`}, + }, +} + +type stepsDemo struct { + stages []steps.Step + current, fail int + small int +} + +var stepsDemos = map[*State]*stepsDemo{} + +func stepsDemoFor(state *State) *stepsDemo { + if demo := stepsDemos[state]; demo != nil { + return demo + } + demo := &stepsDemo{current: 1, fail: 2, stages: []steps.Step{ + {Title: state.Text("账号", "Account"), Description: state.Text("创建登录名", "Create a login")}, + {Title: state.Text("资料", "Profile"), Description: state.Text("填写基本信息", "Tell us about you")}, + {Title: state.Text("完成", "Done")}, + }} + stepsDemos[state] = demo + return demo +} + +func (state *State) paintSteps(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := stepsDemoFor(state) + state.drawPage(canvas, theme, size, 620, state.Text("Steps · 步骤条", "Steps · Progress"), func(c ui.C) { + if state.exampleID == "vertical" { + steps.View(c, state.Text("部署", "Deploy"), &demo.fail, steps.Spec{ + Steps: demo.stages, Direction: steps.Vertical, Type: steps.Dot, Status: steps.Error, + }) + return + } + steps.View(c, state.Text("结账", "Checkout"), &demo.current, steps.Spec{Steps: demo.stages, Clickable: true}).FillWidth() + steps.View(c, state.Text("紧凑", "Compact"), &demo.current, steps.Spec{Steps: demo.stages, Size: steps.Small, Clickable: true}).FillWidth() + }) +} diff --git a/internal/componentdemo/table.go b/internal/componentdemo/table.go index 81724e9a7..75d8cb204 100644 --- a/internal/componentdemo/table.go +++ b/internal/componentdemo/table.go @@ -23,13 +23,12 @@ table.Caption("Click any data row to see its interactive feedback.")`, PageSnipp {"Performance audit", "Unpaid", "¥ 1,280"}, } columns := []style.TableColumn{ - {Width: 112, Alignment: style.TableAlignLeft}, - {Width: 88, Alignment: style.TableAlignCenter}, - {Width: 0, Alignment: style.TableAlignRight}, + {Title: "Item", Width: 112, Alignment: style.TableAlignLeft}, + {Title: "Status", Width: 88, Alignment: style.TableAlignCenter}, + {Title: "Amount", Width: 0, Alignment: style.TableAlignRight}, } ui.Table(c, &m.table, ui.TableSpec{ Columns: columns, - Headers: []string{"Item", "Status", "Amount"}, Source: &bills, }) ui.Text(c, "Total · 3 items · ¥ 4,540").Muted() @@ -39,13 +38,12 @@ ui.Text(c, "Click any data row to see its interactive feedback.").Muted()`, Page {"性能审计", "待付款", "¥ 1,280"}, } columns := []style.TableColumn{ - {Width: 112, Alignment: style.TableAlignLeft}, - {Width: 88, Alignment: style.TableAlignCenter}, - {Width: 0, Alignment: style.TableAlignRight}, + {Title: "项目", Width: 112, Alignment: style.TableAlignLeft}, + {Title: "状态", Width: 88, Alignment: style.TableAlignCenter}, + {Title: "金额", Width: 0, Alignment: style.TableAlignRight}, } ui.Table(c, &m.table, ui.TableSpec{ Columns: columns, - Headers: []string{"项目", "状态", "金额"}, Source: &bills, }) ui.Text(c, "合计 · 3 项 · ¥ 4,540").Muted() @@ -118,13 +116,12 @@ table.Caption("Item is left-aligned, status centered, amount right-aligned.")`, {"Performance audit", "Unpaid", "¥ 1,280"}, } columns := []style.TableColumn{ - {Width: 112, Alignment: style.TableAlignLeft}, - {Width: 88, Alignment: style.TableAlignCenter}, - {Alignment: style.TableAlignRight}, + {Title: "Item", Width: 112, Alignment: style.TableAlignLeft}, + {Title: "Status", Width: 88, Alignment: style.TableAlignCenter}, + {Title: "Amount", Alignment: style.TableAlignRight}, } ui.Table(c, &m.table, ui.TableSpec{ Columns: columns, - Headers: []string{"Item", "Status", "Amount"}, Source: &bills, }) ui.Text(c, "Item is left-aligned, status centered, amount right-aligned.").Muted()`, PageSnippetZh: `bills := ui.TableRows{ @@ -133,16 +130,56 @@ ui.Text(c, "Item is left-aligned, status centered, amount right-aligned.").Muted {"性能审计", "待付款", "¥ 1,280"}, } columns := []style.TableColumn{ - {Width: 112, Alignment: style.TableAlignLeft}, - {Width: 88, Alignment: style.TableAlignCenter}, - {Alignment: style.TableAlignRight}, + {Title: "项目", Width: 112, Alignment: style.TableAlignLeft}, + {Title: "状态", Width: 88, Alignment: style.TableAlignCenter}, + {Title: "金额", Alignment: style.TableAlignRight}, } ui.Table(c, &m.table, ui.TableSpec{ Columns: columns, - Headers: []string{"项目", "状态", "金额"}, Source: &bills, }) ui.Text(c, "项目左对齐,状态居中,金额右对齐。").Muted()`}, + {ID: "checked", Title: "勾选列", Description: "Checked 在最左加一列复选框,表头复选框全选或清空,部分勾选时为半选;勾选与选中行互不影响,列索引仍是 Columns 的。", Snippet: `// m.checked is a ui.Selection kept in the model: the rows ticked. +ui.Table(c, &m.table, ui.TableSpec{ + Columns: m.columns, + Source: &m.bills, + Checked: &m.checked, +}) +if m.table.CheckedChanged() { + // the user ticked or unticked a row, or the header's checkbox +} +// m.checked.Has(row) says whether a row is ticked; m.checked.Len() how many.`, PageSnippet: `// m.checked is a ui.Selection kept in the model: the rows ticked. +ui.Table(c, &m.table, ui.TableSpec{ + Columns: m.columns, + Source: &m.bills, + Checked: &m.checked, +}) +if m.table.CheckedChanged() { + // the user ticked or unticked a row, or the header's checkbox +} +// m.checked.Has(row) says whether a row is ticked; m.checked.Len() how many.`, PageSnippetZh: `// m.checked is a ui.Selection kept in the model: the rows ticked. +ui.Table(c, &m.table, ui.TableSpec{ + Columns: m.columns, + Source: &m.bills, + Checked: &m.checked, +}) +if m.table.CheckedChanged() { + // the user ticked or unticked a row, or the header's checkbox +} +// m.checked.Has(row) says whether a row is ticked; m.checked.Len() how many.`}, + {ID: "filter", Title: "列过滤按钮", Description: "Filterable 在表头末尾加漏斗按钮,Filtered 表示该列已过滤;按钮被按下时 FilterClicked 报告列,用 HeaderRect 定位应用自己的筛选菜单。", Snippet: `// m.columns has Filterable set on the Status column, and Filtered while its filter is on. +table := ui.Table(c, &m.table, ui.TableSpec{Columns: m.columns, Source: &m.bills}) +if column, ok := table.FilterClicked(); ok { + // open a choice anchored at m.table.HeaderRect(column); the application filters its rows +}`, PageSnippet: `// m.columns has Filterable set on the Status column, and Filtered while its filter is on. +table := ui.Table(c, &m.table, ui.TableSpec{Columns: m.columns, Source: &m.bills}) +if column, ok := table.FilterClicked(); ok { + // open a choice anchored at m.table.HeaderRect(column); the application filters its rows +}`, PageSnippetZh: `// m.columns has Filterable set on the Status column, and Filtered while its filter is on. +table := ui.Table(c, &m.table, ui.TableSpec{Columns: m.columns, Source: &m.bills}) +if column, ok := table.FilterClicked(); ok { + // open a choice anchored at m.table.HeaderRect(column); the application filters its rows +}`}, {ID: "overflow", Title: "溢出与表头", Description: "放不下的单元格以省略号结尾;FitTableHeadings 让定宽列至少放得下自己的表头。", Snippet: `columns := []components.TableColumn{{Width: 96}, {Width: 40}, {Alignment: components.TableAlignRight}} headings := []string{"Item", "Status", "Amount"} components.FitTableHeadings(canvas, theme, columns, headings) @@ -184,12 +221,14 @@ ui.Text(c, "项目被省略号截断;状态列已长到放得下表头。").Mu // warm paint allocates nothing. type tableDemo struct { state ui.TableState - rows [3][3]string - source ui.TableRows - columns []style.TableColumn - headers []string - footer string - caption string + checked ui.Selection + // filterColumns is the columns with the filter button set, kept so a warm paint allocates nothing. + filterColumns []style.TableColumn + rows [3][3]string + source ui.TableRows + columns []style.TableColumn + footer string + caption string } var tableDemos = map[*State]*tableDemo{} @@ -205,14 +244,9 @@ func tableDemoFor(state *State) *tableDemo { {state.Text("性能审计", "Performance audit"), state.Text("待付款", "Unpaid"), "¥ 1,280"}, }, columns: []style.TableColumn{ - {Width: 112, Alignment: style.TableAlignLeft}, - {Width: 88, Alignment: style.TableAlignCenter}, - {Width: 0, Alignment: style.TableAlignRight}, - }, - headers: []string{ - state.Text("项目", "Item"), - state.Text("状态", "Status"), - state.Text("金额", "Amount"), + {Title: state.Text("项目", "Item"), Width: 112, Alignment: style.TableAlignLeft}, + {Title: state.Text("状态", "Status"), Width: 88, Alignment: style.TableAlignCenter}, + {Title: state.Text("金额", "Amount"), Width: 0, Alignment: style.TableAlignRight}, }, footer: state.Text("合计 · 3 项 · ¥ 4,540", "Total · 3 items · ¥ 4,540"), caption: state.Text("点击任意数据行以查看交互反馈。", "Click any data row to see its interactive feedback."), @@ -240,13 +274,28 @@ func (state *State) paintTable(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Siz state.drawPage(canvas, theme, size, 620, state.Text("Table · 账单", "Table · Bills"), func(c ui.C) { spec := ui.TableSpec{ Columns: demo.columns, - Headers: demo.headers, Source: &demo.source, } if state.exampleID == "overflow" { spec.FitHeadings = true } + if state.exampleID == "filter" { + // The status column's filter is on once its button is pressed. + columns := append(demo.filterColumns[:0], demo.columns...) + columns[1].Filterable, columns[1].Filtered = true, state.flags&1 != 0 + spec.Columns = columns + demo.filterColumns = columns + } + if state.exampleID == "checked" { + spec.Checked = &demo.checked + spec.SelectAllLabel, spec.SelectRowLabel = state.Text("全选", "Select all rows"), state.Text("选择此行", "Select row") + } table := ui.Table(c, &demo.state, spec) + if state.exampleID == "filter" { + if _, ok := table.FilterClicked(); ok { + state.flags ^= 1 + } + } if state.exampleID == "selection" { if row, ok := table.RowClicked(); ok { demo.state.Select(row) diff --git a/internal/componentdemo/tag.go b/internal/componentdemo/tag.go new file mode 100644 index 000000000..e4604e71d --- /dev/null +++ b/internal/componentdemo/tag.go @@ -0,0 +1,110 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/tag" +) + +var tagComponent = Component{ + ID: "tag", Title: "Tag", Category: "Data Display", Summary: "短标签:状态着色、描边、三种尺寸,可关闭,可作为开关。", + Source: "ui/tag/tag.go", paint: (*State).paintTag, + Examples: []Example{ + {ID: "default", Title: "状态与描边", Description: "默认、成功、警告、危险共用 ui.Status;Outlined 只画边框。", Snippet: `tag.View(c.KeyInt(0), "default", tag.Spec{}) +tag.View(c.KeyInt(1), "success", tag.Spec{Status: ui.StatusSuccess}) +tag.View(c.KeyInt(2), "outlined", tag.Spec{Outlined: true})`, PageSnippet: `tag.View(c.KeyInt(0), "default", tag.Spec{}) +tag.View(c.KeyInt(1), "success", tag.Spec{Status: ui.StatusSuccess}) +tag.View(c.KeyInt(2), "outlined", tag.Spec{Outlined: true})`, PageSnippetZh: `tag.View(c.KeyInt(0), "default", tag.Spec{}) +tag.View(c.KeyInt(1), "success", tag.Spec{Status: ui.StatusSuccess}) +tag.View(c.KeyInt(2), "outlined", tag.Spec{Outlined: true})`}, + {ID: "interactive", Title: "可关闭与可勾选", Description: "点关闭按钮移除标签;可勾选的标签是开关,由页面保存选中状态。", Snippet: `for i, name := range m.tags { + if tag.View(c.Key(name), name, tag.Spec{Closable: true}).Closed { + m.removeTag(i) + } +} +result := tag.View(c, "production", tag.Spec{Checkable: true, Checked: m.production}) +if result.Toggled { + m.production = !m.production +}`, PageSnippet: `for i, name := range m.tags { + if tag.View(c.Key(name), name, tag.Spec{Closable: true}).Closed { + m.removeTag(i) + } +} +result := tag.View(c, "production", tag.Spec{Checkable: true, Checked: m.production}) +if result.Toggled { + m.production = !m.production +}`, PageSnippetZh: `for i, name := range m.tags { + if tag.View(c.Key(name), name, tag.Spec{Closable: true}).Closed { + m.removeTag(i) + } +} +result := tag.View(c, "production", tag.Spec{Checkable: true, Checked: m.production}) +if result.Toggled { + m.production = !m.production +}`}, + {ID: "sizes", Title: "尺寸", Description: "Small、Default、Large 三档,图标与关闭按钮随之缩放。", Snippet: `tag.View(c, "small", tag.Spec{Size: tag.Small, Closable: true}) +tag.View(c, "large", tag.Spec{Size: tag.Large, Closable: true})`, PageSnippet: `tag.View(c, "small", tag.Spec{Size: tag.Small, Closable: true}) +tag.View(c, "large", tag.Spec{Size: tag.Large, Closable: true})`, PageSnippetZh: `tag.View(c, "small", tag.Spec{Size: tag.Small, Closable: true}) +tag.View(c, "large", tag.Spec{Size: tag.Large, Closable: true})`}, + }, +} + +type tagDemo struct { + names []string + production bool +} + +var tagDemos = map[*State]*tagDemo{} + +func tagDemoFor(state *State) *tagDemo { + if demo := tagDemos[state]; demo != nil { + return demo + } + demo := &tagDemo{names: []string{"build-01", "db-primary", "staging", "bastion"}, production: true} + tagDemos[state] = demo + return demo +} + +func (state *State) paintTag(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := tagDemoFor(state) + state.drawPage(canvas, theme, size, 560, state.Text("Tag · 标签", "Tag"), func(c ui.C) { + remove := state.Text("移除", "Remove") + row := func(children func()) { ui.Row(c).Gap(8).Items(ui.Center).Children(children) } + switch state.exampleID { + case "interactive": + row(func() { + for i := 0; i < len(demo.names); i++ { + if tag.View(c.Key(demo.names[i]), demo.names[i], tag.Spec{Closable: true, CloseLabel: remove}).Closed { + demo.names = append(demo.names[:i], demo.names[i+1:]...) + i-- + } + } + if len(demo.names) == 0 { + ui.Text(c, state.Text("标签已全部移除", "Every tag was removed")).Muted() + } + }) + row(func() { + if tag.View(c.KeyInt(100), state.Text("生产环境", "production"), tag.Spec{Checkable: true, Checked: demo.production}).Toggled { + demo.production = !demo.production + } + }) + case "sizes": + row(func() { + tag.View(c.KeyInt(0), "small", tag.Spec{Size: tag.Small, Closable: true, CloseLabel: remove}) + tag.View(c.KeyInt(1), "default", tag.Spec{Closable: true, CloseLabel: remove}) + tag.View(c.KeyInt(2), "large", tag.Spec{Size: tag.Large, Closable: true, CloseLabel: remove}) + }) + default: + row(func() { + tag.View(c.KeyInt(0), state.Text("默认", "default"), tag.Spec{}) + tag.View(c.KeyInt(1), state.Text("成功", "success"), tag.Spec{Status: ui.StatusSuccess}) + tag.View(c.KeyInt(2), state.Text("警告", "warning"), tag.Spec{Status: ui.StatusWarning}) + tag.View(c.KeyInt(3), state.Text("危险", "danger"), tag.Spec{Status: ui.StatusDanger}) + }) + row(func() { + tag.View(c.KeyInt(4), state.Text("描边", "outlined"), tag.Spec{Outlined: true}) + tag.View(c.KeyInt(5), state.Text("成功描边", "success"), tag.Spec{Outlined: true, Status: ui.StatusSuccess}) + }) + } + }) +} diff --git a/internal/componentdemo/textarea.go b/internal/componentdemo/textarea.go index 01d0c4a1a..cf0634e98 100644 --- a/internal/componentdemo/textarea.go +++ b/internal/componentdemo/textarea.go @@ -143,7 +143,7 @@ func (state *State) paintTextareaGrowPage(canvas *gfx.Canvas, theme gfx.Theme, s state.drawPage(canvas, theme, size, 540, state.Text("Textarea · 多行编辑", "Textarea · Multi-line editing"), func(c ui.C) { field := ui.State[ui.Field](c, "notes") state.bindPageField(field, initial) - ui.TextAreaID(c, textareaField, field, label, "").ReadOnly(!state.editing).AutoGrow(textareaGrowMaxRows) + ui.TextArea(c, field, label, "", ui.WithID(textareaField)).ReadOnly(!state.editing).AutoGrow(textareaGrowMaxRows) caption(c, state.Text("高度由控件内容决定,最多五行;超过五行后在框内滚动。", "The control is as tall as its text, up to five rows; after that the box scrolls.")) }) } @@ -160,12 +160,12 @@ func (state *State) paintTextareaStatesPage(canvas *gfx.Canvas, theme gfx.Theme, unavailable := state.pageFieldText(c, "disabled", "") unavailable.Disabled = true ui.Row(c).Gap(12).Children(func() { - ui.TextAreaID(c, textareaInvalid, tooShort, state.Text("错误说明", "Invalid field"), ""). + ui.TextArea(c, tooShort, state.Text("错误说明", "Invalid field"), "", ui.WithID(textareaInvalid)). Grow(1).Basis(0).Height(104).ReadOnly(true) - ui.TextAreaID(c, textareaReadOnly, generated, state.Text("只读说明", "Read-only field"), ""). + ui.TextArea(c, generated, state.Text("只读说明", "Read-only field"), "", ui.WithID(textareaReadOnly)). Grow(1).Basis(0).Height(104).ReadOnly(true) }) - ui.TextAreaID(c, textareaDisabled, unavailable, state.Text("禁用说明", "Disabled field"), state.Text("当前不可填写", "Currently unavailable")).Height(72) + ui.TextArea(c, unavailable, state.Text("禁用说明", "Disabled field"), state.Text("当前不可填写", "Currently unavailable"), ui.WithID(textareaDisabled)).Height(72) }) } @@ -202,7 +202,7 @@ func (state *State) paintTextareaPage(canvas *gfx.Canvas, theme gfx.Theme, size field := ui.State[ui.Field](c, "notes") state.bindPageField(field, initial) field.Hint = hint - ui.TextAreaID(c, textareaField, field, label, "").Height(142) + ui.TextArea(c, field, label, "", ui.WithID(textareaField)).Height(142) caption(c, state.Text("编辑与 IME 事件由应用持有;换行、行内定位与滚动由 Viva 的 TextareaLayout 负责。", "Editing and IME events stay with the app; TextareaLayout handles wrapping, caret placement, and scrolling.")) }) } diff --git a/internal/componentdemo/time_picker.go b/internal/componentdemo/time_picker.go new file mode 100644 index 000000000..f404def84 --- /dev/null +++ b/internal/componentdemo/time_picker.go @@ -0,0 +1,67 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/timepicker" +) + +var timePickerComponent = Component{ + ID: "time-picker", Title: "Time Picker", Category: "Forms", Summary: "选择时间:时、分(可加秒)列表,点击或方向键即时生效。", + Source: "ui/timepicker/timepicker.go", paint: (*State).paintTimePicker, + Examples: []Example{ + {ID: "default", Title: "选择时间", Description: "滚轮滚动列,点击数字选中;上下键改变当前列,左右键换列,回车关闭。", Snippet: `m.start = timepicker.New().Placeholder("Pick a time").MinuteStep(5) +// in the page: +m.start.View(c, "Start", &m.startAt).Width(160) +if m.start.Changed() { + // m.startAt holds the chosen time +}`, PageSnippet: `m.start = timepicker.New().Placeholder("Pick a time").MinuteStep(5) +// in the page: +m.start.View(c, "Start", &m.startAt).Width(160) +if m.start.Changed() { + // m.startAt holds the chosen time +}`, PageSnippetZh: `m.start = timepicker.New().Placeholder("Pick a time").MinuteStep(5) +// 在页面中: +m.start.View(c, "Start", &m.startAt).Width(160) +if m.start.Changed() { + // m.startAt 是选中的时间 +}`}, + {ID: "seconds", Title: "带秒", Description: "Seconds 增加一列;SecondStep 限制秒的步长。", Snippet: `m.exact = timepicker.New().Seconds().MinuteStep(5)`, PageSnippet: `m.exact = timepicker.New().Seconds().MinuteStep(5)`, PageSnippetZh: `m.exact = timepicker.New().Seconds().MinuteStep(5)`}, + }, +} + +type timePickerDemo struct { + basic, exact *timepicker.TimePicker + a, b timepicker.Value +} + +var timePickerDemos = map[*State]*timePickerDemo{} + +func timePickerDemoFor(state *State) *timePickerDemo { + if demo := timePickerDemos[state]; demo != nil { + return demo + } + demo := &timePickerDemo{ + basic: timepicker.New().Placeholder(state.Text("选择时间", "Pick a time")).MinuteStep(5), + exact: timepicker.New().Seconds().MinuteStep(5), + a: timepicker.Value{Hour: 9, Minute: 30, Valid: true}, + b: timepicker.Value{Hour: 9, Minute: 30, Valid: true}, + } + if !state.english { + demo.basic.Units("时", "分", "秒") + demo.exact.Units("时", "分", "秒") + } + timePickerDemos[state] = demo + return demo +} + +func (state *State) paintTimePicker(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := timePickerDemoFor(state) + state.drawPage(canvas, theme, size, 320, state.Text("Time Picker · 时间", "Time Picker"), func(c ui.C) { + if state.exampleID == "seconds" { + demo.exact.View(c, state.Text("精确时间", "Exact time"), &demo.b).Width(200) + return + } + demo.basic.View(c, state.Text("开始时间", "Start"), &demo.a).Width(200) + }) +} diff --git a/internal/componentdemo/timeline.go b/internal/componentdemo/timeline.go new file mode 100644 index 000000000..f0d8c7630 --- /dev/null +++ b/internal/componentdemo/timeline.go @@ -0,0 +1,69 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/timeline" +) + +var timelineComponent = Component{ + ID: "timeline", Title: "Timeline", Category: "Data Display", Summary: "按时间先后排列的事件,圆点用色表达结果。", + Source: "ui/timeline/timeline.go", paint: (*State).paintTimeline, + Examples: []Example{ + {ID: "default", Title: "事件时间线", Description: "圆点颜色表达事件结果;Pending 在末尾补一个空心点表示待办。", Snippet: `// m.events is a []timeline.Item kept in the model. +timeline.View(c, "History", timeline.Spec{ + Items: m.events, + Pending: "Waiting for review", +})`, PageSnippet: `// m.events is a []timeline.Item kept in the model. +timeline.View(c, "History", timeline.Spec{ + Items: m.events, + Pending: "Waiting for review", +})`, PageSnippetZh: `// m.events 是保存在模型里的 []timeline.Item。 +timeline.View(c, "History", timeline.Spec{ + Items: m.events, + Pending: "Waiting for review", +})`}, + {ID: "labels", Title: "时间列", Description: "LabelWidth 把时间对齐成一列。", Snippet: `timeline.View(c, "History", timeline.Spec{ + Items: m.events, + LabelWidth: 48, +})`, PageSnippet: `timeline.View(c, "History", timeline.Spec{ + Items: m.events, + LabelWidth: 48, +})`, PageSnippetZh: `timeline.View(c, "History", timeline.Spec{ + Items: m.events, + LabelWidth: 48, +})`}, + }, +} + +type timelineDemo struct { + events []timeline.Item + pending string +} + +var timelineDemos = map[*State]*timelineDemo{} + +func timelineDemoFor(state *State) *timelineDemo { + if demo := timelineDemos[state]; demo != nil { + return demo + } + demo := &timelineDemo{pending: state.Text("等待复核", "Waiting for review"), events: []timeline.Item{ + {Title: state.Text("已连接", "Connected"), Description: state.Text("build-01 接受了密钥", "build-01 accepted the key"), Label: "09:41"}, + {Title: state.Text("已上传 release.tar.gz", "Uploaded release.tar.gz"), Description: "48.2 MB · 3.1 s", Label: "09:42", Tone: timeline.Success}, + {Title: state.Text("重启失败", "Restart failed"), Description: "exit status 1", Label: "09:44", Tone: timeline.Danger}, + {Title: state.Text("已回滚", "Rolled back"), Label: "09:45", Tone: timeline.Muted}, + }} + timelineDemos[state] = demo + return demo +} + +func (state *State) paintTimeline(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := timelineDemoFor(state) + state.drawPage(canvas, theme, size, 420, state.Text("Timeline · 时间线", "Timeline · History"), func(c ui.C) { + spec := timeline.Spec{Items: demo.events, Pending: demo.pending} + if state.exampleID == "labels" { + spec = timeline.Spec{Items: demo.events, LabelWidth: 48} + } + timeline.View(c, state.Text("历史", "History"), spec).FillWidth() + }) +} diff --git a/internal/componentdemo/tour.go b/internal/componentdemo/tour.go new file mode 100644 index 000000000..b79934108 --- /dev/null +++ b/internal/componentdemo/tour.go @@ -0,0 +1,72 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/tour" +) + +var tourComponent = Component{ + ID: "tour", Title: "Tour", Category: "Overlays", Summary: "引导:逐步指向页面上的控件,其余窗口变暗。", + Source: "ui/tour/tour.go", paint: (*State).paintTour, + Examples: []Example{ + {ID: "default", Title: "逐步引导", Description: "页面在声明控件时用 Target 说明每一步指向哪个控件,最后声明 View;Finish 才算完成,Skip、Esc 与点击外部只是离开。", Snippet: `m.tour = tour.New() +save := ui.Button(c, "Save") +m.tour.Target(0, save) +m.tour.View(c, tour.Spec{Steps: m.steps}) +if m.tour.Finished() { + // remember that the tour was seen +}`, PageSnippet: `m.tour = tour.New() +save := ui.Button(c, "Save") +m.tour.Target(0, save) +m.tour.View(c, tour.Spec{Steps: m.steps}) +if m.tour.Finished() { + // remember that the tour was seen +}`, PageSnippetZh: `m.tour = tour.New() +save := ui.Button(c, "Save") +m.tour.Target(0, save) +m.tour.View(c, tour.Spec{Steps: m.steps}) +if m.tour.Finished() { + // 记住用户已经看过引导 +}`}, + }, +} + +type tourDemo struct { + t *tour.Tour + steps []tour.Step +} + +var tourDemos = map[*State]*tourDemo{} + +func tourDemoFor(state *State) *tourDemo { + if demo := tourDemos[state]; demo != nil { + return demo + } + demo := &tourDemo{t: tour.New(), steps: []tour.Step{ + {Title: state.Text("保存", "Save"), Description: state.Text("把改动写回文件。", "Writes your changes back to the file.")}, + {Title: state.Text("同步", "Sync"), Description: state.Text("把文件发送到远程主机。", "Sends the file to the remote host.")}, + {Title: state.Text("完成", "All set"), Description: state.Text("随时可以重新开始引导。", "You can start the tour again at any time.")}, + }} + tourDemos[state] = demo + return demo +} + +func (state *State) paintTour(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := tourDemoFor(state) + state.drawPage(canvas, theme, size, 520, state.Text("Tour · 引导", "Tour"), func(c ui.C) { + ui.Row(c).Gap(12).Children(func() { + start := ui.Button(c, state.Text("开始引导", "Start tour")).Outline() + if start.Clicked() { + demo.t.Start() + } + save := ui.Button(c, state.Text("保存", "Save")) + demo.t.Target(0, save) + sync := ui.Button(c, state.Text("同步", "Sync")).Secondary() + demo.t.Target(1, sync) + }) + demo.t.View(c, tour.Spec{Steps: demo.steps, Labels: [4]string{ + state.Text("上一步", "Previous"), state.Text("下一步", "Next"), state.Text("完成", "Finish"), state.Text("跳过", "Skip"), + }}) + }) +} diff --git a/internal/componentdemo/transfer.go b/internal/componentdemo/transfer.go new file mode 100644 index 000000000..fb2df916c --- /dev/null +++ b/internal/componentdemo/transfer.go @@ -0,0 +1,71 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/transfer" +) + +var transferComponent = Component{ + ID: "transfer", Title: "Transfer", Category: "Forms", Summary: "穿梭框:在两个列表之间移动条目,支持全选与禁用项。", + Source: "ui/transfer/transfer.go", paint: (*State).paintTransfer, + Examples: []Example{ + {ID: "default", Title: "在两个列表间移动", Description: "勾选条目后点中间的按钮移动;列表头的勾选框全选或清空;禁用项不会被选中或移动。", Snippet: `m.moves = transfer.New() +// m.hosts is a []transfer.Item kept in the model; Target is the right list. +m.moves.View(c, "Hosts", transfer.Spec{ + Items: m.hosts, + Titles: [2]string{"Available", "Selected"}, +}).FillWidth() +if m.moves.Changed() { + // items moved +}`, PageSnippet: `m.moves = transfer.New() +// m.hosts is a []transfer.Item kept in the model; Target is the right list. +m.moves.View(c, "Hosts", transfer.Spec{ + Items: m.hosts, + Titles: [2]string{"Available", "Selected"}, +}).FillWidth() +if m.moves.Changed() { + // items moved +}`, PageSnippetZh: `m.moves = transfer.New() +// m.hosts 是保存在模型里的 []transfer.Item;Target 为 true 表示在右侧列表。 +m.moves.View(c, "Hosts", transfer.Spec{ + Items: m.hosts, + Titles: [2]string{"Available", "Selected"}, +}).FillWidth() +if m.moves.Changed() { + // 条目发生了移动 +}`}, + }, +} + +type transferDemo struct { + moves *transfer.Transfer + items []transfer.Item +} + +var transferDemos = map[*State]*transferDemo{} + +func transferDemoFor(state *State) *transferDemo { + if demo := transferDemos[state]; demo != nil { + return demo + } + demo := &transferDemo{moves: transfer.New(), items: []transfer.Item{ + {Title: "build-01"}, {Title: "build-02", Checked: true}, {Title: "db-primary", Target: true}, + {Title: "db-replica", Target: true, Checked: true}, {Title: "staging", Disabled: true}, {Title: "bastion"}, + {Title: "monitor"}, {Title: "cache-01"}, {Title: "cache-02"}, {Title: "queue"}, + }} + transferDemos[state] = demo + return demo +} + +func (state *State) paintTransfer(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := transferDemoFor(state) + state.drawPage(canvas, theme, size, 640, state.Text("Transfer · 穿梭框", "Transfer"), func(c ui.C) { + demo.moves.View(c, state.Text("主机", "Hosts"), transfer.Spec{ + Items: demo.items, + Titles: [2]string{state.Text("可选", "Available"), state.Text("已选", "Selected")}, + Height: 200, + MoveLabels: [2]string{state.Text("移到右侧", "Move right"), state.Text("移到左侧", "Move left")}, + }).FillWidth() + }) +} diff --git a/internal/componentdemo/upload.go b/internal/componentdemo/upload.go new file mode 100644 index 000000000..b629cb07d --- /dev/null +++ b/internal/componentdemo/upload.go @@ -0,0 +1,87 @@ +package componentdemo + +import ( + "slices" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/upload" +) + +var uploadComponent = Component{ + ID: "upload", Title: "Upload", Category: "Forms", Summary: "文件上传:拖入或选择文件,列表显示进度、失败重试与移除。", + Source: "ui/upload/upload.go", paint: (*State).paintUpload, + Examples: []Example{ + {ID: "default", Title: "拖入或选择文件", Description: "控件只管选择与展示;传输由页面负责,页面通过 Status、Progress 告诉控件每个文件传到哪了。", Snippet: `m.upload = upload.New() +m.upload.View(c, "Attachments", upload.Spec{ + Items: m.files, Multiple: true, Accept: []string{".png", ".jpg"}, +}).FillWidth() +for _, file := range m.upload.Added() { + m.files = append(m.files, upload.Item{Name: file.Name(), Size: file.Size()}) +} +if i, ok := m.upload.Removed(); ok { + m.files = slices.Delete(m.files, i, i+1) +}`, PageSnippet: `m.upload = upload.New() +m.upload.View(c, "Attachments", upload.Spec{ + Items: m.files, Multiple: true, Accept: []string{".png", ".jpg"}, +}).FillWidth() +for _, file := range m.upload.Added() { + m.files = append(m.files, upload.Item{Name: file.Name(), Size: file.Size()}) +} +if i, ok := m.upload.Removed(); ok { + m.files = slices.Delete(m.files, i, i+1) +}`, PageSnippetZh: `m.upload = upload.New() +m.upload.View(c, "Attachments", upload.Spec{ + Items: m.files, Multiple: true, Accept: []string{".png", ".jpg"}, +}).FillWidth() +for _, file := range m.upload.Added() { + m.files = append(m.files, upload.Item{Name: file.Name(), Size: file.Size()}) +} +if i, ok := m.upload.Removed(); ok { + m.files = slices.Delete(m.files, i, i+1) // 并停止传输 +}`}, + }, +} + +var uploadAccept = []string{".png", ".jpg", ".md", ".mov", ".gz"} + +type uploadDemo struct { + up *upload.Upload + items []upload.Item +} + +var uploadDemos = map[*State]*uploadDemo{} + +func uploadDemoFor(state *State) *uploadDemo { + if demo := uploadDemos[state]; demo != nil { + return demo + } + demo := &uploadDemo{up: upload.New(), items: []upload.Item{ + {Name: "release-notes.md", Size: 18 << 10, Status: upload.Done}, + {Name: "product-demo.mov", Size: 42 << 20, Status: upload.Uploading, Progress: 0.64}, + {Name: "backup.tar.gz", Size: 1 << 30, Status: upload.Failed, Error: state.Text("网络中断", "Connection lost")}, + }} + uploadDemos[state] = demo + return demo +} + +func (state *State) paintUpload(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := uploadDemoFor(state) + state.drawPage(canvas, theme, size, 520, state.Text("Upload · 文件上传", "Upload"), func(c ui.C) { + demo.up.View(c, state.Text("附件", "Attachments"), upload.Spec{ + Items: demo.items, Multiple: true, Accept: uploadAccept, + Title: state.Text("把文件拖到这里", "Drag files here"), Choose: state.Text("选择文件", "Choose files"), + Hint: state.Text("PNG、JPG、MD、MOV 或 GZ", "PNG, JPG, MD, MOV or GZ"), + RemoveLabel: state.Text("移除", "Remove"), RetryLabel: state.Text("重试", "Retry"), + }).FillWidth() + for _, file := range demo.up.Added() { + demo.items = append(demo.items, upload.Item{Name: file.Name(), Size: file.Size()}) + } + if i, ok := demo.up.Removed(); ok { + demo.items = slices.Delete(demo.items, i, i+1) + } + if i, ok := demo.up.Retried(); ok { + demo.items[i].Status, demo.items[i].Error = upload.Pending, "" + } + }) +} diff --git a/internal/dbusmenu/dbusmenu.go b/internal/dbusmenu/dbusmenu.go index aed977cac..dcf551f64 100644 --- a/internal/dbusmenu/dbusmenu.go +++ b/internal/dbusmenu/dbusmenu.go @@ -63,6 +63,12 @@ type Object struct { // without first saying it is about to show the menu is reading it again, // so the menu is built again. stale bool + // served is true once a host has been given the whole layout. The build + // that answers the first read is not a change any host has to be told + // about: no host kept an older layout, and announcing it can make a host + // that is still collecting the properties of the read it is completing + // start over, dropping them. + served bool } // New returns the menu of an icon, built by menu on demand. @@ -81,7 +87,9 @@ type Result struct { // changed: entries were added, removed or reordered, and the ids a host // holds no longer name the entries they did. The caller receives the new // layout either way; the signal tells the other hosts, which kept the - // layout they read earlier, to read it. + // layout they read earlier, to read it. A layout no host has read yet is + // not announced: there is nothing older to replace, and the host reading + // it holds the new one already. LayoutUpdated uint32 // ItemsUpdated, when not empty, is the body of an ItemsPropertiesUpdated // signal (ItemsUpdatedSignature): entries kept their ids, but their titles @@ -210,6 +218,7 @@ func (object *Object) Call(call *dbus.Message) Result { return failure("org.freedesktop.DBus.Error.InvalidArgs", "expected (iias)") } var difference change + served := object.served if parent == 0 { // Reading the whole menu again, with no word that it is about to // show, is a host that kept the last layout; reading a submenu is @@ -223,8 +232,11 @@ func (object *Object) Call(call *dbus.Message) Result { if !object.writeLayout(&e, parent, depth, names) { return failure("org.freedesktop.DBus.Error.InvalidArgs", "no such menu item") } + if parent == 0 { + object.served = true + } result := reply("u"+nodeType, &e) - if difference.layout { + if difference.layout && served { result.LayoutUpdated = object.revision } result.ItemsUpdated = difference.items @@ -295,7 +307,7 @@ func (object *Object) Call(call *dbus.Message) Result { } e.Bool(difference.layout) result := reply("b", &e) - if difference.layout { + if difference.layout && object.served { result.LayoutUpdated = object.revision } result.ItemsUpdated = difference.items @@ -320,7 +332,7 @@ func (object *Object) Call(call *dbus.Message) Result { errors := e.BeginArray(4) e.EndArray(errors) result := reply("aiai", &e) - if difference.layout { + if difference.layout && object.served { result.LayoutUpdated = object.revision } result.ItemsUpdated = difference.items diff --git a/internal/dbusmenu/dbusmenu_test.go b/internal/dbusmenu/dbusmenu_test.go index 4229467e2..19e2f3191 100644 --- a/internal/dbusmenu/dbusmenu_test.go +++ b/internal/dbusmenu/dbusmenu_test.go @@ -684,6 +684,43 @@ func TestAReadAnnouncesPropertiesOnce(t *testing.T) { } } +// The build that answers the first layout read must not be announced. No host +// keeps an older layout to replace, and a host that hears the announcement +// while it is still collecting the properties of that read may discard them, +// leaving the menu's rows without their text. +func TestTheBuildThatAnswersAFirstReadIsNotAnnounced(t *testing.T) { + var chosen []string + sessions := []string{"alpha"} + object := newSessionMenu(&chosen, &sessions) + + if result := object.Call(layoutCall(0, -1)); result.LayoutUpdated != 0 { + t.Fatalf("the first layout read announced revision %d", result.LayoutUpdated) + } + sessions = append(sessions, "beta") + if result := object.Call(aboutToShow(0)); result.LayoutUpdated == 0 { + t.Fatal("a layout that changed after one was served was not announced") + } +} + +// AboutToShow can build the menu before any host has read it; that build is +// not a change either, and the read that serves it must stay quiet too. +func TestTheFirstAboutToShowDoesNotAnnounceTheMenuItBuilds(t *testing.T) { + var chosen []string + sessions := []string{"alpha"} + object := newSessionMenu(&chosen, &sessions) + + if result := object.Call(aboutToShow(0)); result.LayoutUpdated != 0 { + t.Fatalf("the first AboutToShow announced revision %d", result.LayoutUpdated) + } + if result := object.Call(layoutCall(0, -1)); result.LayoutUpdated != 0 { + t.Fatalf("the first read after AboutToShow announced revision %d", result.LayoutUpdated) + } + sessions = append(sessions, "beta") + if result := object.Call(aboutToShow(0)); result.LayoutUpdated == 0 { + t.Fatal("a layout that changed after one was served was not announced") + } +} + func TestAboutToShowGroupAnnouncesAChangedLayout(t *testing.T) { var chosen []string sessions := []string{"alpha"} diff --git a/internal/gallery/gallery_drive_test.go b/internal/gallery/gallery_drive_test.go index a3c0c737e..2eded0c9a 100644 --- a/internal/gallery/gallery_drive_test.go +++ b/internal/gallery/gallery_drive_test.go @@ -408,7 +408,7 @@ func TestEveryComponentPageSurvivesBeingOperated(t *testing.T) { // through the platform text service. The rest of the text-entry family is a // fixed snapshot; this list failing means one of them stopped (or started) // being editable and the gallery page should say so. -var editableComponents = []string{"code-diff", "code-editor", "code-merge", "field", "form", "input", "input-group", "input-otp", "textarea"} +var editableComponents = []string{"code-diff", "code-editor", "code-merge", "field", "form", "input", "input-group", "input-number", "input-otp", "mentions", "pagination", "textarea"} func editableHits(driver *app.Driver) []gfx.Hit { var fields []gfx.Hit diff --git a/internal/ibus/ibus.go b/internal/ibus/ibus.go index 3c44113d4..aadbda9ee 100644 --- a/internal/ibus/ibus.go +++ b/internal/ibus/ibus.go @@ -155,33 +155,45 @@ type Context struct { // Address finds the IBus daemon's bus address the way libibus does: the // IBUS_ADDRESS variable, or else the file the daemon writes under the user's -// configuration directory, named by the machine id, the display's host and its -// number. getenv and readFile are os.Getenv and os.ReadFile outside tests. +// configuration directory (IBUS_ADDRESS_FILE names it outright). Otherwise the +// file is named by the machine id, the display's host and its number; a +// Wayland session names the Wayland socket instead, and wins over DISPLAY even +// for an X11 client running on XWayland. getenv and readFile are os.Getenv and +// os.ReadFile outside tests. func Address(getenv func(string) string, readFile func(string) ([]byte, error)) (string, bool) { if address := getenv("IBUS_ADDRESS"); address != "" { return address, true } - var machine string - for _, name := range []string{"/var/lib/dbus/machine-id", "/etc/machine-id"} { - if data, err := readFile(name); err == nil { - if machine = strings.TrimSpace(string(data)); machine != "" { - break + file := getenv("IBUS_ADDRESS_FILE") + if file == "" { + var machine string + for _, name := range []string{"/var/lib/dbus/machine-id", "/etc/machine-id"} { + if data, err := readFile(name); err == nil { + if machine = strings.TrimSpace(string(data)); machine != "" { + break + } } } - } - if machine == "" { - return "", false - } - host, number := displayParts(getenv("DISPLAY")) - config := getenv("XDG_CONFIG_HOME") - if config == "" { - home := getenv("HOME") - if home == "" { + if machine == "" { return "", false } - config = filepath.Join(home, ".config") + host, number := "unix", "" + if wayland := getenv("WAYLAND_DISPLAY"); wayland != "" { + number = wayland + } else { + host, number = displayParts(getenv("DISPLAY")) + } + config := getenv("XDG_CONFIG_HOME") + if config == "" { + home := getenv("HOME") + if home == "" { + return "", false + } + config = filepath.Join(home, ".config") + } + file = filepath.Join(config, "ibus", "bus", machine+"-"+host+"-"+number) } - data, err := readFile(filepath.Join(config, "ibus", "bus", machine+"-"+host+"-"+number)) + data, err := readFile(file) if err != nil { return "", false } diff --git a/internal/ibus/ibus_test.go b/internal/ibus/ibus_test.go index 955db648a..7c9cd1882 100644 --- a/internal/ibus/ibus_test.go +++ b/internal/ibus/ibus_test.go @@ -907,10 +907,12 @@ func BenchmarkHandledContextKey(b *testing.B) { func TestAddressPrefersTheEnvironmentThenTheDisplaysFile(t *testing.T) { files := map[string]string{ - "/var/lib/dbus/machine-id": "abc123\n", - "/home/u/.config/ibus/bus/abc123-unix-1": "# comment\nIBUS_ADDRESS=unix:path=/home/u/.cache/ibus/dbus-1,guid=g\nIBUS_DAEMON_PID=99\n", - "/xdg/ibus/bus/abc123-remote-0": "IBUS_ADDRESS=unix:abstract=/tmp/dbus-x,guid=h\n", - "/home/u/.config/ibus/bus/abc123-unix-0": "IBUS_DAEMON_PID=1\n", + "/var/lib/dbus/machine-id": "abc123\n", + "/home/u/.config/ibus/bus/abc123-unix-1": "# comment\nIBUS_ADDRESS=unix:path=/home/u/.cache/ibus/dbus-1,guid=g\nIBUS_DAEMON_PID=99\n", + "/xdg/ibus/bus/abc123-remote-0": "IBUS_ADDRESS=unix:abstract=/tmp/dbus-x,guid=h\n", + "/home/u/.config/ibus/bus/abc123-unix-0": "IBUS_DAEMON_PID=1\n", + "/home/u/.config/ibus/bus/abc123-unix-wayland-0": "IBUS_ADDRESS=unix:path=/home/u/.cache/ibus/dbus-w,guid=w\n", + "/custom/ibus-address": "IBUS_ADDRESS=unix:path=/custom,guid=c\n", } read := func(name string) ([]byte, error) { if data, ok := files[name]; ok { @@ -931,6 +933,9 @@ func TestAddressPrefersTheEnvironmentThenTheDisplaysFile(t *testing.T) { {"local display", map[string]string{"DISPLAY": ":1", "HOME": "/home/u"}, "unix:path=/home/u/.cache/ibus/dbus-1,guid=g", true}, {"screen suffix is ignored", map[string]string{"DISPLAY": ":1.0", "HOME": "/home/u"}, "unix:path=/home/u/.cache/ibus/dbus-1,guid=g", true}, {"XDG_CONFIG_HOME and a host", map[string]string{"DISPLAY": "remote:0", "XDG_CONFIG_HOME": "/xdg"}, "unix:abstract=/tmp/dbus-x,guid=h", true}, + {"Wayland session names the socket, not the display", map[string]string{"WAYLAND_DISPLAY": "wayland-0", "DISPLAY": ":1", "HOME": "/home/u"}, "unix:path=/home/u/.cache/ibus/dbus-w,guid=w", true}, + {"Wayland without an XWayland display", map[string]string{"WAYLAND_DISPLAY": "wayland-0", "HOME": "/home/u"}, "unix:path=/home/u/.cache/ibus/dbus-w,guid=w", true}, + {"address file named by the environment", map[string]string{"IBUS_ADDRESS_FILE": "/custom/ibus-address", "DISPLAY": ":1"}, "unix:path=/custom,guid=c", true}, {"file without an address", map[string]string{"DISPLAY": ":0", "HOME": "/home/u"}, "", false}, {"no file for this display", map[string]string{"DISPLAY": ":7", "HOME": "/home/u"}, "", false}, {"no home", map[string]string{"DISPLAY": ":1"}, "", false}, diff --git a/internal/ibus/testdata/wayland-seat.py b/internal/ibus/testdata/wayland-seat.py index 1cfbb907b..c087c3e31 100644 --- a/internal/ibus/testdata/wayland-seat.py +++ b/internal/ibus/testdata/wayland-seat.py @@ -166,13 +166,16 @@ def grab(self): raise RuntimeError("AT-SPI editor rejected GrabFocus") return {"accepted": True} - def click(self, reference=None): + def editor_point(self, reference=None): reference = reference or self.editor x, y, width, height = call(self.accessible, reference[0], reference[1], COMPONENT, "GetExtents", GLib.Variant("(u)", (0,)))[0] if width <= 0 or height <= 0 or x < 0 or y < 0 or x + width > 800 or y + height > 600: raise RuntimeError("native click target is outside the private viewport") - return self.click_at(x + width // 2, y + height // 2) + return x + width // 2, y + height // 2 + + def click(self, reference=None): + return self.click_at(*self.editor_point(reference)) def move(self, x, y): if not 0 <= x < 800 or not 0 <= y < 600: @@ -232,6 +235,8 @@ def main(): result = seat.grab() elif operation == "click": result = seat.click() + elif operation == "move-editor": + result = seat.move(*seat.editor_point()) elif operation == "probe-switch": result = seat.probe_switch(int(command["pid"])) elif operation == "move": diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 69b51a04b..f5b451655 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -51,6 +51,15 @@ type Config struct { TitlebarHeight float32 TrafficLightScale float32 ClearColor Color + // Transparent asks for a window composited over the desktop: ClearColor's + // alpha is what shows what is behind it. Adapters that cannot composite + // ignore it, and app.Config only sets it where they report the capability. + Transparent bool + // OnTransparentChange, when set with Transparent, is told once the window + // exists whether the desktop shows through it. It is false where the + // adapter could not composite the window (no compositing manager, or a + // window kind that has no alpha surface). + OnTransparentChange func(active bool) // WindowBorderColor, when set, is read on the window thread with every // frame and names the color of the border the desktop draws around a // custom-titlebar window. Windows 11 composites that border against what @@ -150,8 +159,12 @@ type Config struct { OnCloseRequest CloseRequestHandler // OnClosed runs exactly once on the native event-loop thread after this // window has stopped receiving events and released its platform resources. - OnClosed func() - TextInput *TextInput + OnClosed func() + TextInput *TextInput + // TakeTextMenu hands the adapter the text menu the runtime wants shown, once the + // adapter has delivered a press and presented the frame it produced. It returns + // false when no menu was asked for. Nil means the runtime shows none. + TakeTextMenu func() (TextMenuRequest, bool) DynamicTextInput bool // ReadOnlyTextFocused reports the last painted focused hit. Linux uses it // to recheck a disabled native input before routing a new key. @@ -369,6 +382,46 @@ type MenuItem struct { ID string } +// TextMenuCommand is one command of the menu a text field opens on a secondary +// press. The runtime runs it through the same path as the keyboard shortcut of +// the same name, so a command chosen from the menu and a chord do the same thing. +type TextMenuCommand uint8 + +const ( + // TextMenuNone is no command: a dismissed menu, or a separator in the items. + TextMenuNone TextMenuCommand = iota + TextMenuCut + TextMenuCopy + TextMenuPaste + TextMenuSelectAll +) + +// TextMenuItem is one row of a text menu. A zero Command is a separator. +type TextMenuItem struct { + Command TextMenuCommand + Title string + Disabled bool +} + +// TextMenuRequest is the menu the runtime wants shown for the focused text +// field: where, in logical pixels of the window's content, what rows, and what +// runs with the command chosen. Perform runs on the event-loop thread after the +// menu has closed. +type TextMenuRequest struct { + Items []TextMenuItem + X, Y float32 + Perform func(TextMenuCommand) (Frame, error) +} + +// TextMenuPopper is implemented by the windows of an adapter that can show the +// system's own menu: macOS and Windows. PopupTextMenu returns when the menu has +// closed, with the command chosen, or TextMenuNone. It runs on the event-loop +// thread, from inside the handler of the press that asked for it, as the +// system's own text fields do. +type TextMenuPopper interface { + PopupTextMenu(items []TextMenuItem, x, y float32) (TextMenuCommand, error) +} + // ApplicationStart initializes the first windows before the event loop waits. type ApplicationStart func(Application) error diff --git a/internal/platform/darwin/callback.go b/internal/platform/darwin/callback.go index 54802a9ba..c1badb1ae 100644 --- a/internal/platform/darwin/callback.go +++ b/internal/platform/darwin/callback.go @@ -112,6 +112,13 @@ func deliverPointer(state *runState, view unsafe.Pointer, event PointerEvent) { if err == nil { err = presentFrame(state, view, frame, false) } + if err == nil && event.Kind == PointerDown && event.Button == gfx.PointerButtonSecondary && state.takeTextMenu != nil { + // The press is delivered and its frame is on the screen: the system's menu for + // a text field opens now, as AppKit's own views open theirs from the press. + if request, ok := state.takeTextMenu(); ok { + err = showTextMenu(state, view, request) + } + } if err != nil { state.err = err C.viva_view_close(view) diff --git a/internal/platform/darwin/drag_darwin.go b/internal/platform/darwin/drag_darwin.go index 1842a1f5b..2ad48daa6 100644 --- a/internal/platform/darwin/drag_darwin.go +++ b/internal/platform/darwin/drag_darwin.go @@ -2,19 +2,177 @@ package darwin +/* +#include +#include "native.h" +*/ +import "C" + import ( "fmt" + "io" + "os" + "path/filepath" + "sync" + "unsafe" "github.com/vivaui/viva/internal/platform" ) -// StartFileDrag cannot offer files from a window on macOS yet. A drag out of a -// window is a dragging session: the view under the pointer starts an -// NSDraggingSession whose pasteboard items are file URLs, and the session's -// dragging source reports where it ended and with which operation. This adapter -// binds the view and the general pasteboard, but neither NSDraggingSession nor -// NSDraggingSource is bound, so the window can offer its files only by copying -// them (see SetClipboardFiles), which is a different promise to the user. -func StartFileDrag(paths []string, allowed platform.DragEffect) (platform.DragEffect, error) { - return platform.DragEffectNone, fmt.Errorf("%w: macOS drags files out with an NSDraggingSession, which this adapter does not bind", platform.ErrDragUnsupported) +// fileDragStore keeps the promises of the drags this process has started until +// the last provider that may ask for them is gone. The native side passes its +// key back with each request and releases it from the context that the +// providers keep alive; the content then runs on the promise operation queue. +var fileDragStore struct { + mu sync.Mutex + next int64 + byID map[int64][]platform.FilePromise +} + +// StartFileDrag takes files that exist at paths out of the window handling the +// current press. The session consumes the press, so the application is told the +// press ended when the session ends. +func StartFileDrag(paths []string, allowed platform.DragEffect) error { + if len(paths) == 0 { + return fmt.Errorf("darwin: no files to drag out of the window") + } + strings := make([]*C.char, len(paths)) + for index, path := range paths { + strings[index] = C.CString(path) + } + defer func() { + for _, path := range strings { + C.free(unsafe.Pointer(path)) + } + }() + status := C.viva_start_file_drag((**C.char)(unsafe.Pointer(&strings[0])), C.size_t(len(strings)), C.uint(allowed)) + if status != 0 { + return dragStartError(int(status)) + } + return nil +} + +// StartFilePromiseDrag takes promised files out of the window handling the +// current press: each is written where the target lets go, by asking the +// application for its content then. +func StartFilePromiseDrag(files []platform.FilePromise) error { + if len(files) == 0 { + return fmt.Errorf("darwin: no files to drag out of the window") + } + fileDragStore.mu.Lock() + fileDragStore.next++ + drag := fileDragStore.next + if fileDragStore.byID == nil { + fileDragStore.byID = make(map[int64][]platform.FilePromise) + } + fileDragStore.byID[drag] = append([]platform.FilePromise(nil), files...) + fileDragStore.mu.Unlock() + + names := make([]*C.char, len(files)) + items := make([]C.viva_drag_item, len(files)) + for index, promise := range files { + names[index] = C.CString(promise.Name) + items[index] = C.viva_drag_item{name: names[index], directory: 0, item: C.int(index)} + if promise.Directory { + items[index].directory = 1 + } + } + status := C.viva_start_file_promise_drag(C.intptr_t(drag), &items[0], C.size_t(len(items))) + for _, name := range names { + C.free(unsafe.Pointer(name)) + } + if status != 0 { + finishFileDrag(drag) + return dragStartError(int(status)) + } + return nil +} + +func dragStartError(status int) error { + switch status { + case -1: + return fmt.Errorf("darwin: no window is handling the drag") + case -2: + return fmt.Errorf("darwin: the drag did not start from a mouse press") + case -3: + return fmt.Errorf("darwin: another file drag is already running") + default: + return fmt.Errorf("darwin: the file drag could not start (%d)", status) + } +} + +func finishFileDrag(drag int64) { + fileDragStore.mu.Lock() + delete(fileDragStore.byID, drag) + fileDragStore.mu.Unlock() +} + +//export vivaFilePromiseContent +func vivaFilePromiseContent(drag C.intptr_t, item C.int, path *C.char) C.int { + if path == nil { + return 1 + } + fileDragStore.mu.Lock() + files := fileDragStore.byID[int64(drag)] + fileDragStore.mu.Unlock() + index := int(item) + if index < 0 || index >= len(files) { + return 1 + } + if err := writeFilePromise(files[index], C.GoString(path)); err != nil { + return 1 + } + return 0 +} + +//export vivaFileDragFinished +func vivaFileDragFinished(drag C.intptr_t) { + finishFileDrag(int64(drag)) +} + +// writeFilePromise writes promise where the target asked: a file's bytes, or a +// directory and everything List produces under it. +func writeFilePromise(promise platform.FilePromise, destination string) error { + if !promise.Directory { + return writePromiseFile(promise, destination) + } + if err := os.MkdirAll(destination, 0o755); err != nil { + return err + } + children, err := promise.List() + if err != nil { + return err + } + return platform.WalkFilePromises(children, func(relative string, child platform.FilePromise) error { + target := filepath.Join(destination, filepath.FromSlash(relative)) + if child.Directory { + return os.MkdirAll(target, 0o755) + } + return writePromiseFile(child, target) + }) +} + +func writePromiseFile(promise platform.FilePromise, target string) error { + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + reader, err := promise.Open() + if err != nil { + return err + } + defer reader.Close() + file, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) + if err != nil { + return err + } + if _, err := io.Copy(file, reader); err != nil { + file.Close() + os.Remove(target) + return err + } + if err := file.Close(); err != nil { + os.Remove(target) + return err + } + return nil } diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 76e40f09e..57dc234fd 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -391,6 +391,8 @@ int viva_offscreen_render( ); void viva_offscreen_release(void *offscreen); int viva_run(viva_window_config config); +enum { VIVA_APPLICATION_NOT_MAIN_THREAD = 10 }; +int viva_application_check_thread(void); int viva_application_begin(void); int viva_application_last_status(void); void *viva_application_open_window(viva_window_config config); @@ -464,6 +466,11 @@ int viva_view_update_accessibility( void viva_view_render(void *view); void viva_view_render_sync(void *view); void viva_view_close(void *view); +// viva_view_popup_text_menu shows a menu of count rows at (x, y) of the view, in +// the view's top-left coordinates, and returns once it has closed: the command of +// the row chosen, or 0. A row with command 0 is a separator. +int viva_view_popup_text_menu(void *view, int count, const int *commands, const char *const *titles, + const int *disabled, double x, double y); void viva_view_close_confirmed(void *view); int viva_view_update_text( void *view, @@ -594,4 +601,24 @@ char *viva_list_mono_families(void); // viva_list_font_families is the same for every installed family, fixed-pitch or not. char *viva_list_font_families(void); +// viva_drag_item is one file of a promised drag: the name offered to the +// target, whether it is a folder, and the value the application uses to produce +// its content when the target asks. +typedef struct { + const char *name; + int directory; + int item; +} viva_drag_item; + +// viva_start_file_drag begins a dragging session of the files that already +// exist at paths, from the window handling the current press, offering the +// effects in allowed (the platform.DragEffect bits: 1 copy, 2 move, 4 link). +// It returns 0, or a negative code when no session could start. +int viva_start_file_drag(const char *const *paths, size_t count, unsigned allowed); + +// viva_start_file_promise_drag begins a dragging session of promised files: +// the target asks for each one's content through vivaFilePromiseContent, with +// the drag and item it was given here. It returns 0, or a negative code. +int viva_start_file_promise_drag(intptr_t drag, const viva_drag_item *items, size_t count); + #endif diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 189909c27..0de80c57b 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -1,9 +1,13 @@ //go:build !ios #import "core.h" +#include +#include +#include #include "cursor_owner_darwin.h" #include "label_geometry.h" #include "main_menu_darwin.h" +#import static uint64_t viva_process_start_ticks; static uint64_t viva_pointer_event_count; @@ -1130,6 +1134,20 @@ - (void)setAccessibilitySelectedTextRange:(NSRange)range { @end +@class VivaMetalView; +@class VivaFileDragSource; + +// VivaFileDragSource reports the end of a session the view started. It is not +// retained by the view after the session ends; the system keeps it while the +// session runs. +@interface VivaFileDragSource : NSObject { + VivaMetalView *_view; // not retained: the view owns this source + intptr_t _drag; + NSDragOperation _allowed; +} +- (instancetype)initWithView:(VivaMetalView *)view handle:(uintptr_t)handle drag:(intptr_t)drag allowed:(NSDragOperation)allowed; +@end + @interface VivaMetalView : NSView { CAMetalLayer *_metalLayer; // What the surface draws: the rectangles, the label layers, the pipelines and @@ -1201,6 +1219,10 @@ @interface VivaMetalView : NSView { BOOL _profileEnabled; NSCursor *_cursor; BOOL _nativeCursorActive; + // The drag out of this window while a session is running: the source that + // reports its end and the promise delegates the session asks for content. + VivaFileDragSource *_fileDragSource; + NSArray *_fileDragDelegates; } - (instancetype)initWithFrame:(NSRect)frame @@ -1775,6 +1797,57 @@ - (BOOL)performDragOperation:(id)sender { return [self dropPhase:2 info:sender paths:(const char *)joined.bytes length:joined.length] != NSDragOperationNone; } +// ---- Files dragged out of this window ---- + +// emitPointerCancel ends the application's press when the system took it: the +// dragging session swallows the button release, so the application would +// otherwise keep a press the pointer can no longer follow. +- (void)emitPointerCancel { + if (_callbackHandle == 0 || !_pointerEventsEnabled) { + return; + } + viva_pointer_event_count++; + vivaPointerEvent(_callbackHandle, self, VIVA_POINTER_CANCEL, 0, 0, 0, -1, -1, 0, 0); +} + +// startFileDragWithItems begins a dragging session for the press that is being +// handled now. The system owns the pointer until the drop or Escape reports +// through the source, which is why the application must not keep its own press +// open. drag and delegates are the promised drag's registry key and its +// delegates; both are 0/nil for a drag of paths. +- (int)startFileDragWithItems:(NSArray *)items allowed:(NSDragOperation)allowed drag:(intptr_t)drag delegates:(NSArray *)delegates { + NSEvent *event = [NSApp currentEvent]; + if (event == nil) { + return -1; + } + switch (event.type) { + case NSEventTypeLeftMouseDown: + case NSEventTypeLeftMouseDragged: + case NSEventTypeRightMouseDragged: + case NSEventTypeOtherMouseDragged: + break; + default: + return -2; + } + if (_fileDragSource != nil) { + return -3; + } + VivaFileDragSource *source = [[VivaFileDragSource alloc] initWithView:self handle:_callbackHandle drag:drag allowed:allowed]; + _fileDragSource = source; + _fileDragDelegates = [delegates retain]; + NSDraggingSession *session = [self beginDraggingSessionWithItems:items event:event source:source]; + session.animatesToStartingPositionsOnCancelOrFail = NO; + return 0; +} + +- (void)fileDragSessionEnded { + [_fileDragSource release]; + _fileDragSource = nil; + [_fileDragDelegates release]; + _fileDragDelegates = nil; + [self emitPointerCancel]; +} + - (void)scrollWheel:(NSEvent *)event { if (_callbackHandle == 0 || !_scrollEventsEnabled) { return; @@ -3207,6 +3280,264 @@ - (void)doCommandBySelector:(SEL)selector { @end +/* ---- Files dragged out of this window ---- */ + +extern int vivaFilePromiseContent(intptr_t drag, int item, const char *path); +extern void vivaFileDragFinished(intptr_t drag); + +// viva_drag_operation turns the platform effect bits (1 copy, 2 move, 4 link) +// into the NSDragOperation a dragging source reports. +static NSDragOperation viva_drag_operation(unsigned allowed) { + NSDragOperation operation = NSDragOperationNone; + if (allowed & 1) { + operation |= NSDragOperationCopy; + } + if (allowed & 2) { + operation |= NSDragOperationMove; + } + if (allowed & 4) { + operation |= NSDragOperationLink; + } + return operation; +} + +// viva_drag_view is the view of the window handling the current press: a drag +// starts from the mouse event that is being handled, and the session takes the +// pointer over from it. +static VivaMetalView *viva_drag_view(NSEvent **outEvent) { + NSEvent *event = [NSApp currentEvent]; + if (outEvent != NULL) { + *outEvent = event; + } + if (event == nil || event.window == nil) { + return nil; + } + id view = event.window.contentView; + if (![view isKindOfClass:[VivaMetalView class]]) { + return nil; + } + return (VivaMetalView *)view; +} + +// viva_drag_image is the picture that follows the pointer: the file's own icon +// where there is a path, a folder or a stack of documents for promised content. +static NSImage *viva_drag_image(NSString *path, BOOL directory) { + NSImage *image = nil; + if (path != nil) { + image = [[NSWorkspace sharedWorkspace] iconForFile:path]; + } + if (image == nil) { + image = directory ? [NSImage imageNamed:NSImageNameFolder] : [NSImage imageNamed:NSImageNameMultipleDocuments]; + } + image.size = NSMakeSize(32, 32); + return image; +} + +static NSRect viva_drag_frame(VivaMetalView *view, NSEvent *event) { + NSPoint local = [view convertPoint:event.locationInWindow fromView:nil]; + return NSMakeRect(local.x - 16, local.y - 16, 32, 32); +} + +// VivaFileDragContext is the promised drag's content registry as long as any +// provider may ask for it. The providers keep their delegates (through +// associated objects); the delegates keep this; its deallocation is the moment +// the application can forget the promises. +@interface VivaFileDragContext : NSObject { + intptr_t _drag; +} +- (instancetype)initWithDrag:(intptr_t)drag; +- (intptr_t)drag; +@end + +@implementation VivaFileDragContext +- (instancetype)initWithDrag:(intptr_t)drag { + if ((self = [super init]) != nil) { + _drag = drag; + } + return self; +} +- (intptr_t)drag { + return _drag; +} +- (void)dealloc { + if (_drag != 0) { + vivaFileDragFinished(_drag); + } + [super dealloc]; +} +@end + +// VivaFileDragSource reports the end of a session the view started. It is not +// retained by the view after the session ends; the system keeps it while the +// session runs. +@implementation VivaFileDragSource +- (instancetype)initWithView:(VivaMetalView *)view handle:(uintptr_t)handle drag:(intptr_t)drag allowed:(NSDragOperation)allowed { + if ((self = [super init]) != nil) { + _view = view; + _drag = drag; + _allowed = allowed; + } + return self; +} + +- (NSDragOperation)draggingSession:(NSDraggingSession *)session sourceOperationMaskForDraggingContext:(NSDraggingContext)context { + (void)session; + (void)context; + return _allowed; +} + +- (void)draggingSession:(NSDraggingSession *)session endedAtPoint:(NSPoint)screenPoint operation:(NSDragOperation)operation { + (void)session; + (void)screenPoint; + (void)operation; + // The view releases this source here, so keep it alive across the call. + [self retain]; + [_view fileDragSessionEnded]; + [self release]; +} + +// A drag to another application that also accepts drops is the only thing a +// promised drag does; a link or a move would have to be produced by the source. +- (BOOL)ignoreModifierKeysForDraggingSession:(NSDraggingSession *)session { + (void)session; + return YES; +} +@end + +// VivaFilePromiseDelegate produces one promised item when the target asks. Its +// provider keeps it alive through the association set when the item is built, +// and the context keeps the application's promises alive for as long as any +// provider may ask. +@interface VivaFilePromiseDelegate : NSObject { + NSString *_name; + int _item; + VivaFileDragContext *_context; // retained +} +- (instancetype)initWithName:(NSString *)name item:(int)item context:(VivaFileDragContext *)context; +@end + +@implementation VivaFilePromiseDelegate +- (instancetype)initWithName:(NSString *)name item:(int)item context:(VivaFileDragContext *)context { + if ((self = [super init]) != nil) { + _name = [name copy]; + _item = item; + _context = [context retain]; + } + return self; +} +- (void)dealloc { + [_name release]; + [_context release]; + [super dealloc]; +} + +- (NSString *)filePromiseProvider:(NSFilePromiseProvider *)provider fileNameForType:(NSString *)fileType { + (void)provider; + (void)fileType; + return _name; +} + +- (NSOperationQueue *)operationQueueForFilePromiseProvider:(NSFilePromiseProvider *)provider { + (void)provider; + static NSOperationQueue *queue; + static dispatch_once_t once; + dispatch_once(&once, ^{ + queue = [[NSOperationQueue alloc] init]; + queue.name = @"viva-file-promise"; + }); + return queue; +} + +- (void)filePromiseProvider:(NSFilePromiseProvider *)provider writePromiseToURL:(NSURL *)url completionHandler:(void (^)(NSError *))completionHandler { + (void)provider; + NSString *path = url.path; + const char *representation = path == nil ? NULL : path.fileSystemRepresentation; + int status = representation == NULL ? -1 : vivaFilePromiseContent([_context drag], _item, representation); + if (status == 0) { + completionHandler(nil); + return; + } + NSError *error = [NSError errorWithDomain:@"VivaFilePromiseErrorDomain" + code:status + userInfo:@{ NSLocalizedDescriptionKey : @"The file could not be produced." }]; + completionHandler(error); +} +@end + +int viva_start_file_drag(const char *const *paths, size_t count, unsigned allowed) { + @autoreleasepool { + NSEvent *event = nil; + VivaMetalView *view = viva_drag_view(&event); + if (view == nil) { + return -1; + } + NSMutableArray *items = [NSMutableArray arrayWithCapacity:count]; + NSRect frame = viva_drag_frame(view, event); + for (size_t index = 0; index < count; index++) { + if (paths[index] == NULL) { + continue; + } + NSString *path = [NSString stringWithUTF8String:paths[index]]; + if (path == nil) { + continue; + } + NSPasteboardItem *writer = [[NSPasteboardItem alloc] init]; + [writer setString:[[NSURL fileURLWithPath:path] absoluteString] forType:NSPasteboardTypeFileURL]; + NSDraggingItem *item = [[NSDraggingItem alloc] initWithPasteboardWriter:writer]; + [writer release]; + [item setDraggingFrame:frame contents:viva_drag_image(path, NO)]; + [items addObject:item]; + [item release]; + } + if (items.count == 0) { + return -2; + } + return [view startFileDragWithItems:items allowed:viva_drag_operation(allowed) drag:0 delegates:nil]; + } +} + +int viva_start_file_promise_drag(intptr_t drag, const viva_drag_item *items, size_t count) { + @autoreleasepool { + NSEvent *event = nil; + VivaMetalView *view = viva_drag_view(&event); + if (view == nil) { + return -1; + } + static char delegateKey; + VivaFileDragContext *context = [[VivaFileDragContext alloc] initWithDrag:drag]; + NSMutableArray *dragging = [NSMutableArray arrayWithCapacity:count]; + NSMutableArray *delegates = [NSMutableArray arrayWithCapacity:count]; + NSRect frame = viva_drag_frame(view, event); + for (size_t index = 0; index < count; index++) { + if (items[index].name == NULL) { + continue; + } + NSString *name = [NSString stringWithUTF8String:items[index].name]; + if (name == nil) { + continue; + } + NSString *type = items[index].directory ? @"public.directory" : @"public.data"; + VivaFilePromiseDelegate *delegate = [[VivaFilePromiseDelegate alloc] initWithName:name item:items[index].item context:context]; + NSFilePromiseProvider *provider = [[NSFilePromiseProvider alloc] initWithFileType:type delegate:delegate]; + // The provider's delegate is not retained by it; keep it exactly as + // long as the provider, which the target holds while it copies. + objc_setAssociatedObject(provider, &delegateKey, delegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + NSDraggingItem *item = [[NSDraggingItem alloc] initWithPasteboardWriter:provider]; + [provider release]; + [item setDraggingFrame:frame contents:viva_drag_image(nil, items[index].directory != 0)]; + [dragging addObject:item]; + [item release]; + [delegates addObject:delegate]; + [delegate release]; + } + [context release]; + if (dragging.count == 0) { + return -2; + } + return [view startFileDragWithItems:dragging allowed:NSDragOperationCopy drag:drag delegates:delegates]; + } +} + /* A frameless workspace still owns keyboard focus and the application's main * window role. A plain borderless NSWindow declines both by default. */ @interface VivaFramelessWindow : NSWindow @@ -4313,7 +4644,15 @@ - (void)application:(NSApplication *)application openFiles:(NSArray static VivaApplicationDelegate *viva_application_delegate; +int viva_application_check_thread(void) { + return pthread_main_np() ? 0 : VIVA_APPLICATION_NOT_MAIN_THREAD; +} + int viva_application_begin(void) { + int status = viva_application_check_thread(); + if (status != 0) { + return status; + } @autoreleasepool { if (viva_application_windows != nil) { return 8; @@ -4817,6 +5156,60 @@ void viva_view_render_sync(void *view) { } } +// VivaTextMenuTarget receives the row chosen from a text menu. +@interface VivaTextMenuTarget : NSObject +@property(nonatomic) int chosen; +- (void)choose:(NSMenuItem *)item; +@end + +@implementation VivaTextMenuTarget +- (void)choose:(NSMenuItem *)item { + self.chosen = (int)item.tag; +} +@end + +// viva_text_menu_key is the key equivalent AppKit shows beside a command, as its +// own text fields' menus do. +static NSString *viva_text_menu_key(int command) { + switch (command) { + case 1: return @"x"; + case 2: return @"c"; + case 3: return @"v"; + case 4: return @"a"; + default: return @""; + } +} + +int viva_view_popup_text_menu(void *view, int count, const int *commands, const char *const *titles, + const int *disabled, double x, double y) { + if (view == NULL || count <= 0) { + return 0; + } + @autoreleasepool { + VivaMetalView *target = (VivaMetalView *)view; + VivaTextMenuTarget *chosen = [[[VivaTextMenuTarget alloc] init] autorelease]; + NSMenu *menu = [[[NSMenu alloc] initWithTitle:@""] autorelease]; + menu.autoenablesItems = NO; + for (int index = 0; index < count; index++) { + if (commands[index] == 0) { + [menu addItem:[NSMenuItem separatorItem]]; + continue; + } + NSString *title = [NSString stringWithUTF8String:titles[index] != NULL ? titles[index] : ""]; + NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:title action:@selector(choose:) + keyEquivalent:viva_text_menu_key(commands[index])] autorelease]; + item.keyEquivalentModifierMask = NSEventModifierFlagCommand; + item.tag = commands[index]; + item.target = chosen; + item.enabled = disabled[index] == 0; + [menu addItem:item]; + } + NSPoint location = NSMakePoint(x, target.bounds.size.height - y); + [menu popUpMenuPositioningItem:nil atLocation:location inView:target]; + return chosen.chosen; + } +} + void viva_view_close(void *view) { if (view == NULL) { return; @@ -5003,7 +5396,28 @@ - (instancetype)initWithLibrary:(const unsigned char *)library _size = size; _scale = MAX(scale, 1.0); _clear = clear; - _device = MTLCreateSystemDefaultDevice(); + /* The default stays the system device, which is what a window uses. On + * dual-GPU Intel Macs where offscreen Metal renders black with that device, + * VIVA_HEADLESS_METAL_DEVICE=low-power opts into the integrated GPU. */ + const char *deviceOption = getenv("VIVA_HEADLESS_METAL_DEVICE"); + BOOL preferLowPower = deviceOption != NULL && strcmp(deviceOption, "low-power") == 0; + if (deviceOption != NULL && !preferLowPower && strcmp(deviceOption, "default") != 0) { + fprintf(stderr, "viva: ignoring VIVA_HEADLESS_METAL_DEVICE=%s (expected default or low-power)\n", + deviceOption); + } + if (preferLowPower) { + NSArray> *devices = MTLCopyAllDevices(); + for (id candidate in devices) { + if (candidate.isLowPower) { + _device = [candidate retain]; + break; + } + } + [devices release]; + } + if (_device == nil) { + _device = MTLCreateSystemDefaultDevice(); + } _queue = _device != nil ? [_device newCommandQueue] : nil; if (_queue == nil || library == NULL || length == 0) { [self release]; diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index 1a1dc623b..fe1e96450 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -148,12 +148,14 @@ func (window *nativeWindow) SetAlwaysOnTop(enabled bool) error { } type runState struct { - application *nativeApplication - callbackHandle cgo.Handle - onClosed func() - waker *platform.Waker - closed bool - pointerHandler PointerHandler + application *nativeApplication + callbackHandle cgo.Handle + onClosed func() + waker *platform.Waker + closed bool + pointerHandler PointerHandler + // takeTextMenu is the runtime's text menu for the press just delivered. + takeTextMenu func() (platform.TextMenuRequest, bool) pressAt func(x, y float32) platform.PressKind resizeHandler ResizeHandler frameHandler platform.FrameChangeHandler @@ -367,6 +369,7 @@ func (application *nativeApplication) OpenWindow(config Config) (platform.Window state := &runState{application: application, onClosed: config.OnClosed, waker: config.Waker, closeHandler: config.OnCloseRequest, pressAt: config.PressAt, frameHandler: config.OnFrameChange, minimizeHandler: config.OnMinimize, visibilityHandler: config.OnVisibility, fullscreenHandler: config.OnFullscreen, onReopen: config.OnReopen, onActivate: config.OnActivate} state.pointerHandler = config.OnPointer + state.takeTextMenu = config.TakeTextMenu state.resizeHandler = config.OnResize state.keyHandler = config.OnKey state.focusLostHandler = config.OnFocusLost @@ -464,6 +467,10 @@ func (application *nativeApplication) OpenWindow(config Config) (platform.Window return nil, nativeStatusError(C.viva_application_last_status()) } application.windows++ + if config.Transparent && config.OnTransparentChange != nil { + // The Metal layer and the window turn non-opaque for any clear alpha below one. + config.OnTransparentChange(config.ClearColor.Alpha < 1) + } setApplicationIcon(config.Icon) if config.SetFrameInterval != nil { // Metal's nextDrawable blocks once both drawables are in flight, so the @@ -499,6 +506,8 @@ func nativeStatusError(status C.int) error { return fmt.Errorf("darwin: failed to create initial text texture") case 8: return fmt.Errorf("darwin: application loop is already running") + case C.VIVA_APPLICATION_NOT_MAIN_THREAD: + return fmt.Errorf("darwin: start the application on the process main thread by calling runtime.LockOSThread in an init function in package main") default: return fmt.Errorf("darwin: native application failed with status %d", status) } diff --git a/internal/platform/darwin/run_macos.go b/internal/platform/darwin/run_macos.go index 57d1fa1d8..bdceb1108 100644 --- a/internal/platform/darwin/run_macos.go +++ b/internal/platform/darwin/run_macos.go @@ -9,6 +9,12 @@ import "C" import "github.com/vivaui/viva/internal/platform" +// CheckApplicationThread checks the Cocoa startup requirement before any call +// that would otherwise wait for the main dispatch queue. +func CheckApplicationThread() error { + return nativeStatusError(C.viva_application_check_thread()) +} + // Run enters the Cocoa event loop with one window. func Run(config Config) error { return RunApplication(func(application platform.Application) error { diff --git a/internal/platform/darwin/system_darwin.go b/internal/platform/darwin/system_darwin.go index 8782a3937..3655bc32e 100644 --- a/internal/platform/darwin/system_darwin.go +++ b/internal/platform/darwin/system_darwin.go @@ -38,6 +38,8 @@ type OpenFileOptions struct { type OpenDirectoryOptions struct { Title string + // InitialDirectory is the starting folder. Empty uses the platform default. + InitialDirectory string } type SaveFileOptions struct { @@ -249,6 +251,7 @@ func OpenFiles(options OpenFileOptions) ([]string, bool, error) { var nativeError *C.char status := C.viva_system_open_files( title, + nil, nativeStringPointer(nativeExtensions), C.size_t(len(nativeExtensions)), C.int(systemBoolInt(options.AllowMultiple)), @@ -278,9 +281,14 @@ func OpenDirectory(options OpenDirectoryOptions) (string, bool, error) { return "", false, err } defer C.free(unsafe.Pointer(title)) + directory, err := systemCString("initial directory", options.InitialDirectory) + if err != nil { + return "", false, err + } + defer C.free(unsafe.Pointer(directory)) var result C.viva_system_string_array var nativeError *C.char - status := C.viva_system_open_files(title, nil, 0, 0, 1, &result, &nativeError) + status := C.viva_system_open_files(title, directory, nil, 0, 0, 1, &result, &nativeError) if status == 1 { return "", true, nil } diff --git a/internal/platform/darwin/system_darwin.h b/internal/platform/darwin/system_darwin.h index a4fcbc157..e6f0ce324 100644 --- a/internal/platform/darwin/system_darwin.h +++ b/internal/platform/darwin/system_darwin.h @@ -47,6 +47,7 @@ int viva_system_set_cursor(uint8_t shape, char **error_message); int viva_system_set_cursor_image(int width, int height, int hot_x, int hot_y, double scale, const uint8_t *pixels, char **error_message); int viva_system_open_files( const char *title, + const char *initial_directory, const char *const *extensions, size_t extension_count, int allow_multiple, diff --git a/internal/platform/darwin/system_darwin.m b/internal/platform/darwin/system_darwin.m index 9f72b8d1e..21a3a800f 100644 --- a/internal/platform/darwin/system_darwin.m +++ b/internal/platform/darwin/system_darwin.m @@ -803,6 +803,7 @@ int viva_system_set_cursor_image(int width, int height, int hot_x, int hot_y, do int viva_system_open_files( const char *title, + const char *initial_directory, const char *const *extensions, size_t extension_count, int allow_multiple, @@ -840,6 +841,10 @@ int viva_system_open_files( panel.canChooseDirectories = choose_directories != 0; panel.allowsMultipleSelection = allow_multiple != 0; panel.resolvesAliases = YES; + NSString *directory = viva_string(initial_directory); + if (directory.length > 0) { + panel.directoryURL = [NSURL fileURLWithPath:directory isDirectory:YES]; + } if (panelTitle.length > 0) { panel.title = panelTitle; } diff --git a/internal/platform/darwin/testdata/dock_reopen.m b/internal/platform/darwin/testdata/dock_reopen.m index d173896c2..ce24e5dba 100644 --- a/internal/platform/darwin/testdata/dock_reopen.m +++ b/internal/platform/darwin/testdata/dock_reopen.m @@ -194,3 +194,7 @@ int main(void) { } return 0; } + +// The promised content callbacks the drag source reports to Go. +int vivaFilePromiseContent(intptr_t drag, int item, const char *path) { return 1; } +void vivaFileDragFinished(intptr_t drag) {} diff --git a/internal/platform/darwin/testdata/file_drop.m b/internal/platform/darwin/testdata/file_drop.m index 5837a8cf8..e71475272 100644 --- a/internal/platform/darwin/testdata/file_drop.m +++ b/internal/platform/darwin/testdata/file_drop.m @@ -28,6 +28,25 @@ int vivaFileDropEvent(uintptr_t handle, void *view, int phase, double x, double return drop_answer; } void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) {} +// The promised content callback records what it is asked for and answers as the +// test says. +static int promise_calls, promise_answer = 1, promise_item; +static char promise_path[512]; +int vivaFilePromiseContent(intptr_t drag, int item, const char *path) { + promise_calls++; + promise_item = item; + memset(promise_path, 0, sizeof(promise_path)); + if (path != NULL) { + snprintf(promise_path, sizeof(promise_path), "%s", path); + } + return promise_answer; +} +static int finished_calls; +static intptr_t finished_drag; +void vivaFileDragFinished(intptr_t drag) { + finished_calls++; + finished_drag = drag; +} void vivaViewResized(uintptr_t handle, void *view, double width, double height) {} void vivaRedrawRequested(uintptr_t handle, void *view) {} void vivaKeyEvent(uintptr_t handle, void *view, int key, int modifiers, int repeat, const unsigned char *utf8, size_t utf8Length) {} @@ -125,6 +144,44 @@ int main(void) { int before = drop_calls; assert(![view performDragOperation:(id)drag]); assert(drop_calls == before); + + // The platform's effect bits become what a dragging source reports. + assert(viva_drag_operation(0) == NSDragOperationNone); + assert(viva_drag_operation(1) == NSDragOperationCopy); + assert(viva_drag_operation(2) == NSDragOperationMove); + assert(viva_drag_operation(4) == NSDragOperationLink); + assert(viva_drag_operation(1 | 4) == (NSDragOperationCopy | NSDragOperationLink)); + + // A promised item names itself and asks the application for its content + // at the destination, then completes without an error. + VivaFileDragContext *context = [[VivaFileDragContext alloc] initWithDrag:42]; + VivaFilePromiseDelegate *delegate = [[VivaFilePromiseDelegate alloc] initWithName:@"报告.pdf" item:3 context:context]; + [context release]; + NSFilePromiseProvider *provider = [[NSFilePromiseProvider alloc] initWithFileType:@"public.data" delegate:delegate]; + assert([[delegate filePromiseProvider:provider fileNameForType:@"public.data"] isEqualToString:@"报告.pdf"]); + __block int completed = 0; + __block NSError *failure = nil; + promise_answer = 0; + [delegate filePromiseProvider:provider writePromiseToURL:[NSURL fileURLWithPath:@"/tmp/报告.pdf"] completionHandler:^(NSError *error) { + completed = 1; + failure = error; + }]; + assert(completed == 1 && failure == nil); + assert(promise_calls == 1 && promise_item == 3 && strcmp(promise_path, "/tmp/报告.pdf") == 0); + + // A failure reaches the target as an error rather than an empty file. + completed = 0; + failure = nil; + promise_answer = 1; + [delegate filePromiseProvider:provider writePromiseToURL:[NSURL fileURLWithPath:@"/tmp/failed.txt"] completionHandler:^(NSError *error) { + completed = 1; + failure = error; + }]; + assert(completed == 1 && failure != nil); + [provider release]; + // The provider and its target are gone, so the promises can be forgotten. + [delegate release]; + assert(finished_calls == 1 && finished_drag == 42); printf("file drop: ok\n"); } return 0; diff --git a/internal/platform/darwin/testdata/live_resize.m b/internal/platform/darwin/testdata/live_resize.m index 2be17ebea..ed90feede 100644 --- a/internal/platform/darwin/testdata/live_resize.m +++ b/internal/platform/darwin/testdata/live_resize.m @@ -99,3 +99,7 @@ int main(void) { } return 0; } + +// The promised content callbacks the drag source reports to Go. +int vivaFilePromiseContent(intptr_t drag, int item, const char *path) { return 1; } +void vivaFileDragFinished(intptr_t drag) {} diff --git a/internal/platform/darwin/testdata/modifier_taps.m b/internal/platform/darwin/testdata/modifier_taps.m index 07a2074a3..5ab013d00 100644 --- a/internal/platform/darwin/testdata/modifier_taps.m +++ b/internal/platform/darwin/testdata/modifier_taps.m @@ -109,3 +109,7 @@ int main(void) { printf("modifier taps: ok\n"); return 0; } + +// The promised content callbacks the drag source reports to Go. +int vivaFilePromiseContent(intptr_t drag, int item, const char *path) { return 1; } +void vivaFileDragFinished(intptr_t drag) {} diff --git a/internal/platform/darwin/testdata/text_selection.m b/internal/platform/darwin/testdata/text_selection.m index bf2d9f348..93b0a77d6 100644 --- a/internal/platform/darwin/testdata/text_selection.m +++ b/internal/platform/darwin/testdata/text_selection.m @@ -1272,3 +1272,7 @@ int main(void) { } return 0; } + +// The promised content callbacks the drag source reports to Go. +int vivaFilePromiseContent(intptr_t drag, int item, const char *path) { return 1; } +void vivaFileDragFinished(intptr_t drag) {} diff --git a/internal/platform/darwin/testdata/traffic_lights.m b/internal/platform/darwin/testdata/traffic_lights.m index 04a4b6d75..3f333e0c9 100644 --- a/internal/platform/darwin/testdata/traffic_lights.m +++ b/internal/platform/darwin/testdata/traffic_lights.m @@ -186,3 +186,7 @@ int main(void) { } return 0; } + +// The promised content callbacks the drag source reports to Go. +int vivaFilePromiseContent(intptr_t drag, int item, const char *path) { return 1; } +void vivaFileDragFinished(intptr_t drag) {} diff --git a/internal/platform/darwin/testdata/window_close.m b/internal/platform/darwin/testdata/window_close.m index efda95605..3cb10a1fb 100644 --- a/internal/platform/darwin/testdata/window_close.m +++ b/internal/platform/darwin/testdata/window_close.m @@ -103,3 +103,7 @@ int main(void) { } return 0; } + +// The promised content callbacks the drag source reports to Go. +int vivaFilePromiseContent(intptr_t drag, int item, const char *path) { return 1; } +void vivaFileDragFinished(intptr_t drag) {} diff --git a/internal/platform/darwin/testdata/window_test_callbacks.h b/internal/platform/darwin/testdata/window_test_callbacks.h index a659f6740..26805a1de 100644 --- a/internal/platform/darwin/testdata/window_test_callbacks.h +++ b/internal/platform/darwin/testdata/window_test_callbacks.h @@ -34,3 +34,7 @@ void vivaCompositionInput(uintptr_t handle, void *view, int kind, const unsigned int phase, int64_t rawStart, int64_t rawLength, int hasRaw) {} void vivaTextCompositionLost(uintptr_t handle, void *view, int reason) {} unsigned char *vivaCopyText(uintptr_t handle, void *view, size_t *length) { *length = 0; return NULL; } + +// The promised content callbacks the drag source reports to Go. +int vivaFilePromiseContent(intptr_t drag, int item, const char *path) { return 1; } +void vivaFileDragFinished(intptr_t drag) {} diff --git a/internal/platform/darwin/text_menu_darwin.go b/internal/platform/darwin/text_menu_darwin.go new file mode 100644 index 000000000..4056d6bc0 --- /dev/null +++ b/internal/platform/darwin/text_menu_darwin.go @@ -0,0 +1,53 @@ +//go:build darwin + +package darwin + +/* +#include +#include "native.h" +*/ +import "C" + +import ( + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// showTextMenu shows request as AppKit's menu at the press, waits for it to close, +// and runs the command chosen, presenting the frame that follows. +func showTextMenu(state *runState, view unsafe.Pointer, request platform.TextMenuRequest) error { + count := len(request.Items) + if count == 0 || request.Perform == nil { + return nil + } + commands := make([]C.int, count) + disabled := make([]C.int, count) + titles := make([]*C.char, count) + for index, item := range request.Items { + commands[index] = C.int(item.Command) + if item.Disabled { + disabled[index] = 1 + } + if item.Command != platform.TextMenuNone { + titles[index] = C.CString(item.Title) + } + } + defer func() { + for _, title := range titles { + if title != nil { + C.free(unsafe.Pointer(title)) + } + } + }() + chosen := platform.TextMenuCommand(C.viva_view_popup_text_menu(view, C.int(count), &commands[0], + (**C.char)(unsafe.Pointer(&titles[0])), &disabled[0], C.double(request.X), C.double(request.Y))) + if chosen == platform.TextMenuNone { + return nil + } + frame, err := request.Perform(chosen) + if err != nil { + return err + } + return presentFrame(state, view, frame, false) +} diff --git a/internal/platform/darwin/web_darwin.go b/internal/platform/darwin/web_darwin.go index a3bad7cf4..51fa25105 100644 --- a/internal/platform/darwin/web_darwin.go +++ b/internal/platform/darwin/web_darwin.go @@ -116,11 +116,11 @@ func (w *webState) open(config platform.WebViewConfig) (platform.WebView, error) if view == nil { return nil, platform.ErrWebViewUnsupported } - var url, html, base, scheme *C.char + var url, html, base, scheme, userAgentSuffix *C.char for _, field := range []struct { text string out **C.char - }{{config.URL, &url}, {config.HTML, &html}, {config.BaseURL, &base}} { + }{{config.URL, &url}, {config.HTML, &html}, {config.BaseURL, &base}, {config.UserAgentSuffix, &userAgentSuffix}} { *field.out = C.CString(field.text) defer C.free(unsafe.Pointer(*field.out)) } @@ -149,7 +149,7 @@ func (w *webState) open(config platform.WebViewConfig) (platform.WebView, error) defer C.free(unsafe.Pointer(partition)) } var failure *C.char - native := C.viva_web_open(view, C.uint32_t(config.ID), C.uintptr_t(w.run.callbackHandle), url, html, base, script, mainFrameOnly, scheme, ephemeral, direct, partition, &failure) + native := C.viva_web_open(view, C.uint32_t(config.ID), C.uintptr_t(w.run.callbackHandle), url, html, base, script, mainFrameOnly, scheme, ephemeral, direct, userAgentSuffix, partition, &failure) if native == nil { message := "the page could not be created" if failure != nil { @@ -255,6 +255,20 @@ func (page *darwinWeb) Focus() { } } +// ShowDevTools opens Web Inspector for the page. A WebKit without the inspector SPI still leaves the +// page inspectable, and says it could not open the inspector itself. +func (page *darwinWeb) ShowDevTools() error { + if !page.usable() { + return fmt.Errorf("darwin: the web view with id %d is closed", page.id) + } + if C.viva_web_show_dev_tools(page.native) == 0 { + return fmt.Errorf("%w: this WebKit cannot open Web Inspector from the application; the page is inspectable from its context menu or Safari's Develop menu", platform.ErrWebViewUnsupported) + } + return nil +} + +var _ platform.WebDevTools = (*darwinWeb)(nil) + func (page *darwinWeb) Close() { if !page.usable() { return diff --git a/internal/platform/darwin/web_darwin.h b/internal/platform/darwin/web_darwin.h index 5847f4ea8..d8c16db70 100644 --- a/internal/platform/darwin/web_darwin.h +++ b/internal/platform/darwin/web_darwin.h @@ -19,7 +19,7 @@ void *viva_application_window_view(void *token); // with an error on an older system rather than opened in the default store. void *viva_web_open(void *view, uint32_t id, uintptr_t handle, const char *url, const char *html, const char *base, const char *script, int main_frame_only, const char *scheme, int ephemeral, int direct, - const char *partition, char **error); + const char *user_agent_suffix, const char *partition, char **error); int viva_web_direct_supported(void); // viva_web_partition_supported answers whether this system can name the persistent store a partition uses. int viva_web_partition_supported(void); @@ -30,6 +30,9 @@ void viva_web_back(void *web); void viva_web_forward(void *web); void viva_web_eval(void *web, const char *script); void viva_web_focus(void *web); +// viva_web_show_dev_tools makes the page inspectable and opens Web Inspector for it: 1 when it was +// opened, 0 when this WebKit has no way to open it from the application. +int viva_web_show_dev_tools(void *web); // viva_web_title is the title of the page's current document, as a malloc'd UTF-8 string which the // caller frees, and an empty string when it has none. viva_web_can_go_back, // viva_web_can_go_forward and viva_web_is_loading answer the page's history and its loading, 1 or 0. diff --git a/internal/platform/darwin/web_darwin.m b/internal/platform/darwin/web_darwin.m index 1459e1bad..504666b12 100644 --- a/internal/platform/darwin/web_darwin.m +++ b/internal/platform/darwin/web_darwin.m @@ -5,6 +5,8 @@ #import #import +#import + #include #include @@ -401,11 +403,14 @@ @interface VivaWebView : WKWebView { VivaWebBridge *_bridge; NSTrackingArea *_tracking; CGFloat _topCornerRadius; + BOOL _devToolsOpened; } - (void)setTopCornerRadius:(CGFloat)radius; - (void)setBridge:(VivaWebBridge *)bridge; - (void)setCutRects:(NSArray *)cuts masks:(NSArray *)masks; - (void)cancelSchemeTasks; +- (void)setDevToolsOpened:(BOOL)opened; +- (void)closeDevTools; @end @implementation VivaWebView @@ -434,6 +439,26 @@ - (void)cancelSchemeTasks { [_bridge cancelTasks]; } +- (void)setDevToolsOpened:(BOOL)opened { + _devToolsOpened = opened; +} + +- (void)closeDevTools { + if (!_devToolsOpened) { + return; + } + _devToolsOpened = NO; + SEL inspectorSelector = NSSelectorFromString(@"_inspector"); + if (![self respondsToSelector:inspectorSelector]) { + return; + } + id inspector = ((id (*)(id, SEL))objc_msgSend)(self, inspectorSelector); + SEL closeSelector = NSSelectorFromString(@"close"); + if (inspector != nil && [inspector respondsToSelector:closeSelector]) { + ((void (*)(id, SEL))objc_msgSend)(inspector, closeSelector); + } +} + - (NSView *)hitTest:(NSPoint)point { // The point is in the superview's coordinates. if (_topCornerRadius > 0) { @@ -594,7 +619,7 @@ static int viva_web_named_store(WKWebViewConfiguration *configuration, const cha void *viva_web_open(void *view, uint32_t id, uintptr_t handle, const char *url, const char *html, const char *base, const char *script, int mainFrameOnly, const char *scheme, int ephemeral, int direct, - const char *partition, char **error) { + const char *user_agent_suffix, const char *partition, char **error) { __block VivaWebView *web = nil; viva_web_main(^{ NSView *host = (NSView *)view; @@ -605,6 +630,10 @@ static int viva_web_named_store(WKWebViewConfiguration *configuration, const cha bridge->_handle = handle; bridge->_id = id; WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; + if (user_agent_suffix != NULL && user_agent_suffix[0] != 0) { + // Set the application product before creating the page or its first request. + configuration.applicationNameForUserAgent = [NSString stringWithUTF8String:user_agent_suffix]; + } if (partition != NULL && partition[0] != 0) { // A named partition is a store of its own, which WebKit keeps under an identifier: pages // of one identifier share their cookies and storage, pages of another do not. @@ -727,6 +756,41 @@ void viva_web_focus(void *web) { }); } +int viva_web_show_dev_tools(void *web) { + __block int shown = 0; + viva_web_main(^{ + VivaWebView *view = (VivaWebView *)web; + // The public API only makes a page inspectable (macOS 13.3): the user then opens Web + // Inspector from the context menu or Safari's Develop menu. developerExtrasEnabled is the + // preference behind that menu entry on every release; the configuration copy shares the + // page's preferences object. Neither is turned on before the application asks. + @try { + [view.configuration.preferences setValue:@YES forKey:@"developerExtrasEnabled"]; + } @catch (NSException *exception) { + } +#if defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 130300 + if (@available(macOS 13.3, *)) { + view.inspectable = YES; + } +#endif + // Opening the inspector itself has no public API: WKWebView's _inspector (WKInspector) is + // WebKit SPI, used only when this WebKit answers it. + SEL inspectorSelector = NSSelectorFromString(@"_inspector"); + if (![view respondsToSelector:inspectorSelector]) { + return; + } + id inspector = ((id (*)(id, SEL))objc_msgSend)(view, inspectorSelector); + SEL showSelector = NSSelectorFromString(@"show"); + if (inspector == nil || ![inspector respondsToSelector:showSelector]) { + return; + } + ((void (*)(id, SEL))objc_msgSend)(inspector, showSelector); + [view setDevToolsOpened:YES]; + shown = 1; + }); + return shown; +} + char *viva_web_title(void *web) { __block char *title = NULL; viva_web_main(^{ @@ -758,6 +822,7 @@ int viva_web_is_loading(void *web) { void viva_web_close(void *web) { viva_web_main(^{ VivaWebView *view = (VivaWebView *)web; + [view closeDevTools]; [view cancelSchemeTasks]; [view.configuration.userContentController removeScriptMessageHandlerForName:@"viva"]; view.navigationDelegate = nil; diff --git a/internal/platform/drag.go b/internal/platform/drag.go index 5774af788..92ce33982 100644 --- a/internal/platform/drag.go +++ b/internal/platform/drag.go @@ -1,14 +1,128 @@ package platform -import "errors" +import ( + "errors" + "fmt" + "io" + "strings" +) // ErrDragUnsupported reports that this target has no way to take files out of a // window by dragging them: the application can still offer the files, but only // by copying them (see SetClipboardFiles), which tells the user something else. -// The Web target has no drag of its own to start, macOS needs a dragging session -// and Linux a drag-and-drop protocol, and neither is bound yet. +// The Web target has no drag of its own to start, and a target may lack the +// promise drag described by FilePromise. var ErrDragUnsupported = errors.New("dragging files out of a window is unsupported") +// FilePromise is one item of a drag whose content the application produces when +// the target asks for it, instead of a path that already exists on this +// computer. Dragging a file off a remote server is this: the file is downloaded +// where the user lets go, while the target copies, so nothing is fetched when +// the drag starts. +// +// Name is one path component, unique among its siblings. A file's Open returns +// its bytes when the target reads them; a directory's List returns its children +// on demand, each named relative to it. Both callbacks may run on a goroutine +// other than the one that started the drag, and may run more than once. +type FilePromise struct { + Name string + Size int64 // -1 when unknown; a directory is 0 + Directory bool + Open func() (io.ReadCloser, error) // nil for a directory + List func() ([]FilePromise, error) // nil for a file +} + +// maxFilePromiseDepth bounds how deep a promised directory tree may nest, so a +// tree that keeps producing children cannot walk the stack away. +const maxFilePromiseDepth = 64 + +// ValidateFilePromises checks one level of promises: names, sibling uniqueness +// and the callbacks each kind needs. It does not call List, so validating a tree +// costs nothing; WalkFilePromises validates each level as it reaches it. +func ValidateFilePromises(promises []FilePromise) error { return validateFilePromises(promises, "") } + +func validateFilePromises(promises []FilePromise, at string) error { + seen := make(map[string]struct{}, len(promises)) + for _, promise := range promises { + if err := validateFilePromise(promise); err != nil { + return fmt.Errorf("app: file promise %q: %w", promise.Name, err) + } + if _, duplicate := seen[promise.Name]; duplicate { + return fmt.Errorf("app: two file promises in %q are named %q", at, promise.Name) + } + seen[promise.Name] = struct{}{} + } + return nil +} + +func validateFilePromise(promise FilePromise) error { + name := promise.Name + if name == "" || name == "." || name == ".." || strings.ContainsAny(name, "/\\\x00") { + return fmt.Errorf("a name is one path component") + } + if promise.Directory { + if promise.Open != nil { + return fmt.Errorf("a directory cannot open file content") + } + if promise.List == nil { + return fmt.Errorf("a directory needs the list of its children") + } + return nil + } + if promise.Open == nil { + return fmt.Errorf("a file needs its content") + } + if promise.List != nil { + return fmt.Errorf("a file cannot list children") + } + if promise.Size < -1 { + return fmt.Errorf("a size below -1 is not a size") + } + return nil +} + +// WalkFilePromises visits every promise under roots depth-first, the directory +// before its children, with path its slash-separated path from the drag root. It +// validates each level and refuses a tree with more than MaxClipboardFiles +// items, the bound one drag may carry. +func WalkFilePromises(roots []FilePromise, visit func(path string, promise FilePromise) error) error { + count := 0 + var walk func(prefix string, promises []FilePromise, depth int) error + walk = func(prefix string, promises []FilePromise, depth int) error { + if depth > maxFilePromiseDepth { + return fmt.Errorf("app: file promise %q nests deeper than %d levels", prefix, maxFilePromiseDepth) + } + if err := validateFilePromises(promises, prefix); err != nil { + return err + } + for _, promise := range promises { + count++ + if count > MaxClipboardFiles { + return fmt.Errorf("app: a drag takes at most %d files", MaxClipboardFiles) + } + path := promise.Name + if prefix != "" { + path = prefix + "/" + promise.Name + } + if err := visit(path, promise); err != nil { + return err + } + if !promise.Directory { + continue + } + children, err := promise.List() + if err != nil { + return fmt.Errorf("app: list the children of %q: %w", path, err) + } + if err := walk(path, children, depth+1); err != nil { + return err + } + } + return nil + } + return walk("", roots, 0) +} + // DragEffect is what letting go of dragged files does to them where they land: a // copy leaves them where they were, a move hands them to the target, and a link // leaves a reference behind. The values are the OLE DROPEFFECT flags Windows diff --git a/internal/platform/linux/atspi_bridge.go b/internal/platform/linux/atspi_bridge.go index eaa09f090..d08d9cae6 100644 --- a/internal/platform/linux/atspi_bridge.go +++ b/internal/platform/linux/atspi_bridge.go @@ -8,6 +8,7 @@ import ( "path/filepath" "strconv" "strings" + "unicode/utf8" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/dbus" @@ -437,13 +438,17 @@ func (bridge *atspiBridge) announceChanges(window *atspiWindow, path string, old } isText := next.Patterns().Has(platform.PatternText) if isText && changed&platform.ChangedValue != 0 { - before, after := []rune(old.Value), []rune(next.Value) - start, removed, added := atspiTextEdit(before, after) - if removed > 0 { - bridge.emit(path, atspiEventObject, "TextChanged", "delete", int32(start), int32(removed), string(before[start:start+removed])) - } - if added > 0 { - bridge.emit(path, atspiEventObject, "TextChanged", "insert", int32(start), int32(added), string(after[start:start+added])) + start, removed, added := atspiTextEdit(old.Value, next.Value) + for _, change := range [...]struct{ kind, value string }{{"delete", removed}, {"insert", added}} { + if change.value == "" { + continue + } + length := utf8.RuneCountInString(change.value) + value := change.value + if !utf8.ValidString(value) { + value = string([]rune(value)) + } + bridge.emit(path, atspiEventObject, "TextChanged", change.kind, int32(start), int32(length), value) } } if isText && changed&platform.ChangedSelection != 0 && next.Selection.Valid { diff --git a/internal/platform/linux/atspi_bridge_test.go b/internal/platform/linux/atspi_bridge_test.go index 98d3beafb..63fa1bc7f 100644 --- a/internal/platform/linux/atspi_bridge_test.go +++ b/internal/platform/linux/atspi_bridge_test.go @@ -3,6 +3,7 @@ package linux import ( + "reflect" "strconv" "strings" "testing" @@ -326,6 +327,74 @@ func TestAtspiEventsNameWhatChanged(t *testing.T) { } } +func TestAtspiTextChangePreservesRuneOffsetsAndPayload(t *testing.T) { + type change struct { + kind string + start, length int32 + value string + } + for _, test := range []struct { + name, before, after string + want []change + }{ + {"replace", "a界e\u0301尾", "a界\U0001f642尾", []change{{"delete", 2, 2, "e\u0301"}, {"insert", 2, 1, "\U0001f642"}}}, + {"insert at end", "界", "界尾", []change{{"insert", 1, 1, "尾"}}}, + {"delete repeated rune", "界尾尾", "界尾", []change{{"delete", 2, 1, "尾"}}}, + {"delete all", "界", "", []change{{"delete", 0, 1, "界"}}}, + {"empty before", "", "界", []change{{"insert", 0, 1, "界"}}}, + {"invalid unchanged", "\xff", "\ufffd", nil}, + {"invalid ends match", "\xffab\xfe", "\ufffd界b\ufffd", []change{{"delete", 1, 1, "a"}, {"insert", 1, 1, "界"}}}, + {"invalid changed payload", "a\xff\xfe", "a界", []change{{"delete", 1, 2, "\ufffd\ufffd"}, {"insert", 1, 1, "界"}}}, + {"invalid insert payload", "界", "界\xff", []change{{"insert", 1, 1, "\ufffd"}}}, + } { + t.Run(test.name, func(t *testing.T) { + var got []change + bridge := atspiBridge{send: func(_, iface, member, signature string, body []byte) error { + args := dbus.NewDecoder(body) + kind, start, length := args.String(), args.Int32(), args.Int32() + if iface != atspiEventObject || member != "TextChanged" || signature != "siiva{sv}" || args.Signature() != "s" { + t.Fatalf("unexpected text signal: %s %s %s", iface, member, signature) + } + got = append(got, change{kind, start, length, args.String()}) + return nil + }} + before := platform.AccessibilityNode{Role: platform.A11yRoleTextField, Value: test.before} + after := before + after.Value = test.after + bridge.announceChanges(nil, "/text", before, after) + if !reflect.DeepEqual(got, test.want) { + t.Fatalf("text changes = %+v, want %+v", got, test.want) + } + }) + } +} + +func TestAtspiTextChangeAllocationDoesNotGrowWithUnchangedText(t *testing.T) { + bridge := atspiBridge{send: func(_, _, _, _ string, _ []byte) error { return nil }} + allocations := func(suffix string) float64 { + before := platform.AccessibilityNode{Role: platform.A11yRoleTextField, Value: "a界" + suffix} + after := before + after.Value = "a尾" + suffix + return testing.AllocsPerRun(5, func() { bridge.announceChanges(nil, "/text", before, after) }) + } + short := allocations("z") + if long := allocations(strings.Repeat("z", 1<<20)); long > short { + t.Fatalf("large value used %g allocations, small value used %g", long, short) + } +} + +func BenchmarkAtspiTextChangeLargeValue(b *testing.B) { + bridge := atspiBridge{send: func(_, _, _, _ string, _ []byte) error { return nil }} + suffix := strings.Repeat("a", (16<<20)-4) + before := platform.AccessibilityNode{Role: platform.A11yRoleTextField, Value: "a界" + suffix} + after := before + after.Value = "a尾" + suffix + b.ReportAllocs() + for b.Loop() { + bridge.announceChanges(nil, "/text", before, after) + } +} + func TestAtspiAnnouncesFocusWhenAddingAControl(t *testing.T) { nodes := demoNodes() nodes[4].Focused = true diff --git a/internal/platform/linux/atspi_model.go b/internal/platform/linux/atspi_model.go index 7ece368ed..2ac3e56c0 100644 --- a/internal/platform/linux/atspi_model.go +++ b/internal/platform/linux/atspi_model.go @@ -2,6 +2,7 @@ package linux import ( "strconv" + "unicode/utf8" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" @@ -411,14 +412,38 @@ func atspiTextAfter(text []rune, offset int, granularity uint32) (string, int, i // atspiTextEdit describes the change from one text to another as the single // span that was removed and the text put in its place, found by trimming what // the two share at both ends. -func atspiTextEdit(old, next []rune) (start, removed, added int) { - for start < len(old) && start < len(next) && old[start] == next[start] { +func atspiTextEdit(old, next string) (start int, removed, added string) { + oldStart, nextStart := 0, 0 + for oldStart < len(old) && nextStart < len(next) { + if value := old[oldStart]; value < utf8.RuneSelf && value == next[nextStart] { + oldStart++ + nextStart++ + start++ + continue + } + oldRune, oldWidth := utf8.DecodeRuneInString(old[oldStart:]) + nextRune, nextWidth := utf8.DecodeRuneInString(next[nextStart:]) + if oldRune != nextRune { + break + } + oldStart += oldWidth + nextStart += nextWidth start++ } oldEnd, nextEnd := len(old), len(next) - for oldEnd > start && nextEnd > start && old[oldEnd-1] == next[nextEnd-1] { - oldEnd-- - nextEnd-- + for oldEnd > oldStart && nextEnd > nextStart { + if value := old[oldEnd-1]; value < utf8.RuneSelf && value == next[nextEnd-1] { + oldEnd-- + nextEnd-- + continue + } + oldRune, oldWidth := utf8.DecodeLastRuneInString(old[oldStart:oldEnd]) + nextRune, nextWidth := utf8.DecodeLastRuneInString(next[nextStart:nextEnd]) + if oldRune != nextRune { + break + } + oldEnd -= oldWidth + nextEnd -= nextWidth } - return start, oldEnd - start, nextEnd - start + return start, old[oldStart:oldEnd], next[nextStart:nextEnd] } diff --git a/internal/platform/linux/clipboard_image_linux_test.go b/internal/platform/linux/clipboard_image_linux_test.go index b7b308e2d..6d2a1fc9c 100644 --- a/internal/platform/linux/clipboard_image_linux_test.go +++ b/internal/platform/linux/clipboard_image_linux_test.go @@ -131,8 +131,19 @@ func TestClipboardImageAfterExternalOwnerReplacesCachedText(t *testing.T) { t.Fatal(err) } // Do not pump the window's pending SelectionClear event. - if owner, err := selectionOwner(win.api, win.connection, win.clipboardAtom); err != nil || owner == win.id { - t.Fatalf("external owner did not claim the clipboard: %d, %v", owner, err) + deadline := time.Now().Add(2 * time.Second) + for { + owner, err := selectionOwner(win.api, win.connection, win.clipboardAtom) + if err != nil { + t.Fatal(err) + } + if owner != xcbAtomNone && owner != win.id { + break + } + if !time.Now().Before(deadline) { + t.Fatalf("external owner did not claim the clipboard: %d", owner) + } + time.Sleep(10 * time.Millisecond) } got, err := ClipboardImagePNG() if err != nil || !bytes.Equal(got, picture) { diff --git a/internal/platform/linux/drag_linux.go b/internal/platform/linux/drag_linux.go index a5ef05150..388421f35 100644 --- a/internal/platform/linux/drag_linux.go +++ b/internal/platform/linux/drag_linux.go @@ -3,18 +3,542 @@ package linux import ( + "encoding/binary" "fmt" + "io" + "os" + "path/filepath" + "strings" + "time" + "unsafe" "github.com/vivaui/viva/internal/platform" ) -// StartFileDrag cannot offer files from a window on Linux yet. Dragging out is -// the XDND protocol from the source's side: the window becomes the source, -// offers the paths as text/uri-list on the XdndSelection, answers the target's -// XdndStatus and the conversion requests while the drag lasts, and finishes it -// when the pointer is released. This adapter speaks XDND as a target only (see -// drop_linux.go), so the window can offer its files only by copying them (see -// SetClipboardFiles), which is a different promise to the user. -func StartFileDrag(paths []string, allowed platform.DragEffect) (platform.DragEffect, error) { - return platform.DragEffectNone, fmt.Errorf("%w: the X11 adapter takes XDND drops but does not offer them", platform.ErrDragUnsupported) +// Dragging files out of a window is XDND from the source's side: the window +// under the pointer is told what the drag carries, follows the pointer with +// XdndPosition, and the target either answers XdndStatus (it takes the drop) or +// ignores it. The files themselves are the XdndSelection the target reads when +// the drop happens, as text/uri-list. +// +// X11 file managers only copy files that already exist, so a drag of promised +// content is staged first: the application's Open and List write a private +// temporary copy while the pointer moves, and XdndDrop waits for that copy when +// the user lets go before the drop would otherwise happen. A drag of paths has +// nothing to stage. +// +// The source runs entirely on the event-loop thread. The staging goroutine +// reports back through application.Post; it never touches the X connection. + +const ( + // xdndSourceVersion is the XDND protocol version offered. + xdndSourceVersion = 5 + // sourceDragAction is the only action a drag out offers: a copy leaves the + // files where they came from. A move would have to delete the source. + sourceDragAction = 1 // XdndActionCopy is interned; this is the fallback. + // dragStagingPrefix names the private directories promised drags are staged in. + dragStagingPrefix = "viva-drag-" + // dragStagingAge is how old a staging directory must be before a later drag + // removes it. No timer does this; the removal happens when a drag starts. + dragStagingAge = 24 * time.Hour +) + +// xdndSource is one drag out of this window. The event-loop thread owns every +// field; the staging goroutine only reports a generation through Post. +type xdndSource struct { + active bool + target uint32 + entered bool + accepted bool + time uint32 + rootX int16 + rootY int16 + uris []string + staging string + ready bool + failed bool + pendingDrop bool + dropped bool + generation uint64 +} + +// StartFileDrag takes files that exist at paths out of the window handling the +// current press. X11 offers them as text/uri-list and only a copy. +func StartFileDrag(paths []string, allowed platform.DragEffect) error { + if len(paths) == 0 { + return fmt.Errorf("linux: no files to drag out of the window") + } + win := activeWindow.Load() + if win == nil || win.connection == 0 { + return fmt.Errorf("linux: dragging files out needs a running window") + } + return win.startDragOut(paths, nil) +} + +// StartFilePromiseDrag takes promised files out of the window handling the +// current press: they are written to a private staging directory while the +// pointer moves and offered to the target from there. +func StartFilePromiseDrag(files []platform.FilePromise) error { + if len(files) == 0 { + return fmt.Errorf("linux: no files to drag out of the window") + } + win := activeWindow.Load() + if win == nil || win.connection == 0 { + return fmt.Errorf("linux: dragging files out needs a running window") + } + return win.startDragOut(nil, files) +} + +func (win *window) startDragOut(paths []string, files []platform.FilePromise) error { + if win.source.active { + return fmt.Errorf("linux: another file drag is already running") + } + if err := win.ensureDragSourceAtoms(); err != nil { + return err + } + if err := win.ensureClipboardAtoms(); err != nil { + return err + } + target := win.dragTargetAt() + if target == 0 { + return fmt.Errorf("linux: no window under the pointer takes a drop") + } + removeStaleDragStaging() + source := xdndSource{ + active: true, target: target, entered: true, + time: win.lastEventTime, rootX: win.lastRootX, rootY: win.lastRootY, + generation: win.dragGeneration + 1, + } + if paths != nil { + source.uris = append([]string(nil), paths...) + source.ready = true + } else { + dir, err := os.MkdirTemp("", dragStagingPrefix) + if err != nil { + return fmt.Errorf("linux: stage the dragged files: %w", err) + } + source.staging = dir + source.uris = make([]string, len(files)) + for index, promise := range files { + source.uris[index] = filepath.Join(dir, promise.Name) + } + } + win.dragGeneration = source.generation + win.source = source + win.api.setSelectionOwner(win.connection, win.id, win.xdnd.selection, source.time) + win.sendXdndEnter(target) + win.sendXdndPosition(target, source.rootX, source.rootY, source.time) + win.api.flush(win.connection) + if files != nil { + go win.stagePromisedFiles(files, source.staging, source.generation) + } + return nil +} + +// stagePromisedFiles writes the promises into their staging directory and tells +// the loop when it is done. It runs off the event loop; all it shares with the +// loop is the generation it was started for. +func (win *window) stagePromisedFiles(files []platform.FilePromise, root string, generation uint64) { + err := stageFilePromises(files, root) + win.application.Post(func() { + if !win.source.active || win.source.generation != generation { + return + } + if err != nil { + win.source.failed = true + if win.source.pendingDrop { + win.cancelSourceDrag() + } + return + } + win.source.ready = true + if win.source.pendingDrop { + win.dropSourceDrag() + } + }) +} + +func stageFilePromises(files []platform.FilePromise, root string) error { + for _, promise := range files { + target := filepath.Join(root, promise.Name) + if promise.Directory { + if err := os.MkdirAll(target, 0o755); err != nil { + return err + } + children, err := promise.List() + if err != nil { + return err + } + if err := platform.WalkFilePromises(children, func(relative string, child platform.FilePromise) error { + target := filepath.Join(root, promise.Name, filepath.FromSlash(relative)) + if child.Directory { + return os.MkdirAll(target, 0o755) + } + return stagePromiseFile(child, target) + }); err != nil { + return err + } + continue + } + if err := stagePromiseFile(promise, target); err != nil { + return err + } + } + return nil +} + +func stagePromiseFile(promise platform.FilePromise, target string) error { + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + reader, err := promise.Open() + if err != nil { + return err + } + defer reader.Close() + file, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) + if err != nil { + return err + } + if _, err := io.Copy(file, reader); err != nil { + file.Close() + os.Remove(target) + return err + } + if err := file.Close(); err != nil { + os.Remove(target) + return err + } + return nil +} + +// removeStaleDragStaging removes staging directories a much earlier drag left +// behind. The target copies from them after the drop, so they cannot be removed +// when the drop is sent; this one scan, run when a drag starts, keeps /tmp from +// collecting them forever without a timer. +func removeStaleDragStaging() { + entries, err := os.ReadDir(os.TempDir()) + if err != nil { + return + } + for _, entry := range entries { + if !entry.IsDir() || !strings.HasPrefix(entry.Name(), dragStagingPrefix) { + continue + } + info, err := entry.Info() + if err != nil || time.Since(info.ModTime()) < dragStagingAge { + continue + } + os.RemoveAll(filepath.Join(os.TempDir(), entry.Name())) + } +} + +// noteInputEvent remembers the pointer event the loop just saw, so a drag the +// application starts from its handler knows where the press was and when. +func (win *window) noteInputEvent(input *xcbInputEvent) { + win.lastRootX, win.lastRootY = input.RootX, input.RootY + if input.Time != 0 { + win.lastEventTime = input.Time + } +} + +// isSourceDragMessage reports whether a client message is the target answering +// this window's drag. +func (win *window) isSourceDragMessage(kind uint32) bool { + return win.source.active && (kind == win.xdnd.status || kind == win.xdnd.finished) +} + +// ensureDragSourceAtoms interns what both sides of the handshake use. The +// window may never have taken drops, so this does not depend on setupFileDrop. +func (win *window) ensureDragSourceAtoms() error { + if win.xdnd.enter != 0 && win.xdnd.selection != 0 && win.xdnd.proxy != 0 { + return nil + } + for _, entry := range []struct { + atom *uint32 + name string + }{ + {&win.xdnd.aware, "XdndAware"}, {&win.xdnd.enter, "XdndEnter"}, + {&win.xdnd.position, "XdndPosition"}, {&win.xdnd.status, "XdndStatus"}, + {&win.xdnd.leave, "XdndLeave"}, {&win.xdnd.drop, "XdndDrop"}, + {&win.xdnd.finished, "XdndFinished"}, {&win.xdnd.selection, "XdndSelection"}, + {&win.xdnd.actionCopy, "XdndActionCopy"}, {&win.xdnd.uriList, "text/uri-list"}, + {&win.xdnd.proxy, "XdndProxy"}, + } { + atom, err := win.api.atom(win.connection, entry.name) + if err != nil { + return err + } + if *entry.atom == 0 { + *entry.atom = atom + } + } + return nil +} + +// dragTargetAt finds the window under the pointer that speaks XDND. The pointer +// is over this window's children or another application's; the walk descends to +// the deepest window and then up to the first that set XdndAware, following a +// proxy when it has one. +func (win *window) dragTargetAt() uint32 { + if win.xdnd.aware == 0 { + return 0 + } + window := win.deepestWindowAtPointer() + for depth := 0; window != 0 && window != win.screen.Root && depth < 64; depth++ { + if window == win.id { + return 0 + } + if win.hasAtomProperty(window, win.xdnd.aware) { + if proxy, ok := win.uint32Property(window, win.xdnd.proxy); ok && proxy != 0 { + return proxy + } + return window + } + parent, ok := win.windowParent(window) + if !ok { + return 0 + } + window = parent + } + return 0 +} + +func (win *window) deepestWindowAtPointer() uint32 { + window := win.screen.Root + for depth := 0; depth < 64; depth++ { + var nativeError unsafe.Pointer + reply := win.api.queryPointerReply(win.connection, win.api.queryPointer(win.connection, window), &nativeError) + if nativeError != nil { + win.api.free(nativeError) + } + if reply == nil { + return 0 + } + child := reply.Child + win.api.free(unsafe.Pointer(reply)) + if child == 0 { + return window + } + window = child + } + return window +} + +func (win *window) windowParent(window uint32) (uint32, bool) { + var nativeError unsafe.Pointer + reply := win.api.queryTreeReply(win.connection, win.api.queryTree(win.connection, window), &nativeError) + if nativeError != nil { + win.api.free(nativeError) + } + if reply == nil { + return 0, false + } + parent := reply.Parent + win.api.free(unsafe.Pointer(reply)) + return parent, true +} + +func (win *window) hasAtomProperty(window, atom uint32) bool { + if atom == 0 { + return false + } + var nativeError unsafe.Pointer + reply := win.api.getPropertyReply(win.connection, win.api.getProperty(win.connection, 0, window, atom, xcbAtomAtom, 0, 0), &nativeError) + if nativeError != nil { + win.api.free(nativeError) + } + if reply == nil { + return false + } + present := reply.Type != 0 + win.api.free(unsafe.Pointer(reply)) + return present +} + +func (win *window) uint32Property(window, atom uint32) (uint32, bool) { + if atom == 0 { + return 0, false + } + var nativeError unsafe.Pointer + reply := win.api.getPropertyReply(win.connection, win.api.getProperty(win.connection, 0, window, atom, xcbAtomAtom, 0, 1), &nativeError) + if nativeError != nil { + win.api.free(nativeError) + } + if reply == nil { + return 0, false + } + defer win.api.free(unsafe.Pointer(reply)) + if reply.Type == 0 || reply.ValueLength < 1 { + return 0, false + } + return *(*uint32)(win.api.getPropertyValue(reply)), true +} + +// sourceDragMotion follows the pointer: a target that changed gets XdndLeave, +// and the one under the pointer now gets XdndPosition. +func (win *window) sourceDragMotion(input *xcbInputEvent) { + if !win.source.active || win.source.dropped { + return + } + win.source.rootX, win.source.rootY, win.source.time = input.RootX, input.RootY, input.Time + target := win.dragTargetAt() + if target != win.source.target { + if win.source.entered { + win.sendXdndLeave(win.source.target) + } + win.source.target, win.source.entered, win.source.accepted = target, false, false + if target != 0 { + win.sendXdndEnter(target) + win.source.entered = true + } + } + if win.source.target != 0 { + win.sendXdndPosition(win.source.target, input.RootX, input.RootY, input.Time) + } + win.api.flush(win.connection) +} + +// sourceDragRelease ends the gesture where the pointer was released. A target +// that did not accept takes nothing; one that did gets XdndDrop, after the +// promised files are staged if they are not yet. +func (win *window) sourceDragRelease(input *xcbInputEvent) { + if !win.source.active || win.source.dropped { + return + } + win.source.time = input.Time + if win.source.target == 0 || !win.source.accepted { + win.cancelSourceDrag() + return + } + if win.source.ready { + win.dropSourceDrag() + return + } + win.source.pendingDrop = true +} + +// sourceDragEscape cancels the drag, as Escape cancels every drag on the desktop. +func (win *window) sourceDragEscape() { + if win.source.active && !win.source.dropped { + win.cancelSourceDrag() + } +} + +func (win *window) sendXdndEnter(target uint32) { + var data [5]uint32 + data[0] = win.id + data[1] = xdndSourceVersion << 24 // no type list: one type fits in the message + data[2] = win.xdnd.uriList + win.sendClientMessage(target, win.xdnd.enter, &data) +} + +func (win *window) sendXdndPosition(target uint32, rootX, rootY int16, at uint32) { + var data [5]uint32 + data[0] = win.id + data[2] = uint32(uint16(rootX))<<16 | uint32(uint16(rootY)) + data[3] = at + data[4] = win.xdnd.actionCopy + win.sendClientMessage(target, win.xdnd.position, &data) +} + +func (win *window) sendXdndLeave(target uint32) { + if target == 0 { + return + } + var data [5]uint32 + data[0] = win.id + win.sendClientMessage(target, win.xdnd.leave, &data) +} + +func (win *window) sendClientMessage(target, kind uint32, data *[5]uint32) { + event := xcbClientEvent{ + ResponseType: xcbClientMessage, + Format: 32, + Window: target, + Type: kind, + } + for index, value := range data { + binary.LittleEndian.PutUint32(event.Data[index*4:], value) + } + win.api.sendEvent(win.connection, 0, target, 0, (*byte)(unsafe.Pointer(&event))) +} + +// handleSourceDragMessage takes the target's answers: XdndStatus says whether +// the point takes the drop, and XdndFinished says the target is done with the +// selection. +func (win *window) handleSourceDragMessage(message *xcbClientEvent) { + if !win.source.active { + return + } + first, second := clientLong(message, 0), clientLong(message, 1) + if first != win.source.target { + return + } + switch message.Type { + case win.xdnd.status: + if win.source.dropped { + return + } + win.source.accepted = second&1 != 0 + case win.xdnd.finished: + win.finishSourceDrag() + } +} + +func (win *window) dropSourceDrag() { + if !win.source.active || win.source.dropped { + return + } + if win.source.target == 0 || !win.source.accepted { + win.cancelSourceDrag() + return + } + win.source.dropped = true + var data [5]uint32 + data[0] = win.id + data[2] = win.source.time + win.sendClientMessage(win.source.target, win.xdnd.drop, &data) + win.api.flush(win.connection) +} + +func (win *window) cancelSourceDrag() { + if !win.source.active { + return + } + if win.source.entered && win.source.target != 0 { + win.sendXdndLeave(win.source.target) + } + win.finishSourceDrag() +} + +func (win *window) finishSourceDrag() { + if !win.source.active { + return + } + selection := win.xdnd.selection + win.source = xdndSource{} + if selection != 0 && win.connection != 0 { + win.api.setSelectionOwner(win.connection, xcbAtomNone, selection, 0) + win.api.flush(win.connection) + } +} + +// answerXdndSelection serves the target's request for the drag's file list. The +// caller holds win.mu, as it does for the clipboard's own selections. +func (win *window) answerXdndSelection(request *xcbSelectionRequestEvent, notify *xcbSelectionNotifyWire) { + property := request.Property + if property == xcbAtomNone { + property = request.Target + } + switch request.Target { + case win.targetsAtom: + targets := []uint32{win.targetsAtom, win.xdnd.uriList} + win.api.changeProperty(win.connection, xcbPropertyReplace, request.Requestor, property, xcbAtomAtom, 32, uint32(len(targets)), unsafe.Pointer(&targets[0])) + notify.Property = property + case win.xdnd.uriList: + if win.writeSelection(request.Requestor, property, request.Target, platform.FileURIList(win.source.uris)) { + notify.Property = property + } + } } diff --git a/internal/platform/linux/drag_linux_test.go b/internal/platform/linux/drag_linux_test.go new file mode 100644 index 000000000..557dedda5 --- /dev/null +++ b/internal/platform/linux/drag_linux_test.go @@ -0,0 +1,239 @@ +//go:build linux && !android + +package linux + +import ( + "encoding/binary" + "io" + "net/url" + "os" + "strings" + "testing" + "time" + "unsafe" + + "github.com/ebitengine/purego" + "github.com/vivaui/viva/internal/platform" +) + +// dropTargetClient is another X client playing the file manager a drag from the +// application lands on: it says it takes XDND drags, answers the source's +// positions, and reads the file list from XdndSelection. +type dropTargetClient struct { + t *testing.T + api *xcbAPI + connection uintptr + screen *xcbScreen + id uint32 + property uint32 +} + +func (target *dropTargetClient) message(window, kind uint32, longs ...uint32) { + event := xcbClientEvent{ResponseType: xcbClientMessage, Format: 32, Window: window, Type: kind} + for index, value := range longs { + binary.LittleEndian.PutUint32(event.Data[index*4:], value) + } + target.api.sendEvent(target.connection, 0, window, 0, (*byte)(unsafe.Pointer(&event))) + target.api.flush(target.connection) +} + +// wait returns the next client message of kind, skipping everything else the +// test client receives. +func (target *dropTargetClient) wait(kind uint32, timeout time.Duration) *xcbClientEvent { + deadline := time.Now().Add(timeout) + poll := pollFD{FD: target.api.fileDescriptor(target.connection), Events: xcbPollInput} + for time.Now().Before(deadline) { + if event := target.api.pollForEvent(target.connection); event != nil { + if (*xcbGenericEvent)(event).ResponseType&0x7f == xcbClientMessage { + message := (*xcbClientEvent)(event) + kindSeen := message.Type + copy := *message + target.api.free(event) + if kindSeen == kind { + return © + } + continue + } + target.api.free(event) + continue + } + target.api.poll(&poll, 1, 20) + } + return nil +} + +// readSelection asks owner for text/uri-list and reads the property the owner +// writes back. +func (target *dropTargetClient) readSelection(owner, selection, uriList uint32) (string, bool) { + request := xcbSelectionRequestEvent{ + ResponseType: xcbSelectionRequest, + Time: 0, + Owner: owner, + Requestor: target.id, + Selection: selection, + Target: uriList, + Property: target.property, + } + target.api.sendEvent(target.connection, 0, owner, 0, (*byte)(unsafe.Pointer(&request))) + target.api.flush(target.connection) + deadline := time.Now().Add(5 * time.Second) + poll := pollFD{FD: target.api.fileDescriptor(target.connection), Events: xcbPollInput} + for time.Now().Before(deadline) { + if event := target.api.pollForEvent(target.connection); event != nil { + if (*xcbGenericEvent)(event).ResponseType&0x7f == xcbSelectionNotify { + target.api.free(event) + break + } + target.api.free(event) + continue + } + target.api.poll(&poll, 1, 20) + } + var nativeError unsafe.Pointer + reply := target.api.getPropertyReply(target.connection, target.api.getProperty(target.connection, 0, target.id, target.property, uriList, 0, 1<<20), &nativeError) + if nativeError != nil { + target.api.free(nativeError) + } + if reply == nil || reply.ValueLength == 0 { + if reply != nil { + target.api.free(unsafe.Pointer(reply)) + } + return "", false + } + data := unsafe.Slice((*byte)(target.api.getPropertyValue(reply)), reply.ValueLength) + list := string(data) + target.api.free(unsafe.Pointer(reply)) + return list, true +} + +// TestAFileDragOutReachesAnotherClient runs the source side against a real X +// server: the application starts a drag of paths, the pointer moves over a +// client that takes XDND drops, and that client reads the file list from the +// XdndSelection when the drop happens. +func TestAFileDragOutReachesAnotherClient(t *testing.T) { + if os.Getenv("DISPLAY") == "" { + t.Skip("no X server") + } + done := make(chan error, 1) + go func() { + done <- Run(platform.Config{Title: "drag out", Width: 300, Height: 200}) + }() + var win *window + for deadline := time.Now().Add(15 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { + select { + case err := <-done: + t.Skipf("no window could be opened here: %v", err) + default: + } + if win = activeWindow.Load(); win != nil { + break + } + } + if win == nil { + t.Fatal("the window never showed") + } + + api, connection, screen, err := openSystemConnection() + if err != nil { + t.Fatal(err) + } + defer api.disconnect(connection) + atom := func(name string) uint32 { + value, err := api.atom(connection, name) + if err != nil { + t.Fatal(err) + } + return value + } + target := &dropTargetClient{t: t, api: api, connection: connection, screen: screen, id: api.generateID(connection)} + // An override-redirect window is not moved or stacked by the window + // manager, so it really is at this position when the pointer is warped to + // it and above the application's window. + const cwOverrideRedirect = 1 << 9 + values := [2]uint32{1, 0} + api.createWindow(connection, xcbCopyFromParent, target.id, screen.Root, 10, 10, 200, 200, 0, xcbWindowClassInput, screen.RootVisual, cwOverrideRedirect|xcbCWEventMask, &values[0]) + aware, selection, uriList := atom("XdndAware"), atom("XdndSelection"), atom("text/uri-list") + version := uint32(xdndVersion) + api.changeProperty(connection, xcbPropertyReplace, target.id, aware, xcbAtomAtom, 32, 1, unsafe.Pointer(&version)) + target.property = atom("VIVA_TEST_DRAG_LIST") + api.mapWindow(connection, target.id) + api.flush(connection) + time.Sleep(100 * time.Millisecond) + + // Put the pointer over the client that takes the drop: the source finds its + // target the way it does for a real file manager. + var warp func(uintptr, uint32, uint32, int16, int16, uint16, uint16, int16, int16) xcbVoidCookie + purego.RegisterLibFunc(&warp, api.library, "xcb_warp_pointer") + warp(connection, xcbAtomNone, target.id, 0, 0, 0, 0, 60, 60) + api.flush(connection) + time.Sleep(50 * time.Millisecond) + + promises := []platform.FilePromise{{Name: "报告.txt", Size: 5, Open: func() (io.ReadCloser, error) { + return io.NopCloser(strings.NewReader("hello")), nil + }}} + started := make(chan error, 1) + win.application.Post(func() { + win.lastRootX, win.lastRootY, win.lastEventTime = 60, 60, 0 + started <- win.startDragOut(nil, promises) + }) + select { + case err := <-started: + if err != nil { + t.Fatalf("start the drag: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("the event loop never ran the drag start") + } + enter := target.wait(atom("XdndEnter"), 5*time.Second) + if enter == nil { + t.Fatal("the drag never entered the target") + } + position := target.wait(atom("XdndPosition"), 5*time.Second) + if position == nil { + t.Fatal("the drag never reported a position") + } + source := binary.LittleEndian.Uint32(enter.Data[:4]) + // The target takes the drop, as a file manager does over its window. + var status [5]uint32 + status[0] = target.id + status[1] = 1 // accept + status[4] = atom("XdndActionCopy") + target.message(source, atom("XdndStatus"), status[:]...) + + // Let the source see the status, then let go of the button. The status is a + // message from another connection, so give the loop a moment to read it. + time.Sleep(300 * time.Millisecond) + win.application.Post(func() { + win.sourceDragRelease(&xcbInputEvent{Time: 0}) + }) + if target.wait(atom("XdndDrop"), 5*time.Second) == nil { + t.Fatal("the release did not drop") + } + list, ok := target.readSelection(source, selection, uriList) + if !ok || !strings.Contains(list, "%E6%8A%A5%E5%91%8A.txt") { + t.Fatalf("the drop carried %q (ok %v), want the staged file's URI", list, ok) + } + // The promised content was staged before the drop and is a real file the + // file manager can copy. + line, _, _ := strings.Cut(list, "\r\n") + parsed, err := url.Parse(line) + if err != nil || parsed.Scheme != "file" { + t.Fatalf("the drop's URI %q is not a file URL: %v", line, err) + } + body, err := os.ReadFile(parsed.Path) + if err != nil || string(body) != "hello" { + t.Fatalf("the staged file read %q, %v", body, err) + } + var finished [5]uint32 + finished[0] = target.id + finished[1] = 1 + finished[2] = atom("XdndActionCopy") + target.message(source, atom("XdndFinished"), finished[:]...) + + win.postClientMessage(win.closeAtom, 0) + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("the window did not close") + } +} diff --git a/internal/platform/linux/drop_linux.go b/internal/platform/linux/drop_linux.go index 4f33c9c08..6c3ba6a84 100644 --- a/internal/platform/linux/drop_linux.go +++ b/internal/platform/linux/drop_linux.go @@ -27,6 +27,7 @@ const maxDroppedURIs = 4096 type xdndAtoms struct { aware, enter, position, status, leave, drop, finished uint32 selection, actionCopy, typeList, uriList, dropProperty uint32 + proxy uint32 } // xdndDrag is the drag in progress, as the source has told so far. @@ -129,7 +130,7 @@ func (state *linuxWindowState) handleDragMessage(message *xcbClientEvent) error win.sendDragReply(source, atoms.finished, false, 0) return nil } - text, ok, err := readSelection(win.api, win.connection, win.id, atoms.selection, atoms.uriList, atoms.dropProperty) + text, ok, err := win.readDropSelection() paths := []string(nil) if err == nil && ok { paths = parseURIList(text) @@ -149,6 +150,18 @@ func (state *linuxWindowState) handleDragMessage(message *xcbClientEvent) error return nil } +func (win *window) readDropSelection() (string, bool, error) { + api, connection, requestor, selection, owner, err := openSelectionRequest("XdndSelection") + if err != nil { + return "", false, err + } + defer closeClipboardRequest() + if owner == xcbAtomNone { + return "", false, nil + } + return readSelection(api, connection, requestor, selection, win.xdnd.uriList, win.xdnd.dropProperty) +} + // dragTypeList reads the types the source offers when there are more than three. func (win *window) dragTypeList(source uint32) []uint32 { cookie := win.api.getProperty(win.connection, 0, source, win.xdnd.typeList, xcbAtomAtom, 0, 256) diff --git a/internal/platform/linux/drop_linux_test.go b/internal/platform/linux/drop_linux_test.go index af843665a..e9c8fbf14 100644 --- a/internal/platform/linux/drop_linux_test.go +++ b/internal/platform/linux/drop_linux_test.go @@ -26,11 +26,12 @@ func TestURIListsBecomeLocalPaths(t *testing.T) { // source is another X client playing the program a drag starts from. type source struct { - t *testing.T - api *xcbAPI - connection uintptr - screen *xcbScreen - id uint32 + t *testing.T + api *xcbAPI + connection uintptr + screen *xcbScreen + id uint32 + beforeReply func() } func (s *source) message(target, kind uint32, longs ...uint32) { @@ -50,6 +51,9 @@ func (s *source) next(selectionAtom, listAtom uint32, list string) (unsafe.Point if event := s.api.pollForEvent(s.connection); event != nil { if (*xcbGenericEvent)(event).ResponseType&0x7f == xcbSelectionRequest { request := (*xcbSelectionRequestEvent)(event) + if s.beforeReply != nil { + s.beforeReply() + } data := []byte(list) s.api.changeProperty(s.connection, xcbPropertyReplace, request.Requestor, request.Property, listAtom, 8, uint32(len(data)), unsafe.Pointer(&data[0])) notify := xcbSelectionNotifyWire{xcbSelectionNotifyEvent: xcbSelectionNotifyEvent{ @@ -93,11 +97,24 @@ func TestAFileDragFromAnotherClientIsAcceptedAndDropped(t *testing.T) { t.Skip("no X server") } events := make(chan platform.FileDropEvent, 8) + redrawn := make(chan struct{}, 1) done := make(chan error, 1) go func() { + dropped := false done <- Run(platform.Config{ Title: "drop", Width: 300, Height: 200, + Waker: &platform.Waker{}, + OnRedraw: func() (platform.Frame, error) { + if dropped { + select { + case redrawn <- struct{}{}: + default: + } + } + return platform.Frame{}, nil + }, OnFileDrop: func(event platform.FileDropEvent) (platform.Frame, bool, error) { + dropped = event.Phase == platform.FileDropDrop events <- event return platform.Frame{}, event.Phase != platform.FileDropLeave, nil }, @@ -165,6 +182,7 @@ func TestAFileDragFromAnotherClientIsAcceptedAndDropped(t *testing.T) { t.Fatalf("hover = %+v", hover) } + src.beforeReply = func() { src.message(target.id, target.redrawAtom) } src.message(target.id, drop, src.id, 0, 0) flags, ok = src.reply(finished, selection, uriList, list) if !ok || flags&1 == 0 { @@ -174,6 +192,11 @@ func TestAFileDragFromAnotherClientIsAcceptedAndDropped(t *testing.T) { if dropped.Phase != platform.FileDropDrop || !reflect.DeepEqual(dropped.Paths, []string{"/tmp/a b.txt", "/tmp/dir"}) { t.Fatalf("drop = %+v", dropped) } + select { + case <-redrawn: + case <-time.After(2 * time.Second): + t.Error("redraw sent during the drop selection transfer was lost") + } // A drag that leaves ends the hover. src.message(target.id, enter, src.id, xdndVersion<<24, uriList) diff --git a/internal/platform/linux/gtk_focus_discard_linux_test.go b/internal/platform/linux/gtk_focus_discard_linux_test.go new file mode 100644 index 000000000..4549049f8 --- /dev/null +++ b/internal/platform/linux/gtk_focus_discard_linux_test.go @@ -0,0 +1,55 @@ +//go:build linux && vivagtk + +package linux + +import ( + "slices" + "testing" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" +) + +func TestGTKFocusOutDiscardsNativeResetCommit(t *testing.T) { + for _, scenario := range []struct { + name string + tentative bool + }{{"legacy", false}, {"tentative", true}} { + t.Run(scenario.name, func(t *testing.T) { + library := >kLibrary{} + window := >kWindow{app: >kApplication{g: library}, g: library} + state := platform.TextState{ + Value: "anic", Selection: text.Range{Start: 3, End: 3}, + Composition: text.Range{Start: 1, End: 3}, Composing: true, + TentativeComposition: scenario.tentative, + } + var events []platform.TextEventKind + window.text = &linuxTextInput{config: &window.config, enabled: true, state: state, input: platform.TextInput{ + State: state, HideNativeOverlays: true, + OnEvent: func(event platform.TextEvent) (platform.TextState, error) { + events = append(events, event.Kind) + return state, nil + }, + }} + ime := >kIME{w: window, g: library, ctx: 23, active: true, focused: true, + session: true, engineComposing: true, tentative: scenario.tentative} + window.ime = ime + library.objectRef = func(context uintptr) uintptr { return context } + library.objectUnref = func(uintptr) {} + var nativeCalls []string + library.imReset = func(context uintptr) { + nativeCalls = append(nativeCalls, "reset") + ime.preeditEnded() + ime.commit("ni") + } + library.imFocusOut = func(context uintptr) { nativeCalls = append(nativeCalls, "focus-out") } + ime.setFocused(false) + if !slices.Equal(nativeCalls, []string{"reset", "focus-out"}) || ime.active || ime.session { + t.Fatalf("unexpected blur teardown: calls=%v active=%t session=%t", nativeCalls, ime.active, ime.session) + } + if !slices.Equal(events, []platform.TextEventKind{platform.TextCancelComposition}) { + t.Fatalf("blur events = %v, want a single cancellation", events) + } + }) + } +} diff --git a/internal/platform/linux/gtk_ime_fcitx_native_linux_test.go b/internal/platform/linux/gtk_ime_fcitx_native_linux_test.go index ae111e3dd..fc224c413 100644 --- a/internal/platform/linux/gtk_ime_fcitx_native_linux_test.go +++ b/internal/platform/linux/gtk_ime_fcitx_native_linux_test.go @@ -256,6 +256,16 @@ func (probe *gtkFcitxProbe) settle() { probe.want = "a\uac00\ub098 c" } } + if probe.ending == "window-focus-out" { + switch { + case probe.engine == "hangul": + probe.want = "a\uac00c" + case p.tentative: + probe.want = "ac" + default: + probe.want = "abc" + } + } switch probe.ending { case "commit", "escape": symbol := uint32(' ') @@ -281,6 +291,7 @@ func (probe *gtkFcitxProbe) settle() { func (probe *gtkFcitxProbe) finish(failure string) { p := probe.p + windowBlur := probe.ending == "window-focus-out" var failures []string if failure != "" { failures = append(failures, failure) @@ -304,15 +315,20 @@ func (probe *gtkFcitxProbe) finish(failure string) { } else if probe.ending == "escape" { wantResults, wantCancels = 0, 1 } + if windowBlur { + wantResults-- + wantCancels++ + } if p.tentative && (results != wantResults || cancels != wantCancels) { failures = append(failures, fmt.Sprintf("results/cancels=%d/%d, want=%d/%d", results, cancels, wantResults, wantCancels)) } - if !p.tentative && probe.engine == "pinyin" { + if windowBlur || !p.tentative && probe.engine == "pinyin" { kind := platform.TextInsert - if probe.ending == "escape" { + if windowBlur || probe.ending == "escape" { kind = platform.TextCancelComposition - if p.editor.CanUndo() || p.editor.CanRedo() || p.editor.Selection() != (text.Range{Start: 1, End: 2}) { - failures = append(failures, "Escape did not preserve selection and history") + if !p.tentative && probe.engine == "pinyin" && + (p.editor.CanUndo() || p.editor.CanRedo() || p.editor.Selection() != (text.Range{Start: 1, End: 2})) { + failures = append(failures, "cancellation did not preserve selection and history") } } if len(p.events) == 0 || p.events[len(p.events)-1].Kind != kind { @@ -327,7 +343,7 @@ func (probe *gtkFcitxProbe) finish(failure string) { } } probe.record(failures...) - if failure == "" && !p.tentative && probe.engine == "pinyin" && probe.ending != "escape" { + if failure == "" && !p.tentative && probe.engine == "pinyin" && probe.ending != "escape" && !windowBlur { if !p.editor.Undo() || p.editor.String() != "abc" || p.editor.CanUndo() || !p.editor.Redo() || p.editor.String() != probe.want { last := &p.trials[len(p.trials)-1] last.failures = append(last.failures, "commit did not round-trip in a single undo unit") @@ -336,8 +352,10 @@ func (probe *gtkFcitxProbe) finish(failure string) { if failure == "" && p.tentative { undos := []string{"ac", "abc"} if probe.engine == "hangul" { - undos = []string{"a\uac00c", "ac", "abc"} - } else if probe.ending == "escape" { + if !windowBlur { + undos = []string{"a\uac00c", "ac", "abc"} + } + } else if probe.ending == "escape" || windowBlur { undos = []string{"abc"} } for _, want := range undos { diff --git a/internal/platform/linux/gtk_ime_linux.go b/internal/platform/linux/gtk_ime_linux.go index d6ed4fe06..75a29902e 100644 --- a/internal/platform/linux/gtk_ime_linux.go +++ b/internal/platform/linux/gtk_ime_linux.go @@ -18,12 +18,13 @@ import ( // and commits the choice as it does on the other platforms. The input method owns the candidate // window; this side says when the field has the keyboard and where its caret is. type gtkIME struct { - w *gtkWindow - g *gtkLibrary - ctx uintptr - target gfx.ID - owner text.CompositionIdentity - tentative bool + w *gtkWindow + g *gtkLibrary + ctx uintptr + clientWindow uintptr + target gfx.ID + owner text.CompositionIdentity + tentative bool // focused is whether the window has the keyboard; active is whether the context was told the // field does. focused bool @@ -32,6 +33,7 @@ type gtkIME struct { engineComposing bool // session survives an empty native update until GTK supplies an end or result. session, ending bool + discarding bool nativeDepth int // rootContext is the context of the outermost callContext, the call whose // deferred finishPreedit runs when the native depth returns to zero. A @@ -75,7 +77,25 @@ func (ime *gtkIME) sameOwner(input *platform.TextInput) bool { // realized gives the context its window, which exists once the toplevel is realized. func (ime *gtkIME) realized() { - if window := ime.g.widgetGetWindow(ime.w.toplevel); window != 0 { + window := ime.g.widgetGetWindow(ime.w.toplevel) + if window != 0 && ime.w.wl != nil { + if ime.clientWindow == 0 { + const gdkWindowChild, gdkInputOnly = 2, 1 + attrs := gdkWindowAttr{Width: 1, Height: 1, WindowType: gdkWindowChild, Class: gdkInputOnly} + ime.clientWindow = ime.g.gdkWindowNew(window, &attrs, 0) + if ime.clientWindow != 0 { + ime.g.widgetRegisterWindow(ime.w.area, ime.clientWindow) + empty := ime.g.cairoRegionRect(&[4]int32{}) + ime.g.gdkWindowInputShape(ime.clientWindow, empty, 0, 0) + ime.g.cairoRegionDestroy(empty) + ime.g.gdkWindowShow(ime.clientWindow) + } + } + if ime.clientWindow != 0 { + window = ime.clientWindow + } + } + if window != 0 { ime.callContext(ime.ctx, func(context uintptr) { ime.g.imSetClientWindow(context, window) }) } } @@ -95,6 +115,11 @@ func (ime *gtkIME) close() { ime.callContext(context, ime.g.imFocusOut) } ime.callContext(context, func(context uintptr) { ime.g.imSetClientWindow(context, 0) }) + if window := ime.clientWindow; window != 0 { + ime.clientWindow = 0 + ime.g.widgetUnregisterWindow(ime.w.area, window) + ime.g.gdkWindowDestroy(window) + } ime.w.app.retireIME(context) } @@ -198,6 +223,10 @@ func (ime *gtkIME) sync() { ime.callContext(context, ime.g.imFocusIn) case !want && ime.active: ime.active = false + if !ime.focused && ime.composing() { + ime.discardOnFocusOut(context) + return + } if ime.engineComposing || ime.session { ime.engineComposing = false ime.callContext(context, ime.g.imReset) @@ -224,12 +253,27 @@ func (ime *gtkIME) sync() { ime.updateSurrounding() } -// updateCursor tells the input method's window where the caret is, in the toplevel's coordinates. +func (ime *gtkIME) discardOnFocusOut(context uintptr) { + func() { + ime.discarding = true + defer func() { ime.discarding = false }() + ime.callContext(context, ime.g.imReset) + if ime.ctx == context && !ime.w.closed && !ime.active { + ime.callContext(context, ime.g.imFocusOut) + } + }() + if ime.current(context) && !ime.active { + ime.ending = true + ime.finishPreedit(context) + } +} + +// updateCursor tells the input method where the caret is in its client window. func (ime *gtkIME) updateCursor() { w := ime.w x, y, width, height := ime.caretRectangle() - var left, top int32 - w.g.widgetTranslate(w.area, w.toplevel, int32(x*w.ratio), int32(y*w.ratio), &left, &top) + left, top := int32(x*w.ratio), int32(y*w.ratio) + w.g.widgetTranslate(w.area, w.toplevel, left, top, &left, &top) location := [4]int32{left, top, int32(width * w.ratio), int32(height * w.ratio)} if ime.haveCursor && location == ime.cursor { return @@ -301,6 +345,9 @@ func (ime *gtkIME) deleteSurrounding(offset, count int) uintptr { } func (ime *gtkIME) commit(value string) { + if ime.discarding { + return + } context, revision := ime.ctx, ime.w.text.stateRevision composing := ime.composing() if key := ime.shortcutKey; key != nil && !composing && value == key.Typed { @@ -495,6 +542,9 @@ func (ime *gtkIME) clause(attrs uintptr, value string) (text.Range, bool) { // apply runs one text event through the field and presents the result. func (ime *gtkIME) apply(event platform.TextEvent) { + if ime.discarding { + return + } frame, err := ime.w.text.textEvent(event) ime.w.present(frame, err) } diff --git a/internal/platform/linux/gtk_native_widget_focus_linux_test.go b/internal/platform/linux/gtk_native_widget_focus_linux_test.go index 08ee91750..08a7d58d8 100644 --- a/internal/platform/linux/gtk_native_widget_focus_linux_test.go +++ b/internal/platform/linux/gtk_native_widget_focus_linux_test.go @@ -19,7 +19,7 @@ import ( type gtkNativeWidgetFocusState struct { windowFocused, otherFocused, nativeKeys, imeActive bool windowFocusedAtOtherClick bool - pointerOnOther bool + pointerOnEditor, pointerOnOther bool webFocus, windowFocus, afterTakeKeys uintptr focusLost, focusLostAtOtherClick, focusLostAtReturnClick int otherClicks, editorClicks, entryIn, entryOut int @@ -52,9 +52,10 @@ func gtkNativeWidgetState(ctx context.Context, app *gtkApplication, editor, othe state := gtkNativeWidgetFocusState{ windowFocused: editor.focused, otherFocused: other.focused, nativeKeys: editor.nativeKeys, webFocus: editor.webFocus, - imeActive: editor.ime != nil && editor.ime.active, - pointerOnOther: other.wl != nil && other.wl.s.focus == other.wl, - focusLost: *lost, otherClicks: *otherClicks, editorClicks: *editorClicks, + imeActive: editor.ime != nil && editor.ime.active, + pointerOnEditor: editor.wl != nil && editor.wl.s.focus == editor.wl, + pointerOnOther: other.wl != nil && other.wl.s.focus == other.wl, + focusLost: *lost, otherClicks: *otherClicks, editorClicks: *editorClicks, } if trace := gtkNativeWidgetTraceActive; trace != nil { state.windowFocus = trace.getFocus(editor.toplevel) @@ -262,6 +263,14 @@ func gtkNativeWidgetFocusRun(ctx context.Context, t *testing.T, app *gtkApplicat return append(failures, ctx.Err().Error()) } logState("after B hide, before A click") + if _, err := driver.command("move-editor", "", ""); err != nil { + return append(failures, err.Error()) + } + if err := gtkNativeWidgetWait(ctx, app, p.w, other, lost, otherClicks, editorClicks, "A editor pointer entry", func(s gtkNativeWidgetFocusState) bool { + return s.pointerOnEditor && !s.pointerOnOther + }); err != nil { + return append(failures, err.Error()) + } if _, err := driver.command("click", "", ""); err != nil { return append(failures, err.Error()) } diff --git a/internal/platform/linux/gtk_wayland_keyboard_native_linux_test.go b/internal/platform/linux/gtk_wayland_keyboard_native_linux_test.go index e2d025ef1..a420de74e 100644 --- a/internal/platform/linux/gtk_wayland_keyboard_native_linux_test.go +++ b/internal/platform/linux/gtk_wayland_keyboard_native_linux_test.go @@ -211,7 +211,7 @@ func gtkSeatWait(ctx context.Context, a *gtkApplication, p *gtkTentativeProbe, p } } -func gtkSeatRun(ctx context.Context, t *testing.T, a *gtkApplication, p *gtkTentativeProbe, pointers *gtkSeatPointer, backend, path string, remap bool) (failures []string) { +func gtkSeatRun(ctx context.Context, t *testing.T, a *gtkApplication, p *gtkTentativeProbe, pointers *gtkSeatPointer, backend, path string, remap, retainOnClick bool) (failures []string) { driver, err := newGTKSeatDriver(ctx, path) if err != nil { return []string{fmt.Sprintf("start XTest/AT-SPI driver: %v", err)} @@ -364,6 +364,9 @@ func gtkSeatRun(ctx context.Context, t *testing.T, a *gtkApplication, p *gtkTent return ctx.Err() } } + if retainOnClick { + return gtkSeatRetainPreeditOnClick(ctx, a, p, pointers, driver, typeKey, &failures) + } trial("parent AX focus") if err := reset(); err != nil { return append(failures, err.Error()) @@ -501,17 +504,24 @@ func gtkSeatRun(ctx context.Context, t *testing.T, a *gtkApplication, p *gtkTent } func TestGTKNativeSeatKeyboardAfterContentClick(t *testing.T) { - testGTKNativeSeatKeyboard(t, false) + testGTKNativeSeatKeyboard(t, false, false) } func TestGTKNativeWaylandSeatHideShow(t *testing.T) { if os.Getenv("VIVA_GTK_SEAT_REMAP") != "1" || os.Getenv("VIVA_FCITX_BACKEND") != "wayland" { t.Skip("requires the private Wayland seat remap fixture") } - testGTKNativeSeatKeyboard(t, true) + testGTKNativeSeatKeyboard(t, true, false) +} + +func TestGTKNativeWaylandPointerKeepsFcitxPreedit(t *testing.T) { + if os.Getenv("VIVA_FCITX_BACKEND") != "wayland" { + t.Skip("requires the private Wayland Fcitx seat fixture") + } + testGTKNativeSeatKeyboard(t, false, true) } -func testGTKNativeSeatKeyboard(t *testing.T, remap bool) { +func testGTKNativeSeatKeyboard(t *testing.T, remap, retainOnClick bool) { t.Helper() if os.Getenv("VIVA_GTK_SEAT_NATIVE") != "1" { t.Skip("requires the private Xvfb/DBus/Fcitx seat fixture") @@ -544,15 +554,19 @@ func testGTKNativeSeatKeyboard(t *testing.T, remap bool) { defer func() { gtkTentativeProbeActive = nil }() result := make(chan []string, 1) pointers := gtkSeatPointer{} + mode, titlebarHeight, editorTop := platform.WindowFrameless, float32(0), float32(20) + if retainOnClick { + mode, titlebarHeight, editorTop = platform.WindowCustomTitlebar, 80, 110 + } err = RunGTKApplication(func(application platform.Application) error { a := application.(*gtkApplication) window, openErr := application.OpenWindow(platform.Config{ - Title: "Viva seat keyboard probe", Width: 800, Height: 600, WindowMode: platform.WindowFrameless, + Title: "Viva seat keyboard probe", Width: 800, Height: 600, WindowMode: mode, TitlebarHeight: titlebarHeight, ClearColor: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, DynamicTextInput: true, Accessibility: []platform.AccessibilityNode{{ ID: gfx.Item(1), Role: platform.A11yRoleTextField, Label: "Seat editor", - X: 20, Y: 20, Width: 300, Height: 100, Focusable: true, + X: 20, Y: editorTop, Width: 300, Height: 100, Focusable: true, }}, OnAccessibility: func(request platform.AccessibilityRequest, _ func(platform.Frame) error) (bool, error) { return request.Node == gfx.Item(1) && request.Action == platform.AccessibilityFocus, nil @@ -590,9 +604,12 @@ func testGTKNativeSeatKeyboard(t *testing.T, remap bool) { p.w.destroy() return } + if retainOnClick { + editor.SetSelection(text.Range{Start: 1, End: 2}) + } p.install(editor) go func() { - failures := gtkSeatRun(ctx, t, a, p, &pointers, backend, path, remap) + failures := gtkSeatRun(ctx, t, a, p, &pointers, backend, path, remap, retainOnClick) result <- failures a.enqueue(func() { p.w.destroy() }) }() @@ -611,3 +628,96 @@ func testGTKNativeSeatKeyboard(t *testing.T, remap bool) { t.Fatal(ctx.Err()) } } + +func gtkSeatRetainPreeditOnClick(ctx context.Context, app *gtkApplication, probe *gtkTentativeProbe, pointers *gtkSeatPointer, driver *gtkSeatDriver, typeKey func(string, string, bool), failures *[]string) []string { + region := >kRegionProbe{w: probe.w} + if _, err := driver.commandAt("move", 120, 60); err != nil { + return []string{err.Error()} + } + if err := gtkRegionWait(ctx, app, region, "GDK titlebar coordinate origin", func(state gtkRegionState) bool { + return state.gdkPointer == state.gtkArea && state.gdkX >= 0 && state.gdkY >= 0 && !state.childPointer + }); err != nil { + return []string{err.Error()} + } + position, err := gtkRegionSnapshot(ctx, app, region) + if err != nil { + return []string{err.Error()} + } + originX, originY := 120-int(position.gdkX), 60-int(position.gdkY) + if _, err := driver.command("click", "", ""); err != nil { + return []string{err.Error()} + } + if err := gtkSeatWait(ctx, app, probe, pointers, "initial content click", func(state gtkSeatSnapshot) bool { + return state.pointers == 1 && state.imeActive + }); err != nil { + return []string{err.Error()} + } + for _, symbol := range []string{"n", "i"} { + typeKey("pointer retention", symbol, true) + } + if len(*failures) != 0 { + return *failures + } + before, err := gtkSeatState(ctx, app, probe, pointers) + if err != nil || before.value != "anic" || !before.composing || !before.compositionActive || before.commits != 0 { + return []string{fmt.Sprintf("expected active uncommitted ni: state=%+v error=%v", before, err)} + } + if _, err := driver.commandAt("move", originX+120, originY+60); err != nil { + return []string{err.Error()} + } + if err := gtkRegionWait(ctx, app, region, "pointer over GTK titlebar", func(state gtkRegionState) bool { + return !state.childPointer && state.gdkPointer == state.gtkArea + }); err != nil { + return []string{err.Error()} + } + if _, err := driver.commandAt("click-at", originX+400, originY+300); err != nil { + return []string{err.Error()} + } + if err := gtkSeatWait(ctx, app, probe, pointers, "content action received pointer press", func(state gtkSeatSnapshot) bool { + return state.pointers == before.pointers+1 + }); err != nil { + return []string{err.Error()} + } + after, err := gtkSeatState(ctx, app, probe, pointers) + if err != nil || after.commits != before.commits || after.value != before.value || !after.composing || + !after.compositionActive || after.selection != before.selection || after.composition != before.composition || + after.imeIdentity != before.imeIdentity || after.canUndo != before.canUndo { + return []string{fmt.Sprintf("content action settled unselected Fcitx preedit: before=%+v after=%+v error=%v", before, after, err)} + } + for _, symbol := range []string{"h", "a", "o"} { + typeKey("pointer continuation", symbol, true) + } + if len(*failures) != 0 { + return *failures + } + typeKey("explicit candidate selection", "space", false) + if err := gtkSeatWait(ctx, app, probe, pointers, "explicit Fcitx candidate committed", func(state gtkSeatSnapshot) bool { + return state.value == "a\u4f60\u597dc" && state.commits == 1 && state.lastEvent.CompositionPhase == text.CompositionResult && + !state.composing && !state.compositionActive && state.canUndo && state.pressedKeys == 0 + }); err != nil { + return append(*failures, err.Error()) + } + undone := make(chan error, 1) + app.enqueue(func() { + for _, want := range []string{"ac", "abc"} { + if !probe.editor.Undo() || probe.editor.String() != want { + undone <- fmt.Errorf("candidate Undo: got %q, want %q", probe.editor.String(), want) + return + } + } + if probe.editor.CanUndo() { + undone <- fmt.Errorf("content click added an Undo unit") + return + } + undone <- nil + }) + select { + case err := <-undone: + if err != nil { + return append(*failures, err.Error()) + } + case <-ctx.Done(): + return append(*failures, ctx.Err().Error()) + } + return *failures +} diff --git a/internal/platform/linux/gtk_web_linux.go b/internal/platform/linux/gtk_web_linux.go index cdccdcc89..152b2327f 100644 --- a/internal/platform/linux/gtk_web_linux.go +++ b/internal/platform/linux/gtk_web_linux.go @@ -28,6 +28,10 @@ import ( // webKit is the engine's entry points. type webKit struct { + viewSettings func(view uintptr) uintptr + getUserAgent func(settings uintptr) uintptr + setUserAgent func(settings uintptr, value *byte) + managerNew func() uintptr managerRegister func(manager uintptr, name *byte) int32 managerAddScript func(manager, script uintptr) @@ -98,12 +102,16 @@ type webKit struct { actionRequest func(action uintptr) uintptr actionUserGesture func(action uintptr) int32 actionRedirect func(action uintptr) int32 // 2.20, nil before - uriRequestURI func(request uintptr) uintptr - downloadRequest func(download uintptr) uintptr - downloadWebView func(download uintptr) uintptr - downloadSetDestination func(download uintptr, destination *byte) - downloadAllowOverwrite func(download uintptr, allow int32) - downloadCancel func(download uintptr) + // Web Inspector; nil when the library lacks one, and a page then has no developer tools. + setDeveloperExtras func(settings uintptr, enabled int32) + viewInspector func(view uintptr) uintptr + inspectorShow func(inspector uintptr) + uriRequestURI func(request uintptr) uintptr + downloadRequest func(download uintptr) uintptr + downloadWebView func(download uintptr) uintptr + downloadSetDestination func(download uintptr, destination *byte) + downloadAllowOverwrite func(download uintptr, allow int32) + downloadCancel func(download uintptr) // viewNetworkSession is 2.40; before it the context's download-started is used instead. viewNetworkSession func(view uintptr) uintptr // downloadDestinationPath says set_destination takes a path (2.40 and later) rather than a URI, @@ -161,6 +169,9 @@ func loadWebKit(g *gtkLibrary) (*webKit, error) { symbol string }{ {&k.resultValue, "webkit_javascript_result_get_js_value"}, + {&k.viewSettings, "webkit_web_view_get_settings"}, + {&k.getUserAgent, "webkit_settings_get_user_agent"}, + {&k.setUserAgent, "webkit_settings_set_user_agent"}, {&k.managerNew, "webkit_user_content_manager_new"}, {&k.managerRegister, "webkit_user_content_manager_register_script_message_handler"}, {&k.managerAddScript, "webkit_user_content_manager_add_script"}, {&k.scriptNew, "webkit_user_script_new"}, {&k.viewNew, "webkit_web_view_new_with_user_content_manager"}, {&k.loadURI, "webkit_web_view_load_uri"}, @@ -206,6 +217,9 @@ func loadWebKit(g *gtkLibrary) (*webKit, error) { g.lookup(&k.schemeCORS, "webkit_security_manager_register_uri_scheme_as_cors_enabled") // A redirect is not a user gesture even when the request that led to it was one. g.lookup(&k.actionRedirect, "webkit_navigation_action_is_redirect") + g.lookup(&k.setDeveloperExtras, "webkit_settings_set_enable_developer_extras") + g.lookup(&k.viewInspector, "webkit_web_view_get_inspector") + g.lookup(&k.inspectorShow, "webkit_web_inspector_show") g.lookup(&k.viewNetworkSession, "webkit_web_view_get_network_session") k.free = g.symbol("g_free") if !g.lookup(&k.contextEphemeral, "webkit_web_context_new_ephemeral") || @@ -635,6 +649,13 @@ func (w *gtkWindow) openWebView(c platform.WebViewConfig) (platform.WebView, err if private == nil { v.widget = k.viewNew(v.manager) } + if c.UserAgentSuffix != "" { + // The suffix follows the engine's default string verbatim, as on the other platforms; + // the application-details setter would append "/version" to it. + settings := k.viewSettings(v.widget) + agent := cString(goString(k.getUserAgent(settings)) + " " + c.UserAgentSuffix) + k.setUserAgent(settings, &agent[0]) + } // Placed by its margins from the overlay's top left; hidden until a frame says where. g.widgetSetHAlign(v.widget, 1) g.widgetSetVAlign(v.widget, 1) diff --git a/internal/platform/linux/gtk_window_linux.go b/internal/platform/linux/gtk_window_linux.go index 99c5ac2a3..6e408ea76 100644 --- a/internal/platform/linux/gtk_window_linux.go +++ b/internal/platform/linux/gtk_window_linux.go @@ -533,6 +533,8 @@ func (w *gtkWindow) mapChanged(on bool) { w.focusSerial++ if w.focused { w.setKeyboard(false) + } else if w.ime != nil && w.ime.focused { + w.ime.setFocused(false) } *w.pointer.clicks = input.ClickCounter{} w.pointer.pending, w.pointer.pendingDelivery = false, false diff --git a/internal/platform/linux/gtk_window_teardown_linux_test.go b/internal/platform/linux/gtk_window_teardown_linux_test.go index 68167ff57..dbe5ff7ca 100644 --- a/internal/platform/linux/gtk_window_teardown_linux_test.go +++ b/internal/platform/linux/gtk_window_teardown_linux_test.go @@ -5,13 +5,97 @@ package linux import ( "fmt" "os" + "slices" "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/input" "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/text" ) +func mockGTKIMEClientWindow(library *gtkLibrary) { + library.gdkWindowNew = func(parent uintptr, attrs *gdkWindowAttr, mask int32) uintptr { return 29 } + library.widgetRegisterWindow = func(widget, client uintptr) {} + library.cairoRegionRect = func(rectangle *[4]int32) uintptr { return 31 } + library.gdkWindowInputShape = func(client, region uintptr, x, y int32) {} + library.cairoRegionDestroy = func(region uintptr) {} + library.gdkWindowShow = func(client uintptr) {} +} + +func TestGTKWaylandIMECursorTracksContentOrigin(t *testing.T) { + library := >kLibrary{} + mockGTKIMEClientWindow(library) + window := >kWindow{g: library, toplevel: 17, area: 18, ratio: 1} + window.wl = &waylandSurface{w: window} + window.text = &linuxTextInput{input: platform.TextInput{ + Placed: true, CaretX: 44, CaretY: 59, CaretWidth: 2, CaretHeight: 21, + }} + ime := >kIME{w: window, g: library, ctx: 23} + library.objectRef = func(context uintptr) uintptr { return context } + library.objectUnref = func(context uintptr) {} + library.widgetGetWindow = func(widget uintptr) uintptr { return widget } + var clientWindow uintptr + library.imSetClientWindow = func(context, client uintptr) { clientWindow = client } + offsetX, offsetY := int32(26), int32(60) + library.widgetTranslate = func(source, dest uintptr, x, y int32, destX, destY *int32) int32 { + *destX, *destY = x+offsetX, y+offsetY + return 1 + } + var observed [][4]int32 + library.imSetCursorRect = func(context uintptr, rectangle *[4]int32) { + position := *rectangle + if clientWindow == window.area { + position[0] += offsetX + position[1] += offsetY + } + observed = append(observed, position) + } + + ime.realized() + ime.updateCursor() + offsetX, offsetY = 0, 0 + ime.updateCursor() + ime.updateCursor() + want := [][4]int32{{70, 119, 2, 21}, {44, 59, 2, 21}} + if !slices.Equal(observed, want) { + t.Fatalf("cursor updates after content origin change: got %v, want %v", observed, want) + } +} + +func TestGTKWaylandUnmapEndsPointerActivatedIME(t *testing.T) { + g := >kLibrary{} + mockGTKIMEClientWindow(g) + app := >kApplication{g: g} + window := >kWindow{app: app, g: g, toplevel: 17, area: 18, ratio: 1} + window.pointer.clicks = &input.ClickCounter{} + window.text = &linuxTextInput{enabled: true, input: platform.TextInput{Placed: true}} + window.wl = &waylandSurface{w: window, gdkWindow: 19} + ime := >kIME{w: window, g: g, ctx: 23} + window.ime = ime + g.objectRef = func(context uintptr) uintptr { return context } + g.objectUnref = func(context uintptr) {} + g.widgetGetWindow = func(widget uintptr) uintptr { return widget } + g.widgetTranslate = func(source, dest uintptr, x, y int32, destX, destY *int32) int32 { + *destX, *destY = x, y + return 1 + } + g.imSetClientWindow = func(context, client uintptr) {} + g.imSetCursorRect = func(context uintptr, rectangle *[4]int32) {} + g.imFocusIn = func(context uintptr) {} + focusOuts := 0 + g.imFocusOut = func(context uintptr) { focusOuts++ } + + window.deliverPointer(platform.PointerEvent{Kind: platform.PointerDown}) + if window.focused || !ime.filtering() { + t.Fatalf("pointer did not activate IME before native focus: window=%t ime=%t", window.focused, ime.active) + } + window.mapChanged(false) + if ime.focused || ime.filtering() || focusOuts != 1 { + t.Fatalf("unmap left pointer-activated IME active: focused=%t active=%t focus-outs=%d", ime.focused, ime.active, focusOuts) + } +} + func TestGTKDestroyDetachesInputMethodBeforeNativeWidget(t *testing.T) { g := >kLibrary{} a := >kApplication{g: g} @@ -90,7 +174,11 @@ func TestGTKNativeInputMethodWindowTeardown(t *testing.T) { if os.Getenv("VIVA_GTK_CLOSE_NATIVE") != "1" { t.Skip("native close probe requires a private display and the Fcitx GTK module") } - for _, mode := range []string{"programmatic", "default", "deferred"} { + modes := []string{"programmatic", "default", "deferred"} + if os.Getenv("GDK_BACKEND") == "wayland" { + modes = append(modes, "external") + } + for _, mode := range modes { t.Run(mode, func(t *testing.T) { closed, requests, events := 0, 0, 0 allowed := false @@ -152,9 +240,12 @@ func TestGTKNativeInputMethodWindowTeardown(t *testing.T) { })) } } - if mode == "programmatic" { + switch mode { + case "programmatic": w.Close() - } else { + case "external": + a.g.widgetDestroy(w.toplevel) + default: closeWindow(w.toplevel) } }) diff --git a/internal/platform/linux/ime_daemon_linux.go b/internal/platform/linux/ime_daemon_linux.go index 3727aa382..51df5dd94 100644 --- a/internal/platform/linux/ime_daemon_linux.go +++ b/internal/platform/linux/ime_daemon_linux.go @@ -9,6 +9,7 @@ import ( "github.com/vivaui/viva/internal/fcitx" "github.com/vivaui/viva/internal/ibus" + "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/text" ) @@ -155,18 +156,34 @@ func (daemon fcitxDaemon) Deadline() (time.Time, bool) { return daemon.bus.Deadl func (daemon fcitxDaemon) Expire() { daemon.bus.Expire() } func (daemon fcitxDaemon) open(ime *linuxIME) (inputMethodContext, error) { + context, err := daemon.bus.NewContext("viva", ime.fcitxHandler()) + if err != nil { + return nil, err + } + return fcitxContext{context}, nil +} + +func (ime *linuxIME) fcitxHandler() fcitx.Handler { epoch := ime.epoch valid := func() bool { return ime.contextCurrent(epoch) } - context, err := daemon.bus.NewContext("viva", fcitx.Handler{ + return fcitx.Handler{ Commit: func(value string) { if valid() { ime.commit(value) } }, Preedit: func(event fcitx.PreeditEvent) { - if valid() { - ime.preedit(event.Text, event.Cursor, event.Visible, text.Range{Start: event.Selection.Start, End: event.Selection.End}) + if !valid() { + return + } + if !event.Visible || event.Text == "" { + ime.engineComposing = false + if ime.text.state.Composing { + ime.apply(platform.TextEvent{Kind: platform.TextCancelComposition}) + } + return } + ime.preedit(event.Text, event.Cursor, true, text.Range{Start: event.Selection.Start, End: event.Selection.End}) }, Forward: func(keysym, state uint32, release bool) { if valid() { @@ -178,11 +195,7 @@ func (daemon fcitxDaemon) open(ime *linuxIME) (inputMethodContext, error) { ime.deleteSurrounding(offset, count) } }, - }) - if err != nil { - return nil, err } - return fcitxContext{context}, nil } // fcitxContext is a Fcitx context behind the daemon interface. Fcitx wants the diff --git a/internal/platform/linux/ime_daemon_linux_test.go b/internal/platform/linux/ime_daemon_linux_test.go index f4bba8f27..434c9f78a 100644 --- a/internal/platform/linux/ime_daemon_linux_test.go +++ b/internal/platform/linux/ime_daemon_linux_test.go @@ -5,6 +5,10 @@ package linux import ( "testing" "time" + + "github.com/vivaui/viva/internal/fcitx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" ) // stubDaemon stands in for a framework's connection in a selection test. @@ -77,3 +81,65 @@ func TestDialFallsBackWhenTheNamedFrameworkIsAbsent(t *testing.T) { t.Fatalf("no daemon was reported as %v", daemon) } } + +func TestFcitxPreeditClearKeepsSelectionAndHistory(test *testing.T) { + for _, selection := range []struct { + name string + rangeValue text.Range + }{ + {"forward", text.Range{Start: 1, End: 2}}, + {"backward", text.Range{Start: 2, End: 1}}, + } { + for _, ending := range []string{"cancel", "clear-before-commit", "commit-before-clear"} { + test.Run(selection.name+"/"+ending, func(test *testing.T) { + harness := newIMEHarness(test) + harness.editor = text.NewEditor("abc") + harness.editor.SetSelection(selection.rangeValue) + harness.input.state = platform.EditorState(harness.editor) + harness.focus(test) + handler := harness.ime.fcitxHandler() + assertSelection := func() { + test.Helper() + if harness.editor.Selection() != (text.Range{Start: 1, End: 2}) || harness.editor.Caret() != selection.rangeValue.End { + test.Fatalf("selection = %+v, caret = %d", harness.editor.Selection(), harness.editor.Caret()) + } + } + handler.Preedit(fcitx.PreeditEvent{Text: "\u4f60", Visible: true, Cursor: 1}) + if harness.editor.String() != "a\u4f60c" || harness.editor.CommittedString() != "abc" || !harness.ime.composing() { + test.Fatalf("preedit did not preserve the committed text: %+v", platform.EditorState(harness.editor)) + } + if ending == "commit-before-clear" { + handler.Commit("\u4f60\u597d") + } + handler.Preedit(fcitx.PreeditEvent{}) + if ending != "commit-before-clear" { + if harness.editor.String() != "abc" || harness.ime.composing() || harness.editor.CanUndo() { + test.Fatalf("clear changed the selection's text or history: %q", harness.editor.String()) + } + assertSelection() + } + if ending == "cancel" { + handler.Preedit(fcitx.PreeditEvent{}) + if harness.ime.composing() || harness.editor.CanUndo() || harness.editor.String() != "abc" { + test.Fatal("second clear changed an already canceled editor") + } + assertSelection() + return + } + if ending == "clear-before-commit" { + handler.Commit("\u4f60\u597d") + } + if harness.editor.CommittedString() != "a\u4f60\u597dc" || harness.ime.composing() { + test.Fatalf("commit = %q or still composing", harness.editor.CommittedString()) + } + if !harness.editor.Undo() || harness.editor.String() != "abc" || harness.editor.CanUndo() { + test.Fatalf("one Undo did not restore the original text: %q", harness.editor.String()) + } + assertSelection() + if !harness.editor.Redo() || harness.editor.String() != "a\u4f60\u597dc" { + test.Fatalf("Redo = %q", harness.editor.String()) + } + }) + } + } +} diff --git a/internal/platform/linux/selection_linux.go b/internal/platform/linux/selection_linux.go index f0de4e2cf..6fe98a0f4 100644 --- a/internal/platform/linux/selection_linux.go +++ b/internal/platform/linux/selection_linux.go @@ -160,7 +160,11 @@ func (win *window) handleSelectionRequest(request *xcbSelectionRequestEvent) err }, } win.dropStaleTransfers() - if value, owned := win.selectionText(request.Selection); owned { + if request.Selection == win.xdnd.selection && win.xdnd.selection != 0 && win.source.active { + // A drag out owns XdndSelection while it runs; the target reads the + // file list from it after the drop. + win.answerXdndSelection(request, ¬ify) + } else if value, owned := win.selectionText(request.Selection); owned { property := request.Property if property == xcbAtomNone { property = request.Target @@ -309,6 +313,9 @@ func (win *window) handleSelectionClear(event *xcbSelectionClearEvent) { case event.Selection == xcbAtomPrimary: win.selections.primary = "" win.selections.ownsPrimary = false + case event.Selection == win.xdnd.selection && win.xdnd.selection != 0: + // Another client took XdndSelection: this drag can deliver nothing. + win.cancelSourceDrag() } } diff --git a/internal/platform/linux/selection_live_linux_test.go b/internal/platform/linux/selection_live_linux_test.go index 943b89cc1..1eff6d2e6 100644 --- a/internal/platform/linux/selection_live_linux_test.go +++ b/internal/platform/linux/selection_live_linux_test.go @@ -15,6 +15,7 @@ import ( "unsafe" "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" ) // These tests make a real window own a selection on the X server and have xclip, another @@ -100,10 +101,13 @@ func TestThePrimarySelectionIsPastedByAnotherProgramAndReadBackFromIt(t *testing stop := pumpSelectionEvents(win) defer stop() - if err := SetPrimaryText("选中的 text"); err != nil { - t.Fatal(err) - } - if got := string(xclipOut(t, "primary")); got != "选中的 text" { + const selected = "选中的 text" + value := selected + strings.Repeat("a", 1<<20) + previous := platform.TextState{Value: value} + next := platform.TextState{Value: value, Selection: text.Range{Start: len([]rune(selected))}} + input := &linuxTextInput{} + input.publishPrimary(previous, next) + if got := string(xclipOut(t, "primary")); got != selected { t.Fatalf("xclip read %q from PRIMARY", got) } // An empty CLIPBOARD makes xclip fail; what matters is that it does not hold the selection. diff --git a/internal/platform/linux/system_linux.go b/internal/platform/linux/system_linux.go index 3d608b441..9022dcd47 100644 --- a/internal/platform/linux/system_linux.go +++ b/internal/platform/linux/system_linux.go @@ -22,6 +22,16 @@ const ( maxClipboardBytes = 64 << 20 clipboardWait = 3 * time.Second dialogSeparator = "\x1f" + // clipboardFocusWindow is how long after this window gains the keyboard a + // missing CLIPBOARD owner is still the hand-off from the window that was + // left, not an empty clipboard. The owner is published on focus, and a paste + // in that moment otherwise reads nothing and the shortcut has already been + // consumed. + clipboardFocusWindow = 500 * time.Millisecond + // clipboardOwnerWait bounds that wait. An empty clipboard must not sit for + // clipboardWait. + clipboardOwnerWait = 250 * time.Millisecond + clipboardOwnerPoll = 15 * time.Millisecond ) var ErrUnsupported = errors.New("linux: system integration is unsupported") @@ -39,6 +49,8 @@ type OpenFileOptions struct { type OpenDirectoryOptions struct { Title string + // InitialDirectory is the starting folder. Empty uses the platform default. + InitialDirectory string } type SaveFileOptions struct { @@ -67,7 +79,9 @@ func ClipboardText() (string, error) { func readClipboardX11() (string, error) { return readSelectionTextX11("CLIPBOARD") } // readSelectionTextX11 asks the owner of a selection (CLIPBOARD, PRIMARY) for its text; empty -// when nobody owns it. +// when nobody owns it. Just after this window gains the keyboard the previous owner may +// already have dropped the selection and the next one not claimed it, so an empty answer +// in that moment is waited out instead of reported as an empty clipboard. func readSelectionTextX11(name string) (string, error) { api, connection, requestor, selection, owner, err := openSelectionRequest(name) if err != nil { @@ -75,7 +89,17 @@ func readSelectionTextX11(name string) (string, error) { } defer closeClipboardRequest() if owner == xcbAtomNone { - return "", nil + deadline, wait := clipboardHandoffDeadline() + if !wait { + return "", nil + } + owner, err = awaitSelectionOwner(api, connection, selection, deadline) + if err != nil { + return "", err + } + if owner == xcbAtomNone { + return "", nil + } } property, err := api.atom(connection, "VIVA_CLIPBOARD_TEXT") if err != nil { @@ -143,6 +167,42 @@ func readSelectionTextX11(name string) (string, error) { return "", nil } +// clipboardHandoffDeadline reports whether a clipboard read is still inside the +// focus hand-off, and until when it should wait for an owner. +func clipboardHandoffDeadline() (time.Time, bool) { + win := activeWindow.Load() + if win == nil { + return time.Time{}, false + } + at := win.clipboardFocusedAt.Load() + if at == 0 { + return time.Time{}, false + } + age := time.Duration(monotonicNow() - at) + if age < 0 || age >= clipboardFocusWindow { + return time.Time{}, false + } + return time.Now().Add(clipboardOwnerWait), true +} + +// awaitSelectionOwner polls the selection owner until one appears or deadline +// passes. The caller has already seen none, so the first look waits a poll +// interval rather than asking again immediately. +func awaitSelectionOwner(api *xcbAPI, connection uintptr, selection uint32, deadline time.Time) (uint32, error) { + for time.Now().Before(deadline) { + pause := clipboardOwnerPoll + if remaining := time.Until(deadline); pause > remaining { + pause = remaining + } + time.Sleep(pause) + owner, err := selectionOwner(api, connection, selection) + if err != nil || owner != xcbAtomNone { + return owner, err + } + } + return xcbAtomNone, nil +} + // HasClipboardImage reports whether the X11 CLIPBOARD owner offers image/png. // It asks the owner for its TARGETS, so it waits for another application for up // to clipboardWait; a clipboard this process owns answers without asking. @@ -568,8 +628,10 @@ func waitForNewValue(api *xcbAPI, connection uintptr, requestor, property uint32 return fmt.Errorf("linux: clipboard owner stopped sending the image within %s", clipboardWait) } milliseconds := max(remaining.Milliseconds(), 1) - ready := api.poll(file, 1, int32(min(milliseconds, int64(^uint32(0)>>1)))) - runtime.KeepAlive(file) + ready, interrupted := pollSelection(api, file, int32(min(milliseconds, int64(^uint32(0)>>1)))) + if interrupted { + continue + } if ready < 0 || api.connectionHasError(connection) != 0 { return fmt.Errorf("linux: wait for clipboard chunk failed") } @@ -934,9 +996,12 @@ func openDirectoryDialogArguments(backend string, options OpenDirectoryOptions) if options.Title != "" { arguments = append(arguments, "--title="+options.Title) } + if options.InitialDirectory != "" { + arguments = append(arguments, "--filename="+strings.TrimRight(options.InitialDirectory, "/")+"/") + } return arguments, nil case "kdialog": - arguments := []string{"--getexistingdirectory", ""} + arguments := []string{"--getexistingdirectory", options.InitialDirectory} if options.Title != "" { arguments = append(arguments, "--title", options.Title) } @@ -1185,8 +1250,10 @@ func waitForSelection(api *xcbAPI, connection uintptr, requestor, selection, tar if milliseconds > int64(^uint32(0)>>1) { milliseconds = int64(^uint32(0) >> 1) } - ready := api.poll(&file, 1, int32(milliseconds)) - runtime.KeepAlive(&file) + ready, interrupted := pollSelection(api, &file, int32(milliseconds)) + if interrupted { + continue + } if ready == 0 { return nil, fmt.Errorf("linux: clipboard owner did not respond within %s", timeout) } @@ -1199,6 +1266,15 @@ func waitForSelection(api *xcbAPI, connection uintptr, requestor, selection, tar } } +func pollSelection(api *xcbAPI, file *pollFD, milliseconds int32) (int32, bool) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + ready := api.poll(file, 1, milliseconds) + interrupted := ready < 0 && *api.errnoLocation() == errnoINTR + runtime.KeepAlive(file) + return ready, interrupted +} + func latin1Clipboard(value string) []byte { result := make([]byte, 0, len(value)) for _, character := range value { diff --git a/internal/platform/linux/system_linux_test.go b/internal/platform/linux/system_linux_test.go index 5d1696fd1..a8d3c9fad 100644 --- a/internal/platform/linux/system_linux_test.go +++ b/internal/platform/linux/system_linux_test.go @@ -8,12 +8,116 @@ import ( "path/filepath" "reflect" "strings" + "syscall" "testing" + "time" "unsafe" "github.com/vivaui/viva/internal/platform" ) +func TestClipboardWaitRetriesOnlyInterruptedPoll(test *testing.T) { + selection := xcbSelectionNotifyEvent{ResponseType: xcbSelectionNotify, Requestor: 2, Selection: 3, Target: 4} + property := xcbPropertyEvent{ResponseType: xcbPropertyNotify, Window: 2, Atom: 5} + for _, wait := range []struct { + name string + event unsafe.Pointer + run func(*xcbAPI) error + }{ + {"selection", unsafe.Pointer(&selection), func(api *xcbAPI) error { + event, err := waitForSelection(api, 1, 2, 3, 4, time.Second) + if err == nil && event != unsafe.Pointer(&selection) { + return errors.New("wait did not return the selection reply") + } + return err + }}, + {"chunk", unsafe.Pointer(&property), func(api *xcbAPI) error { + return waitForNewValue(api, 1, 2, 5, &pollFD{FD: 1, Events: xcbPollInput}) + }}, + } { + for _, failure := range []struct { + name string + errno int32 + retry bool + }{ + {"interrupted", int32(syscall.EINTR), true}, + {"bad descriptor", int32(syscall.EBADF), false}, + } { + test.Run(wait.name+"/"+failure.name, func(test *testing.T) { + calls := 0 + api := &xcbAPI{ + fileDescriptor: func(uintptr) int32 { return 1 }, + connectionHasError: func(uintptr) int32 { return 0 }, + errnoLocation: func() *int32 { return &failure.errno }, + free: func(unsafe.Pointer) {}, + pollForEvent: func(uintptr) unsafe.Pointer { + if calls == 2 { + return wait.event + } + return nil + }, + poll: func(*pollFD, uintptr, int32) int32 { + calls++ + if calls == 1 { + return -1 + } + return 1 + }, + } + err := wait.run(api) + if failure.retry && (err != nil || calls != 2) { + test.Fatalf("interrupted wait returned %v after %d polls; want the reply after a retry", err, calls) + } + if !failure.retry && (err == nil || calls != 1) { + test.Fatalf("invalid descriptor returned %v after %d polls; want an immediate error", err, calls) + } + }) + } + } +} + +func TestClipboardInterruptedReplyRetainsDeadline(test *testing.T) { + errno := int32(syscall.EINTR) + calls := 0 + api := &xcbAPI{ + fileDescriptor: func(uintptr) int32 { return 1 }, + connectionHasError: func(uintptr) int32 { return 0 }, + pollForEvent: func(uintptr) unsafe.Pointer { return nil }, + errnoLocation: func() *int32 { return &errno }, + poll: func(_ *pollFD, _ uintptr, timeout int32) int32 { + calls++ + if calls > 1 { + test.Fatal("wait repeated a poll after the original deadline") + } + time.Sleep(time.Duration(timeout+2) * time.Millisecond) + return -1 + }, + } + _, err := waitForSelection(api, 1, 2, 3, 4, 25*time.Millisecond) + if err == nil || !strings.Contains(err.Error(), "did not respond") { + test.Fatalf("wait returned %v after the original deadline; want a timeout", err) + } +} + +func TestClipboardHandoffWaitsOnlyJustAfterFocus(t *testing.T) { + win := &window{} + previous := activeWindow.Load() + activeWindow.Store(win) + t.Cleanup(func() { activeWindow.Store(previous) }) + + if _, wait := clipboardHandoffDeadline(); wait { + t.Fatal("a window that has not gained the keyboard waited for a clipboard owner") + } + win.clipboardFocusedAt.Store(monotonicNow()) + if _, wait := clipboardHandoffDeadline(); !wait { + t.Fatal("a window that just gained the keyboard did not wait for a clipboard owner") + } + win.clipboardFocusedAt.Store(monotonicNow() - int64(clipboardFocusWindow) - int64(time.Millisecond)) + if _, wait := clipboardHandoffDeadline(); wait { + t.Fatal("a focus older than the hand-off window still waited for a clipboard owner") + } +} + func TestUnavailableSystemIntegrationsAreDetectable(t *testing.T) { activeWindow.Store(nil) t.Setenv("PATH", t.TempDir()) @@ -460,3 +564,23 @@ func TestOnClipboardChangeWithoutDisplayReportsUnsupported(t *testing.T) { t.Fatalf("stopping a watch that never ran: %v", err) } } + +func TestOpenDirectoryInitialDirectory(t *testing.T) { + for _, directory := range []string{"/tmp/My projects", "/tmp/My projects/"} { + for _, backend := range []string{"zenity", "kdialog"} { + t.Run(backend+directory, func(t *testing.T) { + got, err := openDirectoryDialogArguments(backend, OpenDirectoryOptions{Title: "Choose folder", InitialDirectory: directory}) + if err != nil { + t.Fatal(err) + } + want := []string{"--getexistingdirectory", directory, "--title", "Choose folder"} + if backend == "zenity" { + want = []string{"--file-selection", "--directory", "--title=Choose folder", "--filename=/tmp/My projects/"} + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("arguments = %#v; want %#v", got, want) + } + }) + } + } +} diff --git a/internal/platform/linux/text_input_linux.go b/internal/platform/linux/text_input_linux.go index e3bbb1443..ad5866c69 100644 --- a/internal/platform/linux/text_input_linux.go +++ b/internal/platform/linux/text_input_linux.go @@ -622,11 +622,28 @@ func primaryCandidate(private bool, previous, next platform.TextState) (string, if selection.Start > selection.End { selection.Start, selection.End = selection.End, selection.Start } - runes := []rune(next.Value) - if selection.Start == selection.End || selection.Start < 0 || selection.End > len(runes) { + if selection.Start == selection.End || selection.Start < 0 { return "", false } - return string(runes[selection.Start:selection.End]), true + start, end, runeIndex := 0, len(next.Value), 0 + for offset := range next.Value { + if runeIndex == selection.Start { + start = offset + } + if runeIndex == selection.End { + end = offset + break + } + runeIndex++ + } + if runeIndex != selection.End { + return "", false + } + selected := next.Value[start:end] + if !utf8.ValidString(selected) { + return string([]rune(selected)), true + } + return strings.Clone(selected), true } // caretIndex is the rune index of the caret: the end of the selection, or of the composition diff --git a/internal/platform/linux/text_input_linux_test.go b/internal/platform/linux/text_input_linux_test.go index 70d1dd419..d6e632812 100644 --- a/internal/platform/linux/text_input_linux_test.go +++ b/internal/platform/linux/text_input_linux_test.go @@ -479,10 +479,15 @@ func TestPrimaryCandidateIsTheNewlySelectedText(t *testing.T) { {"selected", false, state("hello world", 0, 0), state("hello world", 6, 11), "world", true}, {"backwards", false, state("hello", 0, 0), state("hello", 4, 1), "ell", true}, {"multibyte", false, state("输入法测试", 0, 0), state("输入法测试", 1, 3), "入法", true}, + {"end of Unicode text", false, state("a\U0001f600界", 0, 0), state("a\U0001f600界", 3, 1), "\U0001f600界", true}, + {"invalid selected bytes", false, state("a\xff\xfez", 0, 0), state("a\xff\xfez", 1, 3), "\ufffd\ufffd", true}, + {"invalid bytes before selection", false, state("\xffz", 0, 0), state("\xffz", 1, 2), "z", true}, + {"same range after edit", false, state("ab", 0, 1), state("cb", 0, 1), "c", true}, {"collapsed", false, state("hello", 1, 3), state("hello", 2, 2), "", false}, {"unchanged", false, state("hello", 1, 3), state("hello", 1, 3), "", false}, {"password", true, state("secret", 0, 0), state("secret", 0, 6), "", false}, {"out of range", false, state("ab", 0, 0), state("ab", 0, 9), "", false}, + {"invalid reverse", false, state("ab", 0, 0), state("ab", 1, -1), "", false}, } { got, ok := primaryCandidate(test.private, test.previous, test.now) if got != test.want || ok != test.ok { @@ -491,6 +496,43 @@ func TestPrimaryCandidateIsTheNewlySelectedText(t *testing.T) { } } +func TestPrimaryCandidateDoesNotAllocateForTheWholeValue(t *testing.T) { + value := "\u9009\u4e2d" + strings.Repeat("a", 1<<20) + previous := platform.TextState{Value: value + "b"} + check := func(t *testing.T, selection text.Range, want string, maxAllocs float64) { + t.Helper() + next := platform.TextState{Value: value, Selection: selection} + var selected string + var ok bool + allocations := testing.AllocsPerRun(5, func() { selected, ok = primaryCandidate(false, previous, next) }) + if selected != want || ok != (want != "") || allocations > maxAllocs { + t.Fatalf("got %q, %t and %g allocations; want %q with at most %g allocations", selected, ok, allocations, want, maxAllocs) + } + } + t.Run("collapsed", func(t *testing.T) { check(t, text.Range{Start: 12, End: 12}, "", 0) }) + t.Run("small selection", func(t *testing.T) { check(t, text.Range{End: 2}, "\u9009\u4e2d", 1) }) +} + +func BenchmarkPrimaryCandidateLargeValue(b *testing.B) { + value := "\u9009\u4e2d" + strings.Repeat("a", (16<<20)-6) + previous := platform.TextState{Value: value + "b"} + for _, test := range []struct { + name string + selection text.Range + }{ + {"collapsed", text.Range{Start: 12, End: 12}}, + {"small selection", text.Range{End: 2}}, + } { + b.Run(test.name, func(b *testing.B) { + next := platform.TextState{Value: value, Selection: test.selection} + b.ReportAllocs() + for b.Loop() { + primaryCandidate(false, previous, next) + } + }) + } +} + // A terminal's composition stands on the terminal's cells, as its grid draws the text once it is // committed: with the font's own advances a wide character would be narrower than its two cells // and the text would jump. diff --git a/internal/platform/linux/web_dev_tools_linux.go b/internal/platform/linux/web_dev_tools_linux.go new file mode 100644 index 000000000..b89e2f491 --- /dev/null +++ b/internal/platform/linux/web_dev_tools_linux.go @@ -0,0 +1,29 @@ +//go:build linux && vivagtk + +package linux + +import ( + "fmt" + + "github.com/vivaui/viva/internal/platform" +) + +// ShowDevTools turns on the page's developer extras and opens Web Inspector for it. Developer extras +// stay off until the application asks, so a page that never does has no Inspect Element entry. +func (v *gtkWebView) ShowDevTools() error { + if v.closed { + return fmt.Errorf("linux: the web view with id %d is closed", v.id) + } + if v.k.setDeveloperExtras == nil || v.k.viewInspector == nil || v.k.inspectorShow == nil { + return fmt.Errorf("%w: WebKitGTK lacks Web Inspector", platform.ErrWebViewUnsupported) + } + v.k.setDeveloperExtras(v.k.viewSettings(v.widget), 1) + inspector := v.k.viewInspector(v.widget) + if inspector == 0 { + return fmt.Errorf("%w: WebKitGTK gave the page no inspector", platform.ErrWebViewUnsupported) + } + v.k.inspectorShow(inspector) + return nil +} + +var _ platform.WebDevTools = (*gtkWebView)(nil) diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index ce2fb02cc..fde5c284d 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -68,6 +68,10 @@ type window struct { gnomeFilesAtom uint32 pngAtom uint32 ownsClipboard bool + // clipboardFocusedAt is monotonicNow of the last time this window gained the + // keyboard. A clipboard read in the moment after that can see no selection + // owner (system_linux.go). + clipboardFocusedAt atomic.Int64 // selections is the PRIMARY selection and the streams of data too large for one // property (selection_linux.go). selections selectionState @@ -86,6 +90,14 @@ type window struct { keymap xcbKeymap frame frameState xdnd xdndAtoms + // source is the drag out of this window (drag_linux.go). The event-loop + // thread owns it; lastRootX/Y and lastEventTime are the pointer event that + // started it, which the source must know while the application handles it. + source xdndSource + application *linuxApplication + lastRootX, lastRootY int16 + lastEventTime uint32 + dragGeneration uint64 // wmStateAtom is WM_STATE, resolved when the application asked for // minimize changes; minimized is what it last said. wmStateAtom uint32 @@ -986,6 +998,9 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { switch { case message.Window == win.id && win.isDragMessage(message.Type): return false, state.handleDragMessage(message) + case message.Window == win.id && win.isSourceDragMessage(message.Type): + win.handleSourceDragMessage(message) + return false, nil case message.Format == 32 && message.Window == win.id && message.Type == win.closeAtom: return true, nil case message.Format == 32 && message.Window == win.id && message.Type == win.commandAtom: @@ -1115,6 +1130,7 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { } case xcbButtonPress: inputEvent := (*xcbInputEvent)(event) + win.noteInputEvent(inputEvent) if win.beginWindowMove(config, inputEvent) { break } @@ -1125,12 +1141,17 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { return false, err case xcbButtonRelease: inputEvent := (*xcbInputEvent)(event) + win.noteInputEvent(inputEvent) + win.sourceDragRelease(inputEvent) win.endPress() if xcbPointerButton(inputEvent.Detail) != 0 { return false, router.pointer(platform.PointerUp, inputEvent) } case xcbMotionNotify, xcbEnterNotify: - consumed, cancelled := win.dragMotion((*xcbInputEvent)(event)) + inputEvent := (*xcbInputEvent)(event) + win.noteInputEvent(inputEvent) + win.sourceDragMotion(inputEvent) + consumed, cancelled := win.dragMotion(inputEvent) if cancelled { if err := router.pointerExit(); err != nil { return false, err @@ -1144,6 +1165,9 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { return false, router.pointerExit() case xcbKeyPress: inputEvent := (*xcbInputEvent)(event) + if win.source.active && normalizedKeysym(win.keymap.keysym(inputEvent.Detail, 0)) == input.KeyEscape { + win.sourceDragEscape() + } repeat := state.pendingKeyReleaseDetail == inputEvent.Detail && state.pendingKeyReleaseTime == inputEvent.Time state.pendingKeyReleaseDetail, state.pendingKeyReleaseTime = 0, 0 if !win.keymap.key(inputEvent.Detail).IsModifier() { @@ -1185,10 +1209,13 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { // must not forget keys held here. keyboardFocus := focus.Detail == xcbNotifyAncestor || focus.Detail == xcbNotifyNonlinear // The same details, outside a grab, are the window becoming active. - if realFocus && keyboardFocus && config.OnActivate != nil { - config.OnActivate() - if err := state.refreshReadOnlyTextInput(); err != nil { - return false, err + if realFocus && keyboardFocus { + win.clipboardFocusedAt.Store(monotonicNow()) + if config.OnActivate != nil { + config.OnActivate() + if err := state.refreshReadOnlyTextInput(); err != nil { + return false, err + } } } if keyboardFocus { @@ -1427,7 +1454,7 @@ func (application *linuxApplication) openWindow(config platform.Config) (*window api.disconnect(connection) return nil, fmt.Errorf("linux: X server has no screen") } - win := &window{api: api, connection: connection, screen: iterator.Data} + win := &window{api: api, connection: connection, screen: iterator.Data, application: application} // The scale decides the window's size in device pixels. Where the window // will be is not known yet; the requested origin is the best guess of which // monitor, and the first ConfigureNotify corrects it. @@ -1502,6 +1529,11 @@ func (application *linuxApplication) openWindow(config platform.Config) (*window api.createWindow(connection, xcbCopyFromParent, win.id, win.screen.Root, x, y, uint16(win.width), uint16(win.height), 0, xcbWindowClassInput, win.screen.RootVisual, xcbCWBackPixel|xcbCWBitGravity|xcbCWEventMask, &values[0]) win.depth = win.screen.RootDepth } + if config.Transparent && config.OnTransparentChange != nil { + // Only the drawn frame has an alpha surface, and it exists only where a + // compositing manager owns the screen. + config.OnTransparentChange(win.frameWanted) + } if config.WindowMode != platform.WindowTitled { motifHints, atomErr := api.atom(connection, "_MOTIF_WM_HINTS") if atomErr != nil { @@ -1676,6 +1708,9 @@ func (win *window) postClientSize(width, height uint32) { func (win *window) close() { win.mu.Lock() defer win.mu.Unlock() + // A drag out is over with the window that owned it, and a target still + // waiting has nothing left to ask. + win.source = xdndSource{} if win.tracker != nil { win.tracker.close() win.tracker = nil diff --git a/internal/platform/linux/xcb_linux.go b/internal/platform/linux/xcb_linux.go index d7d7b2a39..3af3cd765 100644 --- a/internal/platform/linux/xcb_linux.go +++ b/internal/platform/linux/xcb_linux.go @@ -168,6 +168,20 @@ type xcbPropertyReply struct { ValueLength uint32 Pad [12]byte } + +// xcbQueryTreeReply is the fixed part of a QueryTree reply; the children, when +// any, follow it. Only the parent is read: it is how a drag source walks from +// the window under the pointer up to the one that speaks XDND. +type xcbQueryTreeReply struct { + ResponseType uint8 + Pad0 uint8 + Sequence uint16 + Length uint32 + Root uint32 + Parent uint32 + ChildrenLen uint16 + Pad1 [14]byte +} type xcbGenericEvent struct { ResponseType uint8 Padding uint8 @@ -344,6 +358,10 @@ type xcbAPI struct { translateCoordinates func(uintptr, uint32, uint32, int16, int16) xcbTranslateCookie translateCoordinatesReply func(uintptr, xcbTranslateCookie, *unsafe.Pointer) *xcbTranslateReply sendEvent func(uintptr, uint8, uint32, uint32, *byte) xcbVoidCookie + queryPointer func(uintptr, uint32) xcbVoidCookie + queryPointerReply func(uintptr, xcbVoidCookie, *unsafe.Pointer) *queryPointerReply + queryTree func(uintptr, uint32) xcbVoidCookie + queryTreeReply func(uintptr, xcbVoidCookie, *unsafe.Pointer) *xcbQueryTreeReply ungrabPointer func(uintptr, uint32) xcbVoidCookie requestCheck func(uintptr, xcbVoidCookie) *xcbGenericError flush func(uintptr) int32 @@ -436,6 +454,10 @@ func openXCB() (*xcbAPI, error) { purego.RegisterLibFunc(&api.translateCoordinates, library, "xcb_translate_coordinates") purego.RegisterLibFunc(&api.translateCoordinatesReply, library, "xcb_translate_coordinates_reply") purego.RegisterLibFunc(&api.sendEvent, library, "xcb_send_event") + purego.RegisterLibFunc(&api.queryPointer, library, "xcb_query_pointer") + purego.RegisterLibFunc(&api.queryPointerReply, library, "xcb_query_pointer_reply") + purego.RegisterLibFunc(&api.queryTree, library, "xcb_query_tree") + purego.RegisterLibFunc(&api.queryTreeReply, library, "xcb_query_tree_reply") purego.RegisterLibFunc(&api.ungrabPointer, library, "xcb_ungrab_pointer") purego.RegisterLibFunc(&api.requestCheck, library, "xcb_request_check") purego.RegisterLibFunc(&api.flush, library, "xcb_flush") diff --git a/internal/platform/web/drag_js.go b/internal/platform/web/drag_js.go index 678b0e083..d76350366 100644 --- a/internal/platform/web/drag_js.go +++ b/internal/platform/web/drag_js.go @@ -14,6 +14,12 @@ import ( // adapter paints into has no DataTransfer, and a canvas drag reaches the browser // as a drag of pixels, not of files. So the page can offer its files only by // copying them (see SetClipboardFiles), which is a different promise to the user. -func StartFileDrag(paths []string, allowed platform.DragEffect) (platform.DragEffect, error) { - return platform.DragEffectNone, fmt.Errorf("%w: a browser drags files from a DOM DataTransfer a canvas does not have", platform.ErrDragUnsupported) +func StartFileDrag(paths []string, allowed platform.DragEffect) error { + return fmt.Errorf("%w: a browser drags files from a DOM DataTransfer a canvas does not have", platform.ErrDragUnsupported) +} + +// StartFilePromiseDrag cannot offer promised content for the same reason: a +// canvas has no DataTransfer to put a file promise on. +func StartFilePromiseDrag(files []platform.FilePromise) error { + return fmt.Errorf("%w: a browser drags files from a DOM DataTransfer a canvas does not have", platform.ErrDragUnsupported) } diff --git a/internal/platform/web_dev_tools.go b/internal/platform/web_dev_tools.go new file mode 100644 index 000000000..e6c552e03 --- /dev/null +++ b/internal/platform/web_dev_tools.go @@ -0,0 +1,9 @@ +package platform + +// WebDevTools is the part of a WebView that can open the engine's developer tools. It is optional: +// a platform whose pages do not implement it has no developer tools, and app.WebView reports +// ErrUnsupported. ShowDevTools runs on the event-loop thread; an error wrapping +// ErrWebViewUnsupported says the engine cannot open them from the application. +type WebDevTools interface { + ShowDevTools() error +} diff --git a/internal/platform/web_host.go b/internal/platform/web_host.go index 93a8c997c..c8a976d7b 100644 --- a/internal/platform/web_host.go +++ b/internal/platform/web_host.go @@ -45,6 +45,8 @@ type WebHost struct { // WebViewConfig describes a page to open. type WebViewConfig struct { + // UserAgentSuffix is appended to the system engine's user agent before navigation. + UserAgentSuffix string // ID names the view in Frame.NativeViews; it is chosen by the opener and unique in the window. ID uint32 // URL is loaded when the view opens, if HTML is empty. diff --git a/internal/platform/windows/api_windows.go b/internal/platform/windows/api_windows.go index 8e0ab2470..46031556c 100644 --- a/internal/platform/windows/api_windows.go +++ b/internal/platform/windows/api_windows.go @@ -168,6 +168,7 @@ var releaseCapture = user.NewProc("ReleaseCapture") var trackMouseEvent = user.NewProc("TrackMouseEvent") var getKeyState = user.NewProc("GetKeyState") var loadCursor = user.NewProc("LoadCursorW") +var isWindow = user.NewProc("IsWindow") var getModule = kernel.NewProc("GetModuleHandleW") var ole = systemDLL("ole32.dll") var initializeCOM = ole.NewProc("CoInitializeEx") diff --git a/internal/platform/windows/backdrop_windows_test.go b/internal/platform/windows/backdrop_windows_test.go index 9a99158bf..d70c1aa34 100644 --- a/internal/platform/windows/backdrop_windows_test.go +++ b/internal/platform/windows/backdrop_windows_test.go @@ -23,6 +23,20 @@ func TestBackdropUnconfiguredKeepsOrdinaryRenderer(t *testing.T) { } } +// A transparent window is composed by DirectComposition, since only a premultiplied swap chain +// lets the clear color's alpha reach the desktop; one that did not ask keeps the ordinary renderer. +func TestTransparentWindowIsComposed(t *testing.T) { + state := &windowState{window: 1} + state.config.Transparent = true + if state.backdropWindowStyle() != wsExNoRedirectionBitmap { + t.Fatal("a transparent window needs the composition style") + } + state.configureBackdropRenderer() + if !state.renderer.usesComposition() { + t.Fatal("a transparent window did not select the composition renderer") + } +} + // A window that did not ask for a material is not changed by the messages that would update one: // they go on to the ordinary window procedure, and the power broadcast is not swallowed. func TestBackdropMessagesLeaveAnUnconfiguredWindowAlone(t *testing.T) { diff --git a/internal/platform/windows/clipboard_html_windows.go b/internal/platform/windows/clipboard_html_windows.go index d9c57c723..175959f13 100644 --- a/internal/platform/windows/clipboard_html_windows.go +++ b/internal/platform/windows/clipboard_html_windows.go @@ -30,10 +30,7 @@ func SetClipboardHTML(html, alt string) error { block := cfHTML(html) clipboardMu.Lock() defer clipboardMu.Unlock() - owner := uintptr(0) - if state := active.Load(); state != nil { - owner = state.window - } + owner := activeOwnerWindow() if opened, _, callErr := openClipboard.Call(owner); opened == 0 { return windowsCallError("open clipboard", callErr) } diff --git a/internal/platform/windows/clipboard_image_windows.go b/internal/platform/windows/clipboard_image_windows.go index f281a0222..fdaa2fc9a 100644 --- a/internal/platform/windows/clipboard_image_windows.go +++ b/internal/platform/windows/clipboard_image_windows.go @@ -38,10 +38,7 @@ func SetClipboardImage(png []byte) error { } clipboardMu.Lock() defer clipboardMu.Unlock() - owner := uintptr(0) - if state := active.Load(); state != nil { - owner = state.window - } + owner := activeOwnerWindow() if err := openClipboardForWrite(owner); err != nil { return err } diff --git a/internal/platform/windows/clipboard_watch_windows.go b/internal/platform/windows/clipboard_watch_windows.go index fc40ee333..0346aebab 100644 --- a/internal/platform/windows/clipboard_watch_windows.go +++ b/internal/platform/windows/clipboard_watch_windows.go @@ -79,9 +79,12 @@ func listenToClipboard(window uintptr) error { return nil } -// forgetClipboardListener drops a window that is being destroyed: Windows removes it from the -// listener list itself. -func forgetClipboardListener(window uintptr) { clipboardListeners.Delete(window) } +// forgetClipboardListener removes a window that is being destroyed from the clipboard format listener list. +func forgetClipboardListener(window uintptr) { + if _, ok := clipboardListeners.LoadAndDelete(window); ok { + removeClipboardFormatListener.Call(window) + } +} // notifyClipboardChange runs in the window procedure. func notifyClipboardChange() { diff --git a/internal/platform/windows/clipboard_watch_windows_test.go b/internal/platform/windows/clipboard_watch_windows_test.go index c4ae05658..52419261c 100644 --- a/internal/platform/windows/clipboard_watch_windows_test.go +++ b/internal/platform/windows/clipboard_watch_windows_test.go @@ -89,3 +89,12 @@ func TestClipboardChangeMayBeRegisteredBeforeAnyWindowAndStops(t *testing.T) { t.Fatalf("a stopped watch still added a window: %v", err) } } + +func TestForgetClipboardListenerUnregistersWindow(t *testing.T) { + fakeHwnd := uintptr(0xdeadbeef) + clipboardListeners.Store(fakeHwnd, struct{}{}) + forgetClipboardListener(fakeHwnd) + if _, ok := clipboardListeners.Load(fakeHwnd); ok { + t.Fatal("clipboardListeners still has fakeHwnd after forgetClipboardListener") + } +} diff --git a/internal/platform/windows/drag_promise_windows.go b/internal/platform/windows/drag_promise_windows.go new file mode 100644 index 000000000..784bd44cb --- /dev/null +++ b/internal/platform/windows/drag_promise_windows.go @@ -0,0 +1,544 @@ +//go:build windows + +package windows + +import ( + "fmt" + "io" + "runtime" + "strings" + "sync" + "syscall" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// A promised drag offers files the application has not written yet: instead of +// CF_HDROP, its IDataObject hands the target a file group descriptor and, for +// each item, an IStream that the application fills as the target reads it. The +// shell's copy engine treats those as files: it creates them where the user let +// go, shows a progress dialog from the descriptor's sizes, and calls Read in +// order. This is what dragging a file off a remote server needs, because the +// file may not exist on this computer at all until the drop happens. +// +// The descriptor is the whole tree, so it is built before DoDragDrop starts: +// Windows has no way to add an item to a drag in progress. A very large folder +// is therefore enumerated before the pointer leaves the application (bounded by +// platform.MaxClipboardFiles). +// +// The shell may keep the streams after DoDragDrop returns, so the objects are +// kept in an explicit registry (promiseRoots) that the garbage collector cannot +// collect while the shell holds a raw pointer. + +const ( + // TYMED_ISTREAM: the medium is an IStream the target reads and releases. + tymedIStream = 4 + // FILEDESCRIPTOR flags. + fdAttributes = 0x4 + fdFileSize = 0x40 + fdProgressUI = 0x4000 + // File attributes. + fileAttributeDirectory = 0x10 + // STG_E_READFAULT: the stream could not produce the bytes asked for. + stgEReadFault = 0x8003001E + // STATSTG types and modes. + stgtYStream = 2 + stgmRead = 0 + // IStream::Seek origins. + streamSeekSet = 0 + streamSeekCur = 1 + // MAX_PATH is the name FILEDESCRIPTORW carries, NUL included. + maxDescriptorName = 260 +) + +var ( + groupDescriptorOnce sync.Once + groupDescriptorID uint16 + fileContentsOnce sync.Once + fileContentsID uint16 + iidStream = guid{0x0000000c, 0x0000, 0x0000, [8]byte{0xc0, 0, 0, 0, 0, 0, 0, 0x46}} +) + +// fileGroupDescriptorFormat is CFSTR_FILEDESCRIPTORW, the shell's name for the +// block of file descriptions a virtual-file drag offers. +func fileGroupDescriptorFormat() uint16 { + groupDescriptorOnce.Do(func() { + name, _ := syscall.UTF16PtrFromString("FileGroupDescriptorW") + format, _, _ := registerClipboardFormat.Call(uintptr(unsafe.Pointer(name))) + groupDescriptorID = uint16(format) + }) + return groupDescriptorID +} + +// fileContentsFormat is CFSTR_FILECONTENTS, the format whose lindex names the +// item an IStream produces. +func fileContentsFormat() uint16 { + fileContentsOnce.Do(func() { + name, _ := syscall.UTF16PtrFromString("FileContents") + format, _, _ := registerClipboardFormat.Call(uintptr(unsafe.Pointer(name))) + fileContentsID = uint16(format) + }) + return fileContentsID +} + +// fileDescriptorW mirrors FILEDESCRIPTORW: one item of the group descriptor. +type fileDescriptorW struct { + Flags uint32 + Clsid guid + Sizel [2]int32 + Pointl [2]int32 + Attributes uint32 + CreationTime fileTime + LastAccessTime fileTime + LastWriteTime fileTime + SizeHigh uint32 + SizeLow uint32 + Name [maxDescriptorName]uint16 +} + +type fileTime struct{ Low, High uint32 } + +// promiseItem is one flattened item of a promised drag: a file or a folder with +// its path inside the drag and the content callback of a file. +type promiseItem struct { + name string + size int64 + directory bool + open func() (io.ReadCloser, error) +} + +// promiseDrag is the promised payload of a fileDataObject. +type promiseDrag struct { + items []promiseItem + descriptor uint16 + contents uint16 +} + +func (drag *promiseDrag) formatAt(index int) formatEtc { + switch index { + case 0: + return formatEtc{Format: drag.descriptor, Aspect: dvAspectContent, Index: lindexNone, Medium: tymedHGlobal} + case 1: + return formatEtc{Format: drag.contents, Aspect: dvAspectContent, Index: lindexNone, Medium: tymedIStream} + } + return formatEtc{} +} + +// takes reports whether the object can answer a FORMATETC. A contents request +// is answered for lindex -1 (the format as enumerated) and for each item. +func (drag *promiseDrag) takes(asked formatEtc) bool { + if asked.Aspect&dvAspectContent == 0 { + return false + } + switch asked.Format { + case drag.descriptor: + return asked.Index == lindexNone && asked.Medium&tymedHGlobal != 0 + case drag.contents: + return asked.Index >= lindexNone && int(asked.Index) < len(drag.items) && asked.Medium&tymedIStream != 0 + } + return false +} + +// getData answers one question from the target: the group descriptor or a +// stream for one item. The stream starts its content on the first Read. +func (data *fileDataObject) promiseGetData(asked formatEtc, medium uintptr) uintptr { + drag := data.promise + if !drag.takes(asked) { + return dvEFormatEtc + } + if asked.Format == drag.descriptor { + handle, err := drag.descriptorHandle() + if err != nil { + return eFail + } + *(*storageMedium)(pointer(medium)) = storageMedium{Medium: tymedHGlobal, Handle: handle} + return sOK + } + if asked.Index == lindexNone { + return dvEFormatEtc + } + stream := drag.newStream(data, int(asked.Index)) + if stream == nil { + return dvEFormatEtc + } + *(*storageMedium)(pointer(medium)) = storageMedium{Medium: tymedIStream, Handle: uintptr(unsafe.Pointer(stream))} + return sOK +} + +// descriptorHandle builds the FILEGROUPDESCRIPTORW in shared memory the target +// owns: a count, then one fixed-size descriptor per item. +func (drag *promiseDrag) descriptorHandle() (uintptr, error) { + descriptorSize := int(unsafe.Sizeof(fileDescriptorW{})) + total := 4 + len(drag.items)*descriptorSize + handle, _, callErr := globalAlloc.Call(globalMoveable|globalZeroInit, uintptr(total)) + if handle == 0 { + return 0, windowsCallError("allocate a dragged file group", callErr) + } + memory, _, callErr := globalLock.Call(handle) + if memory == 0 { + globalFree.Call(handle) + return 0, windowsCallError("lock a dragged file group", callErr) + } + block := unsafe.Slice((*byte)(pointer(memory)), total) + *(*uint32)(unsafe.Pointer(&block[0])) = uint32(len(drag.items)) + descriptors := unsafe.Slice((*fileDescriptorW)(unsafe.Pointer(&block[4])), len(drag.items)) + for index, item := range drag.items { + descriptors[index] = item.descriptor() + } + globalUnlock.Call(handle) + return handle, nil +} + +// descriptor is this item's FILEDESCRIPTORW. The shell copies from the size the +// descriptor names, so a file whose size is unknown is still offered, without +// the size and its progress. +func (item promiseItem) descriptor() fileDescriptorW { + var out fileDescriptorW + out.Flags = fdAttributes + if item.directory { + out.Attributes = fileAttributeDirectory + } else { + out.Attributes = fileAttributeNormal + out.Flags |= fdProgressUI + if item.size >= 0 { + out.Flags |= fdFileSize + out.SizeHigh = uint32(uint64(item.size) >> 32) + out.SizeLow = uint32(item.size) + } + } + units, _ := syscall.UTF16FromString(item.name) + if len(units) > len(out.Name) { + units = units[:len(out.Name)] + } + copy(out.Name[:], units) + return out +} + +// promiseItems flattens the tree Windows must describe before the drag starts. +// The names become the backslash-separated relative paths the shell understands. +func promiseItems(files []platform.FilePromise) ([]promiseItem, error) { + items := make([]promiseItem, 0, len(files)) + err := platform.WalkFilePromises(files, func(path string, promise platform.FilePromise) error { + name := strings.ReplaceAll(path, "/", `\`) + units, err := syscall.UTF16FromString(name) + if err != nil || len(units) > maxDescriptorName { + return fmt.Errorf("windows: the dragged file name %q is too long for the shell", name) + } + items = append(items, promiseItem{name: name, size: promise.Size, directory: promise.Directory, open: promise.Open}) + return nil + }) + if err != nil { + return nil, err + } + return items, nil +} + +// promiseStream is the IStream of one promised file. It produces its content on +// the first Read and serves the rest of the reads from the same reader, so the +// shell sees one sequential file. +type promiseStream struct { + table *[14]uintptr + refs int32 + owner *fileDataObject + item promiseItem + mu sync.Mutex + // reader is the content, opened on the first Read. + reader io.ReadCloser + started bool + failed bool + offset uint64 +} + +var ( + streamTableOnce sync.Once + streamTable [14]uintptr +) + +func newPromiseStreamTable() { + streamTable = [14]uintptr{ + guarded3("drag and drop: stream QueryInterface", streamQueryInterface), + guarded1("drag and drop: stream AddRef", streamAddRef), + guarded1("drag and drop: stream Release", streamRelease), + guarded4("drag and drop: stream Read", streamRead), + guarded4("drag and drop: stream Write", streamWrite), + guarded4("drag and drop: stream Seek", streamSeek), + guarded2("drag and drop: stream SetSize", streamSetSize), + guarded5("drag and drop: stream CopyTo", streamCopyTo), + guarded2("drag and drop: stream Commit", streamCommit), + guarded1("drag and drop: stream Revert", streamRevert), + guarded4("drag and drop: stream LockRegion", streamLockRegion), + guarded4("drag and drop: stream UnlockRegion", streamUnlockRegion), + guarded3("drag and drop: stream Stat", streamStat), + guarded2("drag and drop: stream Clone", streamClone), + } +} + +func streamOf(this uintptr) *promiseStream { return (*promiseStream)(pointer(this)) } + +func (drag *promiseDrag) newStream(owner *fileDataObject, index int) *promiseStream { + if index < 0 || index >= len(drag.items) || drag.items[index].directory { + return nil + } + streamTableOnce.Do(newPromiseStreamTable) + stream := &promiseStream{table: &streamTable, refs: 1, owner: owner, item: drag.items[index]} + pinPromiseStream(stream) + return stream +} + +// promiseRoots are the objects the shell may still call through pointers the +// garbage collector cannot see: a promised drag's data object until its own +// reference count ends, and every stream until the target releases it. +var promiseRoots struct { + mu sync.Mutex + objects map[*fileDataObject]struct{} + streams map[*promiseStream]struct{} +} + +func pinPromiseDrag(data *fileDataObject) { + promiseRoots.mu.Lock() + if promiseRoots.objects == nil { + promiseRoots.objects = make(map[*fileDataObject]struct{}) + } + promiseRoots.objects[data] = struct{}{} + promiseRoots.mu.Unlock() +} + +func unpinPromiseDrag(data *fileDataObject) { + promiseRoots.mu.Lock() + delete(promiseRoots.objects, data) + promiseRoots.mu.Unlock() +} + +func pinPromiseStream(stream *promiseStream) { + promiseRoots.mu.Lock() + if promiseRoots.streams == nil { + promiseRoots.streams = make(map[*promiseStream]struct{}) + } + promiseRoots.streams[stream] = struct{}{} + promiseRoots.mu.Unlock() +} + +func unpinPromiseStream(stream *promiseStream) { + promiseRoots.mu.Lock() + delete(promiseRoots.streams, stream) + promiseRoots.mu.Unlock() +} + +func streamQueryInterface(this, riid, object uintptr) uintptr { + return answerInterface(this, riid, object, &streamOf(this).refs, iidStream) +} + +func streamAddRef(this uintptr) uintptr { + stream := streamOf(this) + stream.refs++ + return uintptr(stream.refs) +} + +func streamRelease(this uintptr) uintptr { + stream := streamOf(this) + if stream.refs > 0 { + stream.refs-- + } + if stream.refs == 0 { + stream.mu.Lock() + if stream.reader != nil { + stream.reader.Close() + stream.reader = nil + } + stream.mu.Unlock() + unpinPromiseStream(stream) + } + return uintptr(stream.refs) +} + +// streamRead produces the file's bytes. The first call opens the content; a +// short read is S_FALSE, which is how an IStream says the file ended. An error +// with nothing read is STG_E_READFAULT, which the shell shows as a failed copy. +func streamRead(this, pv, cb, pcbRead uintptr) uintptr { + stream := streamOf(this) + want := int(uint32(cb)) + stream.mu.Lock() + defer stream.mu.Unlock() + if stream.failed { + setUint32(pcbRead, 0) + return stgEReadFault + } + if !stream.started { + reader, err := stream.item.open() + if err != nil { + stream.failed = true + setUint32(pcbRead, 0) + return stgEReadFault + } + stream.reader, stream.started = reader, true + } + read := 0 + if want > 0 && pv != 0 { + buffer := unsafe.Slice((*byte)(pointer(pv)), want) + for read < want { + n, err := stream.reader.Read(buffer[read:]) + read += n + if err != nil { + if err != io.EOF { + stream.failed = true + } + break + } + if n == 0 { + break + } + } + } + stream.offset += uint64(read) + setUint32(pcbRead, uint32(read)) + if stream.failed && read == 0 { + return stgEReadFault + } + if read < want { + return sFalse + } + return sOK +} + +func setUint32(address uintptr, value uint32) { + if address != 0 { + *(*uint32)(pointer(address)) = value + } +} + +// streamSeek allows asking where the stream is and rewinding before it started. +// The content is produced forwards, so a target that seeks into it gets +// E_NOTIMPL, which the shell reports rather than corrupting the copy. +func streamSeek(this, move, origin, newPosition uintptr) uintptr { + stream := streamOf(this) + offset := int64(move) + stream.mu.Lock() + defer stream.mu.Unlock() + switch uint32(origin) { + case streamSeekCur: + if offset != 0 { + return eNotImpl + } + case streamSeekSet: + if offset != 0 || stream.started || stream.offset != 0 { + return eNotImpl + } + default: + return eNotImpl + } + if newPosition != 0 { + *(*uint64)(pointer(newPosition)) = stream.offset + } + return sOK +} + +func streamWrite(this, pv, cb, written uintptr) uintptr { + setUint32(written, 0) + return eNotImpl +} + +func streamSetSize(this, size uintptr) uintptr { return eNotImpl } + +func streamCopyTo(this, other, cb, read, written uintptr) uintptr { return eNotImpl } + +func streamCommit(this, flags uintptr) uintptr { return sOK } + +func streamRevert(this uintptr) uintptr { return eNotImpl } + +func streamLockRegion(this, offset, count, lockType uintptr) uintptr { return eNotImpl } + +func streamUnlockRegion(this, offset, count, lockType uintptr) uintptr { return eNotImpl } + +func streamClone(this, out uintptr) uintptr { + if out != 0 { + *(*uintptr)(pointer(out)) = 0 + } + return eNotImpl +} + +// statStg mirrors STATSTG, the description a target reads to learn the stream's +// size before copying it. +type statStg struct { + Name uintptr + Type uint32 + _ uint32 + Size uint64 + Mtime fileTime + Ctime fileTime + Atime fileTime + Mode uint32 + Locks uint32 + Clsid guid + State uint32 + Reserved uint32 +} + +func streamStat(this, stat, flags uintptr) uintptr { + if stat == 0 { + return eNotImpl + } + stream := streamOf(this) + size := uint64(0) + if stream.item.size > 0 { + size = uint64(stream.item.size) + } + *(*statStg)(pointer(stat)) = statStg{Type: stgtYStream, Size: size, Mode: stgmRead} + return sOK +} + +// StartFilePromiseDrag takes files out of the application's active window whose +// content the application produces when the target reads it. The whole tree is +// described to the shell before the drag starts, so the call may walk a folder on +// the event-loop thread; Open runs when the shell reads each file. +func StartFilePromiseDrag(files []platform.FilePromise) error { + state := active.Load() + if state == nil || state.window == 0 { + return fmt.Errorf("windows: no window to drag files out of") + } + thread, _, _ := getCurrentThread.Call() + if uint32(thread) != state.application.thread { + return fmt.Errorf("windows: files are dragged out on the event-loop thread that owns the window") + } + if len(files) == 0 { + return fmt.Errorf("windows: no files to drag out of the window") + } + descriptor, contents := fileGroupDescriptorFormat(), fileContentsFormat() + if descriptor == 0 || contents == 0 { + return fmt.Errorf("windows: the shell's file formats could not be registered") + } + items, err := promiseItems(files) + if err != nil { + return err + } + if !state.application.oleReady { + if status, _, _ := oleInitialize.Call(0); int32(uint32(status)) < 0 { + return hresult(status) + } + state.application.oleReady = true + } + dataTableOnce.Do(newFileDataTable) + sourceTableOnce.Do(newFileSourceTable) + data := &fileDataObject{table: &dataTable, refs: 1} + data.promise = &promiseDrag{items: items, descriptor: descriptor, contents: contents} + pinPromiseDrag(data) + source := &fileDropSource{table: &sourceTable, refs: 1} + var effect uint32 + status, _, _ := doDragDrop.Call( + uintptr(unsafe.Pointer(data)), + uintptr(unsafe.Pointer(source)), + uintptr(platform.DragEffectCopy), + uintptr(unsafe.Pointer(&effect)), + ) + runtime.KeepAlive(data) + runtime.KeepAlive(source) + if uint32(status) == dragdropSDrop || uint32(status) == dragdropSCancel { + postMessage.Call(state.window, wmDragEnded, 0, 0) + } + if err := hresult(status); err != nil { + // The drag never ran, so nothing holds the object it was built for. + unpinPromiseDrag(data) + return err + } + return nil +} diff --git a/internal/platform/windows/drag_promise_windows_test.go b/internal/platform/windows/drag_promise_windows_test.go new file mode 100644 index 000000000..6a4f04c41 --- /dev/null +++ b/internal/platform/windows/drag_promise_windows_test.go @@ -0,0 +1,199 @@ +//go:build windows + +package windows + +import ( + "bytes" + "io" + "runtime" + "slices" + "strings" + "syscall" + "testing" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// promiseFixture is a file and a folder, as a promised drag flattens them. +func promiseFixture(t *testing.T) []platform.FilePromise { + t.Helper() + file := func(name, value string) platform.FilePromise { + return platform.FilePromise{Name: name, Size: int64(len(value)), Open: func() (io.ReadCloser, error) { + return io.NopCloser(strings.NewReader(value)), nil + }} + } + return []platform.FilePromise{ + file("notes.txt", "hello world"), + {Name: "docs", Directory: true, List: func() ([]platform.FilePromise, error) { + return []platform.FilePromise{file("guide.md", "guide")}, nil + }}, + } +} + +// newPromiseObject builds the data object of a promised drag with format ids +// that need no registration: the tests ask for these, not the shell's names. +func newPromiseObject(t *testing.T, files []platform.FilePromise) (*fileDataObject, uintptr) { + t.Helper() + items, err := promiseItems(files) + if err != nil { + t.Fatal(err) + } + dataTableOnce.Do(newFileDataTable) + data := &fileDataObject{table: &dataTable, refs: 1} + data.promise = &promiseDrag{items: items, descriptor: 0x9001, contents: 0x9002} + pinPromiseDrag(data) + t.Cleanup(func() { unpinPromiseDrag(data) }) + return data, uintptr(unsafe.Pointer(data)) +} + +func descriptorFormat(id uint16) formatEtc { + return formatEtc{Format: id, Aspect: dvAspectContent, Index: lindexNone, Medium: tymedHGlobal} +} + +func contentsFormat(id uint16, index int32) formatEtc { + return formatEtc{Format: id, Aspect: dvAspectContent, Index: index, Medium: tymedIStream} +} + +// TestThePromiseDataObjectDescribesTheWholeTree checks the group descriptor the +// shell reads to create the files: the names, folders, sizes and attributes. +func TestThePromiseDataObjectDescribesTheWholeTree(t *testing.T) { + data, object := newPromiseObject(t, promiseFixture(t)) + data.promise.descriptor = 0x9001 + defer runtime.KeepAlive(data) + format := descriptorFormat(0x9001) + if status := uint32(comCall1(object, 5, uintptr(unsafe.Pointer(&format)))); status != sOK { + t.Fatalf("QueryGetData(FileGroupDescriptor) = %#x, want S_OK", status) + } + var medium storageMedium + if status := uint32(comCall2(object, 3, uintptr(unsafe.Pointer(&format)), uintptr(unsafe.Pointer(&medium)))); status != sOK { + t.Fatalf("GetData(FileGroupDescriptor) = %#x, want S_OK", status) + } + defer releaseStgMedium.Call(uintptr(unsafe.Pointer(&medium))) + if medium.Medium != tymedHGlobal || medium.Handle == 0 { + t.Fatalf("the descriptor medium is %+v, want memory the target owns", medium) + } + memory, _, _ := globalLock.Call(medium.Handle) + if memory == 0 { + t.Fatal("the descriptor block cannot be locked") + } + defer globalUnlock.Call(medium.Handle) + block := unsafe.Slice((*byte)(pointer(memory)), 4+3*int(unsafe.Sizeof(fileDescriptorW{}))) + items := *(*uint32)(unsafe.Pointer(&block[0])) + if items != 3 { + t.Fatalf("the group names %d items, want 3 (notes.txt, docs, docs\\guide.md)", items) + } + if size := unsafe.Sizeof(fileDescriptorW{}); size != 592 { + t.Fatalf("FILEDESCRIPTORW is %d bytes, want 592", size) + } + descriptors := unsafe.Slice((*fileDescriptorW)(unsafe.Pointer(&block[4])), int(items)) + names := make([]string, 0, len(descriptors)) + for _, descriptor := range descriptors { + names = append(names, syscall.UTF16ToString(descriptor.Name[:])) + } + if want := []string{"notes.txt", "docs", `docs\guide.md`}; !slices.Equal(names, want) { + t.Fatalf("the group names %q, want %q", names, want) + } + if got := syscall.UTF16ToString(descriptors[0].Name[:]); got != "notes.txt" { + t.Fatalf("the first name is %q", got) + } + if descriptors[0].Flags&fdFileSize == 0 || descriptors[0].SizeLow != 11 || descriptors[0].Attributes != fileAttributeNormal { + t.Errorf("the file descriptor is %+v, want 11 bytes and a normal attribute", descriptors[0]) + } + if descriptors[1].Attributes != fileAttributeDirectory || descriptors[1].Flags&fdFileSize != 0 { + t.Errorf("the folder descriptor is %+v, want a directory without a size", descriptors[1]) + } +} + +// TestThePromiseStreamProducesTheFileAsTheTargetReads checks the IStream the +// shell copies from: its size, its bytes, its end, and that a folder has none. +func TestThePromiseStreamProducesTheFileAsTheTargetReads(t *testing.T) { + data, object := newPromiseObject(t, promiseFixture(t)) + data.promise.contents = 0x9002 + defer runtime.KeepAlive(data) + format := contentsFormat(0x9002, 0) + var medium storageMedium + if status := uint32(comCall2(object, 3, uintptr(unsafe.Pointer(&format)), uintptr(unsafe.Pointer(&medium)))); status != sOK { + t.Fatalf("GetData(FileContents, 0) = %#x, want S_OK", status) + } + if medium.Medium != tymedIStream || medium.Handle == 0 { + t.Fatalf("the content medium is %+v, want a stream", medium) + } + stream := medium.Handle + if size := unsafe.Sizeof(statStg{}); size != 80 { + t.Fatalf("STATSTG is %d bytes, want 80", size) + } + var stat statStg + if status := uint32(comCall2(stream, 12, uintptr(unsafe.Pointer(&stat)), 0)); status != sOK { + t.Fatalf("Stat = %#x, want S_OK", status) + } + if stat.Type != stgtYStream || stat.Size != 11 { + t.Errorf("Stat reports type %d size %d, want a stream of 11 bytes", stat.Type, stat.Size) + } + buffer := make([]byte, 8) + var read uint32 + if status := uint32(comCall3(stream, 3, uintptr(unsafe.Pointer(&buffer[0])), 8, uintptr(unsafe.Pointer(&read)))); status != sOK || read != 8 { + t.Fatalf("Read(8) = %#x with %d bytes, want S_OK with 8", status, read) + } + if string(buffer) != "hello wo" { + t.Fatalf("the first read is %q", buffer) + } + rest := make([]byte, 8) + if status := uint32(comCall3(stream, 3, uintptr(unsafe.Pointer(&rest[0])), 8, uintptr(unsafe.Pointer(&read)))); status != sFalse || read != 3 { + t.Fatalf("Read at the end = %#x with %d bytes, want S_FALSE with 3", status, read) + } + if !bytes.Equal(rest[:3], []byte("rld")) { + t.Fatalf("the last bytes are %q, want \"rld\"", rest[:3]) + } + if status := uint32(comCall3(stream, 3, uintptr(unsafe.Pointer(&rest[0])), 8, uintptr(unsafe.Pointer(&read)))); status != sFalse || read != 0 { + t.Fatalf("Read past the end = %#x with %d bytes, want S_FALSE with 0", status, read) + } + comCall0(stream, 2) // Release, as the shell does with the medium + if status := uint32(comCall2(object, 3, uintptr(unsafe.Pointer(&format)), uintptr(unsafe.Pointer(&medium)))); status != sOK || medium.Handle == 0 { + t.Fatalf("a second GetData = %#x with %+v, want a fresh stream", status, medium) + } + var second storageMedium = medium + releaseStgMedium.Call(uintptr(unsafe.Pointer(&second))) + // A folder is described, not streamed. + folder := contentsFormat(0x9002, 1) + if status := uint32(comCall2(object, 3, uintptr(unsafe.Pointer(&folder)), uintptr(unsafe.Pointer(&medium)))); status != dvEFormatEtc { + t.Errorf("GetData for a folder = %#x, want DV_E_FORMATETC", status) + } +} + +// TestThePromiseEnumeratorListsBothFormats checks what OLE's standard +// marshaling reads: the descriptor and the contents format, and nothing more. +func TestThePromiseEnumeratorListsBothFormats(t *testing.T) { + data, object := newPromiseObject(t, promiseFixture(t)) + defer runtime.KeepAlive(data) + var enum uintptr + if status := uint32(comCall2(object, 8, dataDirGet, uintptr(unsafe.Pointer(&enum)))); status != sOK || enum == 0 { + t.Fatalf("EnumFormatEtc = %#x with %#x, want an enumerator", status, enum) + } + var offered [2]formatEtc + var fetched uint32 + if status := uint32(comCall3(enum, 3, 2, uintptr(unsafe.Pointer(&offered[0])), uintptr(unsafe.Pointer(&fetched)))); status != sOK || fetched != 2 { + t.Fatalf("Next(2) = %#x with %d formats, want S_OK with 2", status, fetched) + } + if offered[0].Format != 0x9001 || offered[0].Medium != tymedHGlobal { + t.Errorf("the first format is %+v, want the group descriptor", offered[0]) + } + if offered[1].Format != 0x9002 || offered[1].Medium != tymedIStream { + t.Errorf("the second format is %+v, want file contents as a stream", offered[1]) + } + if status := uint32(comCall3(enum, 3, 1, uintptr(unsafe.Pointer(&offered[0])), uintptr(unsafe.Pointer(&fetched)))); status != sFalse || fetched != 0 { + t.Errorf("Next after the end = %#x with %d, want S_FALSE with 0", status, fetched) + } +} + +// TestPromiseNamesCheckTheShellLimit keeps a name the descriptor cannot hold +// from starting a drag that would fail when the shell reads it. +func TestPromiseNamesCheckTheShellLimit(t *testing.T) { + long := strings.Repeat("a", maxDescriptorName) + files := []platform.FilePromise{{Name: long, Open: func() (io.ReadCloser, error) { + return io.NopCloser(strings.NewReader("")), nil + }}} + if _, err := promiseItems(files); err == nil { + t.Fatal("a name longer than the descriptor was accepted") + } +} diff --git a/internal/platform/windows/drag_windows.go b/internal/platform/windows/drag_windows.go index f68b6c9cb..8339fde05 100644 --- a/internal/platform/windows/drag_windows.go +++ b/internal/platform/windows/drag_windows.go @@ -71,19 +71,40 @@ var ( ) // fileDataObject is the IDataObject of a drag of files: a pointer to the method -// table first, as every COM object begins, then the paths it hands out. The -// drag owns it, so the garbage collector keeps it for as long as the shell may -// call it. +// table first, as every COM object begins, then either the paths it hands out or +// the promises that produce them. The drag owns it, so the garbage collector +// keeps it for as long as the shell may call it. type fileDataObject struct { table *[12]uintptr refs int32 paths []string + // promise is the content of a promised drag, nil for a drag of paths. + promise *promiseDrag // enums are the enumerators given away. The shell holds them by a pointer // the garbage collector cannot see, so the object keeps them for as long as // the drag it belongs to lives. Only the drag's own thread appends. enums []*fileFormatEnum } +// formats is what this object offers a target: the drop list of paths, or a +// file group descriptor and its per-file contents. +func (data *fileDataObject) formatCount() int { + if data.promise != nil { + return 2 + } + return 1 +} + +func (data *fileDataObject) formatAt(index int) formatEtc { + if data.promise == nil { + if index == 0 { + return fileFormat() + } + return formatEtc{} + } + return data.promise.formatAt(index) +} + // fileDropSource is the IDropSource of the same drag: what ends it and which // cursors it shows. type fileDropSource struct { @@ -224,16 +245,25 @@ func dataRelease(this uintptr) uintptr { if data.refs > 0 { data.refs-- } + if data.refs == 0 && data.promise != nil { + unpinPromiseDrag(data) + } return uintptr(data.refs) } // dataGetData hands the target a fresh copy of the list: OLE gives the memory to -// the target, and the next question asks for another. +// the target, and the next question asks for another. A promised drag hands over +// its descriptor block, or the stream that produces one file. func dataGetData(this, format, medium uintptr) uintptr { - if !takesFileFormat(*(*formatEtc)(pointer(format))) { + data := dataOf(this) + asked := *(*formatEtc)(pointer(format)) + if data.promise != nil { + return data.promiseGetData(asked, medium) + } + if !takesFileFormat(asked) { return dvEFormatEtc } - handle, err := dropListHandle(dataOf(this).paths) + handle, err := dropListHandle(data.paths) if err != nil { return eFail } @@ -244,7 +274,15 @@ func dataGetData(this, format, medium uintptr) uintptr { func dataGetDataHere(this, format, medium uintptr) uintptr { return eNotImpl } func dataQueryGetData(this, format uintptr) uintptr { - if !takesFileFormat(*(*formatEtc)(pointer(format))) { + data := dataOf(this) + asked := *(*formatEtc)(pointer(format)) + if data.promise != nil { + if data.promise.takes(asked) { + return sOK + } + return dvEFormatEtc + } + if !takesFileFormat(asked) { return dvEFormatEtc } return sOK @@ -341,16 +379,21 @@ func enumRelease(this uintptr) uintptr { func enumNext(this, count, formats, fetched uintptr) uintptr { enum := enumOf(this) + total := 0 + if enum.owner != nil { + total = enum.owner.formatCount() + } + asked := uint32(count) given := uint32(0) - if asked := uint32(count); asked > 0 && enum.at == 0 { - *(*formatEtc)(pointer(formats)) = fileFormat() - enum.at = 1 - given = 1 + for given < asked && int(enum.at) < total { + *(*formatEtc)(unsafe.Add(pointer(formats), int(given)*int(unsafe.Sizeof(formatEtc{})))) = enum.owner.formatAt(int(enum.at)) + enum.at++ + given++ } if fetched != 0 { *(*uint32)(pointer(fetched)) = given } - if given != uint32(count) { + if given != asked { return sFalse } return sOK @@ -361,11 +404,18 @@ func enumSkip(this, count uintptr) uintptr { if uint32(count) == 0 { return sOK } + total := 0 + if enum.owner != nil { + total = enum.owner.formatCount() + } // Skipping past the end moves to the end and reports S_FALSE, as the // enumerator contract asks, when fewer formats remain than were asked for. - left := 1 - enum.at - enum.at = 1 - if uint32(count) > left { + left := total - int(enum.at) + if left < 0 { + left = 0 + } + enum.at = uint32(total) + if uint32(count) > uint32(left) { return sFalse } return sOK @@ -388,25 +438,23 @@ func enumClone(this, out uintptr) uintptr { // StartFileDrag takes files out of the application's active window, as a file // manager does when the user drags a selection to another window: the drag lasts -// until the pointer is released or Escape is pressed, and the effect the target -// took is returned, DragEffectNone when it took nothing. +// until the pointer is released or Escape is pressed. // -// allowed is the mask of effects the application offers; a target that takes one -// of them reports it. It is called on the event-loop thread, from the handler of -// the pointer event that starts the drag, and does not return until the drag has -// ended. The files are read while the drop happens, so they must still exist -// where they were when the user lets go. -func StartFileDrag(paths []string, allowed platform.DragEffect) (platform.DragEffect, error) { +// allowed is the mask of effects the application offers. It is called on the +// event-loop thread, from the handler of the pointer event that starts the drag, +// and does not return until the drag has ended. The files are read while the +// drop happens, so they must still exist where they were when the user lets go. +func StartFileDrag(paths []string, allowed platform.DragEffect) error { state := active.Load() if state == nil || state.window == 0 { - return platform.DragEffectNone, fmt.Errorf("windows: no window to drag files out of") + return fmt.Errorf("windows: no window to drag files out of") } thread, _, _ := getCurrentThread.Call() if uint32(thread) != state.application.thread { - return platform.DragEffectNone, fmt.Errorf("windows: files are dragged out on the event-loop thread that owns the window") + return fmt.Errorf("windows: files are dragged out on the event-loop thread that owns the window") } if len(paths) == 0 { - return platform.DragEffectNone, fmt.Errorf("windows: no files to drag out of the window") + return fmt.Errorf("windows: no files to drag out of the window") } // DoDragDrop needs OLE, which CoInitializeEx does not set up: the drag-and-drop // services answer CO_E_NOTINITIALIZED until OleInitialize has run on the @@ -414,7 +462,7 @@ func StartFileDrag(paths []string, allowed platform.DragEffect) (platform.DragEf // and closeOLE gives it back once. if !state.application.oleReady { if status, _, _ := oleInitialize.Call(0); int32(uint32(status)) < 0 { - return platform.DragEffectNone, hresult(status) + return hresult(status) } state.application.oleReady = true } @@ -444,8 +492,9 @@ func StartFileDrag(paths []string, allowed platform.DragEffect) (platform.DragEf if uint32(status) == dragdropSDrop || uint32(status) == dragdropSCancel { postMessage.Call(state.window, wmDragEnded, 0, 0) } - if err := hresult(status); err != nil { - return platform.DragEffectNone, err - } - return platform.DragEffectOf(allowed, platform.DragEffect(effect)), nil + return hresult(status) } + +// StartFilePromiseDrag takes files out of the application's active window whose +// content the application produces when the target reads it. It lives in +// drag_promise_windows.go with the COM objects that serve it. diff --git a/internal/platform/windows/drag_windows_test.go b/internal/platform/windows/drag_windows_test.go index 469bc8f0a..ef7f503bb 100644 --- a/internal/platform/windows/drag_windows_test.go +++ b/internal/platform/windows/drag_windows_test.go @@ -218,7 +218,7 @@ func TestAFileDragIsRefusedOffTheEventLoopThread(t *testing.T) { if state.application.thread == 0 { t.Fatal("the window's application has no event-loop thread") } - if _, err := StartFileDrag([]string{`C:\Temp\one.txt`}, platform.DragEffectCopy); err == nil { + if err := StartFileDrag([]string{`C:\Temp\one.txt`}, platform.DragEffectCopy); err == nil { t.Fatal("a drag started from another goroutine") } else if !strings.Contains(err.Error(), "event-loop thread") { t.Fatalf("the refusal says %q, want the event-loop thread", err) diff --git a/internal/platform/windows/materials_windows.go b/internal/platform/windows/materials_windows.go index fbf647f40..15ac77f0d 100644 --- a/internal/platform/windows/materials_windows.go +++ b/internal/platform/windows/materials_windows.go @@ -1,6 +1,10 @@ package windows -import "github.com/vivaui/viva/internal/platform" +import ( + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) type backdropState struct { backdropStyle platform.BackdropStyle @@ -22,6 +26,11 @@ func (state *windowState) backdropWindowStyle() uintptr { if state.config.WindowBackdrop != nil && nativeBackdropAPI() != backdropUnavailable { return wsExNoRedirectionBitmap } + // A transparent window is composed by DirectComposition from a premultiplied + // swap chain, which is what lets the clear color's alpha reach the desktop. + if state.config.Transparent { + return wsExNoRedirectionBitmap + } return 0 } @@ -82,3 +91,29 @@ func (renderer *renderer) releaseComposition() { release(object) } } + +var dwmEnableBlurBehind = dwm.NewProc("DwmEnableBlurBehindWindow") + +// dwmBlurBehind is DWM_BLURBEHIND. +type dwmBlurBehind struct { + Flags uint32 + Enable int32 + Region uintptr + TransitionOnMaximized int32 +} + +// applyTransparent lets the swap chain's alpha reach the desktop. Without a +// DWM composition attribute the window is composed against an opaque white +// sheet; an enabled blur-behind with an empty region turns that sheet off and +// blurs nothing. +func (state *windowState) applyTransparent() { + if !state.config.Transparent || !state.renderer.composition || dwmEnableBlurBehind.Find() != nil { + return + } + empty, _, _ := createRectRgn.Call(0, 0, ^uintptr(0), ^uintptr(0)) + blur := dwmBlurBehind{Flags: 1 | 2, Enable: 1, Region: empty} // DWM_BB_ENABLE | DWM_BB_BLURREGION + dwmEnableBlurBehind.Call(state.window, uintptr(unsafe.Pointer(&blur))) + if empty != 0 { + deleteObject.Call(empty) + } +} diff --git a/internal/platform/windows/system_directory_windows_test.go b/internal/platform/windows/system_directory_windows_test.go new file mode 100644 index 000000000..85564d471 --- /dev/null +++ b/internal/platform/windows/system_directory_windows_test.go @@ -0,0 +1,49 @@ +package windows + +import ( + "fmt" + "os" + "testing" + "unsafe" +) + +func TestFileDialogInitialDirectory(t *testing.T) { + directory := t.TempDir() + err := withSTA(func() error { + dialog, err := createFileDialog(&openDialogClass, &openDialogInterface) + if err != nil { + return err + } + defer release(&dialog) + if err := setFileDialogDirectory(dialog, directory); err != nil { + return err + } + var item uintptr + if err := hresult(comCall1(dialog, 13, uintptr(unsafe.Pointer(&item)))); err != nil { + return err + } + defer release(&item) + got, err := shellItemPath(item) + if err != nil { + return err + } + // The temporary directory may be named in its 8.3 short form (RUNNER~1) while + // the shell reports the long one: they are the same folder when the file + // system says so, whatever the spelling. + gotInfo, err := os.Stat(got) + if err != nil { + return err + } + wantInfo, err := os.Stat(directory) + if err != nil { + return err + } + if !os.SameFile(gotInfo, wantInfo) { + return fmt.Errorf("dialog folder = %q; want %q", got, directory) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} diff --git a/internal/platform/windows/system_windows.go b/internal/platform/windows/system_windows.go index ddb7f862f..ea6bb8877 100644 --- a/internal/platform/windows/system_windows.go +++ b/internal/platform/windows/system_windows.go @@ -58,6 +58,8 @@ type OpenFileOptions struct { type OpenDirectoryOptions struct { Title string + // InitialDirectory is the starting folder. Empty uses the platform default. + InitialDirectory string } type SaveFileOptions struct { @@ -205,6 +207,17 @@ func HasClipboardImage() bool { return false } +// activeOwnerWindow returns the HWND of the currently active window, or 0 if none +// or if the HWND is no longer valid. +func activeOwnerWindow() uintptr { + if state := active.Load(); state != nil && state.window != 0 { + if valid, _, _ := isWindow.Call(state.window); valid != 0 { + return state.window + } + } + return 0 +} + // ClipboardImagePNG returns the clipboard's image as PNG bytes: the registered // "PNG" format as it is, otherwise CF_DIBV5 or CF_DIB converted. func ClipboardImagePNG() ([]byte, error) { @@ -226,16 +239,20 @@ func ClipboardImagePNG() ([]byte, error) { return nil, windowsCallError("open clipboard", callErr) } defer closeClipboard.Call() + var readErr error if format := registeredPNGFormat(); format != 0 { if available, _, _ := clipboardFormatAvailable.Call(format); available != 0 { data, err := clipboardBytes(format, platform.MaxClipboardImageBytes+1<<10) - if err != nil { - return nil, err + if err == nil { + data, err = platform.TrimClipboardPNG(data) + } + if err == nil { + err = platform.CheckClipboardPNG(data) } - if data, err = platform.TrimClipboardPNG(data); err != nil { - return nil, err + if err == nil { + return data, nil } - return data, platform.CheckClipboardPNG(data) + readErr = err } } for _, format := range [...]uintptr{clipboardDIBV5, clipboardDIB} { @@ -243,10 +260,16 @@ func ClipboardImagePNG() ([]byte, error) { continue } dib, err := clipboardBytes(format, platform.MaxClipboardRawBytes) - if err != nil { - return nil, err + if err == nil { + var data []byte + if data, err = platform.DIBToPNG(dib); err == nil { + return data, nil + } } - return platform.DIBToPNG(dib) + readErr = err + } + if readErr != nil { + return nil, readErr } return nil, platform.ErrNoClipboardImage } @@ -369,10 +392,7 @@ func setClipboardText(value string, rectangular bool) error { } copy(unsafe.Slice((*uint16)(pointer(memory)), len(encoded)), encoded) globalUnlock.Call(handle) - owner := uintptr(0) - if state := active.Load(); state != nil { - owner = state.window - } + owner := activeOwnerWindow() if opened, _, callErr := openClipboard.Call(owner); opened == 0 { return windowsCallError("open clipboard", callErr) } @@ -412,10 +432,7 @@ func SetClipboardFiles(paths []string) error { } clipboardMu.Lock() defer clipboardMu.Unlock() - owner := uintptr(0) - if state := active.Load(); state != nil { - owner = state.window - } + owner := activeOwnerWindow() if opened, _, callErr := openClipboard.Call(owner); opened == 0 { return windowsCallError("open clipboard", callErr) } @@ -537,6 +554,9 @@ func OpenDirectory(options OpenDirectoryOptions) (string, bool, error) { if err := configureFileDialog(dialog, options.Title, nil, flags); err != nil { return err } + if err := setFileDialogDirectory(dialog, options.InitialDirectory); err != nil { + return err + } status := uint32(comCall1(dialog, 3, dialogOwner())) if status == dialogCanceled { canceled = true @@ -556,6 +576,29 @@ func OpenDirectory(options OpenDirectoryOptions) (string, bool, error) { return path, canceled, err } +func setFileDialogDirectory(dialog uintptr, directory string) error { + if directory == "" { + return nil + } + name, err := syscall.UTF16PtrFromString(directory) + if err != nil { + return err + } + itemInterface := guid{Data1: 0x43826d1e, Data2: 0xe718, Data3: 0x42ee, Data4: [8]byte{0xbc, 0x55, 0xa1, 0xe2, 0x61, 0xc3, 0x7b, 0xfe}} + var item uintptr + status, _, _ := shell.NewProc("SHCreateItemFromParsingName").Call( + uintptr(unsafe.Pointer(name)), 0, uintptr(unsafe.Pointer(&itemInterface)), uintptr(unsafe.Pointer(&item)), + ) + if err := hresult(status); err != nil { + return fmt.Errorf("windows: create initial directory shell item: %w", err) + } + defer release(&item) + if err := hresult(comCall1(dialog, 12, item)); err != nil { + return fmt.Errorf("windows: set initial directory: %w", err) + } + return nil +} + func SaveFile(options SaveFileOptions) (string, bool, error) { path, _, canceled, err := saveFile(options, "", false) return path, canceled, err diff --git a/internal/platform/windows/text_menu_windows.go b/internal/platform/windows/text_menu_windows.go new file mode 100644 index 000000000..37bbe78e3 --- /dev/null +++ b/internal/platform/windows/text_menu_windows.go @@ -0,0 +1,73 @@ +package windows + +import ( + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// textMenuKeys is the chord shown at the end of a text menu's row, as the +// system's own edit menus show it. +func textMenuKeys(command platform.TextMenuCommand) string { + switch command { + case platform.TextMenuCut: + return "\tCtrl+X" + case platform.TextMenuCopy: + return "\tCtrl+C" + case platform.TextMenuPaste: + return "\tCtrl+V" + case platform.TextMenuSelectAll: + return "\tCtrl+A" + } + return "" +} + +// popTextMenu shows the text menu at the screen point (x, y) in device pixels +// and returns the command the user chose, or TextMenuNone. The window that +// receives its messages must be the foreground window while the menu is up, or a +// click elsewhere would not close it. +func popTextMenu(window uintptr, items []platform.TextMenuItem, x, y int32) platform.TextMenuCommand { + if len(items) == 0 { + return platform.TextMenuNone + } + allowDarkMenus() + menu, _, _ := createPopupMenu.Call() + if menu == 0 { + return platform.TextMenuNone + } + defer destroyMenu.Call(menu) + for _, item := range items { + if item.Command == platform.TextMenuNone { + appendMenu.Call(menu, mfSeparator, 0, 0) + continue + } + flags := uintptr(mfString) + if item.Disabled { + flags |= mfGrayed + } + appendMenu.Call(menu, flags, uintptr(item.Command), uintptr(unsafe.Pointer(menuTitle(item.Title+textMenuKeys(item.Command))))) + } + setForegroundWindow.Call(window) + chosen, _, _ := trackPopupMenuEx.Call(menu, tpmRightButton|tpmNoNotify|tpmReturnCmd, uintptr(x), uintptr(y), window, 0) + // The documented way to end a menu that belongs to a window. + postMessage.Call(window, wmNull, 0, 0) + return platform.TextMenuCommand(chosen) +} + +// showTextMenu opens the runtime's text menu for the press that has just been +// released, at the pointer, as the system's own edit controls do, and runs the +// command chosen. The pointer capture a press holds is let go first: a menu that +// tracks the pointer cannot while another window owns it. +func (state *windowState) showTextMenu(window uintptr, at point) { + request, ok := state.config.TakeTextMenu() + if !ok || request.Perform == nil { + return + } + releaseCapture.Call() + chosen := popTextMenu(window, request.Items, at.X, at.Y) + if chosen == platform.TextMenuNone { + return + } + frame, err := request.Perform(chosen) + state.frame(frame, err) +} diff --git a/internal/platform/windows/web_dev_tools_windows.go b/internal/platform/windows/web_dev_tools_windows.go new file mode 100644 index 000000000..d040bf528 --- /dev/null +++ b/internal/platform/windows/web_dev_tools_windows.go @@ -0,0 +1,19 @@ +package windows + +import ( + "fmt" + + "github.com/vivaui/viva/internal/platform" +) + +// ShowDevTools opens the WebView2 DevTools window for the page, once the page exists. WebView2 +// leaves AreDevToolsEnabled on unless an application turns it off, which Viva does not. +func (page *windowsWeb) ShowDevTools() error { + if page.closed { + return fmt.Errorf("windows: the web view with id %d is closed", page.config.ID) + } + page.do(func() { comCall0(page.view, viewOpenDevToolsWindow) }) + return nil +} + +var _ platform.WebDevTools = (*windowsWeb)(nil) diff --git a/internal/platform/windows/web_windows.go b/internal/platform/windows/web_windows.go index c81a22985..41b4202f2 100644 --- a/internal/platform/windows/web_windows.go +++ b/internal/platform/windows/web_windows.go @@ -316,6 +316,10 @@ func (page *windowsWeb) fail(err error) { // attach wires the page's events and what it is given, and runs what was asked of it meanwhile. func (page *windowsWeb) attach(environment uintptr) { view := page.view + if err := page.applyUserAgentSuffix(); err != nil { + page.fail(err) + return + } var token int64 comCall2(view, viewAddMessageReceived, newHandler(func(_, args uintptr) uintptr { var text uintptr @@ -1020,3 +1024,32 @@ func (w *webHost) closeAll() { var _ = syscall.Errno(0) var _ render.Rectangle + +// applyUserAgentSuffix runs before navigation, and changes only this WebView's settings. +func (page *windowsWeb) applyUserAgentSuffix() error { + if page.config.UserAgentSuffix == "" { + return nil + } + var settings uintptr + if status := comCall1(page.view, viewGetSettings, uintptr(unsafe.Pointer(&settings))); int32(uint32(status)) < 0 || settings == 0 { + return fmt.Errorf("windows: get WebView2 settings: HRESULT %#x", uint32(status)) + } + defer comCall0(settings, 2) + var extended uintptr + if status := comCall2(settings, 0, uintptr(unsafe.Pointer(&iidSettings2)), uintptr(unsafe.Pointer(&extended))); int32(uint32(status)) < 0 || extended == 0 { + return fmt.Errorf("%w: a user agent suffix needs ICoreWebView2Settings2", platform.ErrWebViewUnsupported) + } + defer comCall0(extended, 2) + var address uintptr + if status := comCall1(extended, settingsGetUserAgent, uintptr(unsafe.Pointer(&address))); int32(uint32(status)) < 0 || address == 0 { + if address != 0 { + coTaskMemFree.Call(address) + } + return fmt.Errorf("windows: read WebView2 user agent: HRESULT %#x", uint32(status)) + } + value := wideString(address) + " " + page.config.UserAgentSuffix + if status := comCall1(extended, settingsPutUserAgent, uintptr(unsafe.Pointer(wide(value)))); int32(uint32(status)) < 0 { + return fmt.Errorf("windows: set WebView2 user agent: HRESULT %#x", uint32(status)) + } + return nil +} diff --git a/internal/platform/windows/webview2_windows.go b/internal/platform/windows/webview2_windows.go index 88e7ac8e2..b2a9a5ad0 100644 --- a/internal/platform/windows/webview2_windows.go +++ b/internal/platform/windows/webview2_windows.go @@ -393,6 +393,9 @@ const ( controllerMoveFocus = 12 controllerClose = 24 controllerGetWebView = 25 + viewGetSettings = 3 + settingsGetUserAgent = 21 + settingsPutUserAgent = 22 viewNavigate = 5 viewNavigateToString = 6 viewAddNavStarting = 7 @@ -411,11 +414,13 @@ const ( // get_DocumentTitle 48 (add_DocumentTitleChanged is 46, remove_DocumentTitleChanged 47). The // load's end is NavigationCompleted 15 on that same interface, and a failed one is told apart // through its event args below. - viewGetCanGoBack = 38 - viewGetCanGoForward = 39 - viewGetDocumentTitle = 48 - viewAddWebResourceReq = 55 - viewAddResourceFilter = 57 + viewGetCanGoBack = 38 + viewGetCanGoForward = 39 + viewGetDocumentTitle = 48 + // OpenDevToolsWindow follows RemoveHostObjectFromScript 50. + viewOpenDevToolsWindow = 51 + viewAddWebResourceReq = 55 + viewAddResourceFilter = 57 // ICoreWebView2_4 adds DownloadStarting after every ICoreWebView2_3 method. viewAddDownloadStarting = 75 messageTryGetString = 5 @@ -460,6 +465,9 @@ const ( // runtime older than that does not answer for it. var iidEnvironment10 = guid{0xee0eb9df, 0x6f12, 0x46ce, [8]byte{0xb5, 0x3f, 0x3f, 0x47, 0xb9, 0xc9, 0x28, 0xe0}} +// ICoreWebView2Settings2 from WebView2 SDK WebView2.h; UserAgent follows base settings. +var iidSettings2 = guid{0xee9a0f68, 0xf46c, 0x4e32, [8]byte{0xac, 0x23, 0xef, 0x8c, 0xac, 0x22, 0x4d, 0x2a}} + // iidProcessFailedArgs2 is ICoreWebView2ProcessFailedEventArgs2, the arguments of ProcessFailed that // say why the process went (WebView2 SDK 1.0.818.41, Runtime 94 and newer, which is older than the // runtime 101 that an ephemeral page already needs); a runtime without it gives the kind alone. diff --git a/internal/platform/windows/window_minimized_windows_test.go b/internal/platform/windows/window_minimized_windows_test.go index c93bde4c3..6d4f5bb21 100644 --- a/internal/platform/windows/window_minimized_windows_test.go +++ b/internal/platform/windows/window_minimized_windows_test.go @@ -1,17 +1,67 @@ package windows import ( + "fmt" "runtime" "testing" "time" "unsafe" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" ) // swMinimize is SW_MINIMIZE: minimize the window and activate the next one. const swMinimize = 6 +// A window being minimized must not report the small iconic rectangle as its +// content frame. WM_MOVE can run before WM_SIZE sets state.minimized, so a +// frame handler that trusts the flag alone records the off-screen sentinel +// position as where the window is; the window manager already knows it is +// iconic. +func TestMinimizeDoesNotReportTheIconicFrame(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + var frames []gfx.Rect + minimized := false + err := RunApplication(func(application platform.Application) error { + opened, err := application.OpenWindow(platform.Config{ + Title: "Viva minimized frame test", Width: 640, Height: 400, + ClearColor: platform.Color{Alpha: 1}, + OnFrameChange: func(frame gfx.Rect) { + frames = append(frames, frame) + }, + OnMinimize: func(value bool) { + if value { + minimized = true + } + }, + }) + if err != nil { + return err + } + defer opened.Close() + state := opened.(*nativeWindow).state + showWindow.Call(state.window, swMinimize) + deadline := time.Now().Add(2 * time.Second) + for !minimized { + if time.Now().After(deadline) { + return fmt.Errorf("window did not report minimization") + } + time.Sleep(10 * time.Millisecond) + } + for _, frame := range frames { + if frame.X <= -30000 || frame.Y <= -30000 || frame.Width < 1 || frame.Height < 1 { + return fmt.Errorf("reported the iconic frame %+v as the window's content area", frame) + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} + // A paint caused by minimizing must not present at the minimized client size. A // window with a custom frame reports the small minimized window itself (160x28), // not an empty client area, so presenting would resize the swap chain to the diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index fd3868d32..dc5d97a8d 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -214,7 +214,7 @@ type nativeWindow struct { // reportFrame tells the application where its content area is now, in logical // pixels of the window's display. It reports only changes. func (state *windowState) reportFrame() { - if !state.ready || state.config.OnFrameChange == nil || state.window == 0 || state.minimized || state.zoomed() || state.fullscreen.Load() || state.fullscreenChanging { + if !state.ready || state.config.OnFrameChange == nil || state.window == 0 || state.iconic() || state.zoomed() || state.fullscreen.Load() || state.fullscreenChanging { return } var client rect @@ -425,6 +425,10 @@ func (application *windowsApplication) OpenWindow(config platform.Config) (platf return nil, err } state.installFrame() + state.applyTransparent() + if config.Transparent && config.OnTransparentChange != nil { + config.OnTransparentChange(state.renderer.composition) + } if config.SetFrameInterval != nil { // Present(1) in WM_PAINT blocks until the display takes the frame, so // the display paces the window; the runtime needs no interval of its own. @@ -956,6 +960,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { } else if handled { state.handleTextEvent(textEvent) } + if kind == wmRightUp && state.config.TakeTextMenu != nil { + state.showTextMenu(window, screen) + } if (kind == wmLeftUp || kind == wmRightUp || kind == wmMiddleUp || kind == wmXButtonUp) && first&mkAnyButton == 0 { // The capture is held until the last button is up, so a drag that // started with one button keeps going when another is released. @@ -1376,9 +1383,7 @@ func (state *windowState) destroyed(window uintptr) { } defer func() { release() - if state.application.windows == 0 { - active.CompareAndSwap(state, nil) - } + active.CompareAndSwap(state, nil) }() state.stopCaretTimer() state.closeBackdropPower() diff --git a/style/moved_types.go b/style/moved_types.go index 51d3c916e..c95a17e16 100644 --- a/style/moved_types.go +++ b/style/moved_types.go @@ -69,9 +69,22 @@ const ( // TableColumn is a statically typed column declaration. Width is measured in // logical pixels; the final non-positive width consumes the remaining space. +// Title, Sortable, Filterable and Filtered are read by ui.Table, which draws the heading and the sort +// hit of each column from them; components.Table takes its headings separately and +// ignores both. type TableColumn struct { + // Title is the column's heading; a ui.Table none of whose columns has a title + // draws no header row. + Title string Width float32 Alignment TableAlignment + // Sortable lets a click on the heading sort by the column: ui.Table gives it a + // hit in TableSpec.Header and shows the arrow of the column TableState sorts by. + Sortable bool + // Filterable puts a filter button at the end of the heading: ui.Table gives it a + // hit, and Box.FilterClicked reports a press on it, for the application to open + // the choice of what to show. Filtered paints the button as one that is on. + Filterable, Filtered bool // Inset reserves leading content space inside a left-aligned cell, for // example an application-painted file icon. Inset float32 diff --git a/style/style.go b/style/style.go index a26a68e37..1f1acd926 100644 --- a/style/style.go +++ b/style/style.go @@ -10,6 +10,22 @@ // here. package style +// Status is the outcome a control reports through color: the one vocabulary an +// alert, a tag and a field share, so a state is written the same way wherever it +// shows. +type Status uint8 + +const ( + // StatusDefault is no outcome: the neutral look. It is the zero value. + StatusDefault Status = iota + // StatusSuccess is something that went well. + StatusSuccess + // StatusWarning is something that needs attention but has not failed. + StatusWarning + // StatusDanger is something that failed or is wrong. + StatusDanger +) + // Variant selects a control's look among the design system's variants. type Variant uint8 diff --git a/style/tabs.go b/style/tabs.go index e596f4eae..831beed91 100644 --- a/style/tabs.go +++ b/style/tabs.go @@ -25,5 +25,5 @@ func TabsGeometry(m gfx.Metrics) (listHeight, listPadding, triggerHeight, trigge // TabsListRadius is the corner radius of the strip behind its triggers, and // TabsTriggerRadius the radius of one trigger's surface. -func TabsListRadius(m gfx.Metrics) float32 { return m.RadiusControl + 2 } +func TabsListRadius(m gfx.Metrics) float32 { return gfx.RadiusOutset(m.RadiusControl, 2) } func TabsTriggerRadius(m gfx.Metrics) float32 { return m.RadiusControl } diff --git a/style/tree.go b/style/tree.go index 5218e5db2..eb9a1db0d 100644 --- a/style/tree.go +++ b/style/tree.go @@ -17,4 +17,8 @@ type TreeItem struct { // Dragging marks the row being dragged: it keeps its chosen fill but gives // up its focus ring, which otherwise reads as the drop target. Dragging bool + // Loading shows a spinner in place of a branch's chevron: its children are + // being fetched. Phase is the spinner's frame, 0 to 7. + Loading bool + Phase uint8 } diff --git a/text/multi_replace.go b/text/multi_replace.go index 3606e010e..31f240a58 100644 --- a/text/multi_replace.go +++ b/text/multi_replace.go @@ -90,28 +90,18 @@ func (editor *Editor) ReplaceRangesWith(edits []Replacement, options ReplaceRang contexts = make([]lineContext, 0, len(edits)) } position := start - runePosition, bytePosition := 0, 0 - linePosition, lineShift := 0, 0 + lineShift := 0 labels := editor.lfLabelState() var labelSpans []lfLabelSpan for _, edit := range edits { - for runePosition < edit.Range.Start { - if contexts != nil && editor.runes.At(runePosition) == '\n' { - linePosition++ - } - bytePosition += runeBytes(editor.runes.At(runePosition)) - runePosition++ - } - primitive := Edit{Start: bytePosition} - sourceLine := linePosition - for runePosition < edit.Range.End { - if contexts != nil && editor.runes.At(runePosition) == '\n' { - linePosition++ - } - width := runeBytes(editor.runes.At(runePosition)) - primitive.Removed += width - bytePosition += width - runePosition++ + // Where the edit is in the original text, in bytes and lines, from the store's + // index rather than a walk from the start: a batch near the end of a long text + // costs its own runes. + from := editor.runes.ByteOffset(edit.Range.Start) + primitive := Edit{Start: from, Removed: editor.runes.ByteOffset(edit.Range.End) - from} + sourceLine := 0 + if contexts != nil { + sourceLine = editor.runes.Line(edit.Range.Start) } inserted := []rune(edit.Text) for _, character := range inserted { diff --git a/text/multi_replace_bench_test.go b/text/multi_replace_bench_test.go new file mode 100644 index 000000000..4f5fab396 --- /dev/null +++ b/text/multi_replace_bench_test.go @@ -0,0 +1,21 @@ +package text + +import ( + "strings" + "testing" +) + +// BenchmarkReplaceRangesAtTheEndOfALongText replaces a range at the end of a text of +// 20000 lines, as a log bound to a field grows: the cost is the edit's, not the text's. +func BenchmarkReplaceRangesAtTheEndOfALongText(b *testing.B) { + editor := NewEditor(strings.Repeat("line of a log with 中文 in it\n", 20000)) + editor.ClearHistory() + end := editor.RuneCount() + edits := [2][1]Replacement{{{Range: Range{Start: end, End: end}, Text: "appended\n"}}, {{Range: Range{Start: end, End: end + 9}}}} + b.ReportAllocs() + for i := 0; b.Loop(); i++ { + if err := editor.ReplaceRanges(edits[i%2][:]); err != nil { + b.Fatal(err) + } + } +} diff --git a/tools/dmg/build.go b/tools/dmg/build.go index 1ac30494b..0565d3f9e 100644 --- a/tools/dmg/build.go +++ b/tools/dmg/build.go @@ -73,12 +73,6 @@ func Build(options Options) error { if err := settle(writable, options, app); err != nil { return err } - // Detaching returns before the disk image service lets go of the file; - // converting it while the service still holds it fails with "Resource - // temporarily unavailable", which hosted runners show for over a minute. - if err := released(writable); err != nil { - return err - } // Write beside the target first so a failure leaves the previous image alone. temporary := strings.TrimSuffix(options.Image, ".dmg") + ".viva-tmp.dmg" @@ -114,8 +108,18 @@ func settle(writable string, options Options, app string) (err error) { return err } defer func() { - if detachErr := detach(device); err == nil { - err = detachErr + cleanupErr := detach(device) + // A busy disk can outlive the short detach retries, and even a successful + // detach can leave the backing file held. Wait for this image in both cases. + if cleanupErr == nil || transient("detach", cleanupErr.Error()) { + if waitErr := released(writable); waitErr != nil { + cleanupErr = errors.Join(cleanupErr, waitErr) + } else { + cleanupErr = nil + } + } + if err == nil { + err = cleanupErr } }() @@ -275,16 +279,18 @@ func released(image string) error { if err != nil { return err } - if !strings.Contains(out, ""+path+"") && !strings.Contains(out, ""+image+"") { + held, device, err := imageRecord(out, path, image) + if err != nil { + return err + } + if !held { return nil } attached = out - if redetachAt[attempt] { + if redetachAt[attempt] && device != "" { // The service can keep an image attached, and hold the file, after a detach // that reported success: take its disk away again. - if device := diskOf(out, path, image); device != "" { - _ = hdiutil("detach", "-force", device) - } + _ = hdiutil("detach", "-force", device) } pause(releaseWait) } @@ -295,22 +301,54 @@ func released(image string) error { // detached again. var redetachAt = map[int]bool{5: true, 20: true, 50: true, 90: true} -var diskNode = regexp.MustCompile(`(/dev/disk\d+)`) +var diskNode = regexp.MustCompile(`^/dev/disk\d+$`) -// diskOf is the disk of the attached image at one of the paths, from hdiutil info's -// list: the first disk its entry names, since an entry lists its image's path before -// its system entities. -func diskOf(info string, paths ...string) string { - for _, path := range paths { - at := strings.Index(info, ""+path+"") - if at < 0 { +type imageInfoValue struct { + XMLName xml.Name + Text string `xml:",chardata"` + Values []imageInfoValue `xml:",any"` +} + +func (value imageInfoValue) field(key string) imageInfoValue { + for i := 0; i+1 < len(value.Values); i += 2 { + if entry := value.Values[i]; entry.XMLName.Local == "key" && entry.Text == key { + return value.Values[i+1] + } + } + return imageInfoValue{} +} + +// imageRecord only takes an ejectable device from the matching image's own +// system entities. A held entry can temporarily have no device at all. +func imageRecord(info string, canonical, original string) (bool, string, error) { + var list struct { + XMLName xml.Name `xml:"plist"` + Root imageInfoValue `xml:"dict"` + } + if err := xml.Unmarshal([]byte(info), &list); err != nil { + return false, "", fmt.Errorf("dmg: reading attached images: %w", err) + } + images := list.Root.field("images") + if images.XMLName.Local != "array" { + return false, "", errors.New("dmg: disk image information has no images array") + } + for _, image := range images.Values { + path := image.field("image-path") + if path.XMLName.Local != "string" || (path.Text != canonical && path.Text != original) { continue } - if match := diskNode.FindStringSubmatch(info[at:]); match != nil { - return match[1] + entities := image.field("system-entities") + if entities.XMLName.Local == "array" { + for _, entity := range entities.Values { + entry := entity.field("dev-entry") + if device := wholeDisk(entry.Text); entry.XMLName.Local == "string" && diskNode.MatchString(device) { + return true, device, nil + } + } } + return true, "", nil } - return "" + return false, "", nil } func hdiutil(arguments ...string) error { diff --git a/tools/dmg/busy_test.go b/tools/dmg/busy_test.go index c6107b129..5ac043de3 100644 --- a/tools/dmg/busy_test.go +++ b/tools/dmg/busy_test.go @@ -1,8 +1,13 @@ package dmg import ( + "encoding/xml" "errors" + "os" "os/exec" + "path/filepath" + "runtime" + "slices" "strings" "testing" "time" @@ -117,8 +122,8 @@ func TestHdiutilReportsOtherFailuresAtOnce(t *testing.T) { // does. func TestReleasedDetachesTheDiskAgainWhileTheImageStaysAttached(t *testing.T) { const image = "/tmp/viva-release-test/writable.dmg" - held := reply{"image-path" + image + "dev-entry/dev/disk7", nil} - free := reply{"", nil} + held := reply{imageInfoFixture(imageEntryFixture(image, "/dev/disk7")), nil} + free := reply{imageInfoFixture(""), nil} replies := []reply{} for i := 0; i < 7; i++ { // attempts 0 to 5 find it held, and the force detach of attempt 5 is one more run replies = append(replies, held) @@ -141,8 +146,8 @@ func TestReleasedDetachesTheDiskAgainWhileTheImageStaysAttached(t *testing.T) { func TestReleasedWaitsUntilTheImageIsNoLongerAttached(t *testing.T) { const image = "/tmp/viva-release-test/writable.dmg" - held := reply{"image-path" + image + "", nil} - free := reply{"", nil} + held := reply{imageInfoFixture(imageEntryFixture(image, "")), nil} + free := reply{imageInfoFixture(""), nil} runs, waits := stub(t, []reply{held, held, free}) if err := released(image); err != nil { t.Fatal(err) @@ -156,6 +161,120 @@ func TestReleasedWaitsUntilTheImageIsNoLongerAttached(t *testing.T) { } } +func imageInfoFixture(entries string) string { + return `images` + entries + `` +} + +func imageEntryFixture(path, device string) string { + var escaped strings.Builder + _ = xml.EscapeText(&escaped, []byte(path)) + entry := `image-path` + escaped.String() + `` + if device != "" { + entry += `system-entitiesdev-entry` + device + `` + } + return entry + `` +} + +func TestReleasedNeverForcesTheNextImageWhenTheOwnedEntryHasNoDisk(t *testing.T) { + const owned = "/tmp/owned.dmg" + other := imageEntryFixture("/tmp/other.dmg", "/dev/disk11") + held := reply{imageInfoFixture(imageEntryFixture(owned, "") + other), nil} + replies := slices.Repeat([]reply{held}, 7) + replies = append(replies, reply{imageInfoFixture(other), nil}) + runs, _ := stub(t, replies) + if err := released(owned); err != nil { + t.Fatal(err) + } + for _, arguments := range *runs { + if arguments[0] != "info" { + t.Fatalf("unexpected command while the owned entry has no disk: %v", arguments) + } + } +} + +func TestImageRecordDecodesTheOwnedPathAndUsesItsPartition(t *testing.T) { + const owned = "/tmp/one & two.dmg" + info := imageInfoFixture(imageEntryFixture(owned, "/dev/disk7s1") + imageEntryFixture("/tmp/other.dmg", "/dev/disk11")) + held, device, err := imageRecord(info, owned, owned) + if !held || device != "/dev/disk7" || err != nil { + t.Fatalf("held=%v, device=%q, error=%v", held, device, err) + } + if _, _, err := imageRecord(``, owned, owned); err == nil { + t.Fatal("missing image information was treated as released") + } +} + +func TestBuildWaitsForOwnedImageAfterBusyDetach(t *testing.T) { + if runtime.GOOS != "darwin" { + t.Skip("the mocked build uses Darwin file metadata") + } + dir := t.TempDir() + bundle := filepath.Join(dir, "Sample.app") + if err := os.Mkdir(bundle, 0o755); err != nil { + t.Fatal(err) + } + layout, err := Resolve(Config{}) + if err != nil { + t.Fatal(err) + } + stub(t, nil) // Restore the command and disable real delays. + var staging, writable string + forced, converted := 0, false + runHdiutil = func(arguments ...string) ([]byte, error) { + switch arguments[0] { + case "create": + staging = arguments[slices.Index(arguments, "-srcfolder")+1] + writable = arguments[len(arguments)-1] + return nil, os.WriteFile(writable, nil, 0o644) + case "attach": + mount := arguments[slices.Index(arguments, "-mountpoint")+1] + for _, name := range []string{backgroundFile, stagedBundle} { + if err := os.Rename(filepath.Join(staging, name), filepath.Join(mount, name)); err != nil { + t.Fatal(err) + } + } + mount, err := filepath.EvalSymlinks(mount) + if err != nil { + t.Fatal(err) + } + return []byte(`system-entitiesdev-entry/dev/disk7s1mount-point` + mount + ``), nil + case "detach": + if arguments[len(arguments)-1] != "/dev/disk7" { + t.Fatalf("attempted to detach an unrelated disk: %v", arguments) + } + if slices.Contains(arguments, "-force") { + forced++ + if forced == 2 { + return nil, nil + } + } + return []byte(`hdiutil: couldn't eject "disk7" - Resource busy`), errExit + case "info": + entries := imageEntryFixture("/tmp/other.dmg", "/dev/disk11") + if forced < 2 { + entries += imageEntryFixture(writable, "/dev/disk7") + } + return []byte(imageInfoFixture(entries)), nil + case "convert": + if forced != 2 { + t.Fatal("conversion began while the image was still attached") + } + converted = true + return nil, os.WriteFile(arguments[len(arguments)-1], []byte("converted"), 0o644) + default: + t.Fatalf("unexpected hdiutil call: %v", arguments) + return nil, errExit + } + } + image := filepath.Join(dir, "sample.dmg") + if err := Build(Options{Bundle: bundle, Volume: "Sample", Image: image, Layout: layout}); err != nil { + t.Fatal(err) + } + if got, err := os.ReadFile(image); err != nil || !converted || string(got) != "converted" { + t.Fatalf("final image = %q, converted=%v, err=%v", got, converted, err) + } +} + // A volume's node is a slice of a disk, and detaching the slice leaves the image // attached: detach is given the disk. func TestDetachTargetsTheWholeDisk(t *testing.T) { diff --git a/tools/dmg/dmg_test.go b/tools/dmg/dmg_test.go index 610acb76a..f34b5c38f 100644 --- a/tools/dmg/dmg_test.go +++ b/tools/dmg/dmg_test.go @@ -112,9 +112,7 @@ func TestPropertyListsAreReadByTheSystem(t *testing.T) { } func TestBuiltImageHoldsTheLayoutTheFinderReads(t *testing.T) { - if runtime.GOOS != "darwin" { - t.Skip("disk images are made on macOS") - } + requireDiskImages(t) bundle := filepath.Join(t.TempDir(), "Sample.app") if err := os.MkdirAll(filepath.Join(bundle, "Contents"), 0o755); err != nil { t.Fatal(err) @@ -262,3 +260,17 @@ func TestNoArrowIsDrawnWhereTheIconsLeaveNoRoom(t *testing.T) { t.Fatal("an arrow was drawn between icons with no room for it") } } + +// requireDiskImages skips a test that makes real disk images with hdiutil unless +// VIVA_DISK_IMAGE_TESTS is set. The disk image service of a shared macOS machine fails +// now and then whatever the code does, so these run where a change can affect how an +// image is made (the disk-image CI job), not on every change. +func requireDiskImages(t *testing.T) { + t.Helper() + if runtime.GOOS != "darwin" { + t.Skip("disk images are made on macOS") + } + if os.Getenv("VIVA_DISK_IMAGE_TESTS") == "" { + t.Skip("makes real disk images with hdiutil; set VIVA_DISK_IMAGE_TESTS=1 to run") + } +} diff --git a/tools/docs/api.go b/tools/docs/api.go index b5fba276a..2c615c3aa 100644 --- a/tools/docs/api.go +++ b/tools/docs/api.go @@ -10,17 +10,50 @@ import ( "go/parser" "go/printer" "go/token" + "os" "path" "path/filepath" "sort" "strings" ) -// The packages whose exported API the website documents, in display order. Each -// is documented as built for macOS on Apple silicon, so the output does not -// depend on the machine that runs the generator. +// The core packages whose exported API the website documents, in display order. +// Optional ui/ packages are appended by apiPackagePaths. Each is +// documented as built for macOS on Apple silicon, so the output does not depend +// on the machine that runs the generator. var apiPackages = []string{"app", "ui", "gfx", "components", "text", "headless", "keymap", "inspector"} +// apiPackagePaths lists the directories the API reference documents: the core +// packages, then every optional ui/ directory that has Go source. +func apiPackagePaths(root string) ([]string, error) { + paths := append([]string{}, apiPackages...) + entries, err := os.ReadDir(filepath.Join(root, "ui")) + if err != nil { + return nil, fmt.Errorf("api: optional packages: %w", err) + } + for _, entry := range entries { + if !entry.IsDir() { + continue + } + files, err := os.ReadDir(filepath.Join(root, "ui", entry.Name())) + if err != nil { + return nil, fmt.Errorf("api: ui/%s: %w", entry.Name(), err) + } + hasSource := false + for _, file := range files { + name := file.Name() + if !file.IsDir() && strings.HasSuffix(name, ".go") && !strings.HasSuffix(name, "_test.go") { + hasSource = true + break + } + } + if hasSource { + paths = append(paths, "ui/"+entry.Name()) + } + } + return paths, nil +} + // APIData is the generated API reference: every exported identifier of the // public packages, with its declaration and doc comment. type APIData struct { @@ -48,11 +81,19 @@ type APIValue struct { // APIFunc is a function or a method. type APIFunc struct { - Name string `json:"name"` - Receiver string `json:"receiver,omitempty"` - Decl string `json:"decl"` - Synopsis string `json:"synopsis"` - Doc []DocBlock `json:"doc"` + Name string `json:"name"` + Receiver string `json:"receiver,omitempty"` + Decl string `json:"decl"` + Signature string `json:"signature,omitempty"` + Synopsis string `json:"synopsis"` + Doc []DocBlock `json:"doc"` +} + +// APIField is one exported field of a documented struct type. +type APIField struct { + Name string `json:"name"` + Type string `json:"type"` + Doc []DocBlock `json:"doc"` } // APIType is a type with the functions that return it and its methods. @@ -61,6 +102,7 @@ type APIType struct { Decl string `json:"decl"` Synopsis string `json:"synopsis"` Doc []DocBlock `json:"doc"` + Fields []APIField `json:"fields,omitempty"` Constants []APIValue `json:"constants"` Variables []APIValue `json:"variables"` Constructors []APIFunc `json:"constructors"` @@ -90,123 +132,168 @@ type DocInline struct { // anchor that documents the symbol. type symbolIndex map[string]string -func loadAPI(root string) (APIData, error) { +type loadedPackage struct { + name, importPath string + pkg *doc.Package + comments []*ast.CommentGroup + fset *token.FileSet +} + +// loadDocPackage parses one package's exported declarations the way the API +// reference documents them: as built for macOS on Apple silicon, so the result +// does not depend on the machine that runs the generator. +func loadDocPackage(root, path string) (loadedPackage, error) { context := build.Default context.GOOS, context.GOARCH, context.CgoEnabled = "darwin", "arm64", true context.Dir = root - - type loaded struct { - name, importPath string - pkg *doc.Package - comments []*ast.CommentGroup - fset *token.FileSet + directory := filepath.Join(root, path) + info, err := context.ImportDir(directory, 0) + if err != nil { + return loadedPackage{}, fmt.Errorf("api: %s: %w", path, err) } - var packages []loaded - index := symbolIndex{} - for _, name := range apiPackages { - directory := filepath.Join(root, name) - info, err := context.ImportDir(directory, 0) + fset := token.NewFileSet() + files := map[string]*ast.File{} + var comments []*ast.CommentGroup + for _, file := range append(append([]string{}, info.GoFiles...), info.CgoFiles...) { + parsed, err := parser.ParseFile(fset, filepath.Join(directory, file), nil, parser.ParseComments) if err != nil { - return APIData{}, fmt.Errorf("api: %s: %w", name, err) - } - fset := token.NewFileSet() - files := map[string]*ast.File{} - var comments []*ast.CommentGroup - for _, file := range append(append([]string{}, info.GoFiles...), info.CgoFiles...) { - parsed, err := parser.ParseFile(fset, filepath.Join(directory, file), nil, parser.ParseComments) - if err != nil { - return APIData{}, fmt.Errorf("api: %s: %w", file, err) - } - files[file] = parsed - comments = append(comments, parsed.Comments...) + return loadedPackage{}, fmt.Errorf("api: %s: %w", file, err) } - var ordered []*ast.File - keys := make([]string, 0, len(files)) - for key := range files { - keys = append(keys, key) - } - sort.Strings(keys) - for _, key := range keys { - ordered = append(ordered, files[key]) - } - importPath := "github.com/vivaui/viva/" + name - pkg, err := doc.NewFromFiles(fset, ordered, importPath) + files[file] = parsed + comments = append(comments, parsed.Comments...) + } + var ordered []*ast.File + keys := make([]string, 0, len(files)) + for key := range files { + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + ordered = append(ordered, files[key]) + } + importPath := "github.com/vivaui/viva/" + path + pkg, err := doc.NewFromFiles(fset, ordered, importPath) + if err != nil { + return loadedPackage{}, fmt.Errorf("api: %s: %w", path, err) + } + return loadedPackage{pkg.Name, importPath, pkg, comments, fset}, nil +} + +func loadAPI(root string) (APIData, error) { + paths, err := apiPackagePaths(root) + if err != nil { + return APIData{}, err + } + var packages []loadedPackage + index := symbolIndex{} + documented := map[string]string{} + for _, path := range paths { + entry, err := loadDocPackage(root, path) if err != nil { - return APIData{}, fmt.Errorf("api: %s: %w", name, err) + return APIData{}, err } - packages = append(packages, loaded{name, importPath, pkg, comments, fset}) - indexPackage(index, name, pkg) + packages = append(packages, entry) + documented[entry.name] = entry.importPath + indexPackage(index, entry.name, entry.pkg) } + // base holds the state behind ui's aliases (ui.Toaster is base.Toaster). + // Load it to give an alias the fields and methods its type page needs, but + // do not document the package itself: ui is the public surface. + base, err := loadDocPackage(root, "base") + if err != nil { + return APIData{}, fmt.Errorf("api: base aliases: %w", err) + } + baseTypes := map[string]*doc.Type{} + for _, typ := range base.pkg.Types { + baseTypes[typ.Name] = typ + } + baseFuncs := map[string]*doc.Func{} + for _, function := range base.pkg.Funcs { + baseFuncs[function.Name] = function + } + baseConverter := docConverter{importPath: base.importPath, index: index, packages: documented} var data APIData for _, entry := range packages { - converter := docConverter{importPath: entry.importPath, index: index} + converter := docConverter{importPath: entry.importPath, index: index, packages: documented} output := APIPackage{ Name: entry.name, ImportPath: entry.importPath, Synopsis: entry.pkg.Synopsis(entry.pkg.Doc), Doc: converter.blocks(entry.pkg.Doc), } - printDecl := func(node any) (string, error) { - var buffer bytes.Buffer - config := printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 4} - if err := config.Fprint(&buffer, entry.fset, &printer.CommentedNode{Node: node, Comments: entry.comments}); err != nil { - return "", err - } - return strings.TrimSpace(buffer.String()), nil - } - values := func(list []*doc.Value) ([]APIValue, error) { - result := []APIValue{} - for _, value := range list { - decl, err := printDecl(value.Decl) - if err != nil { - return nil, err - } - result = append(result, APIValue{Names: value.Names, Decl: decl, Doc: converter.blocks(value.Doc)}) - } - return result, nil - } - functions := func(list []*doc.Func) ([]APIFunc, error) { - result := []APIFunc{} - for _, function := range list { - decl, err := printDecl(function.Decl) - if err != nil { - return nil, err - } - result = append(result, APIFunc{ - Name: function.Name, Receiver: strings.TrimPrefix(function.Recv, "*"), Decl: decl, - Synopsis: entry.pkg.Synopsis(function.Doc), Doc: converter.blocks(function.Doc), - }) - } - return result, nil - } var err error - if output.Constants, err = values(entry.pkg.Consts); err != nil { + if output.Constants, err = apiValues(entry.fset, entry.pkg.Consts, entry.comments, converter); err != nil { return APIData{}, err } - if output.Variables, err = values(entry.pkg.Vars); err != nil { + if output.Variables, err = apiValues(entry.fset, entry.pkg.Vars, entry.comments, converter); err != nil { return APIData{}, err } - if output.Functions, err = functions(entry.pkg.Funcs); err != nil { + if output.Functions, err = apiFunctions(entry.fset, entry.pkg.Funcs, entry.comments, entry.pkg.Synopsis, converter); err != nil { return APIData{}, err } + if entry.name == "ui" { + // The page facade is thin: ui.Button wraps base.Button without its + // own comment. Give the API table the underlying function's doc. + for index := range output.Functions { + item := &output.Functions[index] + if item.Synopsis != "" { + continue + } + if baseFunc, ok := baseFuncs[item.Name]; ok { + item.Synopsis = base.pkg.Synopsis(baseFunc.Doc) + item.Doc = baseConverter.blocks(baseFunc.Doc) + } + } + } for _, typ := range entry.pkg.Types { - decl, err := printDecl(typ.Decl) + decl, err := printCommented(entry.fset, typ.Decl, entry.comments) if err != nil { return APIData{}, err } item := APIType{Name: typ.Name, Decl: decl, Synopsis: entry.pkg.Synopsis(typ.Doc), Doc: converter.blocks(typ.Doc)} - if item.Constants, err = values(typ.Consts); err != nil { + item.Fields = structFields(entry.fset, typ.Decl, converter) + if item.Constants, err = apiValues(entry.fset, typ.Consts, entry.comments, converter); err != nil { return APIData{}, err } - if item.Variables, err = values(typ.Vars); err != nil { + if item.Variables, err = apiValues(entry.fset, typ.Vars, entry.comments, converter); err != nil { return APIData{}, err } - if item.Constructors, err = functions(typ.Funcs); err != nil { + if item.Constructors, err = apiFunctions(entry.fset, typ.Funcs, entry.comments, entry.pkg.Synopsis, converter); err != nil { return APIData{}, err } - if item.Methods, err = functions(typ.Methods); err != nil { + if item.Methods, err = apiFunctions(entry.fset, typ.Methods, entry.comments, entry.pkg.Synopsis, converter); err != nil { return APIData{}, err } + if target := aliasTarget(typ.Decl, "base"); target != "" { + if baseType, ok := baseTypes[target]; ok { + item.Fields = structFields(base.fset, baseType.Decl, baseConverter) + if item.Methods, err = apiFunctions(base.fset, userMethods(base.fset, baseType.Methods), base.comments, base.pkg.Synopsis, baseConverter); err != nil { + return APIData{}, err + } + if item.Synopsis == "" { + item.Synopsis = base.pkg.Synopsis(baseType.Doc) + } + if len(item.Doc) == 0 { + item.Doc = baseConverter.blocks(baseType.Doc) + } + // The ui facade's constructors are thin wrappers too: copy + // the base constructor's comment when the wrapper has none. + baseConstructors := map[string]*doc.Func{} + for _, constructor := range baseType.Funcs { + baseConstructors[constructor.Name] = constructor + } + for index := range item.Constructors { + constructor := &item.Constructors[index] + if constructor.Synopsis != "" { + continue + } + if baseFunc, ok := baseConstructors[constructor.Name]; ok { + constructor.Synopsis = base.pkg.Synopsis(baseFunc.Doc) + constructor.Doc = baseConverter.blocks(baseFunc.Doc) + } + } + } + } output.Types = append(output.Types, item) } data.Packages = append(data.Packages, output) @@ -214,6 +301,155 @@ func loadAPI(root string) (APIData, error) { return data, nil } +func printCommented(fset *token.FileSet, node any, comments []*ast.CommentGroup) (string, error) { + var buffer bytes.Buffer + config := printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 4} + if err := config.Fprint(&buffer, fset, &printer.CommentedNode{Node: node, Comments: comments}); err != nil { + return "", err + } + return strings.TrimSpace(buffer.String()), nil +} + +func apiValues(fset *token.FileSet, list []*doc.Value, comments []*ast.CommentGroup, converter docConverter) ([]APIValue, error) { + result := []APIValue{} + for _, value := range list { + decl, err := printCommented(fset, value.Decl, comments) + if err != nil { + return nil, err + } + result = append(result, APIValue{Names: value.Names, Decl: decl, Doc: converter.blocks(value.Doc)}) + } + return result, nil +} + +// userMethods drops the generated accessors that let the engine read fields; +// they are exported for the framework, not for the application's API table. +func userMethods(fset *token.FileSet, list []*doc.Func) []*doc.Func { + result := make([]*doc.Func, 0, len(list)) + for _, function := range list { + if function.Decl != nil && strings.HasSuffix(fset.Position(function.Decl.Pos()).Filename, "accessors.go") { + continue + } + result = append(result, function) + } + return result +} + +func apiFunctions(fset *token.FileSet, list []*doc.Func, comments []*ast.CommentGroup, synopsis func(string) string, converter docConverter) ([]APIFunc, error) { + result := []APIFunc{} + for _, function := range list { + decl, err := printCommented(fset, function.Decl, comments) + if err != nil { + return nil, err + } + signature := "" + if function.Decl != nil { + copy := *function.Decl + copy.Body = nil + signature = printNode(fset, ©) + } + result = append(result, APIFunc{ + Name: function.Name, Receiver: strings.TrimPrefix(function.Recv, "*"), Decl: decl, + Signature: signature, Synopsis: synopsis(function.Doc), Doc: converter.blocks(function.Doc), + }) + } + return result, nil +} + +// aliasTarget is the name a type spec aliases from pkg, or empty when it is not +// an alias there. +func aliasTarget(decl *ast.GenDecl, pkg string) string { + if decl == nil || len(decl.Specs) == 0 { + return "" + } + spec, ok := decl.Specs[0].(*ast.TypeSpec) + if !ok || !spec.Assign.IsValid() { + return "" + } + selector, ok := spec.Type.(*ast.SelectorExpr) + if !ok { + return "" + } + ident, ok := selector.X.(*ast.Ident) + if !ok || ident.Name != pkg { + return "" + } + return selector.Sel.Name +} + +// printNode prints one AST node without the comments around it, for a type or +// a signature a table cell holds. +func printNode(fset *token.FileSet, node ast.Node) string { + var buffer bytes.Buffer + config := printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 4} + if err := config.Fprint(&buffer, fset, node); err != nil { + return "" + } + return strings.TrimSpace(buffer.String()) +} + +// structFields lists the exported fields of a documented struct type, each with +// its written type and doc comment. Other types have none. +func structFields(fset *token.FileSet, decl *ast.GenDecl, converter docConverter) []APIField { + if decl == nil { + return nil + } + var structure *ast.StructType + for _, spec := range decl.Specs { + typeSpec, ok := spec.(*ast.TypeSpec) + if !ok { + continue + } + if value, ok := typeSpec.Type.(*ast.StructType); ok { + structure = value + break + } + } + if structure == nil { + return nil + } + var fields []APIField + for _, field := range structure.Fields.List { + doc := field.Doc + if doc == nil { + doc = field.Comment + } + text := "" + if doc != nil { + text = doc.Text() + } + typ := printNode(fset, field.Type) + names := field.Names + if len(names) == 0 { + name := embeddedFieldName(field.Type) + if name == "" || !ast.IsExported(name) { + continue + } + fields = append(fields, APIField{Name: name, Type: typ, Doc: converter.blocks(text)}) + continue + } + for _, name := range names { + if !name.IsExported() { + continue + } + fields = append(fields, APIField{Name: name.Name, Type: typ, Doc: converter.blocks(text)}) + } + } + return fields +} + +func embeddedFieldName(expr ast.Expr) string { + switch expr := expr.(type) { + case *ast.Ident: + return expr.Name + case *ast.StarExpr: + return embeddedFieldName(expr.X) + case *ast.SelectorExpr: + return expr.Sel.Name + } + return "" +} + func indexPackage(index symbolIndex, name string, pkg *doc.Package) { importPath := "github.com/vivaui/viva/" + name for _, value := range pkg.Consts { @@ -255,6 +491,7 @@ func indexPackage(index symbolIndex, name string, pkg *doc.Package) { type docConverter struct { importPath string index symbolIndex + packages map[string]string } func (converter docConverter) blocks(text string) []DocBlock { @@ -263,13 +500,8 @@ func (converter docConverter) blocks(text string) []DocBlock { } var parser comment.Parser parser.LookupPackage = func(name string) (string, bool) { - importPath := "github.com/vivaui/viva/" + name - for _, known := range apiPackages { - if known == name { - return importPath, true - } - } - return "", false + importPath, ok := converter.packages[name] + return importPath, ok } parser.LookupSym = func(recv, name string) bool { key := converter.importPath + "." + name @@ -345,6 +577,75 @@ func (converter docConverter) resolve(link *comment.DocLink) string { return converter.index[key] } +// pageAPISymbol reports whether symbol names a type, function, constructor or +// method the API data documents. Constants and variables have no table row, so +// a derived page list drops them. +func pageAPISymbol(data APIData, symbol string) bool { + pkgName, name, ok := strings.Cut(symbol, ".") + if !ok || pkgName == "" || name == "" { + return false + } + for _, pkg := range data.Packages { + if pkg.Name != pkgName { + continue + } + for _, function := range pkg.Functions { + if function.Name == name { + return true + } + } + for _, typ := range pkg.Types { + if typ.Name == name { + return true + } + for _, function := range typ.Constructors { + if function.Name == name { + return true + } + } + for _, method := range typ.Methods { + if method.Name == name { + return true + } + } + } + } + return false +} + +// prunePageAPI drops the symbols a derived page list guessed but the API data +// does not document, such as package constants and local example identifiers. +func prunePageAPI(pages []Page, data APIData) { + for index := range pages { + seen := map[string]bool{} + kept := pages[index].API[:0] + for _, symbol := range pages[index].API { + if seen[symbol] || !pageAPISymbol(data, symbol) { + continue + } + seen[symbol] = true + kept = append(kept, symbol) + } + pages[index].API = kept + } +} + +// validatePageAPI reports a component page that names a symbol the API data +// does not contain, which would render an empty or broken table. +func validatePageAPI(pages []Page, data APIData) error { + for _, page := range pages { + for _, symbol := range page.API { + if _, _, ok := strings.Cut(symbol, "."); !ok { + return fmt.Errorf("catalog: %s API symbol %q is not package.Name", page.ID, symbol) + } + if !pageAPISymbol(data, symbol) { + return fmt.Errorf("catalog: %s names unknown API symbol %s", page.ID, symbol) + } + } + } + return nil +} + // validateAPI reports a structural problem that would produce a broken page. func validateAPI(data APIData) error { seen := map[string]bool{} diff --git a/tools/docs/api_test.go b/tools/docs/api_test.go index 0116a7e90..0664a4901 100644 --- a/tools/docs/api_test.go +++ b/tools/docs/api_test.go @@ -38,8 +38,16 @@ func findType(t *testing.T, data APIData, pkg, name string) APIType { func TestAPIDocumentsTheRealExportedSurface(t *testing.T) { data := loadTestAPI(t) - if len(data.Packages) != len(apiPackages) { - t.Fatalf("packages = %d, want %d", len(data.Packages), len(apiPackages)) + root, err := findRoot() + if err != nil { + t.Fatal(err) + } + paths, err := apiPackagePaths(root) + if err != nil { + t.Fatal(err) + } + if len(data.Packages) != len(paths) { + t.Fatalf("packages = %d, want %d", len(data.Packages), len(paths)) } config := findType(t, data, "app", "Config") for _, want := range []string{"Paint func(canvas *gfx.Canvas, size gfx.Size)", "OnPointer func(event gfx.PointerEvent) gfx.EventResult", "Invalidator *Invalidator"} { @@ -108,7 +116,14 @@ func TestDocLinksResolveToDocumentedSymbolsOnly(t *testing.T) { "github.com/vivaui/viva/gfx.Canvas.Hovered": "ui/Canvas#method-Hovered", "github.com/vivaui/viva/app.RunCanvas": "app#func-RunCanvas", } - converter := docConverter{importPath: "github.com/vivaui/viva/app", index: index} + converter := docConverter{ + importPath: "github.com/vivaui/viva/app", + index: index, + packages: map[string]string{ + "app": "github.com/vivaui/viva/app", + "gfx": "github.com/vivaui/viva/gfx", + }, + } blocks := converter.blocks("RunCanvas uses a [Config] and a [gfx.Canvas]; see [gfx.Canvas.Hovered] and [Missing].\n\n\tcode := block()\n\nThen:\n\n - one\n - two\n") if len(blocks) != 4 || blocks[0].Kind != "paragraph" || blocks[1].Kind != "code" || blocks[2].Kind != "paragraph" || blocks[3].Kind != "list" || len(blocks[3].Items) != 2 { t.Fatalf("blocks = %+v", blocks) diff --git a/tools/docs/catalog.go b/tools/docs/catalog.go index c03575843..8709dfdfe 100644 --- a/tools/docs/catalog.go +++ b/tools/docs/catalog.go @@ -9,6 +9,7 @@ import ( "io/fs" "os" "path/filepath" + "regexp" "sort" "strings" @@ -44,7 +45,11 @@ type Page struct { PageSource string // Source is the Go file the examples call, relative to the repository root: // components/.go, or ui/list.go for a page-layer control. - Source string + Source string + // API lists the symbols the component page summarizes, as "package.Name". + // The page renders them from api.json, so the tables cannot drift from the + // code they document. + API []string `json:"api,omitempty"` All []Nav Examples []Demo InstallCommand string @@ -69,6 +74,81 @@ type Manifest struct { Coverage []Coverage `json:"coverage"` } +// componentAPI maps a component page to the API symbols it summarizes. Pilot: +// the toast pages. Sites keep this list explicit because a page often calls +// symbols outside its own recipe file: the toast page's page API lives in base. +// pageAPIHelpers are the page-layout and measurement calls every example uses; +// they are not the component's own API and stay out of its table. +var pageAPIHelpers = map[string]bool{ + "Row": true, "Column": true, "Text": true, "Textf": true, "Grid": true, + "Box": true, "Slot": true, "Spacer": true, "Children": true, + "If": true, "For": true, "Start": true, "Center": true, "End": true, + "Stretch": true, "Baseline": true, "Wrap": true, "Gap": true, "Pad": true, + "PadX": true, "PadY": true, "Margin": true, "MarginY": true, "Width": true, + "Height": true, "Size": true, "Fill": true, "FillWidth": true, "Shrink": true, + "Grow": true, "Self": true, "Align": true, "Justify": true, "Position": true, + "Padding": true, "ID": true, "C": true, "Theme": true, + "DrawContext": true, +} + +var apiSymbolPattern = regexp.MustCompile(`\b([a-z][a-z0-9]*)\.([A-Z][A-Za-z0-9_]*)`) + +// derivePageAPI is the first pass for a component page without an explicit +// list: the page symbols its examples call, then the recipe symbols their +// canvas snippets call. Unknown names are dropped against api.json later. +func derivePageAPI(examples []Demo, pagePackages map[string]bool) []string { + var symbols []string + seen := map[string]bool{} + add := func(symbol string) { + if !seen[symbol] { + seen[symbol] = true + symbols = append(symbols, symbol) + } + } + for _, example := range examples { + for _, snippet := range []string{example.PageSnippet, example.PageSnippetZh} { + for _, match := range apiSymbolPattern.FindAllStringSubmatch(snippet, -1) { + pkg, name := match[1], match[2] + if pkg == "components" { + continue + } + if pkg != "ui" && !pagePackages[pkg] { + continue + } + if pkg == "ui" && pageAPIHelpers[name] { + continue + } + add(pkg + "." + name) + } + } + } + for _, example := range examples { + for _, match := range apiSymbolPattern.FindAllStringSubmatch(example.Snippet, -1) { + if match[1] == "components" { + add("components." + match[2]) + } + } + } + return symbols +} + +// componentAPIExtra adds a page API the example snippets do not name, such as +// a control built through a local variable. +var componentAPIExtra = map[string][]string{ + "toggle-group": {"togglegroup.Group"}, +} + +var componentAPI = map[string][]string{ + "toast": { + "ui.Toaster", "ui.ToastConfig", "ui.Toasts", + "components.PaintToast", "components.ToastOptions", "components.ToastSnapshot", + }, + "sonner": { + "ui.Toaster", "ui.ToastConfig", "ui.Toasts", + "components.PaintSonner", "components.SonnerOptions", "components.SonnerToast", + }, +} + func loadPages(root string) ([]Page, Manifest, error) { manifest, err := sourceManifest(root) if err != nil { @@ -83,6 +163,16 @@ func loadPages(root string) ([]Page, Manifest, error) { seen[component.ID] = true navigation = append(navigation, Nav{component.ID, component.Title, component.Category}) } + paths, err := apiPackagePaths(root) + if err != nil { + return nil, manifest, err + } + pagePackages := map[string]bool{"ui": true} + for _, path := range paths { + if strings.HasPrefix(path, "ui/") { + pagePackages[strings.TrimPrefix(path, "ui/")] = true + } + } metadata := documentation() var pages []Page for _, component := range componentdemo.Catalog() { @@ -110,6 +200,12 @@ func loadPages(root string) ([]Page, Manifest, error) { } page.Examples = append(page.Examples, Demo{example.ID, example.Title, example.Description, example.Snippet, example.PageSnippet, example.PageSnippetZh, example.Height}) } + if explicit, ok := componentAPI[component.ID]; ok { + page.API = explicit + } else { + page.API = derivePageAPI(page.Examples, pagePackages) + } + page.API = append(page.API, componentAPIExtra[component.ID]...) pages = append(pages, page) } if len(metadata) != len(pages) { @@ -166,7 +262,7 @@ func validID(value string) bool { func sourceManifest(root string) (Manifest, error) { manifest := Manifest{} - for _, directory := range []string{"app", "ui", "gfx", "components", "internal", "cmd/component-preview", "cmd/viva/templates", "tools/docs"} { + for _, directory := range []string{"app", "ui", "base", "gfx", "components", "internal", "cmd/component-preview", "cmd/viva/templates", "tools/docs"} { err := filepath.WalkDir(filepath.Join(root, filepath.FromSlash(directory)), func(path string, entry fs.DirEntry, err error) error { if err != nil { return err @@ -218,6 +314,17 @@ func writeData(root, output string, pages []Page, manifest Manifest) error { } return os.WriteFile(path, data, 0o644) } + api, err := loadAPI(root) + if err != nil { + return err + } + if err := validateAPI(api); err != nil { + return err + } + prunePageAPI(pages, api) + if err := validatePageAPI(pages, api); err != nil { + return err + } catalog := struct { Pages []Page `json:"pages"` Revision string `json:"revision"` @@ -230,13 +337,6 @@ func writeData(root, output string, pages []Page, manifest Manifest) error { if err := write("catalog.json", data); err != nil { return err } - api, err := loadAPI(root) - if err != nil { - return err - } - if err := validateAPI(api); err != nil { - return err - } data, err = json.MarshalIndent(api, "", " ") if err != nil { return err diff --git a/tools/docs/catalog_test.go b/tools/docs/catalog_test.go index d3ddc9eb2..c0ad678e7 100644 --- a/tools/docs/catalog_test.go +++ b/tools/docs/catalog_test.go @@ -105,7 +105,7 @@ func TestCatalogAndExportUseActualGoSource(t *testing.T) { func manifestFixture(t *testing.T) string { t.Helper() root := t.TempDir() - for _, directory := range []string{"app", "ui", "gfx", "components", "internal", "cmd/component-preview", "cmd/viva/templates", "tools/docs"} { + for _, directory := range []string{"app", "ui", "base", "gfx", "components", "internal", "cmd/component-preview", "cmd/viva/templates", "tools/docs"} { if err := os.MkdirAll(filepath.Join(root, directory), 0o755); err != nil { t.Fatal(err) } @@ -453,7 +453,7 @@ func TestPageUsageIsPageLevel(t *testing.T) { func TestPageSnippetsHaveNoUndeclaredNames(t *testing.T) { packages := map[string]bool{ "ui": true, "base": true, "gfx": true, "window": true, "text": true, - "style": true, "strings": true, "utf8": true, "time": true, "math": true, + "style": true, "strings": true, "slices": true, "utf8": true, "time": true, "math": true, "codeeditor": true, "chart": true, "calendar": true, "carousel": true, "multiselect": true, "hierarchypicker": true, "markdown": true, "columnresize": true, @@ -461,6 +461,31 @@ func TestPageSnippetsHaveNoUndeclaredNames(t *testing.T) { "sidebar": true, "marker": true, "metriccard": true, + "typography": true, + "divider": true, + "popconfirm": true, + "editabletabs": true, + "pagination": true, + "result": true, + "empty": true, + "card": true, + "breadcrumb": true, + "tag": true, + "alert": true, + "steps": true, + "descriptions": true, + "timeline": true, + "rate": true, + "inputnumber": true, + "datepicker": true, + "timepicker": true, + "transfer": true, + "upload": true, + "anchor": true, + "comment": true, + "imagepreview": true, + "mentions": true, + "tour": true, "questionnaire": true, "inputotp": true, "inputgroup": true, @@ -633,7 +658,32 @@ func TestModelFreePageSnippetsCompile(t *testing.T) { "skeleton": "github.com/vivaui/viva/ui/skeleton", "inputgroup": "github.com/vivaui/viva/ui/inputgroup", "inputotp": "github.com/vivaui/viva/ui/inputotp", "questionnaire": "github.com/vivaui/viva/ui/questionnaire", "metriccard": "github.com/vivaui/viva/ui/metriccard", "marker": "github.com/vivaui/viva/ui/marker", - "sidebar": "github.com/vivaui/viva/ui/sidebar", "multiselect": "github.com/vivaui/viva/ui/multiselect", + "typography": "github.com/vivaui/viva/ui/typography", + "divider": "github.com/vivaui/viva/ui/divider", + "popconfirm": "github.com/vivaui/viva/ui/popconfirm", + "editabletabs": "github.com/vivaui/viva/ui/editabletabs", + "pagination": "github.com/vivaui/viva/ui/pagination", + "result": "github.com/vivaui/viva/ui/result", + "empty": "github.com/vivaui/viva/ui/empty", + "card": "github.com/vivaui/viva/ui/card", + "breadcrumb": "github.com/vivaui/viva/ui/breadcrumb", + "tag": "github.com/vivaui/viva/ui/tag", + "alert": "github.com/vivaui/viva/ui/alert", + "steps": "github.com/vivaui/viva/ui/steps", + "descriptions": "github.com/vivaui/viva/ui/descriptions", + "timeline": "github.com/vivaui/viva/ui/timeline", + "rate": "github.com/vivaui/viva/ui/rate", + "inputnumber": "github.com/vivaui/viva/ui/inputnumber", + "datepicker": "github.com/vivaui/viva/ui/datepicker", + "timepicker": "github.com/vivaui/viva/ui/timepicker", + "transfer": "github.com/vivaui/viva/ui/transfer", + "upload": "github.com/vivaui/viva/ui/upload", + "anchor": "github.com/vivaui/viva/ui/anchor", + "comment": "github.com/vivaui/viva/ui/comment", + "imagepreview": "github.com/vivaui/viva/ui/imagepreview", + "mentions": "github.com/vivaui/viva/ui/mentions", + "tour": "github.com/vivaui/viva/ui/tour", + "sidebar": "github.com/vivaui/viva/ui/sidebar", "multiselect": "github.com/vivaui/viva/ui/multiselect", "hierarchypicker": "github.com/vivaui/viva/ui/hierarchypicker", } wordM := regexp.MustCompile(`\bm\b`) diff --git a/tools/docs/main.go b/tools/docs/main.go index 604748acf..6e953a428 100644 --- a/tools/docs/main.go +++ b/tools/docs/main.go @@ -46,6 +46,10 @@ func run(output string, check bool) error { if err := validateAPI(api); err != nil { return err } + prunePageAPI(pages, api) + if err := validatePageAPI(pages, api); err != nil { + return err + } fmt.Printf("validated %d documented components and %d API packages · source %s\n", len(pages), len(api.Packages), manifest.Revision) return nil } diff --git a/tools/tarball/tarball_test.go b/tools/tarball/tarball_test.go index 86416c1ef..69444a4f5 100644 --- a/tools/tarball/tarball_test.go +++ b/tools/tarball/tarball_test.go @@ -8,6 +8,7 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" "testing" "time" @@ -217,6 +218,20 @@ func TestLinuxArchiveRejectsBadSpecs(t *testing.T) { } } +// shellPath is path as the sh these tests run sees it. install.sh is a POSIX +// script that insists on an absolute prefix; on Windows sh is MSYS or Git +// Bash, which reads a drive letter as a relative name and wants /c/Users/... +func shellPath(path string) string { + if runtime.GOOS != "windows" { + return path + } + path = filepath.ToSlash(path) + if len(path) >= 2 && path[1] == ':' { + return "/" + strings.ToLower(path[:1]) + path[2:] + } + return path +} + // TestInstallScript unpacks the archive and runs install.sh with sh: install, // replace, and uninstall under a prefix, and the checks on the prefix. func TestInstallScript(t *testing.T) { @@ -247,8 +262,9 @@ func TestInstallScript(t *testing.T) { } prefix := filepath.Join(t.TempDir(), "prefix") + shellPrefix := shellPath(prefix) for round := 0; round < 2; round++ { // the second round replaces - if out, err := run("--prefix", prefix); err != nil { + if out, err := run("--prefix", shellPrefix); err != nil { t.Fatalf("install: %v\n%s", err, out) } } @@ -258,11 +274,12 @@ func TestInstallScript(t *testing.T) { } } info, _ := os.Stat(filepath.Join(prefix, "bin", "fixture-notes")) - if info.Mode()&0o111 == 0 { + // NTFS has no execute bit; Go reports every file there as 0666 or 0444. + if runtime.GOOS != "windows" && info.Mode()&0o111 == 0 { t.Error("the installed program is not executable") } desktop, _ := os.ReadFile(filepath.Join(prefix, "share/applications/fixture-notes.desktop")) - for _, want := range []string{"Exec=" + prefix + "/bin/fixture-notes\n", "Icon=" + prefix + "/share/icons/hicolor/256x256/apps/fixture-notes.png\n", "Name=Fixture Notes\n"} { + for _, want := range []string{"Exec=" + shellPrefix + "/bin/fixture-notes\n", "Icon=" + shellPrefix + "/share/icons/hicolor/256x256/apps/fixture-notes.png\n", "Name=Fixture Notes\n"} { if !strings.Contains(string(desktop), want) { t.Errorf("the installed desktop file lacks %q:\n%s", want, desktop) } @@ -271,7 +288,7 @@ func TestInstallScript(t *testing.T) { t.Errorf("bin holds %d files; a temporary file was left", len(entries)) } - if out, err := run("uninstall", "--prefix="+prefix); err != nil || !strings.Contains(out, "removed") { + if out, err := run("uninstall", "--prefix="+shellPrefix); err != nil || !strings.Contains(out, "removed") { t.Fatalf("uninstall: %v\n%s", err, out) } for _, path := range []string{"bin/fixture-notes", "share/applications/fixture-notes.desktop", "share/icons/hicolor/256x256/apps/fixture-notes.png"} { @@ -335,7 +352,7 @@ func TestFileTypesAreInstalledAndRemoved(t *testing.T) { t.Fatalf("%v: %v\n%s", arguments, err, out) } } - run("--prefix", prefix) + run("--prefix", shellPath(prefix)) installed := filepath.Join(prefix, "share", "applications", "fixture-notes.desktop") if data, err := os.ReadFile(installed); err != nil || !strings.Contains(string(data), "/bin/fixture-notes %F\n") { t.Errorf("installed entry: %v\n%s", err, data) @@ -344,7 +361,7 @@ func TestFileTypesAreInstalledAndRemoved(t *testing.T) { if data, err := os.ReadFile(types); err != nil || !strings.Contains(string(data), ``) { t.Errorf("installed mime package: %v\n%s", err, data) } - run("uninstall", "--prefix", prefix) + run("uninstall", "--prefix", shellPath(prefix)) if _, err := os.Stat(types); err == nil { t.Error("uninstall left the mime package") } diff --git a/tools/visualparity/scenes.go b/tools/visualparity/scenes.go index 37ae234f6..6847dc9d8 100644 --- a/tools/visualparity/scenes.go +++ b/tools/visualparity/scenes.go @@ -133,13 +133,16 @@ func tableScene() *scene { {"db-replica", "Running", "15 ms"}, {"cache", "Stopped", "-"}, {"build-agent-long-name", "Running", "103 ms"}, {"监控服务器", "运行中", "7 ms"}, } - columns := []components.TableColumn{{Width: 200}, {Width: 120}, {Alignment: components.TableAlignRight}} + columns := []components.TableColumn{ + {Title: "Name", Width: 200, Sortable: true}, + {Title: "State", Width: 120, Sortable: true}, + {Title: "Latency", Alignment: components.TableAlignRight, Sortable: true}, + } return &scene{name: "table", width: 560, height: 360, build: func(c ui.C, theme gfx.Theme) { ui.Column(c).Pad(24).Gap(12).Children(func() { ui.Text(c, "Servers").FontSize(theme.Metrics.FontSizeL).Bold() ui.Table(c, &state, ui.TableSpec{ - Rows: scopeRows, Header: scopeHeads, Columns: columns, - Headers: []string{"Name", "State", "Latency"}, Sortable: []bool{true, true, true}, Source: &data, + Rows: scopeRows, Header: scopeHeads, Columns: columns, Source: &data, }).FillWidth() }) }} diff --git a/ui/alert/alert.go b/ui/alert/alert.go new file mode 100644 index 000000000..796536d39 --- /dev/null +++ b/ui/alert/alert.go @@ -0,0 +1,196 @@ +// Package alert is the opt-in page control for a notice that stays in the page: +// a status icon, a title, a description, and optionally a button for what to do +// about it and a close button. A page keeps an Alert in its model, because it +// remembers whether the user closed it: +// +// m.notice = alert.New() +// // in the page: +// m.notice.View(c, alert.Spec{ +// Status: ui.StatusWarning, +// Title: "Host key changed", +// Description: "The key of build-01 differs from the one you trusted.", +// Action: "Review", +// Closable: true, +// }).FillWidth() +// if m.notice.ActionClicked() { +// // the user pressed Review +// } +// +// Status colors the icon and the rim: ui.StatusDefault is an information notice +// in the neutral look, and success, warning and danger are tinted. Icon gives a +// notice an icon of its own in place of the status icon. Banner makes the notice +// a full-width strip with square corners and no side rims, for the top of a page. +// +// A closed alert stays closed until Reopen; View of a closed alert declares an +// empty box, so a page that wants no trace of it checks Closed first. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an Alert in the model: its state and handlers are made +// once, so a warm paint allocates nothing. Do not copy an Alert after it has been +// declared. +package alert + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// circle is the outline of a circle of radius 10 around (12, 12) as four cubic +// curves, the frame of the status icons. +var circle = []gfx.PathCommand{ + gfx.MoveTo(22, 12), gfx.CubicTo(22, 17.52, 17.52, 22, 12, 22), gfx.CubicTo(6.48, 22, 2, 17.52, 2, 12), + gfx.CubicTo(2, 6.48, 6.48, 2, 12, 2), gfx.CubicTo(17.52, 2, 22, 6.48, 22, 12), +} + +func icon(extra ...gfx.PathCommand) gfx.Icon { + commands := append(append([]gfx.PathCommand(nil), circle...), extra...) + return gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: commands} +} + +var ( + infoIcon = icon(gfx.MoveTo(12, 16), gfx.LineTo(12, 12), gfx.MoveTo(12, 8), gfx.LineTo(12.01, 8)) + successIcon = icon(gfx.MoveTo(9, 12), gfx.LineTo(11, 14), gfx.LineTo(15, 10)) + dangerIcon = icon(gfx.MoveTo(15, 9), gfx.LineTo(9, 15), gfx.MoveTo(9, 9), gfx.LineTo(15, 15)) + warningIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(10.29, 3.86), gfx.LineTo(1.82, 18), gfx.QuadTo(1, 20, 3, 20), gfx.LineTo(21, 20), gfx.QuadTo(23, 20, 22.18, 18), + gfx.LineTo(13.71, 3.86), gfx.QuadTo(12, 2, 10.29, 3.86), + gfx.MoveTo(12, 9), gfx.LineTo(12, 13), gfx.MoveTo(12, 17), gfx.LineTo(12.01, 17), + }} + closeIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(18, 6), gfx.LineTo(6, 18), gfx.MoveTo(6, 6), gfx.LineTo(18, 18), + }} +) + +// statusIcon is the icon a status carries. +func statusIcon(status ui.Status) gfx.Icon { + switch status { + case ui.StatusSuccess: + return successIcon + case ui.StatusWarning: + return warningIcon + case ui.StatusDanger: + return dangerIcon + } + return infoIcon +} + +// Spec declares one notice. +type Spec struct { + // Status is the outcome the notice reports; the neutral information notice by + // default. + Status ui.Status + // Title is the notice's heading; Description is the line or lines under it. + // Either may be empty. + Title, Description string + // Icon replaces the icon of the status. A zero icon keeps it. + Icon gfx.Icon + // NoIcon leaves the icon out. + NoIcon bool + // Action is the label of a button at the end of the notice; ActionClicked + // reports a press on it. It is not drawn when empty. + Action string + // Closable adds a close button; Closed reports that it was pressed. + Closable bool + // Banner makes the notice a full-width strip with square corners and no side + // rims. + Banner bool + // CloseLabel is the accessible name of the close button, "Close" when empty. + CloseLabel string +} + +// Alert is one notice and what the user did to it. Its zero value is an open +// alert; New is the readable way to make one. +type Alert struct { + closed bool + acted bool // the action was pressed in the paint being declared +} + +// New returns an open alert. +func New() *Alert { return &Alert{} } + +// Closed reports whether the user closed the notice. +func (a *Alert) Closed() bool { return a.closed } + +// Reopen shows a closed notice again. +func (a *Alert) Reopen() { a.closed = false } + +// ActionClicked reports whether the paint just made delivered a press on the +// action button. +func (a *Alert) ActionClicked() bool { return a.acted } + +// tint is color at the given opacity, the fill and the rim of a status. +func tint(color gfx.Color, alpha float32) gfx.Color { + color.Alpha *= alpha + return color +} + +// View declares the notice at c. The notice is as tall as its text; give it +// FillWidth. Declare the view on its own, not inside a Memo. +func (a *Alert) View(c ui.C, spec Spec) ui.Box { + if a == nil { + panic("alert: View needs its Alert") + } + a.acted = false + if a.closed { + return ui.Spacer(c).Size(0, 0) + } + theme := c.Theme() + metrics := theme.Metrics + ink := theme.Foreground + fill, rim := theme.Card, theme.Border + switch spec.Status { + case ui.StatusSuccess: + ink = theme.Success + case ui.StatusWarning: + ink = theme.WarningColor() + case ui.StatusDanger: + ink = theme.Danger + } + if spec.Status != ui.StatusDefault { + fill, rim = tint(ink, 0.08), tint(ink, 0.4) + } + root := ui.Row(c).Items(ui.Start).Gap(metrics.GapItem).Background(fill) + root = root.Pad(metrics.PadSurface * 0.75) + if spec.Banner { + root = root.Radius(0).Border(0, rim) + } else { + root = root.Radius(metrics.RadiusSurface).Border(1, rim) + } + label := spec.Title + if label == "" { + label = spec.Description + } + root = root.HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleStatus, SkipFocus: true}) + root.Children(func() { + if !spec.NoIcon { + glyph := spec.Icon + if glyph.ViewBox == 0 { + glyph = statusIcon(spec.Status) + } + ui.Icon(c, glyph).Size(16, 16).Color(ink).MarginSides(2, 0, 0, 0).Shrink(0) + } + ui.Column(c).Grow(1).Basis(0).Gap(2).Children(func() { + if spec.Title != "" { + ui.Text(c, spec.Title).Weight(gfx.WeightMedium) + } + if spec.Description != "" { + ui.Wrap(c, spec.Description).FontSize(metrics.FontSizeS).Muted() + } + }) + if spec.Action != "" { + if ui.Button(c, spec.Action).Outline().Small().Shrink(0).Clicked() { + a.acted = true + } + } + if spec.Closable { + name := spec.CloseLabel + if name == "" { + name = "Close" + } + if ui.Button(c, name).Icon(closeIcon).IconOnly().Ghost().Shrink(0).Clicked() { + a.closed = true + } + } + }) + return root +} diff --git a/ui/alert/alert_test.go b/ui/alert/alert_test.go new file mode 100644 index 000000000..6aea1071a --- /dev/null +++ b/ui/alert/alert_test.go @@ -0,0 +1,134 @@ +//go:build !js + +package alert_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/alert" +) + +var shown int // the paints in which ActionClicked was true + +func open(t *testing.T, a *alert.Alert, spec alert.Spec) *headless.Session { + t.Helper() + shown = 0 + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + a.View(c, spec).FillWidth() + if a.ActionClicked() { + shown++ + } + ui.Button(c, "After") + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Alert", Width: 480, Height: 240}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +// The notice announces its title as a status, with the words it was given. +func TestAlertIsAStatusNamedByItsTitle(t *testing.T) { + session := open(t, alert.New(), alert.Spec{Status: ui.StatusWarning, Title: "Host key changed", Description: "Review it."}) + node, ok := session.AccessByName("Host key changed") + if !ok || node.Role != gfx.RoleStatus { + t.Fatalf("access node = %+v, %v; want a status named by the title", node, ok) + } + if err := session.Expect("text", "Review it."); err != nil { + t.Fatal(err) + } +} + +// A press on the action is reported once, in the paint that delivered it. +func TestActionClickIsReported(t *testing.T) { + session := open(t, alert.New(), alert.Spec{Title: "Update", Action: "Review"}) + if err := session.ClickLabel("Review"); err != nil { + t.Fatal(err) + } + if shown != 1 { + t.Fatalf("ActionClicked was true in %d paints after one press, want 1", shown) + } +} + +// The close button closes the notice for good, until it is reopened. +func TestCloseButtonClosesTheNotice(t *testing.T) { + a := alert.New() + session := open(t, a, alert.Spec{Title: "Update", Closable: true}) + if err := session.ClickLabel("Close"); err != nil { + t.Fatal(err) + } + if !a.Closed() { + t.Fatal("Closed was false after the close button was pressed") + } + if _, ok := session.AccessByName("Update"); ok { + t.Fatal("a closed notice is still in the accessibility tree") + } + a.Reopen() + if err := session.Frame(); err != nil { + t.Fatal(err) + } + if _, ok := session.AccessByName("Update"); !ok { + t.Fatal("a reopened notice is not shown again") + } +} + +// A notice with no close button or action offers neither. +func TestPlainNoticeHasNoButtons(t *testing.T) { + session := open(t, alert.New(), alert.Spec{Title: "Saved", Status: ui.StatusSuccess}) + for _, name := range []string{"Close", "Review"} { + if _, err := session.Locate(name); err == nil { + t.Fatalf("a plain notice offers %q", name) + } + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + for name, spec := range map[string]alert.Spec{ + "plain": {Title: "Saved", Description: "All changes were written.", Status: ui.StatusSuccess}, + "full": {Title: "Update", Description: "A new version is ready.", Action: "Review", Closable: true, Status: ui.StatusWarning}, + "banner": {Title: "Offline", Banner: true, Status: ui.StatusDanger}, + } { + t.Run(name, func(t *testing.T) { + a := alert.New() + view := func(c ui.C) { a.View(c, spec).FillWidth() } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 480, Height: 240}, view) + canvas.EndFrame() + } + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } + }) + } +} + +func BenchmarkViewPaint(b *testing.B) { + a := alert.New() + spec := alert.Spec{Title: "Update", Description: "A new version is ready.", Action: "Review", Closable: true, Status: ui.StatusWarning} + view := func(c ui.C) { a.View(c, spec).FillWidth() } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + b.ReportAllocs() + for range b.N { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 480, Height: 240}, view) + canvas.EndFrame() + } +} diff --git a/ui/anchor/anchor.go b/ui/anchor/anchor.go new file mode 100644 index 000000000..fcbeef940 --- /dev/null +++ b/ui/anchor/anchor.go @@ -0,0 +1,93 @@ +// Package anchor is the opt-in page control for an in-page table of contents: a +// vertical list of links to the sections of a long page, with a rail down its +// side that marks the section in view. A page keeps an Anchor in its model: +// +// m.toc = anchor.New() +// // in the page: +// m.toc.View(c, "On this page", anchor.Spec{Items: m.sections, Active: m.section}) +// if i, ok := m.toc.Clicked(); ok { +// m.scrollTo(m.sections[i]) // and m.section = i +// } +// +// The control owns neither the scrolling nor which section is in view: the page +// knows where its sections are, so it scrolls to the one a click reports and +// tells the control which is Active as it scrolls. An Item with Level 1 or more +// is indented under the item before it, for the headings below a heading. Active +// below zero marks none. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an Anchor in the model; a warm paint allocates nothing. +// Do not copy an Anchor after it has been declared. +package anchor + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Item is one link. +type Item struct { + // Title is the link's words. + Title string + // Level is how far the link is indented: zero for a top-level section. + Level int +} + +// Spec declares the list. +type Spec struct { + // Items are the links, in the order of the page. Keep the slice in the + // model: a slice made in each paint allocates in each paint. + Items []Item + // Active is the index of the section in view, or below zero for none. + Active int +} + +// Anchor is one list of links. +type Anchor struct { + clicked int // 1 + the link pressed in the paint being declared, or 0 +} + +// New returns an anchor. +func New() *Anchor { return &Anchor{} } + +// Clicked reports which link the user pressed in the paint just made. +func (a *Anchor) Clicked() (int, bool) { return a.clicked - 1, a.clicked > 0 } + +// View declares the list at c. label names it for assistive technology. The list +// is as wide as its longest link and as tall as its links; give it a width to +// wrap or clip longer ones. Declare the view on its own, not inside a Memo. +func (a *Anchor) View(c ui.C, label string, spec Spec) ui.Box { + if a == nil { + panic("anchor: View needs its Anchor") + } + a.clicked = 0 + theme := c.Theme() + metrics := theme.Metrics + root := ui.Column(c).HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true}) + root.Children(func() { + for i := range spec.Items { + item := spec.Items[i] + row := c.KeyInt(i) + rail := theme.Border + if i == spec.Active { + rail = theme.Primary + } + ui.Row(row).FillWidth().Children(func() { + ui.Spacer(row).Width(2).Grow(0).Shrink(0).Background(rail) + text := ui.Text(row, item.Title).FontSize(metrics.FontSizeS).Ellipsis().Grow(1).Basis(0) + text = text.MarginSides(4, 0, 4, metrics.GapItem+float32(item.Level)*metrics.GapItem*1.5) + if i == spec.Active { + text.Color(theme.Primary).Weight(gfx.WeightMedium) + } else { + text.Muted() + text.Hover(ui.Look{}.Color(theme.Foreground)) + } + text.HitWith(ui.ID(row), item.Title, gfx.HitOptions{Role: gfx.RoleLink}) + if text.Clicked() { + a.clicked = i + 1 + } + }) + } + }) + return root +} diff --git a/ui/anchor/anchor_test.go b/ui/anchor/anchor_test.go new file mode 100644 index 000000000..9c436552f --- /dev/null +++ b/ui/anchor/anchor_test.go @@ -0,0 +1,86 @@ +package anchor_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/anchor" +) + +var items = []anchor.Item{{Title: "Overview"}, {Title: "Install", Level: 0}, {Title: "From source", Level: 1}, {Title: "Usage"}} + +type model struct { + a *anchor.Anchor + active int + clicked []int +} + +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(16).Children(func() { + m.a.View(c, "On this page", anchor.Spec{Items: items, Active: m.active}) + if i, ok := m.a.Clicked(); ok { + m.clicked = append(m.clicked, i) + m.active = i + } + }) +} + +func TestClickReportsTheLink(t *testing.T) { + m := &model{a: anchor.New()} + page := ui.NewPage(ui.PageConfig{View: m.page}) + d, err := app.NewDriver(ui.Configure(page, app.Config{Width: 320, Height: 240, Invalidator: new(app.Invalidator)}), nil) + if err != nil { + t.Fatal(err) + } + defer d.Close() + for _, want := range []int{2, 0} { + var hit gfx.Hit + for _, h := range d.Snapshot().Hits { + if h.Label == items[want].Title && h.Role == gfx.RoleLink { + hit = h + } + } + if hit.ID.IsZero() { + t.Fatalf("no link %q", items[want].Title) + } + if err := d.Click(hit.Bounds.X+hit.Bounds.Width/2, hit.Bounds.Y+hit.Bounds.Height/2); err != nil { + t.Fatal(err) + } + } + if len(m.clicked) != 2 || m.clicked[0] != 2 || m.clicked[1] != 0 || m.active != 0 { + t.Fatalf("clicked %v, active %d", m.clicked, m.active) + } +} + +func warm() func() { + m := &model{a: anchor.New(), active: 1} + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: m.page, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + return func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 320, Height: 240}, m.page) + canvas.EndFrame() + } +} + +func TestWarmPaintDoesNotAllocate(t *testing.T) { + draw := warm() + draw() + if n := testing.AllocsPerRun(100, draw); n != 0 { + t.Fatalf("a warm paint allocates %v times", n) + } +} + +func BenchmarkViewPaint(b *testing.B) { + draw := warm() + draw() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + draw() + } +} diff --git a/ui/app_facade.go b/ui/app_facade.go index 8c16151c3..d0f4476b7 100644 --- a/ui/app_facade.go +++ b/ui/app_facade.go @@ -7,7 +7,7 @@ import ( ) // Configure returns base with the page's Tree, Paint, TextInput, OnScroll, -// OnKey, OnShortcut and OnPointer: +// OnKey, OnShortcut, OnPointer and OnFileDrop: // // - Tree: base's is adopted when the page was given none; a different one panics. // - Paint paints view over the whole window. @@ -17,6 +17,8 @@ import ( // what they leave to base's. // - OnKey, OnShortcut and OnPointer give a DragState its drag, a Shortcut its // chord and a Control its own events, then base's the rest. +// - OnFileDrop gives files dragged from the system to the FileDropState area +// under them, then base's when no area is there. // // Configure gives the page an Invalidator when neither PageConfig.Invalidator // nor base has one, for the page's Effects and, with FollowSystemTheme, the @@ -32,13 +34,21 @@ func Configure(page *Page, base app.Config) app.Config { panic("ui: Configure: the app.Config has another Tree than the page's; give NewPage the window's Tree") } config := base + if config.TextMenu == nil && !page.GetConfig().CanvasMenus { + // The system's menu for a text field, in the words the page keeps. + if config.TextMenu = page.GetConfig().EditMenu; config.TextMenu == nil { + config.TextMenu = new(gfx.TextMenuLabels) + } + } host := Host{ Tree: config.Tree, Paint: config.Paint, TextInput: config.TextInput, OnScroll: config.OnScroll, OnKey: config.OnKey, OnShortcut: config.OnShortcut, OnPointer: config.OnPointer, + OnFileDrop: config.OnFileDrop, } page.Attach(&host) config.Tree, config.Paint, config.TextInput = host.Tree, host.Paint, host.TextInput config.OnScroll, config.OnKey, config.OnShortcut, config.OnPointer = host.OnScroll, host.OnKey, host.OnShortcut, host.OnPointer + config.OnFileDrop = host.OnFileDrop concrete, _ := page.GetConfig().Invalidator.(*app.Invalidator) if concrete == nil { concrete = base.Invalidator @@ -78,6 +88,8 @@ func systemAppearance() window.Appearance { return app.SystemAppearance() } // in one call. page is what OpenWindow takes: its View declares what the window // shows, and its Theme, Styles and the rest configure the page. The config's // Tree, Paint, TextInput and OnScroll are the page's (see Configure). +// For a native macOS window, call runtime.LockOSThread in an init function in +// package main and run from main to satisfy AppKit's main-thread requirement. // // ui.Run(app.Config{Title: "Hosts", Width: 480, Height: 360}, ui.PageConfig{View: m.page}) func Run(config app.Config, page PageConfig) error { diff --git a/ui/breadcrumb/breadcrumb.go b/ui/breadcrumb/breadcrumb.go new file mode 100644 index 000000000..bbe0cc9bc --- /dev/null +++ b/ui/breadcrumb/breadcrumb.go @@ -0,0 +1,144 @@ +// Package breadcrumb is the opt-in page control for a breadcrumb: the path to +// where the user is, each place a link back, the last one the current place. A +// page keeps a Breadcrumb in its model, because a collapsed path opens a menu of +// the places it hides: +// +// m.path = breadcrumb.New() +// // in the page: +// m.path.View(c, "Location", breadcrumb.Spec{Items: m.places, Max: 4}) +// if i, ok := m.path.Clicked(); ok { +// m.goTo(i) +// } +// +// The items are in order from the root; every item but the last is a link, and +// the last is the current place and is not. Max, when above two, keeps the first +// place and the last Max-1 and puts the ones between behind an ellipsis that opens +// a menu: choosing a place there reports it as a click on that item. A Disabled +// item is shown but cannot be chosen. Separator is the word between places, "/" +// by default. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Breadcrumb in the model: its menu state is made once, so +// a warm paint allocates nothing. Do not copy a Breadcrumb after it has been +// declared. +package breadcrumb + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +var dotsIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(5, 12), gfx.LineTo(5.01, 12), gfx.MoveTo(12, 12), gfx.LineTo(12.01, 12), gfx.MoveTo(19, 12), gfx.LineTo(19.01, 12), +}} + +// Item is one place on the path. +type Item struct { + // Label names the place. + Label string + // Disabled shows the place but takes no press. + Disabled bool +} + +// Spec declares the path. +type Spec struct { + // Items are the places, from the root to where the user is. Keep the slice in + // the model: a slice made in each paint allocates in each paint. + Items []Item + // Max is how many places are shown before the ones in between collapse behind + // an ellipsis; zero, or any number below three, shows them all. + Max int + // Separator is the word between places; "/" when empty. + Separator string + // MoreLabel is the accessible name of the ellipsis, "More" when empty. + MoreLabel string +} + +// Breadcrumb is one path and the menu of the places it collapses. +type Breadcrumb struct { + open bool + clicked int // 1 + the item chosen in the paint being declared, or 0 +} + +// New returns a breadcrumb. +func New() *Breadcrumb { return &Breadcrumb{} } + +// Clicked reports which place the user chose in the paint just made, whether from +// the path or from the menu behind the ellipsis. +func (b *Breadcrumb) Clicked() (int, bool) { return b.clicked - 1, b.clicked > 0 } + +// View declares the path at c. label names it for assistive technology. The path +// is one line high. Declare the view on its own, not inside a Memo. +func (b *Breadcrumb) View(c ui.C, label string, spec Spec) ui.Box { + if b == nil { + panic("breadcrumb: View needs its Breadcrumb") + } + b.clicked = 0 + theme := c.Theme() + metrics := theme.Metrics + separator := spec.Separator + if separator == "" { + separator = "/" + } + more := spec.MoreLabel + if more == "" { + more = "More" + } + last := len(spec.Items) - 1 + // The places shown: all of them, or the first, an ellipsis and the last Max-1. + hideFrom, hideTo := 0, 0 + if spec.Max >= 3 && len(spec.Items) > spec.Max { + hideFrom, hideTo = 1, len(spec.Items)-(spec.Max-1) + } + root := ui.Row(c).Items(ui.Center).Gap(metrics.GapItem * 0.5) + root = root.HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true}) + root.Children(func() { + for i := range spec.Items { + if i >= hideFrom && i < hideTo { + if i == hideFrom { + b.ellipsis(c, spec, hideFrom, hideTo, more) + ui.Text(c, separator).Muted().Shrink(0) + } + continue + } + item := spec.Items[i] + text := ui.Text(c.KeyInt(i), item.Label).Shrink(0) + switch { + case i == last: + text.Weight(gfx.WeightMedium) + case item.Disabled: + text.Muted().Opacity(0.5) + default: + text.Muted() + text.HitWith(ui.ID(c), item.Label, gfx.HitOptions{Role: gfx.RoleLink}) + text.Hover(ui.Look{}.Color(theme.Foreground)) + if text.Clicked() { + b.clicked = i + 1 + } + } + if i != last { + ui.Text(c, separator).Muted().Shrink(0) + } + } + }) + return root +} + +// ellipsis declares the button for the hidden places and the menu that lists them. +func (b *Breadcrumb) ellipsis(c ui.C, spec Spec, from, to int, label string) { + trigger := ui.Button(c, label).Icon(dotsIcon).IconOnly().Ghost().Shrink(0) + if trigger.Clicked() { + b.open = !b.open + } + ui.Menu(c, trigger, &b.open, func(menu *ui.MenuItems) { + for i := from; i < to; i++ { + item := menu.Item(spec.Items[i].Label) + if spec.Items[i].Disabled { + item.Disabled(true) + } + if item.Clicked() { + b.clicked = i + 1 + } + } + }) +} diff --git a/ui/breadcrumb/breadcrumb_test.go b/ui/breadcrumb/breadcrumb_test.go new file mode 100644 index 000000000..e1e370a58 --- /dev/null +++ b/ui/breadcrumb/breadcrumb_test.go @@ -0,0 +1,135 @@ +//go:build !js + +package breadcrumb_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/breadcrumb" +) + +var places = []breadcrumb.Item{ + {Label: "Home"}, {Label: "Hosts"}, {Label: "Production"}, {Label: "build-01"}, {Label: "Logs"}, +} + +var chosen []int + +func open(t *testing.T, b *breadcrumb.Breadcrumb, spec breadcrumb.Spec) *headless.Session { + t.Helper() + chosen = nil + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + b.View(c, "Location", spec) + if i, ok := b.Clicked(); ok { + chosen = append(chosen, i) + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Path", Width: 640, Height: 200}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +// Every place but the last is a link that reports its index; the last is the +// current place and is not a control. +func TestLinksReportTheirIndexAndTheCurrentPlaceIsNotOne(t *testing.T) { + session := open(t, breadcrumb.New(), breadcrumb.Spec{Items: places}) + if err := session.ClickLabel("Hosts"); err != nil { + t.Fatal(err) + } + if len(chosen) != 1 || chosen[0] != 1 { + t.Fatalf("chosen = %v after a click on Hosts, want [1]", chosen) + } + if _, err := session.Locate("Logs"); err == nil { + t.Fatal("the current place is a control") + } + if err := session.Expect("text", "Logs"); err != nil { + t.Fatal(err) + } +} + +// A disabled place is shown and offers nothing to press. +func TestDisabledPlaceTakesNoPress(t *testing.T) { + items := []breadcrumb.Item{{Label: "Home"}, {Label: "Archive", Disabled: true}, {Label: "2025"}} + session := open(t, breadcrumb.New(), breadcrumb.Spec{Items: items}) + if _, err := session.Locate("Archive"); err == nil { + t.Fatal("a disabled place is a control") + } + if err := session.Expect("text", "Archive"); err != nil { + t.Fatal(err) + } +} + +// With Max the middle places collapse behind an ellipsis; choosing one in its +// menu reports that place's index in the whole path. +func TestCollapsedPlacesAreChosenFromTheMenu(t *testing.T) { + session := open(t, breadcrumb.New(), breadcrumb.Spec{Items: places, Max: 3}) + for _, hidden := range []string{"Hosts", "Production"} { + if _, err := session.Locate(hidden); err == nil { + t.Fatalf("%q is shown though it collapsed", hidden) + } + } + if err := session.ClickLabel("More"); err != nil { + t.Fatal(err) + } + if err := session.ClickLabel("Production"); err != nil { + t.Fatal(err) + } + if len(chosen) != 1 || chosen[0] != 2 { + t.Fatalf("chosen = %v after choosing Production in the menu, want [2]", chosen) + } + for _, shown := range []string{"Home", "build-01", "Logs"} { + if err := session.Expect("text", shown); err != nil { + t.Fatal(err) + } + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + for name, spec := range map[string]breadcrumb.Spec{ + "all": {Items: places}, + "collapsed": {Items: places, Max: 3, Separator: ">"}, + } { + t.Run(name, func(t *testing.T) { + b := breadcrumb.New() + view := func(c ui.C) { b.View(c, "Location", spec) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 640, Height: 200}, view) + canvas.EndFrame() + } + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } + }) + } +} + +func BenchmarkViewPaint(b *testing.B) { + path := breadcrumb.New() + view := func(c ui.C) { path.View(c, "Location", breadcrumb.Spec{Items: places, Max: 4}) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + b.ReportAllocs() + for range b.N { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 640, Height: 200}, view) + canvas.EndFrame() + } +} diff --git a/ui/bubble.go b/ui/bubble.go index 6d76de7cf..065069357 100644 --- a/ui/bubble.go +++ b/ui/bubble.go @@ -51,7 +51,7 @@ func Bubble(c C, text string, variant BubbleVariant) Box { fill.Alpha *= 2 } } - bubble := base.Column(c).MaxWidthPercent(80).Radius(theme.Metrics.RadiusSurface + 4) + bubble := base.Column(c).MaxWidthPercent(80).Radius(gfx.RadiusOutset(theme.Metrics.RadiusSurface, 4)) if variant != BubbleGhost { bubble = bubble.PadSides(padY, padX, padY, padX).Background(fill) } diff --git a/ui/button_loading_test.go b/ui/button_loading_test.go new file mode 100644 index 000000000..9d4107250 --- /dev/null +++ b/ui/button_loading_test.go @@ -0,0 +1,92 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/ui" +) + +// A busy button delivers no press, so work cannot be started twice, and is not +// dimmed as a Disabled one is. +func TestLoadingButtonDeliversNoPress(t *testing.T) { + loading, clicks := false, 0 + d := openPage(t, func(c ui.C) { + if ui.Button(c, "Connect").Loading(loading).Clicked() { + clicks++ + } + }) + d.click("Connect") + if clicks != 1 { + t.Fatalf("clicks = %d after a press on an idle button, want 1", clicks) + } + loading = true + d.repaint() + d.click("Connect") + if clicks != 1 { + t.Fatalf("clicks = %d after a press on a busy button, want it still 1", clicks) + } + if d.hit("Connect").Disabled { + t.Fatal("a busy button is announced as disabled") + } +} + +// The spinner stands in the icon's place, or before the label when there is no +// icon, so the busy button is wider than the idle one by an icon. +func TestLoadingButtonPaintsASpinnerAndHoldsRoomForIt(t *testing.T) { + width := func(loading bool) (float32, int) { + var box ui.Box + d := openPage(t, func(c ui.C) { box = ui.Button(c, "Connect").Loading(loading) }) + return box.Rect().Width, len(d.driver.Snapshot().Primitives) + } + idleWidth, idlePrimitives := width(false) + busyWidth, busyPrimitives := width(true) + if busyWidth <= idleWidth { + t.Fatalf("busy width %v is not above idle width %v", busyWidth, idleWidth) + } + if busyPrimitives <= idlePrimitives { + t.Fatalf("a busy button paints %d primitives, an idle one %d; want the spinner's spokes in addition", busyPrimitives, idlePrimitives) + } +} + +func TestLoadingButtonRepaintsWithoutAllocating(t *testing.T) { + d := openPage(t, func(c ui.C) { ui.Button(c, "Connect").Loading(true) }) + d.repaint() + d.repaint() + if allocs := testing.AllocsPerRun(100, d.repaint); allocs != 0 { + t.Fatalf("%v allocations a repaint", allocs) + } +} + +// A busy switch does not flip its bound value, keeps its look, and paints the +// spinner on its thumb. +func TestLoadingSwitchHoldsItsValueAndSpins(t *testing.T) { + on, loading := false, false + d := openPage(t, func(c ui.C) { ui.Switch(c, &on, "Forwarding").Loading(loading) }) + idle := len(d.driver.Snapshot().Primitives) + d.click("Forwarding") + if !on { + t.Fatal("an idle switch did not flip") + } + loading = true + d.repaint() + if busy := len(d.driver.Snapshot().Primitives); busy <= idle { + t.Fatalf("a busy switch paints %d primitives, an idle one %d; want the spinner's spokes in addition", busy, idle) + } + d.click("Forwarding") + if !on { + t.Fatal("a press on a busy switch flipped its value") + } + if d.hit("Forwarding").Disabled { + t.Fatal("a busy switch is announced as disabled") + } +} + +func TestLoadingSwitchRepaintsWithoutAllocating(t *testing.T) { + on := true + d := openPage(t, func(c ui.C) { ui.Switch(c, &on, "Forwarding").Loading(true) }) + d.repaint() + d.repaint() + if allocs := testing.AllocsPerRun(100, d.repaint); allocs != 0 { + t.Fatalf("%v allocations a repaint", allocs) + } +} diff --git a/ui/card/card.go b/ui/card/card.go new file mode 100644 index 000000000..75b3383f7 --- /dev/null +++ b/ui/card/card.go @@ -0,0 +1,109 @@ +// Package card is the opt-in page control for a card: a raised surface that +// groups what belongs together, with an optional header (a title, a description +// and something at its end), a body and an optional footer. A page declares it +// with a Spec and the body: +// +// card.View(c, card.Spec{ +// Title: "Native preview", +// Description: "Keeps scene nodes and repaints only when content changes.", +// Extra: func() { ui.Button(c, "Open").Outline().Small() }, +// }, func() { +// ui.Text(c, "0").FontSize(28).Bold() +// }).FillWidth() +// +// The body, Extra and Footer are page declarations, so what they hold keeps its +// own identity and handlers. HeaderBorder and FooterBorder draw a rule between a +// section and the body; Size: Small is the compact card; Flat leaves out the +// shadow. The body is the closure after the Spec, as for ui.Popover and ui.Modal. +// +// It is a separate package so an application that does not import it pays +// nothing for it, and it depends only on the public gfx and ui packages. +package card + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Size is how roomy the card is. +type Size uint8 + +const ( + // Default is the zero value. + Default Size = iota + // Small is the compact card. + Small +) + +// Spec declares one card. Its zero value is a card with no header or footer. +type Spec struct { + // Title and Description head the card; the header is not drawn when both are + // empty and there is no Extra. + Title, Description string + // Extra declares what sits at the end of the header, such as a button or a + // menu. It is not called when nil. + Extra func() + // Footer declares the card's last section. It is not called when nil. + Footer func() + // HeaderBorder draws a rule between the header and the body; FooterBorder one + // between the body and the footer. + HeaderBorder, FooterBorder bool + // Size is how roomy the card is. + Size Size + // Flat leaves out the shadow. + Flat bool +} + +// View declares the card at c with body as its content. The card is as tall as +// its sections; give it FillWidth or a Width. Declare the view on its own, not +// inside a Memo. +func View(c ui.C, spec Spec, body func()) ui.Box { + theme := c.Theme() + metrics := theme.Metrics + pad, gap := float32(24), float32(8) + if spec.Size == Small { + pad, gap = 16, 6 + } + rim := theme.Foreground + rim.Alpha *= 0.10 + box := ui.Column(c).Pad(pad).Gap(gap).Background(theme.Card).Border(1, rim).Radius(metrics.RadiusSurface + 4) + if !spec.Flat { + box = box.Shadow(gfx.ShadowXS) + } + box.Children(func() { + if spec.Title != "" || spec.Description != "" || spec.Extra != nil { + header(c, theme, spec) + if spec.HeaderBorder { + ui.Divider(c) + } + } + if body != nil { + body() + } + if spec.Footer != nil { + if spec.FooterBorder { + ui.Divider(c) + } + spec.Footer() + } + }) + return box +} + +// header declares the title and description with the Extra at their end. +func header(c ui.C, theme *gfx.Theme, spec Spec) { + metrics := theme.Metrics + ui.Row(c).FillWidth().Items(ui.Start).Gap(metrics.GapItem).Children(func() { + ui.Column(c).Grow(1).Basis(0).Gap(2).Children(func() { + if spec.Title != "" { + ui.Text(c, spec.Title).FontSize(metrics.FontSizeM + 2).Weight(gfx.WeightSemibold) + } + if spec.Description != "" { + ui.Wrap(c, spec.Description).FontSize(metrics.FontSizeS).Muted() + } + }) + if spec.Extra != nil { + spec.Extra() + } + }) +} diff --git a/ui/card/card_test.go b/ui/card/card_test.go new file mode 100644 index 000000000..5f18ee924 --- /dev/null +++ b/ui/card/card_test.go @@ -0,0 +1,119 @@ +package card_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/card" +) + +func measure(value string, size, weight float32) float32 { return float32(len(value)) * size * 0.55 } + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 480, Height: 320}, view) + canvas.EndFrame() +} + +func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { + t.Helper() + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetMeasurer(measure) + canvas.SetReduceMotion(true) + draw(page, canvas, view) + return page, canvas +} + +func textAt(canvas *gfx.Canvas, value string) (gfx.Text, bool) { + for _, text := range canvas.Texts() { + if text.Value == value { + return text, true + } + } + return gfx.Text{}, false +} + +// The sections are declared in order, each with the page's own content: header, +// body, then footer, and what Extra declares sits at the end of the header. +func TestSectionsRunDownAndExtraSitsAtTheHeaderEnd(t *testing.T) { + view := func(c ui.C) { + card.View(c, card.Spec{ + Title: "Preview", Description: "Keeps nodes.", + Extra: func() { ui.Text(c, "extra") }, + Footer: func() { ui.Text(c, "footer") }, + }, func() { ui.Text(c, "body") }).FillWidth() + } + _, canvas := open(t, view) + title, _ := textAt(canvas, "Preview") + extra, ok := textAt(canvas, "extra") + body, _ := textAt(canvas, "body") + footer, ok2 := textAt(canvas, "footer") + if !ok || !ok2 { + t.Fatal("the card did not paint its extra and footer") + } + if !(title.Bounds.Y < body.Bounds.Y && body.Bounds.Y < footer.Bounds.Y) { + t.Fatalf("sections are not in order: title %v, body %v, footer %v", title.Bounds.Y, body.Bounds.Y, footer.Bounds.Y) + } + if extra.Bounds.X <= title.Bounds.X+title.Bounds.Width { + t.Fatalf("extra at %v is not after the title ending %v", extra.Bounds.X, title.Bounds.X+title.Bounds.Width) + } +} + +// A card with no header text and no Extra has no header; the small card is +// tighter than the default one. +func TestHeaderIsOmittedAndSmallIsTighter(t *testing.T) { + height := func(spec card.Spec) float32 { + var box ui.Box + view := func(c ui.C) { box = card.View(c, spec, func() { ui.Text(c, "body") }).FillWidth() } + open(t, view) + return box.Rect().Height + } + plain, headed := height(card.Spec{}), height(card.Spec{Title: "Title"}) + if headed <= plain { + t.Fatalf("a card with a title is %v high, not above a card without one (%v)", headed, plain) + } + if small := height(card.Spec{Size: card.Small}); small >= plain { + t.Fatalf("a small card is %v high, want it tighter than the default %v", small, plain) + } +} + +// Flat leaves the shadow out. +func TestFlatHasNoShadow(t *testing.T) { + shadows := func(flat bool) int { + view := func(c ui.C) { card.View(c, card.Spec{Flat: flat}, func() { ui.Text(c, "body") }).FillWidth() } + _, canvas := open(t, view) + return len(canvas.Shadows()) + } + if shadows(false) == 0 || shadows(true) != 0 { + t.Fatalf("shadows: raised %d, flat %d; want some and none", shadows(false), shadows(true)) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + extra := func() {} + spec := card.Spec{Title: "Preview", Description: "Keeps nodes.", Extra: extra, Footer: extra, HeaderBorder: true, FooterBorder: true} + var c0 ui.C + body := func() { ui.Text(c0, "body") } + view := func(c ui.C) { c0 = c; card.View(c, spec, body).FillWidth() } + page, canvas := open(t, view) + if allocations := testing.AllocsPerRun(100, func() { draw(page, canvas, view) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + spec := card.Spec{Title: "Preview", Description: "Keeps nodes."} + var c0 ui.C + body := func() { ui.Text(c0, "body") } + view := func(c ui.C) { c0 = c; card.View(c, spec, body).FillWidth() } + page, canvas := open(b, view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, view) + } +} diff --git a/ui/color_test.go b/ui/color_test.go index b43519961..105bc0a32 100644 --- a/ui/color_test.go +++ b/ui/color_test.go @@ -120,7 +120,7 @@ func TestColorPickerDraftFollowsTheDragBeforeApply(t *testing.T) { } } -// ColorPickerID names the trigger with the application's identity, so a row's +// A ColorPicker given WithID names the trigger with the application's identity, so a row's // words can be its label: clicking them opens the panel. func TestColorPickerKeepsTheApplicationID(t *testing.T) { var state ui.ColorPickerState @@ -133,7 +133,7 @@ func TestColorPickerKeepsTheApplicationID(t *testing.T) { ui.Row(c).Children(func() { words := ui.Text(c, "Accent").LabelFor(id) _ = words - ui.ColorPickerID(c, id, &state, &color, "Accent") + ui.ColorPicker(c, &state, &color, "Accent", ui.WithID(id)) }) }) var trigger gfx.Rect diff --git a/ui/comment/comment.go b/ui/comment/comment.go new file mode 100644 index 000000000..aba9848d5 --- /dev/null +++ b/ui/comment/comment.go @@ -0,0 +1,93 @@ +// Package comment is the opt-in page layout for one comment in a discussion: the +// author's avatar, the author and the time, the text, a row of actions and the +// replies nested under it. A page declares each comment with a Spec, and the +// replies by declaring comments inside Replies: +// +// comment.View(c, comment.Spec{ +// Avatar: &m.avatars[i], Author: post.Author, Time: post.When, Content: post.Text, +// Actions: func() { +// if ui.Button(c, "Reply").Ghost().Small().Clicked() { +// m.replyTo = i +// } +// }, +// Replies: func() { m.replies(c, post) }, +// }).FillWidth() +// +// The control keeps no state: the actions are the page's own buttons, so it +// reads their clicks where it declares them, and the replies are comments the +// page declares in turn, so a thread of any depth is one function calling +// itself. The avatar is an avatar.State the page keeps beside the comment's +// data, configured for the author; a nil Avatar leaves the column out. +// +// It is a separate package so an application that does not import it pays +// nothing for it. A warm paint allocates nothing beyond the closures the page +// passes. +package comment + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/avatar" +) + +// avatarSize is the diameter of the author's avatar. +const avatarSize = 32 + +// Spec declares one comment. +type Spec struct { + // Avatar is the author's avatar; nil draws none. + Avatar *avatar.State + // Author and Time head the comment, the time muted after the author. Either + // may be empty. + Author, Time string + // Content is the comment's text, wrapped to the room it has. + Content string + // Actions declares the buttons under the text, as small ghost buttons in a + // row; nil draws none. + Actions func() + // Replies declares the comments nested under this one, indented to the text's + // column; nil draws none. + Replies func() +} + +// View declares the comment at c. The comment is as wide as the room it is +// given and as tall as its content; give it FillWidth. Declare it on its own, +// not inside a Memo; key the comments of a list with c.Key so each keeps its +// own state. +func View(c ui.C, spec Spec) ui.Box { + theme := c.Theme() + metrics := theme.Metrics + root := ui.Row(c).Items(ui.Start).Gap(metrics.GapItem) + root.Children(func() { + if spec.Avatar != nil { + label := spec.Author + if label == "" { + label = "Avatar" + } + spec.Avatar.Diameter(avatarSize) + spec.Avatar.View(c, label).Size(avatarSize, avatarSize).Shrink(0) + } + ui.Column(c).Grow(1).Basis(0).Gap(4).Children(func() { + if spec.Author != "" || spec.Time != "" { + ui.Row(c).Items(ui.Center).Gap(metrics.GapItem).Children(func() { + if spec.Author != "" { + ui.Text(c, spec.Author).Weight(gfx.WeightMedium).Ellipsis().Shrink(1) + } + if spec.Time != "" { + ui.Text(c, spec.Time).FontSize(metrics.FontSizeS).Muted().Shrink(0) + } + }) + } + if spec.Content != "" { + ui.Wrap(c, spec.Content).FillWidth() + } + if spec.Actions != nil { + ui.Row(c).Items(ui.Center).Gap(metrics.GapItem * 0.5).Children(spec.Actions) + } + if spec.Replies != nil { + ui.Column(c).FillWidth().Gap(metrics.GapItem).MarginSides(metrics.GapItem, 0, 0, 0).Children(spec.Replies) + } + }) + }) + return root +} diff --git a/ui/comment/comment_test.go b/ui/comment/comment_test.go new file mode 100644 index 000000000..5ff44ffc1 --- /dev/null +++ b/ui/comment/comment_test.go @@ -0,0 +1,92 @@ +package comment_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/avatar" + "github.com/vivaui/viva/ui/comment" +) + +type model struct { + avatars [2]*avatar.State + replied int + view func(ui.C) + actions [2]func() + reply func() + top func(ui.C) +} + +func newModel() *model { + m := &model{} + for i := range m.avatars { + m.avatars[i] = avatar.New().Initials("AB") + } + var c ui.C + m.actions[0] = func() { + if ui.Button(c, "Reply").Ghost().Small().Clicked() { + m.replied++ + } + } + m.reply = func() { + comment.View(c, comment.Spec{Avatar: m.avatars[1], Author: "Grace", Time: "1h", Content: "Agreed.", Actions: m.actions[1]}).FillWidth() + } + m.actions[1] = func() {} + m.view = func(cc ui.C) { + c = cc + ui.Column(c).Fill().Pad(16).Children(func() { + comment.View(c, comment.Spec{Avatar: m.avatars[0], Author: "Ada", Time: "2h ago", Content: "A longer comment that wraps over more than one line when the column is narrow enough.", Actions: m.actions[0], Replies: m.reply}).FillWidth() + }) + } + return m +} + +func TestActionsAndRepliesAreDeclared(t *testing.T) { + m := newModel() + page := ui.NewPage(ui.PageConfig{View: m.view}) + d, err := app.NewDriver(ui.Configure(page, app.Config{Width: 320, Height: 320, Invalidator: new(app.Invalidator)}), nil) + if err != nil { + t.Fatal(err) + } + defer d.Close() + seen := map[string]bool{} + for _, text := range d.Snapshot().Texts { + seen[text.Value] = true + } + for _, want := range []string{"Ada", "2h ago", "Grace", "Agreed."} { + if !seen[want] { + t.Errorf("%q is not painted", want) + } + } + for _, h := range d.Snapshot().Hits { + if h.Label == "Reply" && !h.IsLabel { + if err := d.Click(h.Bounds.X+h.Bounds.Width/2, h.Bounds.Y+h.Bounds.Height/2); err != nil { + t.Fatal(err) + } + break + } + } + if m.replied != 1 { + t.Fatalf("the action was pressed %d times, want 1", m.replied) + } +} + +func TestWarmPaintDoesNotAllocate(t *testing.T) { + m := newModel() + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: m.view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 320, Height: 320}, m.view) + canvas.EndFrame() + } + draw() + if n := testing.AllocsPerRun(100, draw); n != 0 { + t.Fatalf("a warm paint allocates %v times", n) + } +} diff --git a/ui/controls_paint.go b/ui/controls_paint.go index 5eda8b44e..539e29ce8 100644 --- a/ui/controls_paint.go +++ b/ui/controls_paint.go @@ -173,7 +173,13 @@ func paintSwitch(f *Frame, v ControlView, n *Node) { if disabled { control = control.Disabled() } - control.Paint() + result := control.Paint() + if n.Loading && result.Thumb.Width > 0 { + spinner := f.Palette + spinner.Foreground = f.Palette.MutedForeground + size := result.Thumb.Width * 0.75 + components.PaintSpinner(canvas, spinner, Rect{X: result.Thumb.X + (result.Thumb.Width-size)/2, Y: result.Thumb.Y + (result.Thumb.Height-size)/2, Width: size, Height: size}, components.SpinnerPhase(buttonSpinnerPhase(f, n))) + } } func paintInputGroup(f *Frame, v ControlView) { @@ -339,7 +345,7 @@ func measureTextareaNode(f *Frame, n *Node) { // paint records and then asks for before it is shown. if layout := snapshot.Layout; layout != nil { if width := layout.BoxWidth(); width > 0 { - height := layout.ContentHeight(f.Surface, f.Palette, snapshot.LayoutText(), width, snapshot.NoWrap) + height := layout.ContentHeightUpTo(f.Surface, f.Palette, snapshot.LayoutText(), width, snapshot.NoWrap, int(n.MaxLines)) maxHeight := float32(n.MaxLines)*line + 2*base.TextareaPadY n.Pref[AxisY] = max(64, min(height, maxHeight)) } @@ -352,6 +358,9 @@ func measureWidgetNode(f *Frame, n *Node) { f.MeasureWidget(n) } func measureProgressNode(f *Frame, n *Node) { n.Pref = [2]float32{ProgressWidth, ProgressHeight} + if n.Circle { + n.Pref = [2]float32{ProgressRing, ProgressRing} + } } func measureSpinnerNode(f *Frame, n *Node) { n.Pref = [2]float32{16, 16} } @@ -386,7 +395,7 @@ func measureButton(f *Frame, n *Node) [2]float32 { return [2]float32{height, height} // an icon button is as wide as it is tall } width := n.PadX() + f.Surface.TextWidthWeight(n.Label, fontSize, buttonWeight(n)) - if icon := f.Exts[n.Ext].GetIcon(); len(icon.Commands) > 0 || len(icon.Layers) > 0 { + if icon := f.Exts[n.Ext].GetIcon(); len(icon.Commands) > 0 || len(icon.Layers) > 0 || n.Loading { width += style.ButtonIconExtent(height) if n.Label != "" { width += n.Gap @@ -428,7 +437,7 @@ func paintButton(f *Frame, n *Node) { area := buttonContentArea(f, n) room := f.ContentRect(n) need := f.Surface.TextWidthWeight(n.Label, fontSize, buttonWeight(n)) - if icon := extra.GetIcon(); len(icon.Commands) != 0 || len(icon.Layers) != 0 { + if icon := extra.GetIcon(); len(icon.Commands) != 0 || len(icon.Layers) != 0 || n.Loading { need += style.ButtonIconExtent(n.Rect.Height) if n.Label != "" { need += n.Gap @@ -442,9 +451,38 @@ func paintButton(f *Frame, n *Node) { Label: n.Label, Icon: extra.GetIcon(), IconTransform: extra.GetIconTransform(), FontSize: fontSize, Weight: buttonWeight(n), Color: n.Color, Gap: n.Gap, Height: n.Rect.Height, IconOnly: iconOnly, Underlined: f.GetButtonLook().Underlined, + PaintLoading: buttonLoading(n), Phase: buttonSpinnerPhase(f, n), Theme: &f.Palette, }) } +// buttonSpinnerPhase is the frame of the indicator of a busy button: it turns while the +// button is on screen and holds still when the system asks for reduced motion. +func buttonSpinnerPhase(f *Frame, n *Node) uint8 { + if !n.Loading || f.Surface.ReduceMotion() { + return 0 + } + if f.Visible(n) { + f.Surface.RequestFrameIn(SpinnerStep) + } + return uint8(f.Surface.Now() / SpinnerStep % 8) +} + +// buttonLoading is the painter of a busy button's indicator, nil for an idle one. +func buttonLoading(n *Node) components.ButtonLoadingPainter { + if !n.Loading { + return nil + } + return paintButtonSpinner +} + +// paintButtonSpinner is the Spinner of package components, in the color of the button's +// label. +func paintButtonSpinner(canvas *gfx.Canvas, theme *gfx.Theme, bounds gfx.Rect, color gfx.Color, phase uint8) { + spinner := *theme + spinner.Foreground = color + components.PaintSpinner(canvas, spinner, bounds, components.SpinnerPhase(phase)) +} + func paintInput(f *Frame, n *Node) { // What the element says of its text (FontSize, Weight, Color) is the field's text style, // over the snapshot's own: the one value the glyphs, the caret and the platform follow. diff --git a/ui/datepicker/datepicker.go b/ui/datepicker/datepicker.go new file mode 100644 index 000000000..c6c15ae8e --- /dev/null +++ b/ui/datepicker/datepicker.go @@ -0,0 +1,406 @@ +// Package datepicker is the opt-in page control for choosing a date: a button +// that shows the date and opens a month to choose it from. A page keeps a +// DatePicker in its model beside the date it edits: +// +// m.due = datepicker.New().Placeholder("Pick a date") +// // in the page: +// m.due.View(c, "Due date", &m.dueDate).Width(220) +// if m.due.Changed() { +// // the user chose a date; m.dueDate holds it +// } +// +// The date is a time.Time at midnight in its own location; the zero time is no +// date. A date the page sets with a time of day is brought back to midnight. +// The month opens at the chosen date, or at today when there is none. Arrow +// keys move by a day or a week, PageUp and PageDown by a month, Home and End to +// the start and end of the week, and Enter or Space chooses the day; Escape +// closes the month. Min and Max limit the dates that can be chosen, and a day +// outside them is dimmed. +// +// The words of the month are English by default; Labels gives another +// language's, and Layout is the time.Format layout the date is shown in. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a DatePicker in the model: its handlers and draw function +// are made once, so a warm paint allocates nothing. Do not copy a DatePicker +// after it has been declared. +package datepicker + +import ( + "strconv" + "time" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Labels are the words of the month and of its buttons. +type Labels struct { + // Months are the names of the months, January first. + Months [12]string + // Weekdays are the short names of the days of the week, Sunday first. + Weekdays [7]string + // Previous and Next name the buttons that move to the month before and after. + Previous, Next string +} + +// English is the default words. +var English = Labels{ + Months: [12]string{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}, + Weekdays: [7]string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"}, + Previous: "Previous month", Next: "Next month", +} + +var ( + calendarIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(8, 2), gfx.LineTo(8, 6), gfx.MoveTo(16, 2), gfx.LineTo(16, 6), + gfx.MoveTo(5, 4), gfx.LineTo(19, 4), gfx.QuadTo(21, 4, 21, 6), gfx.LineTo(21, 20), gfx.QuadTo(21, 22, 19, 22), + gfx.LineTo(5, 22), gfx.QuadTo(3, 22, 3, 20), gfx.LineTo(3, 6), gfx.QuadTo(3, 4, 5, 4), + gfx.MoveTo(3, 10), gfx.LineTo(21, 10), + }} + previousIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(15, 18), gfx.LineTo(9, 12), gfx.LineTo(15, 6), + }} + nextIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(9, 18), gfx.LineTo(15, 12), gfx.LineTo(9, 6), + }} +) + +// numbers are the words of the days of a month, made once. +var numbers [32]string + +func init() { + for i := range numbers { + numbers[i] = strconv.Itoa(i) + } +} + +const ( + cell = 36 // the width and height of a day + weeks = 6 // the lines of the grid + padding = 12 // the room around the month inside its panel + panel = 7*cell + 2*padding +) + +// DatePicker is one date field and its month. Configure it with the chainable +// methods; they may be called before each View. +type DatePicker struct { + handlers ui.Handlers + drawFn func(*ui.DrawContext) + + placeholder string + layout string + labels Labels + min, max time.Time + first time.Weekday + now func() time.Time + + value *time.Time + open bool + cursor time.Time // the day the keyboard rests on; its month is the one shown + + focusOnOpen bool + changed bool + reported bool + + // What the trigger and the title say, made when the date or the month changes. + shownDate time.Time + shownText string + titleMonth time.Time + titleText string +} + +// New returns a date field of English words that shows a date as 2006-01-02. +func New() *DatePicker { + d := &DatePicker{layout: "2006-01-02", labels: English, now: time.Now} + d.handlers.Key = d.key + d.handlers.Pointer = d.pointer + d.drawFn = d.draw + return d +} + +// Placeholder is the text shown while there is no date. +func (d *DatePicker) Placeholder(text string) *DatePicker { + d.placeholder = text + return d +} + +// Layout is the time.Format layout the date is shown in; 2006-01-02 by default. +func (d *DatePicker) Layout(layout string) *DatePicker { + d.layout, d.shownText = layout, "" + return d +} + +// Labels gives the words of the month and its buttons in another language. +func (d *DatePicker) Labels(labels Labels) *DatePicker { + d.labels, d.titleText, d.shownText = labels, "", "" + return d +} + +// Min is the earliest date that can be chosen; the zero time sets none. +func (d *DatePicker) Min(min time.Time) *DatePicker { + d.min = day(min) + return d +} + +// Max is the latest date that can be chosen; the zero time sets none. +func (d *DatePicker) Max(max time.Time) *DatePicker { + d.max = day(max) + return d +} + +// FirstWeekday is the day the weeks of the month start on; Sunday by default. +func (d *DatePicker) FirstWeekday(weekday time.Weekday) *DatePicker { + d.first = weekday + return d +} + +// Clock gives the time that decides which day is today, instead of the system's, +// for a test or a page that runs on its own clock. +func (d *DatePicker) Clock(now func() time.Time) *DatePicker { + if now != nil { + d.now = now + } + return d +} + +// Changed reports whether the user chose a new date in the paint that +// delivered it. +func (d *DatePicker) Changed() bool { return d.reported } + +// day is t at midnight of its own day and location; the zero time stays zero. +func day(t time.Time) time.Time { + if t.IsZero() { + return t + } + return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) +} + +func (d *DatePicker) allowed(t time.Time) bool { + return (d.min.IsZero() || !t.Before(d.min)) && (d.max.IsZero() || !t.After(d.max)) +} + +// clamp is t brought into the range that can be chosen. +func (d *DatePicker) clamp(t time.Time) time.Time { + if !d.min.IsZero() && t.Before(d.min) { + return d.min + } + if !d.max.IsZero() && t.After(d.max) { + return d.max + } + return t +} + +// monthStart is the first day of the month of t. +func monthStart(t time.Time) time.Time { + return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location()) +} + +// gridStart is the first day of the grid that shows the month of t: the start of +// the week the month begins in. +func (d *DatePicker) gridStart(t time.Time) time.Time { + first := monthStart(t) + back := (int(first.Weekday()) - int(d.first) + 7) % 7 + return first.AddDate(0, 0, -back) +} + +// index is where day t is in the grid of the month of the cursor. +func (d *DatePicker) index(t time.Time) int { + start := d.gridStart(d.cursor) + return int(day(t).Sub(start).Hours()/24 + 0.5) +} + +// move puts the cursor on t, within the dates that can be chosen. +func (d *DatePicker) move(t time.Time) { + d.cursor = d.clamp(day(t)) +} + +// shiftMonth moves the cursor by months, keeping its day of the month where the +// month is long enough. +func (d *DatePicker) shiftMonth(months int) { + target := monthStart(d.cursor).AddDate(0, months, 0) + last := monthStart(target).AddDate(0, 1, -1).Day() + d.move(time.Date(target.Year(), target.Month(), min(d.cursor.Day(), last), 0, 0, 0, 0, target.Location())) +} + +// choose makes t the chosen date and closes the month. +func (d *DatePicker) choose(t time.Time) { + t = day(t) + if !d.allowed(t) { + return + } + if !t.Equal(*d.value) { + *d.value, d.changed = t, true + } + d.open = false +} + +func (d *DatePicker) pointer(event gfx.PointerEvent) gfx.EventResult { + if d.value == nil || event.Kind != gfx.PointerDown || event.Button != gfx.PointerButtonPrimary { + return gfx.EventResult{} + } + i, ok := event.Target.In(d.handlers.Parts()) + if !ok { + return gfx.EventResult{} + } + t := d.gridStart(d.cursor).AddDate(0, 0, i) + if !d.allowed(t) { + return gfx.EventResult{Handled: true} + } + d.choose(t) + return gfx.EventResult{Handled: true, Repaint: true} +} + +func (d *DatePicker) key(event gfx.KeyEvent) gfx.EventResult { + if d.value == nil || event.Text != "" { + return gfx.EventResult{} + } + switch event.Key { + case gfx.KeyLeft: + d.move(d.cursor.AddDate(0, 0, -1)) + case gfx.KeyRight: + d.move(d.cursor.AddDate(0, 0, 1)) + case gfx.KeyUp: + d.move(d.cursor.AddDate(0, 0, -7)) + case gfx.KeyDown: + d.move(d.cursor.AddDate(0, 0, 7)) + case gfx.KeyPageUp: + d.shiftMonth(-1) + case gfx.KeyPageDown: + d.shiftMonth(1) + case gfx.KeyHome: + d.move(d.cursor.AddDate(0, 0, -((int(d.cursor.Weekday()) - int(d.first) + 7) % 7))) + case gfx.KeyEnd: + d.move(d.cursor.AddDate(0, 0, 6-((int(d.cursor.Weekday())-int(d.first)+7)%7))) + case gfx.KeyEnter, gfx.KeySpace: + d.choose(d.cursor) + return gfx.EventResult{Handled: true, Repaint: true} + default: + return gfx.EventResult{} + } + return gfx.EventResult{Handled: true, Repaint: true, Focus: d.handlers.Parts().At(d.index(d.cursor)), FocusVisible: true} +} + +// View declares the field at c, showing and editing *value. label names it for +// assistive technology. The button is one control high; give it a Width. Declare +// the view on its own, not inside a Memo. +func (d *DatePicker) View(c ui.C, label string, value *time.Time) ui.Box { + if d == nil { + panic("datepicker: View needs its DatePicker") + } + if value == nil { + panic("datepicker: View needs the date") + } + d.reported, d.changed = d.changed, false + d.value = value + *value = day(*value) + if !value.Equal(d.shownDate) || d.shownText == "" { + d.shownDate = *value + d.shownText = d.placeholder + if !value.IsZero() { + d.shownText = value.Format(d.layout) + } + } + trigger := ui.Button(c, d.shownText).Outline().Icon(calendarIcon) + if value.IsZero() { + trigger.Muted() + } + if trigger.Clicked() { + d.open = !d.open + if d.open { + d.cursor = d.clamp(day(d.now())) + if !value.IsZero() { + d.cursor = *value + } + d.focusOnOpen = true + } + } + ui.Popover(c, trigger, &d.open, ui.PopoverSpec{Align: ui.Start, Padding: padding, Width: panel}, func() { + d.month(c, label) + }) + return trigger +} + +// month declares the header, the days of the week and the days of the month. +func (d *DatePicker) month(c ui.C, label string) { + if !monthStart(d.cursor).Equal(d.titleMonth) || d.titleText == "" { + d.titleMonth = monthStart(d.cursor) + d.titleText = d.labels.Months[d.cursor.Month()-1] + " " + strconv.Itoa(d.cursor.Year()) + } + ui.Column(c).Gap(4).Children(func() { + ui.Row(c).Items(ui.Center).Children(func() { + previous := ui.Button(c, d.labels.Previous).Icon(previousIcon).IconOnly().Ghost() + ui.Text(c, d.titleText).Grow(1).TextCenter().Weight(gfx.WeightMedium) + next := ui.Button(c, d.labels.Next).Icon(nextIcon).IconOnly().Ghost() + if previous.Clicked() { + d.shiftMonth(-1) + } + if next.Clicked() { + d.shiftMonth(1) + } + }) + ui.Row(c).Children(func() { + for i := range 7 { + name := d.labels.Weekdays[(int(d.first)+i)%7] + ui.Row(c).Size(cell, cell*2/3).Shrink(0).Center().Children(func() { + ui.Text(c, name).Muted().FontSize(c.Theme().Metrics.FontSizeS) + }) + } + }) + ui.Control(c, label, &d.handlers).Size(7*cell, weeks*cell).Shrink(0).Draw(d.drawFn) + }) +} + +// draw paints the days of the month and declares each as a part of the control. +func (d *DatePicker) draw(dc *ui.DrawContext) { + if d.value == nil { + return + } + canvas, theme := dc.Canvas, dc.Theme + parts := d.handlers.Parts() + start := d.gridStart(d.cursor) + today := day(d.now()) + cursor := d.index(d.cursor) + if d.focusOnOpen { + d.focusOnOpen = false + canvas.RequestFocus(parts.At(cursor)) + } + size := theme.Metrics.FontSizeM + for i := range 7 * weeks { + date := start.AddDate(0, 0, i) + bounds := gfx.Rect{X: dc.Rect.X + float32(i%7)*cell, Y: dc.Rect.Y + float32(i/7)*cell, Width: cell, Height: cell} + inner := gfx.Rect{X: bounds.X + 2, Y: bounds.Y + 2, Width: cell - 4, Height: cell - 4} + allowed := d.allowed(date) + chosen := date.Equal(*d.value) + hovered := allowed && canvas.Hovered() == parts.At(i) + ink := theme.Foreground + switch { + case chosen: + canvas.Rounded(inner, theme.Metrics.RadiusControl, theme.Primary) + ink = theme.PrimaryForeground + case hovered: + canvas.Rounded(inner, theme.Metrics.RadiusControl, theme.Hover) + case date.Equal(today): + canvas.RoundedBorder(inner, theme.Metrics.RadiusControl, 1, theme.Border, gfx.Color{}) + } + if date.Month() != d.cursor.Month() && !chosen { + ink = theme.MutedForeground + } + if !allowed { + ink = theme.MutedForeground + ink.Alpha *= 0.5 + } + canvas.LabelCenter(numbers[date.Day()], bounds, gfx.TextStyle{Size: size, Weight: gfx.WeightRegular, Color: ink}) + if canvas.FocusVisible() == parts.At(i) { + ring(canvas, theme, inner) + } + canvas.HitWithOptions(parts.At(i), bounds, numbers[date.Day()], gfx.HitOptions{ + Role: gfx.RoleButton, Disabled: !allowed, Selected: chosen, SkipFocus: i != cursor, SkipTab: i != cursor, + }) + } +} + +// ring paints the focus ring around a day. +func ring(canvas *gfx.Canvas, theme *gfx.Theme, b gfx.Rect) { + canvas.RoundedBorder(b, theme.Metrics.RadiusControl, 2, theme.Ring, gfx.Color{}) +} diff --git a/ui/datepicker/datepicker_test.go b/ui/datepicker/datepicker_test.go new file mode 100644 index 000000000..e6762bdda --- /dev/null +++ b/ui/datepicker/datepicker_test.go @@ -0,0 +1,196 @@ +//go:build !js + +package datepicker_test + +import ( + "testing" + "time" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/datepicker" +) + +func date(y int, m time.Month, d int) time.Time { return time.Date(y, m, d, 0, 0, 0, 0, time.Local) } + +var today = func() time.Time { return time.Date(2026, 11, 25, 15, 30, 0, 0, time.Local) } + +// changes counts the paints that reported a change, as a page reads Changed. +var changes int + +// open runs a page holding one date field over *value, headlessly. +func open(t *testing.T, d *datepicker.DatePicker, value *time.Time) *headless.Session { + t.Helper() + changes = 0 + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + d.View(c, "Due", value).Width(220) + if d.Changed() { + changes++ + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Date", Width: 420, Height: 460}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +// A click on a day chooses it and closes the month. +func TestClickingADayChoosesIt(t *testing.T) { + value := date(2026, 11, 18) + session := open(t, datepicker.New().Clock(today), &value) + if err := session.ClickLabel("2026-11-18"); err != nil { + t.Fatal(err) + } + if err := session.ClickLabel("button:24"); err != nil { + t.Fatal(err) + } + if !value.Equal(date(2026, 11, 24)) { + t.Fatalf("value = %v after a click on the 24th, want 2026-11-24", value) + } + if changes != 1 { + t.Fatalf("Changed was reported in %d paints, want 1", changes) + } + if _, err := session.Locate("Next month"); err == nil { + t.Fatal("the month stayed open after a day was chosen") + } +} + +// The month opens on the chosen date, and the arrow keys move from there: a day +// at a time, a week at a time, and Enter chooses the day the cursor rests on. +func TestKeysMoveThroughTheMonth(t *testing.T) { + value := date(2026, 11, 18) + session := open(t, datepicker.New().Clock(today), &value) + if err := session.ClickLabel("2026-11-18"); err != nil { + t.Fatal(err) + } + for _, key := range []string{"right", "right", "down"} { + if err := session.Keys(key); err != nil { + t.Fatal(err) + } + } + if err := session.Keys("enter"); err != nil { + t.Fatal(err) + } + if !value.Equal(date(2026, 11, 27)) { + t.Fatalf("value = %v after Right, Right, Down and Enter from the 18th, want 2026-11-27", value) + } +} + +// PageUp and PageDown move by a month and keep the day where the month is long +// enough, and the end of a short month otherwise. +func TestPagesMoveByAMonth(t *testing.T) { + value := date(2026, 3, 31) + session := open(t, datepicker.New().Clock(today), &value) + if err := session.ClickLabel("2026-03-31"); err != nil { + t.Fatal(err) + } + if err := session.Keys("pageup"); err != nil { + t.Fatal(err) + } + if err := session.Keys("enter"); err != nil { + t.Fatal(err) + } + if !value.Equal(date(2026, 2, 28)) { + t.Fatalf("value = %v after PageUp from March 31, want 2026-02-28", value) + } +} + +// A day outside Min and Max cannot be chosen: the click does nothing and the +// month stays open. +func TestDaysOutsideTheRangeCannotBeChosen(t *testing.T) { + value := date(2026, 11, 18) + session := open(t, datepicker.New().Clock(today).Min(date(2026, 11, 5)).Max(date(2026, 11, 28)), &value) + if err := session.ClickLabel("2026-11-18"); err != nil { + t.Fatal(err) + } + session.ClickLabel("button:3") + session.ClickLabel("button:29") + if !value.Equal(date(2026, 11, 18)) { + t.Fatalf("value = %v after a click on a day out of the range, want it kept", value) + } + if err := session.ClickLabel("button:28"); err != nil { + t.Fatal(err) + } + if !value.Equal(date(2026, 11, 28)) { + t.Fatalf("value = %v after a click on the last day of the range, want 2026-11-28", value) + } +} + +// The month opens on today when there is no date, and a date with a time of day +// is brought back to midnight. +func TestTodayOpensTheMonthAndDatesAreMidnight(t *testing.T) { + var value time.Time + session := open(t, datepicker.New().Clock(today).Placeholder("Pick a date"), &value) + if err := session.ClickLabel("Pick a date"); err != nil { + t.Fatal(err) + } + if err := session.Keys("enter"); err != nil { + t.Fatal(err) + } + if !value.Equal(date(2026, 11, 25)) { + t.Fatalf("value = %v after Enter on a fresh month, want today 2026-11-25", value) + } + + late := time.Date(2026, 11, 18, 23, 59, 0, 0, time.Local) + open(t, datepicker.New().Clock(today), &late) + if !late.Equal(date(2026, 11, 18)) { + t.Fatalf("a date with a time of day became %v, want midnight", late) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + value := date(2026, 11, 18) + d := datepicker.New().Clock(today) + view := func(c ui.C) { d.View(c, "Due", &value).Width(220) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 420, Height: 460}, view) + canvas.EndFrame() + } + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +// An open month repaints without allocating too: the numbers and the title are +// made once, and the days are values. +func TestOpenMonthAllocatesNothing(t *testing.T) { + value := date(2026, 11, 18) + session := open(t, datepicker.New().Clock(today), &value) + if err := session.ClickLabel("2026-11-18"); err != nil { + t.Fatal(err) + } + session.Frame() + if allocations := testing.AllocsPerRun(50, func() { session.Frame() }); allocations != 0 { + t.Fatalf("an open month allocated %v times a frame, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + value := date(2026, 11, 18) + d := datepicker.New().Clock(today) + view := func(c ui.C) { d.View(c, "Due", &value).Width(220) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + b.ReportAllocs() + for range b.N { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 420, Height: 460}, view) + canvas.EndFrame() + } +} diff --git a/ui/descriptions/descriptions.go b/ui/descriptions/descriptions.go new file mode 100644 index 000000000..318a5599d --- /dev/null +++ b/ui/descriptions/descriptions.go @@ -0,0 +1,240 @@ +// Package descriptions is the opt-in page control for a list of labelled +// values: the details of a record, laid out in columns. A page keeps the items +// in its model and declares the list with a Spec: +// +// descriptions.View(c, "Host details", descriptions.Spec{ +// Title: "Host details", +// Items: m.details, // a []descriptions.Item kept in the model +// Columns: 2, +// Bordered: true, +// }).FillWidth() +// +// An item has a Label and a Value, and a Span of the columns it takes, one by +// default. The items fill the lines in order; the last item of a line takes +// the columns the line has left, so a line is always full. A Value is text, or +// Content declares the page's own elements, such as a badge. +// +// By default a label is a muted word before its value. Bordered draws the list +// as a table, Vertical puts each label above its value, and Size: Small is the +// compact list. LabelWidth gives every label the same width, so the values line +// up down the list. It composes the page's own primitives, so it takes the +// page's theme and density. +// +// It is a separate package so an application that does not import it pays +// nothing for it, and it depends only on the public gfx and ui packages. +package descriptions + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Size is how large the text and the padding are. +type Size uint8 + +const ( + // Default is the zero value. + Default Size = iota + // Small is the compact list. + Small +) + +// Item is one labelled value. +type Item struct { + // Label names the value. + Label string + // Value is the value, as text. + Value string + // Content declares the value with the page's own elements instead of Value. + // Its elements are the caller's: they take their own identities and + // handlers. It is not called when nil. + Content func(ui.C) + // Span is how many columns the item takes; one when zero or less. A span + // wider than the list is the whole line. + Span int +} + +// Spec declares the list. Its zero value is a three-column, borderless list. +type Spec struct { + // Title heads the list. It is not drawn when empty. + Title string + // Items are the labelled values, in order. Keep the slice in the model: a + // slice made in each paint allocates in each paint. + Items []Item + // Columns is how many columns a line has; three when zero or less. + Columns int + // Bordered draws the list as a table: lines around every label and value, and + // a tinted label. + Bordered bool + // Vertical puts each label above its value, instead of before it. + Vertical bool + // Size is how large the text and the padding are. + Size Size + // LabelWidth is the width of every label, so the values line up; zero lets a + // label be as wide as its words. A Vertical list ignores it. + LabelWidth float32 +} + +func (s Spec) columns() int { + if s.Columns <= 0 { + return 3 + } + return s.Columns +} + +// span is how many columns item i takes, never more than the line has. +func (s Spec) span(i int) int { + span := s.Items[i].Span + if span <= 0 { + span = 1 + } + return min(span, s.columns()) +} + +// lineEnd is the index after the last item of the line that starts at start: +// the items that fit the columns in order. +func (s Spec) lineEnd(start int) int { + used, end := 0, start + for end < len(s.Items) { + span := s.span(end) + if used+span > s.columns() { + break + } + used += span + end++ + } + return max(end, start+1) +} + +// View declares the list at c. label names it for assistive technology. The list +// is as tall as its lines; give it FillWidth. Declare the view on its own, not +// inside a Memo. +func View(c ui.C, label string, spec Spec) ui.Box { + if c == nil { + panic("descriptions: View needs a page") + } + theme := c.Theme() + metrics := theme.Metrics + look := look{theme: theme, pad: metrics.GapItem, size: metrics.FontSizeM} + if spec.Size == Small { + look.pad, look.size = metrics.GapItem*0.5, metrics.FontSizeS + } + root := ui.Column(c).Gap(look.pad) + root = root.HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true}) + root.Children(func() { + if spec.Title != "" { + ui.Text(c, spec.Title).FontSize(look.size + 2).Weight(gfx.WeightSemibold) + } + body := ui.Column(c).FillWidth().Gap(look.pad) + if spec.Bordered { + body = ui.Column(c).FillWidth().Border(1, theme.Border).Radius(metrics.RadiusControl).Clip() + } + body.Children(func() { + for start := 0; start < len(spec.Items); { + end := spec.lineEnd(start) + if spec.Bordered && start > 0 { + ui.Spacer(c).FillWidth().Height(1).Background(theme.Border) + } + // Cells are not spaced with the line's gap: a line of two cells would + // share its width differently from a line of three, and the columns + // would not line up. A cell keeps its own room inside itself. + line := ui.Row(c).FillWidth().Items(ui.Stretch) + line.Children(func() { + used := 0 + for i := start; i < end; i++ { + span := spec.span(i) + if i == end-1 { + span = max(span, spec.columns()-used) + } + used += span + if spec.Bordered { + look.tableCell(c, spec, spec.Items[i], span, i > start) + } else { + look.plainCell(c, spec, spec.Items[i], span) + } + } + }) + start = end + } + }) + }) + return root +} + +// look is what a list paints with: the page's theme and the spec's size. +type look struct { + theme *gfx.Theme + pad float32 + size float32 +} + +// plainCell declares one item of a borderless line: a muted label and its value. +func (l look) plainCell(c ui.C, spec Spec, item Item, span int) { + var cell ui.Box + if spec.Vertical { + cell = ui.Column(c).Gap(l.pad * 0.25) + } else { + cell = ui.Row(c).Gap(l.pad).Items(ui.Start) + } + cell.Basis(0).Grow(float32(span)) + cell.Children(func() { + label := ui.Text(c, item.Label).FontSize(l.size).Muted().Shrink(0) + if spec.LabelWidth > 0 && !spec.Vertical { + label.Width(spec.LabelWidth) + } + // The room to the next cell is the value's, so the cell itself is exactly + // its share of the line. + value := ui.Row(c).Items(ui.Center).PadSides(0, l.pad*2, 0, 0) + if spec.Vertical { + value.FillWidth() + } else { + value.Grow(1).Basis(0) + } + value.Children(func() { l.value(c, item) }) + }) +} + +// tableCell declares one item of a bordered line: a tinted label cell and a +// value cell, side by side or, for a vertical list, one above the other. The line +// that parts it from the cell before it is inside it, so the cell is exactly its +// share of the line and the columns of two lines line up. +func (l look) tableCell(c ui.C, spec Spec, item Item, span int, parted bool) { + cell := ui.Row(c).Basis(0).Grow(float32(span)).Items(ui.Stretch) + cell.Children(func() { + if parted { + ui.Spacer(c).Width(1).Grow(0).Shrink(0).Background(l.theme.Border) + } + var inner ui.Box + if spec.Vertical { + inner = ui.Column(c) + } else { + inner = ui.Row(c).Items(ui.Stretch) + } + inner.Grow(1).Basis(0) + inner.Children(func() { + label := ui.Row(c).Pad(l.pad).Background(l.theme.Muted).Items(ui.Center) + if spec.Vertical { + label.FillWidth() + } else { + label.Shrink(0) + if spec.LabelWidth > 0 { + label.Width(spec.LabelWidth) + } + } + label.Children(func() { + ui.Text(c, item.Label).FontSize(l.size).Weight(gfx.WeightMedium) + }) + value := ui.Row(c).Grow(1).Basis(0).Pad(l.pad).Items(ui.Center) + value.Children(func() { l.value(c, item) }) + }) + }) +} + +// value declares the value of an item. +func (l look) value(c ui.C, item Item) { + if item.Content != nil { + item.Content(c) + return + } + ui.Text(c, item.Value).FontSize(l.size) +} diff --git a/ui/descriptions/descriptions_test.go b/ui/descriptions/descriptions_test.go new file mode 100644 index 000000000..afbcf00d3 --- /dev/null +++ b/ui/descriptions/descriptions_test.go @@ -0,0 +1,143 @@ +package descriptions_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/descriptions" +) + +var items = []descriptions.Item{ + {Label: "Host", Value: "build-01"}, + {Label: "Port", Value: "22"}, + {Label: "User", Value: "deploy"}, + {Label: "Key", Value: "ed25519", Span: 2}, + {Label: "Jump", Value: "bastion"}, + {Label: "Notes", Value: "Nightly agent", Span: 3}, +} + +func measure(value string, size, weight float32) float32 { + return float32(len(value)) * size * 0.55 +} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 600, Height: 400}, view) + canvas.EndFrame() +} + +func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { + t.Helper() + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetMeasurer(measure) + canvas.SetReduceMotion(true) + draw(page, canvas, view) + return page, canvas +} + +func textAt(canvas *gfx.Canvas, value string) (gfx.Text, bool) { + for _, text := range canvas.Texts() { + if text.Value == value { + return text, true + } + } + return gfx.Text{}, false +} + +// Every label and value is painted, the items fill the lines in order and a +// line starts where the columns run out. +func TestItemsFillLinesInOrder(t *testing.T) { + view := func(c ui.C) { + descriptions.View(c, "Details", descriptions.Spec{Title: "Details", Items: items}).FillWidth() + } + _, canvas := open(t, view) + for _, value := range []string{"Details", "Host", "build-01", "Port", "User", "Key", "ed25519", "Jump", "Notes", "Nightly agent"} { + if _, ok := textAt(canvas, value); !ok { + t.Fatalf("the list did not paint %q", value) + } + } + host, _ := textAt(canvas, "Host") + user, _ := textAt(canvas, "User") + key, _ := textAt(canvas, "Key") + notes, _ := textAt(canvas, "Notes") + if host.Bounds.Y != user.Bounds.Y { + t.Fatalf("Host and User are on different lines (%v, %v), want the first line of three columns", host.Bounds.Y, user.Bounds.Y) + } + if key.Bounds.Y <= host.Bounds.Y || notes.Bounds.Y <= key.Bounds.Y { + t.Fatalf("the lines are not in order: first %v, second %v, third %v", host.Bounds.Y, key.Bounds.Y, notes.Bounds.Y) + } +} + +// The columns line up: what sits in the same column of two lines starts at the +// same place, whatever the number of cells in either line. +func TestColumnsLineUpAcrossLines(t *testing.T) { + for name, spec := range map[string]descriptions.Spec{ + "plain": {Items: items}, + "bordered": {Items: items, Bordered: true}, + "vertical": {Items: items, Vertical: true}, + } { + t.Run(name, func(t *testing.T) { + view := func(c ui.C) { descriptions.View(c, "Details", spec).FillWidth() } + _, canvas := open(t, view) + user, _ := textAt(canvas, "User") + jump, _ := textAt(canvas, "Jump") + // User is the third column of the first line; Jump is the third column + // of the second, after an item that spans two. + if user.Bounds.X != jump.Bounds.X { + t.Fatalf("User starts at %v and Jump at %v, want one third column", user.Bounds.X, jump.Bounds.X) + } + }) + } +} + +// A value the page declares itself takes the place of the text. +func TestContentReplacesTheValue(t *testing.T) { + called := 0 + custom := []descriptions.Item{{Label: "State", Value: "ignored", Content: func(c ui.C) { + called++ + ui.Text(c, "Online") + }}} + view := func(c ui.C) { descriptions.View(c, "Details", descriptions.Spec{Items: custom}).FillWidth() } + _, canvas := open(t, view) + if called == 0 { + t.Fatal("Content was not called") + } + if _, ok := textAt(canvas, "Online"); !ok { + t.Fatal("the content was not painted") + } + if _, ok := textAt(canvas, "ignored"); ok { + t.Fatal("the value was painted beside its content") + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + for name, spec := range map[string]descriptions.Spec{ + "plain": {Title: "Details", Items: items}, + "bordered": {Items: items, Bordered: true, Columns: 2, LabelWidth: 80}, + "vertical": {Items: items, Vertical: true, Size: descriptions.Small}, + } { + t.Run(name, func(t *testing.T) { + view := func(c ui.C) { descriptions.View(c, "Details", spec).FillWidth() } + page, canvas := open(t, view) + if allocations := testing.AllocsPerRun(100, func() { draw(page, canvas, view) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } + }) + } +} + +func BenchmarkViewPaint(b *testing.B) { + view := func(c ui.C) { + descriptions.View(c, "Details", descriptions.Spec{Items: items, Bordered: true}).FillWidth() + } + page, canvas := open(b, view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, view) + } +} diff --git a/ui/divider/divider.go b/ui/divider/divider.go new file mode 100644 index 000000000..3c804a9d6 --- /dev/null +++ b/ui/divider/divider.go @@ -0,0 +1,62 @@ +// Package divider is the opt-in page control for a rule with a word in it: the +// line that parts two sections and says what the second one is. A plain rule is +// ui.Divider; this is for a rule that carries a label, as "or" between two ways to +// sign in does: +// +// divider.View(c, "or", divider.Spec{}) +// divider.View(c, "Advanced", divider.Spec{Align: divider.Start}) +// +// The label is centered by default; Start and End put it near an end, with a short +// run of line before it. The rule is horizontal and as wide as the container it is +// in. +// +// It is a separate package so an application that does not import it pays +// nothing for it, and it depends only on the public gfx and ui packages. +package divider + +import ( + "github.com/vivaui/viva/ui" +) + +// Align is where the label sits along the rule. +type Align uint8 + +const ( + // Center is the zero value: the label in the middle. + Center Align = iota + // Start puts the label near the start of the rule. + Start + // End puts the label near the end of the rule. + End +) + +// Spec declares the rule. +type Spec struct { + // Align is where the label sits. + Align Align +} + +// run is the short length of line before a label at an end. +const run = 24 + +// View declares the rule with label at c. It is as wide as the container it is in and +// as tall as the label. Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, spec Spec) ui.Box { + theme := c.Theme() + metrics := theme.Metrics + row := ui.Row(c).FillWidth().Items(ui.Center).Gap(metrics.GapItem) + row.Children(func() { + if spec.Align == Start { + ui.Spacer(c).Width(run).Height(1).Grow(0).Shrink(0).Background(theme.Border) + } else { + ui.Spacer(c).Height(1).Grow(1).Background(theme.Border) + } + ui.Text(c, label).FontSize(metrics.FontSizeS).Muted().Shrink(0) + if spec.Align == End { + ui.Spacer(c).Width(run).Height(1).Grow(0).Shrink(0).Background(theme.Border) + } else { + ui.Spacer(c).Height(1).Grow(1).Background(theme.Border) + } + }) + return row +} diff --git a/ui/divider/divider_test.go b/ui/divider/divider_test.go new file mode 100644 index 000000000..d0085a344 --- /dev/null +++ b/ui/divider/divider_test.go @@ -0,0 +1,62 @@ +package divider_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/divider" +) + +func measure(value string, size, weight float32) float32 { return float32(len(value)) * size * 0.55 } + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 400, Height: 100}, view) + canvas.EndFrame() +} + +func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { + t.Helper() + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetMeasurer(measure) + canvas.SetReduceMotion(true) + draw(page, canvas, view) + return page, canvas +} + +// The label sits in the middle, or near the start or the end, with line on both +// sides of it in the middle and a short run of line before it at an end. +func TestLabelAlignment(t *testing.T) { + at := func(align divider.Align) float32 { + view := func(c ui.C) { + ui.Column(c).Pad(0).Children(func() { divider.View(c, "or", divider.Spec{Align: align}) }) + } + _, canvas := open(t, view) + for _, text := range canvas.Texts() { + if text.Value == "or" { + return text.Bounds.X + text.Bounds.Width/2 + } + } + t.Fatal("the label was not painted") + return 0 + } + center, start, end := at(divider.Center), at(divider.Start), at(divider.End) + if center < 190 || center > 210 { + t.Fatalf("centered label at %v in a 400 wide row, want about 200", center) + } + if !(start < center && center < end) { + t.Fatalf("label positions start %v, center %v, end %v are not in order", start, center, end) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + view := func(c ui.C) { divider.View(c, "or", divider.Spec{Align: divider.Start}) } + page, canvas := open(t, view) + if allocations := testing.AllocsPerRun(100, func() { draw(page, canvas, view) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} diff --git a/ui/drag_test.go b/ui/drag_test.go index c8e71e09c..2995d2204 100644 --- a/ui/drag_test.go +++ b/ui/drag_test.go @@ -374,3 +374,31 @@ func BenchmarkDragRepaint(b *testing.B) { func centerX(r gfx.Rect) float32 { return r.X + r.Width/2 } func centerY(r gfx.Rect) float32 { return r.Y + r.Height/2 } + +// OnMove is how a drag that leaves the page sees its own moves: the page +// routes them to the state and the application never gets them. +func TestDragStateReportsEveryMoveOfAnActiveDrag(t *testing.T) { + m := newDragModel(true) + var moves []gfx.PointerEvent + m.state.OnMove = func(event gfx.PointerEvent) { moves = append(moves, event) } + d := m.open(t) + source, target := d.hit("Source"), d.hit("Target") + sx, sy := center(source.Bounds) + if err := d.driver.Press(sx, sy, gfx.PointerButtonPrimary); err != nil { + t.Fatal(err) + } + // A press below the drag threshold is still a click; it is not reported. + if err := d.driver.Move(sx+1, sy+1); err != nil { + t.Fatal(err) + } + if len(moves) != 0 { + t.Fatalf("a click's move was reported as a drag move: %+v", moves) + } + tx, ty := center(target.Bounds) + if err := d.driver.Move(tx, ty); err != nil { + t.Fatal(err) + } + if len(moves) != 1 || moves[0].X != tx || moves[0].Y != ty { + t.Fatalf("moves = %+v, want the drag's own move", moves) + } +} diff --git a/ui/edit_menu.go b/ui/edit_menu.go new file mode 100644 index 000000000..00e74fc36 --- /dev/null +++ b/ui/edit_menu.go @@ -0,0 +1,34 @@ +package ui + +import ( + "sync" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/base" +) + +// EditMenuLabels are the words of the Cut, Copy, Paste and Select All menu every +// TextField and TextArea opens on a secondary press; see PageConfig.EditMenu. +type EditMenuLabels = base.EditMenuLabels + +// WithoutEditMenu keeps a TextField or TextArea from that menu, for a field the +// application gives a ContextMenu of its own. +func WithoutEditMenu() Option { return base.WithoutEditMenu() } + +var installEditMenu sync.Once + +// useEditMenu installs the menu painter and the system clipboard the edit menu of +// a TextField or TextArea needs. +func useEditMenu() { + useMenu() + installEditMenu.Do(func() { + base.ClipboardText, base.SetClipboardText = app.ClipboardText, app.SetClipboardText + }) +} + +// SetClipboardText puts text on the system clipboard, for a button that copies a +// value (a fingerprint, a command): call it where the press is read. It returns the +// platform's error when the clipboard cannot be written. +// +// if ui.Button(c, "Copy").Clicked() { _ = ui.SetClipboardText(m.fingerprint) } +func SetClipboardText(text string) error { return app.SetClipboardText(text) } diff --git a/ui/edit_menu_test.go b/ui/edit_menu_test.go new file mode 100644 index 000000000..fe395044b --- /dev/null +++ b/ui/edit_menu_test.go @@ -0,0 +1,312 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" +) + +func (d *pageDriver) secondaryClick(Label string) { + d.t.Helper() + x, y := center(d.hit(Label).Bounds) + if err := d.driver.Press(x, y, gfx.PointerButtonSecondary); err != nil { + d.t.Fatal(err) + } + if err := d.driver.Release(x, y, gfx.PointerButtonSecondary); err != nil { + d.t.Fatal(err) + } +} + +// menuItem finds a row of the open menu by its name. +func (d *pageDriver) menuItem(Label string) (gfx.Hit, bool) { + for _, hit := range d.driver.Snapshot().Hits { + if hit.Role == gfx.RoleMenuItem && hit.Label == Label { + return hit, true + } + } + return gfx.Hit{}, false +} + +// openCanvasMenus is openPage for a page that keeps its text menus its own, drawn +// in the window: the platform's is shown otherwise. +func openCanvasMenus(t *testing.T, View func(ui.C)) *pageDriver { + t.Helper() + return openPageWith(t, ui.PageConfig{View: View, CanvasMenus: true}, app.Config{}) +} + +// A TextField opens the standard edit menu on a secondary press: it takes the +// keyboard, Copy and Cut act on the selection, Paste folds the clipboard into one +// line at the caret, and Select All selects the value. +func TestTextFieldEditMenu(t *testing.T) { + var name, other ui.Field + editor := text.NewEditor("hello world") + name.Bind(editor) + d := openCanvasMenus(t, func(c ui.C) { + ui.Column(c).Pad(16).Gap(8).Children(func() { + ui.TextField(c, &name, "Name", "") + ui.TextField(c, &other, "Other", "") + }) + }) + d.click("Other") + d.secondaryClick("Name") + for _, label := range []string{"Cut", "Copy", "Paste", "Select All"} { + if _, ok := d.menuItem(label); !ok { + t.Fatalf("the edit menu has no %s", label) + } + } + if hit, _ := d.menuItem("Copy"); !hit.Disabled { + t.Fatal("Copy is enabled with nothing selected") + } + d.click("Select All") + if sel := editor.Selection(); sel != (text.Range{Start: 0, End: 11}) { + t.Fatalf("selection after Select All = %v", sel) + } + if got := d.Focused(); got != "Name" { + t.Fatalf("focus after the menu closed = %q, want the field", got) + } + + d.secondaryClick("Name") + d.click("Copy") + if got := d.driver.Clipboard(); got != "hello world" { + t.Fatalf("clipboard after Copy = %q", got) + } + d.secondaryClick("Name") + d.click("Cut") + if name.Text() != "" || d.driver.Clipboard() != "hello world" { + t.Fatalf("after Cut: text %q, clipboard %q", name.Text(), d.driver.Clipboard()) + } + + d.driver.SetClipboard("a\r\nb\tc") + d.secondaryClick("Name") + d.click("Paste") + if got := name.Text(); got != "a b c" { + t.Fatalf("Paste into a single line = %q", got) + } + if !editor.CanUndo() { + t.Fatal("Paste is not an edit the field can undo") + } +} + +// A TextArea keeps the lines it pastes. +func TestTextAreaEditMenuKeepsLines(t *testing.T) { + var notes ui.Field + d := openCanvasMenus(t, func(c ui.C) { + ui.TextArea(c, ¬es, "Notes", "").Height(120) + }) + d.driver.SetClipboard("one\ntwo") + d.secondaryClick("Notes") + d.click("Paste") + if got := notes.Text(); got != "one\ntwo" { + t.Fatalf("Paste into a text area = %q", got) + } +} + +// A secret field offers no way out for its text, and a read-only one none in. +func TestEditMenuHonoursSecretAndReadOnly(t *testing.T) { + var password, token ui.Field + password.Secure = true + password.SetText("hunter2") + token.SetText("abc") + d := openCanvasMenus(t, func(c ui.C) { + ui.Column(c).Pad(16).Gap(8).Children(func() { + ui.TextField(c, &password, "Password", "") + ui.TextField(c, &token, "Token", "").ReadOnly(true) + }) + }) + d.secondaryClick("Password") + for _, label := range []string{"Cut", "Copy"} { + if _, ok := d.menuItem(label); ok { + t.Fatalf("a secret field offers %s", label) + } + } + if _, ok := d.menuItem("Paste"); !ok { + t.Fatal("a secret field cannot be pasted into") + } + d.key(gfx.KeyEscape) + + d.driver.SetClipboard("zzz") + d.secondaryClick("Token") + for _, label := range []string{"Cut", "Paste"} { + if hit, ok := d.menuItem(label); !ok || !hit.Disabled { + t.Fatalf("%s of a read-only field = %+v, %v; want disabled", label, hit, ok) + } + } + if hit, _ := d.menuItem("Select All"); hit.Disabled { + t.Fatal("Select All of a read-only field is disabled") + } + d.click("Paste") + if token.Text() != "abc" { + t.Fatalf("a read-only field took a paste: %q", token.Text()) + } +} + +// A page names the words in its own language, and a field with a menu of its +// own opts out. +func TestEditMenuLabelsAndOptOut(t *testing.T) { + var plain, own ui.Field + d := openPageWith(t, ui.PageConfig{ + EditMenu: &ui.EditMenuLabels{Paste: "粘贴"}, CanvasMenus: true, + View: func(c ui.C) { + ui.Column(c).Pad(16).Gap(8).Children(func() { + ui.TextField(c, &plain, "Plain", "") + box := ui.TextField(c, &own, "Own", "", ui.WithoutEditMenu()) + ui.ContextMenu(c, box, func(menu *ui.MenuItems) { menu.Item("Mine") }) + }) + }, + }, app.Config{}) + d.secondaryClick("Plain") + if _, ok := d.menuItem("粘贴"); !ok { + t.Fatal("the page's Paste label is not used") + } + if _, ok := d.menuItem("Cut"); !ok { + t.Fatal("a label the page leaves empty is not English") + } + d.key(gfx.KeyEscape) + d.secondaryClick("Own") + if _, ok := d.menuItem("Mine"); !ok { + t.Fatal("the field's own menu is not shown") + } + if _, ok := d.menuItem("Cut"); ok { + t.Fatal("an opted-out field has the edit menu") + } +} + +// A field in a Dialog has its menu over the dialog, where it can be reached. +func TestEditMenuOverADialog(t *testing.T) { + var name ui.Field + d := openCanvasMenus(t, func(c ui.C) { + dialog := ui.Dialog(c, ui.DialogSpec{Title: "Host", Scope: gfx.Item(900), DismissID: gfx.Item(901), CloseID: gfx.Item(902)}) + dialog.Body(func() { ui.TextField(c, &name, "Name", "") }) + }) + d.driver.SetClipboard("db1") + d.secondaryClick("Name") + d.click("Paste") + if name.Text() != "db1" { + t.Fatalf("Paste in a dialog's field = %q", name.Text()) + } + if d.Focused() != "Name" { + t.Fatalf("the keyboard is on %q after the menu closed", d.Focused()) + } +} + +// denseFields is a form of forty text fields, with or without the edit menu. +type denseFields struct { + fields [40]ui.Field + plain bool +} + +func (m *denseFields) page(c ui.C) { + ui.Column(c).Fill().Pad(12).Gap(6).Children(func() { + for i := range m.fields { + if m.plain { + ui.TextField(c, &m.fields[i], "Field", "", ui.WithID(gfx.Item(100+i)), ui.WithoutEditMenu()) + } else { + ui.TextField(c, &m.fields[i], "Field", "", ui.WithID(gfx.Item(100+i))) + } + } + }) +} + +func BenchmarkPageTextFieldsEditMenu(b *testing.B) { + for _, plain := range []bool{false, true} { + name := "menu" + if plain { + name = "none" + } + b.Run(name, func(b *testing.B) { + m := &denseFields{plain: plain} + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + b.ReportAllocs() + for b.Loop() { + drawPage(page, canvas, m.page) + } + }) + } +} + +// The keyboard goes to the field the menu was opened on, also in a Dialog that +// had it on another control. +func TestEditMenuTakesTheKeyboardInADialog(t *testing.T) { + var name ui.Field + name.SetText("abc") + d := openCanvasMenus(t, func(c ui.C) { + dialog := ui.Dialog(c, ui.DialogSpec{Title: "Host", Scope: gfx.Item(900), DismissID: gfx.Item(901), CloseID: gfx.Item(902)}) + dialog.Body(func() { + ui.Button(c, "First") + ui.TextField(c, &name, "Name", "") + }) + }) + if d.Focused() == "Name" { + t.Skip("the dialog starts on the field") + } + d.secondaryClick("Name") + d.click("Select All") + if d.Focused() != "Name" { + t.Fatalf("the keyboard is on %q after the menu closed, want the field", d.Focused()) + } +} + +// By default a text field's menu is the system's, not the page's: the window is +// asked for it with the page's words, a field with a ContextMenu of its own keeps +// that menu, and the choice acts on the field. +func TestTextFieldMenuIsTheSystemsByDefault(t *testing.T) { + var name, own ui.Field + words := &ui.EditMenuLabels{Paste: "粘贴"} + d := openPageWith(t, ui.PageConfig{EditMenu: words, View: func(c ui.C) { + ui.Column(c).Pad(16).Gap(8).Children(func() { + ui.TextField(c, &name, "Name", "") + box := ui.TextField(c, &own, "Own", "", ui.WithoutEditMenu()) + ui.ContextMenu(c, box, func(menu *ui.MenuItems) { menu.Item("Mine") }) + }) + }}, app.Config{}) + d.secondaryClick("Name") + items := d.driver.TextMenu() + if len(items) == 0 { + t.Fatal("a secondary press opened no system menu") + } + for _, item := range items { + if item.Command == app.TextMenuPaste && item.Title != "粘贴" { + t.Fatalf("Paste is %q, want the page's words", item.Title) + } + } + if d.has("Cut") { + t.Fatal("the page drew a menu of its own beside the system's") + } + words.Paste = "貼上" + d.driver.DismissTextMenu() + d.secondaryClick("Name") + for _, item := range d.driver.TextMenu() { + if item.Command == app.TextMenuPaste && item.Title != "貼上" { + t.Fatalf("Paste is %q after the page changed its words", item.Title) + } + } + d.driver.SetClipboard("db1") + if err := d.driver.ChooseTextMenu(app.TextMenuPaste); err != nil { + t.Fatal(err) + } + if name.Text() != "db1" || d.Focused() != "Name" { + t.Fatalf("after Paste: text %q, keyboard on %q", name.Text(), d.Focused()) + } + d.secondaryClick("Own") + if d.driver.TextMenu() != nil || !d.has("Mine") { + t.Fatalf("a field with its own menu: system menu %v, own menu shown %v", d.driver.TextMenu() != nil, d.has("Mine")) + } +} + +// A read-only field has no editor for the system's menu to act on, so it keeps +// the page's, with the copy it still offers. +func TestReadOnlyFieldKeepsThePagesMenuBesideTheSystems(t *testing.T) { + var token ui.Field + token.SetText("abc") + d := openPage(t, func(c ui.C) { ui.TextField(c, &token, "Token", "").ReadOnly(true) }) + d.secondaryClick("Token") + if d.driver.TextMenu() != nil { + t.Fatal("the system's menu opened for a field it has no editor for") + } + if _, ok := d.menuItem("Copy"); !ok { + t.Fatal("a read-only field has no menu to copy from") + } +} diff --git a/ui/editabletabs/editabletabs.go b/ui/editabletabs/editabletabs.go new file mode 100644 index 000000000..c30d4f002 --- /dev/null +++ b/ui/editabletabs/editabletabs.go @@ -0,0 +1,425 @@ +// Package editabletabs is the opt-in page control for a strip of tabs the user +// can close and add, as the tabs of an editor or a terminal are: each tab is as +// wide as its title, with a close button, a button after the last tab adds one, +// and a strip longer than its room scrolls. A page keeps the tabs in its model and +// the control beside them: +// +// m.strip = editabletabs.New() +// // in the page: +// m.strip.View(c, "Sessions", &m.active, editabletabs.Spec{Tabs: m.tabs, Addable: true}).FillWidth() +// if i, ok := m.strip.Closed(); ok { +// m.closeTab(i) +// } +// if m.strip.Added() { +// m.openTab() +// } +// +// The control only reports: it never removes or appends a tab, because the tabs +// are the page's. Active is the index of the active tab; a click, an arrow key or +// the close of a tab before it moves it, and the page keeps it in range as tabs +// come and go. What the active tab shows is the page's, declared after the strip. +// +// The strip is one tab stop. Left and Right move to the previous and next tab and +// make it active, Home and End to the first and last, Delete or Backspace closes +// the tab the focus is on, and Enter or Space on the add button adds a tab. A +// middle click closes a tab, as in an editor. A Pinned tab has no close button and +// is not closed by the keys. The wheel scrolls a strip that is longer than its +// room, and the active tab is kept in view. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an EditableTabs in the model: its handlers and draw +// function are made once, so a warm paint allocates nothing. Do not copy an +// EditableTabs after it has been declared. +package editabletabs + +import ( + "math" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +var ( + closeIcon = gfx.Icon{ViewBox: 24, Stroke: 2.5, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(18, 6), gfx.LineTo(6, 18), gfx.MoveTo(6, 6), gfx.LineTo(18, 18), + }} + plusIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(5, 12), gfx.LineTo(19, 12), gfx.MoveTo(12, 5), gfx.LineTo(12, 19), + }} +) + +// Tab is one tab of the strip. +type Tab struct { + // Title names the tab. + Title string + // Icon is drawn before the title. A zero icon draws none. + Icon gfx.Icon + // Pinned takes away the close button, and the keys that close. + Pinned bool + // Disabled dims the tab and takes no press. + Disabled bool +} + +// Spec declares the strip. +type Spec struct { + // Tabs are the tabs, in order. Keep the slice in the model: a slice made in each + // paint allocates in each paint. + Tabs []Tab + // Addable adds the button after the last tab. + Addable bool + // CloseLabel and AddLabel are the accessible names of the buttons, "Close" and + // "Add tab" when empty. + CloseLabel, AddLabel string +} + +// Layout constants, in pixels. +const ( + height = 36 + padX = 12 + gap = 6 + closeSz = 18 + addSz = 28 +) + +// EditableTabs is one strip and what the user did to it. +type EditableTabs struct { + handlers ui.Handlers + drawFn func(*ui.DrawContext) + + spec Spec + active *int + offset float32 // how far the strip is scrolled + revealI int // the tab to bring into view at the next draw, or -1 + seen int // the active tab as of the last View: a change the page makes is revealed too + focus int // the tab the keyboard rests on + + hoverPart int // the part under the pointer, or -1 + + closed int // 1 + the tab closed since the last View, or 0 + closedNow int + added, addedNow bool + width float32 // the strip's width as last drawn +} + +// New returns a strip. +func New() *EditableTabs { + t := &EditableTabs{revealI: -1, seen: -1, hoverPart: -1} + t.handlers.Role = gfx.RoleGroup + t.handlers.Key = t.key + t.handlers.Pointer = t.pointer + t.handlers.Scroll = t.scroll + t.drawFn = t.draw + return t +} + +// Closed reports which tab the user closed in the paint that delivered it. +func (t *EditableTabs) Closed() (int, bool) { return t.closed - 1, t.closed > 0 } + +// Added reports whether the user pressed the add button in the paint that delivered it. +func (t *EditableTabs) Added() bool { return t.added } + +// parts: tab i is 3i, its close button 3i+1, and the add button 3n. +func tabPart(i int) int { return 3 * i } +func closePart(i int) int { return 3*i + 1 } + +func (t *EditableTabs) closable(i int) bool { + return i >= 0 && i < len(t.spec.Tabs) && !t.spec.Tabs[i].Pinned && !t.spec.Tabs[i].Disabled +} + +// View declares the strip at c, showing *active as the active tab. label names the +// strip for assistive technology. The strip is one line high; give it FillWidth. +// Declare the view on its own, not inside a Memo. +func (t *EditableTabs) View(c ui.C, label string, active *int, spec Spec) ui.Box { + if t == nil { + panic("editabletabs: View needs its EditableTabs") + } + if active == nil { + panic("editabletabs: View needs the active tab") + } + t.closed, t.added = t.closedNow, t.addedNow + t.closedNow, t.addedNow = 0, false + if spec.CloseLabel == "" { + spec.CloseLabel = "Close" + } + if spec.AddLabel == "" { + spec.AddLabel = "Add tab" + } + t.spec, t.active = spec, active + if len(spec.Tabs) > 0 { + *active = min(max(*active, 0), len(spec.Tabs)-1) + } else { + *active = 0 + } + t.focus = *active + if *active != t.seen { + t.seen, t.revealI = *active, *active + } + return ui.Control(c, label, &t.handlers).Height(height).Shrink(0).Draw(t.drawFn) +} + +func (t *EditableTabs) focusInside() bool { + return t.focus >= 0 && t.focus < len(t.spec.Tabs) && t.hoverPart >= -1 +} + +// widths are the x of each tab's left edge and the right edge of the last, in the +// strip's own coordinates before scrolling; add is where the add button starts. +func (t *EditableTabs) widthOf(canvas *gfx.Canvas, theme *gfx.Theme, tab Tab) float32 { + w := canvas.TextWidthWeight(tab.Title, theme.Metrics.FontSizeM, gfx.WeightMedium) + 2*padX + if tab.Icon.ViewBox > 0 { + w += theme.Metrics.FontSizeM + gap + } + if !tab.Pinned { + w += closeSz + gap/2 + } + // Whole pixels, so the edges of neighbors are the same numbers however far the + // strip is scrolled: tabs share an edge and do not overlap by rounding. + return float32(math.Ceil(float64(w))) +} + +// layout calls fn with the rectangle of each tab, scrolled, and returns the total +// width of the tabs and the add button. +func (t *EditableTabs) layout(canvas *gfx.Canvas, theme *gfx.Theme, origin gfx.Rect, fn func(i int, r gfx.Rect)) float32 { + x := float32(0) + for i, tab := range t.spec.Tabs { + w := t.widthOf(canvas, theme, tab) + if fn != nil { + fn(i, gfx.Rect{X: origin.X + x - t.offset, Y: origin.Y, Width: w, Height: origin.Height}) + } + x += w + } + if t.spec.Addable { + x += gap + addSz + } + return x +} + +func (t *EditableTabs) limit(total float32) float32 { return max(total-t.width, 0) } + +func (t *EditableTabs) scroll(event gfx.ScrollEvent) gfx.EventResult { + delta := event.DeltaX + if math.Abs(float64(event.DeltaY)) > math.Abs(float64(event.DeltaX)) { + delta = event.DeltaY + } + if delta == 0 { + return gfx.EventResult{} + } + before := t.offset + t.offset = max(t.offset-delta, 0) + return gfx.EventResult{Handled: t.offset != before, Repaint: t.offset != before} +} + +func (t *EditableTabs) closeTab(i int) gfx.EventResult { + if !t.closable(i) { + return gfx.EventResult{} + } + t.closedNow = i + 1 + return gfx.EventResult{Handled: true, Repaint: true} +} + +func (t *EditableTabs) pointer(event gfx.PointerEvent) gfx.EventResult { + if t.active == nil { + return gfx.EventResult{} + } + parts := t.handlers.Parts() + part, on := event.Target.In(parts) + switch event.Kind { + case gfx.PointerExit: + if t.hoverPart == -1 { + return gfx.EventResult{} + } + t.hoverPart = -1 + return gfx.EventResult{Repaint: true} + case gfx.PointerMove: + hover := -1 + if on { + hover = part + } + if hover == t.hoverPart { + return gfx.EventResult{} + } + t.hoverPart = hover + return gfx.EventResult{Repaint: true} + case gfx.PointerDown: + if !on { + return gfx.EventResult{} + } + n := len(t.spec.Tabs) + switch { + case part == 3*n && t.spec.Addable: + if event.Button == gfx.PointerButtonPrimary { + t.addedNow = true + return gfx.EventResult{Handled: true, Repaint: true} + } + case part%3 == 1: + if event.Button == gfx.PointerButtonPrimary { + return t.closeTab(part / 3) + } + case part%3 == 0 && part/3 < n && !t.spec.Tabs[part/3].Disabled: + i := part / 3 + if event.Button == gfx.PointerButtonMiddle { + return t.closeTab(i) + } + if event.Button == gfx.PointerButtonPrimary { + *t.active, t.focus = i, i + t.revealI = i + return gfx.EventResult{Handled: true, Repaint: true, Focus: parts.At(tabPart(i))} + } + } + } + return gfx.EventResult{} +} + +// step is the nearest enabled tab from i in a direction, or i. +func (t *EditableTabs) step(i, dir int) int { + for j := i + dir; j >= 0 && j < len(t.spec.Tabs); j += dir { + if !t.spec.Tabs[j].Disabled { + return j + } + } + return i +} + +func (t *EditableTabs) key(event gfx.KeyEvent) gfx.EventResult { + if t.active == nil || event.Release || event.Text != "" || event.Modifiers != 0 { + return gfx.EventResult{} + } + parts := t.handlers.Parts() + part, on := event.Target.In(parts) + n := len(t.spec.Tabs) + if on && part == 3*n && t.spec.Addable { + if event.Key == gfx.KeyEnter || event.Key == gfx.KeySpace { + t.addedNow = true + return gfx.EventResult{Handled: true, Repaint: true} + } + if event.Key == gfx.KeyLeft && n > 0 { + return gfx.EventResult{Handled: true, Repaint: true, Focus: parts.At(tabPart(n - 1)), FocusVisible: true} + } + return gfx.EventResult{} + } + if n == 0 { + return gfx.EventResult{} + } + i := min(max(t.focus, 0), n-1) + switch event.Key { + case gfx.KeyLeft: + i = t.step(i, -1) + case gfx.KeyRight: + if j := t.step(i, 1); j != i { + i = j + } else if t.spec.Addable { + return gfx.EventResult{Handled: true, Repaint: true, Focus: parts.At(3 * n), FocusVisible: true} + } + case gfx.KeyHome: + i = t.step(-1, 1) + case gfx.KeyEnd: + i = t.step(n, -1) + case gfx.KeyDelete, gfx.KeyBackspace: + return t.closeTab(i) + default: + return gfx.EventResult{} + } + *t.active, t.focus, t.revealI = i, i, i + return gfx.EventResult{Handled: true, Repaint: true, Focus: parts.At(tabPart(i)), FocusVisible: true} +} + +// draw paints the strip and declares each tab, close button and the add button as +// a part of the control. +func (t *EditableTabs) draw(d *ui.DrawContext) { + if t.active == nil { + return + } + canvas, theme := d.Canvas, d.Theme + metrics := theme.Metrics + parts := t.handlers.Parts() + t.width = d.Rect.Width + total := t.layout(canvas, theme, d.Rect, nil) + if t.revealI >= 0 && t.revealI < len(t.spec.Tabs) { + var left, right float32 + x := float32(0) + for i, tab := range t.spec.Tabs { + w := t.widthOf(canvas, theme, tab) + if i == t.revealI { + left, right = x, x+w + } + x += w + } + switch { + case left < t.offset: + t.offset = left + case right > t.offset+d.Rect.Width: + t.offset = right - d.Rect.Width + } + t.revealI = -1 + } + t.offset = float32(math.Round(float64(min(max(t.offset, 0), t.limit(total))))) + // The rule under the strip, and the clip that keeps scrolled tabs inside it. + canvas.Fill(gfx.Rect{X: d.Rect.X, Y: d.Rect.Y + d.Rect.Height - 1, Width: d.Rect.Width, Height: 1}, theme.Border) + canvas.Clip(d.Rect) + defer canvas.Unclip() + size := metrics.FontSizeM + n := len(t.spec.Tabs) + rest := min(max(t.focus, 0), max(n-1, 0)) + end := d.Rect.X + t.layout(canvas, theme, d.Rect, func(i int, r gfx.Rect) { + tab := t.spec.Tabs[i] + end = r.X + r.Width + selected := i == *t.active + hovered := !tab.Disabled && t.hoverPart == tabPart(i) + ink := theme.MutedForeground + switch { + case selected: + ink = theme.Foreground + canvas.Fill(gfx.Rect{X: r.X, Y: r.Y + r.Height - 2, Width: r.Width, Height: 2}, theme.Primary) + case hovered: + ink = theme.Foreground + canvas.Fill(gfx.Rect{X: r.X, Y: r.Y, Width: r.Width, Height: r.Height - 1}, theme.Hover) + } + if tab.Disabled { + ink.Alpha *= 0.5 + } + x := r.X + padX + if tab.Icon.ViewBox > 0 { + canvas.DrawIcon(tab.Icon, gfx.Rect{X: x, Y: r.Y + (r.Height-size)/2, Width: size, Height: size}, ink) + x += size + gap + } + labelWidth := r.Width - (x - r.X) - padX + if !tab.Pinned { + labelWidth -= closeSz + gap/2 + } + canvas.Label(tab.Title, gfx.Rect{X: x, Y: r.Y, Width: max(labelWidth, 0), Height: r.Height}, gfx.TextStyle{Size: size, Weight: gfx.WeightMedium, Color: ink}) + if canvas.FocusVisible() == parts.At(tabPart(i)) { + canvas.RoundedBorder(gfx.Rect{X: r.X + 2, Y: r.Y + 2, Width: r.Width - 4, Height: r.Height - 5}, metrics.RadiusControl, 2, theme.Ring, gfx.Color{}) + } + canvas.HitWithOptions(parts.At(tabPart(i)), r, tab.Title, gfx.HitOptions{ + Role: gfx.RoleTab, Selected: selected, Disabled: tab.Disabled, + SkipFocus: tab.Disabled, SkipTab: i != rest, + }) + if tab.Pinned { + return + } + button := gfx.Rect{X: r.X + r.Width - padX/2 - closeSz, Y: r.Y + (r.Height-closeSz)/2, Width: closeSz, Height: closeSz} + if t.hoverPart == closePart(i) { + canvas.Rounded(button, metrics.RadiusControl, theme.Hover) + } + show := ink + if selected || hovered || t.hoverPart == closePart(i) { + show = theme.Foreground + } + canvas.DrawIcon(closeIcon, gfx.Rect{X: button.X + 4, Y: button.Y + 4, Width: closeSz - 8, Height: closeSz - 8}, show) + canvas.HitWithOptions(parts.At(closePart(i)), button, t.spec.CloseLabel, gfx.HitOptions{ + Role: gfx.RoleButton, Description: tab.Title, Disabled: tab.Disabled, SkipTab: true, SkipFocus: true, + }) + }) + if t.spec.Addable { + button := gfx.Rect{X: end + gap, Y: d.Rect.Y + (d.Rect.Height-addSz)/2, Width: addSz, Height: addSz} + add := parts.At(3 * n) + if canvas.Hovered() == add { + canvas.Rounded(button, metrics.RadiusControl, theme.Hover) + } + canvas.DrawIcon(plusIcon, gfx.Rect{X: button.X + 7, Y: button.Y + 7, Width: addSz - 14, Height: addSz - 14}, theme.MutedForeground) + if canvas.FocusVisible() == add { + canvas.RoundedBorder(button, metrics.RadiusControl, 2, theme.Ring, gfx.Color{}) + } + canvas.HitWithOptions(add, button, t.spec.AddLabel, gfx.HitOptions{Role: gfx.RoleButton, SkipTab: true}) + } +} diff --git a/ui/editabletabs/editabletabs_test.go b/ui/editabletabs/editabletabs_test.go new file mode 100644 index 000000000..a25f4fe22 --- /dev/null +++ b/ui/editabletabs/editabletabs_test.go @@ -0,0 +1,229 @@ +//go:build !js + +package editabletabs_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/editabletabs" +) + +type model struct { + strip *editabletabs.EditableTabs + tabs []editabletabs.Tab + active int + closed []int + added int +} + +func newModel(titles ...string) *model { + m := &model{strip: editabletabs.New()} + for _, title := range titles { + m.tabs = append(m.tabs, editabletabs.Tab{Title: title}) + } + return m +} + +func (m *model) open(t *testing.T, width int, addable bool) *headless.Session { + t.Helper() + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Children(func() { + m.strip.View(c, "Sessions", &m.active, editabletabs.Spec{Tabs: m.tabs, Addable: addable}).FillWidth() + // The page owns the tabs: it removes what the strip reports closed. + if i, ok := m.strip.Closed(); ok { + m.closed = append(m.closed, i) + m.tabs = append(m.tabs[:i], m.tabs[i+1:]...) + if m.active > i || m.active >= len(m.tabs) { + m.active = max(m.active-1, 0) + } + } + if m.strip.Added() { + m.added++ + m.tabs = append(m.tabs, editabletabs.Tab{Title: "new"}) + m.active = len(m.tabs) - 1 + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Tabs", Width: width, Height: 160}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +// A click on a tab makes it active. +func TestClickActivates(t *testing.T) { + m := newModel("alpha", "beta", "gamma") + session := m.open(t, 600, false) + if err := session.ClickLabel("gamma"); err != nil { + t.Fatal(err) + } + if m.active != 2 { + t.Fatalf("active = %d after a click on gamma, want 2", m.active) + } +} + +// The close button of a tab, the Delete key and a middle click each report the +// tab, and a pinned tab offers none of them. +func TestClosingReportsTheTab(t *testing.T) { + m := newModel("alpha", "beta", "gamma") + m.tabs[0].Pinned = true + session := m.open(t, 600, false) + closeButtons := 0 + var first gfx.Hit + for _, hit := range session.Driver().Snapshot().Hits { + if hit.Label == "Close" { + if closeButtons == 0 { + first = hit + } + closeButtons++ + } + } + if closeButtons != 2 { + t.Fatalf("close buttons = %d, want one for each tab that is not pinned (2)", closeButtons) + } + if err := session.Click(first.Bounds.X+first.Bounds.Width/2, first.Bounds.Y+first.Bounds.Height/2); err != nil { + t.Fatal(err) + } + if len(m.closed) != 1 || m.closed[0] != 1 { + t.Fatalf("closed = %v after the close button of beta, want [1]", m.closed) + } + // Delete on the focused tab closes it; the pinned first tab is not closed by it. + if err := session.ClickLabel("alpha"); err != nil { + t.Fatal(err) + } + if err := session.Keys("delete"); err != nil { + t.Fatal(err) + } + if len(m.closed) != 1 { + t.Fatalf("Delete closed a pinned tab: %v", m.closed) + } + if err := session.Keys("right"); err != nil { + t.Fatal(err) + } + if err := session.Keys("delete"); err != nil { + t.Fatal(err) + } + if len(m.closed) != 2 || m.closed[1] != 1 { + t.Fatalf("closed = %v after Right and Delete, want [1 1]", m.closed) + } +} + +func TestMiddleClickClosesATab(t *testing.T) { + m := newModel("alpha", "beta") + session := m.open(t, 600, false) + hit, err := session.Locate("beta") + if err != nil { + t.Fatal(err) + } + x, y := hit.Bounds.X+hit.Bounds.Width/3, hit.Bounds.Y+hit.Bounds.Height/2 + if err := session.Driver().ClickButton(x, y, gfx.PointerButtonMiddle); err != nil { + t.Fatal(err) + } + if len(m.closed) != 1 || m.closed[0] != 1 { + t.Fatalf("closed = %v after a middle click on beta, want [1]", m.closed) + } +} + +// The arrow keys move the focus and make the tab active, Home and End go to the +// ends, and the add button is reached with Right and pressed with Enter. +func TestKeysMoveThroughTheStripAndAdd(t *testing.T) { + m := newModel("alpha", "beta", "gamma") + session := m.open(t, 600, true) + if err := session.Keys("tab"); err != nil { + t.Fatal(err) + } + for _, step := range []struct { + key string + want int + }{{"right", 1}, {"end", 2}, {"left", 1}, {"home", 0}} { + if err := session.Keys(step.key); err != nil { + t.Fatal(err) + } + if m.active != step.want { + t.Fatalf("active = %d after %q, want %d", m.active, step.key, step.want) + } + } + session.Keys("end") + session.Keys("right") // past the last tab: onto the add button + if err := session.Keys("enter"); err != nil { + t.Fatal(err) + } + if m.added != 1 || len(m.tabs) != 4 || m.active != 3 { + t.Fatalf("added %d, tabs %d, active %d after Enter on the add button; want 1, 4, 3", m.added, len(m.tabs), m.active) + } +} + +// The add button is a button of its own, and absent unless asked for. +func TestAddButtonOnlyWhenAddable(t *testing.T) { + for _, addable := range []bool{false, true} { + m := newModel("alpha") + session := m.open(t, 600, addable) + _, err := session.Locate("Add tab") + if (err == nil) != addable { + t.Fatalf("addable %v: add button present = %v", addable, err == nil) + } + } +} + +// A strip longer than its room scrolls with the wheel and keeps the active tab in view. +func TestLongStripScrollsAndKeepsTheActiveTabInView(t *testing.T) { + m := newModel("first tab", "second tab", "third tab", "fourth tab", "fifth tab", "sixth tab") + session := m.open(t, 300, false) + if err := session.ClickLabel("first tab"); err != nil { + t.Fatal(err) + } + session.Keys("end") + hit, err := session.Locate("sixth tab") + if err != nil { + t.Fatal(err) + } + if hit.Bounds.X+hit.Bounds.Width > 300.5 || hit.Bounds.X < -0.5 { + t.Fatalf("the active tab is at %+v, outside a 300 wide strip", hit.Bounds) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + m := newModel("alpha", "beta", "gamma") + m.tabs[0].Pinned = true + view := func(c ui.C) { + m.strip.View(c, "Sessions", &m.active, editabletabs.Spec{Tabs: m.tabs, Addable: true}).FillWidth() + } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 600, Height: 160}, view) + canvas.EndFrame() + } + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + m := newModel("alpha", "beta", "gamma", "delta") + view := func(c ui.C) { + m.strip.View(c, "Sessions", &m.active, editabletabs.Spec{Tabs: m.tabs, Addable: true}).FillWidth() + } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + b.ReportAllocs() + for range b.N { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 600, Height: 160}, view) + canvas.EndFrame() + } +} diff --git a/ui/empty/empty.go b/ui/empty/empty.go new file mode 100644 index 000000000..c49d21581 --- /dev/null +++ b/ui/empty/empty.go @@ -0,0 +1,72 @@ +// Package empty is the opt-in page control for an empty state: what a list, a +// table or a page shows when there is nothing in it, with the next step to take. +// A page declares it with a Spec and, optionally, the actions under the words: +// +// empty.View(c, empty.Spec{ +// Icon: m.folderIcon, +// Boxed: true, +// Title: "No projects yet", +// Description: "Create a project to get started.", +// }, func() { +// ui.Button(c, "Create project") +// }).Fill() +// +// The media is the icon, bare or Boxed in a muted rounded square; the title is +// medium weight and the description is muted and wraps. The actions closure +// declares page elements, so a button there has its own identity and is read +// where it is declared. The state is centered in the room it is given: give it +// Fill, or a size. +// +// It is a separate package so an application that does not import it pays +// nothing for it, and it depends only on the public gfx and ui packages. +package empty + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// maxWidth is the widest the words go, so a long description wraps into a +// readable column in a wide window. +const maxWidth = 384 + +// Spec declares an empty state. +type Spec struct { + // Icon is the media above the title. A zero icon leaves it out. + Icon gfx.Icon + // Boxed draws the icon in a muted rounded square instead of bare. + Boxed bool + // Title says what is missing; Description says what to do about it. Either may + // be empty. + Title, Description string +} + +// View declares the empty state at c, with actions, when not nil, declaring what +// the user can do under the words. Declare the view on its own, not inside a Memo. +func View(c ui.C, spec Spec, actions func()) ui.Box { + theme := c.Theme() + metrics := theme.Metrics + root := ui.Column(c).Center().Gap(metrics.GapItem).Pad(metrics.PadSurface * 2) + root.Children(func() { + if spec.Icon.ViewBox > 0 { + if spec.Boxed { + side := metrics.ControlHeight + metrics.GapItem + ui.Column(c).Size(side, side).Center().Radius(metrics.RadiusSurface).Background(theme.Muted).Children(func() { + ui.Icon(c, spec.Icon).Size(24, 24) + }) + } else { + ui.Icon(c, spec.Icon).Size(32, 32).Muted() + } + } + if spec.Title != "" { + ui.Text(c, spec.Title).FontSize(metrics.FontSizeM + 5).Weight(gfx.WeightMedium).TextCenter().MaxWidth(maxWidth) + } + if spec.Description != "" { + ui.Wrap(c, spec.Description).Muted().TextCenter().MaxWidth(maxWidth) + } + if actions != nil { + ui.Row(c).Gap(metrics.GapItem).MarginSides(metrics.GapItem, 0, 0, 0).Items(ui.Center).Children(actions) + } + }) + return root +} diff --git a/ui/empty/empty_test.go b/ui/empty/empty_test.go new file mode 100644 index 000000000..9d51e383d --- /dev/null +++ b/ui/empty/empty_test.go @@ -0,0 +1,108 @@ +package empty_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/empty" +) + +var icon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{gfx.MoveTo(4, 20), gfx.LineTo(20, 4)}} + +func measure(value string, size, weight float32) float32 { return float32(len(value)) * size * 0.55 } + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 600, Height: 400}, view) + canvas.EndFrame() +} + +func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { + t.Helper() + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetMeasurer(measure) + canvas.SetReduceMotion(true) + draw(page, canvas, view) + return page, canvas +} + +func textAt(canvas *gfx.Canvas, value string) (gfx.Text, bool) { + for _, text := range canvas.Texts() { + if text.Value == value { + return text, true + } + } + return gfx.Text{}, false +} + +// The words are centered in the room given, with the actions under them. +func TestStateIsCenteredWithActionsBelow(t *testing.T) { + var c0 ui.C + actions := func() { ui.Button(c0, "Create project") } + view := func(c ui.C) { + c0 = c + empty.View(c, empty.Spec{Icon: icon, Title: "No projects yet", Description: "Create one."}, actions).Fill() + } + _, canvas := open(t, view) + title, ok := textAt(canvas, "No projects yet") + if !ok { + t.Fatal("the empty state did not paint its title") + } + middle := title.Bounds.X + title.Bounds.Width/2 + if middle < 295 || middle > 305 { + t.Fatalf("the title is centered at %v in a 600 wide window, want about 300", middle) + } + description, _ := textAt(canvas, "Create one.") + button, ok := textAt(canvas, "Create project") + if !ok || !(title.Bounds.Y < description.Bounds.Y && description.Bounds.Y < button.Bounds.Y) { + t.Fatalf("title %v, description %v, action %v are not in order", title.Bounds.Y, description.Bounds.Y, button.Bounds.Y) + } +} + +// Boxed puts a muted square behind the icon; bare does not. +func TestBoxedIconHasAMutedSquare(t *testing.T) { + theme := gfx.LightTheme() + squares := func(boxed bool) int { + view := func(c ui.C) { empty.View(c, empty.Spec{Icon: icon, Boxed: boxed, Title: "None"}, nil).Fill() } + _, canvas := open(t, view) + n := 0 + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color == theme.Muted && rectangle.Bounds.Width == rectangle.Bounds.Height { + n++ + } + } + return n + } + if squares(true) != 1 || squares(false) != 0 { + t.Fatalf("muted squares: boxed %d, bare %d; want 1 and 0", squares(true), squares(false)) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + var c0 ui.C + actions := func() { ui.Button(c0, "Create") } + view := func(c ui.C) { + c0 = c + empty.View(c, empty.Spec{Icon: icon, Boxed: true, Title: "None", Description: "Create one."}, actions).Fill() + } + page, canvas := open(t, view) + if allocations := testing.AllocsPerRun(100, func() { draw(page, canvas, view) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + view := func(c ui.C) { + empty.View(c, empty.Spec{Icon: icon, Title: "None", Description: "Create one."}, nil).Fill() + } + page, canvas := open(b, view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, view) + } +} diff --git a/ui/engine.go b/ui/engine.go index 6f4f5f7a5..909504b69 100644 --- a/ui/engine.go +++ b/ui/engine.go @@ -36,6 +36,9 @@ type DimKind = base.DimKind type Dimension = base.Dimension type Direction = base.Direction type DragState = base.DragState + +// FileDropState is one area that takes files dragged from the system. +type FileDropState = base.FileDropState type DrawContext = base.DrawContext type DrawerDeclaration = base.DrawerDeclaration type DrawerRects = base.DrawerRects @@ -107,6 +110,7 @@ type TextValue = base.TextValue type ToastID = base.ToastID type ToastKind = base.ToastKind type ToastPosition = base.ToastPosition +type ToastConfig = base.ToastConfig type Toaster = base.Toaster type TooltipSide = base.TooltipSide type TreeDrop = base.TreeDrop @@ -168,6 +172,7 @@ const ( PKToaster = base.PKToaster ProgressHeight = base.ProgressHeight ProgressWidth = base.ProgressWidth + ProgressRing = base.ProgressRing ScrollbarLinger = base.ScrollbarLinger SpinnerStep = base.SpinnerStep TabIndicator = base.TabIndicator diff --git a/ui/facade.go b/ui/facade.go index c0d5d57a6..d3593c32d 100644 --- a/ui/facade.go +++ b/ui/facade.go @@ -196,14 +196,9 @@ func Choice[T comparable](c C, Value *T, choices []T, Label func(T) string) Box return base.Choice(c, Value, choices, Label) } -func Radio[T comparable](c C, Value *T, option T, Label string) Box { +func Radio[T comparable](c C, Value *T, option T, Label string, opts ...Option) Box { useCheckbox() - return base.Radio(c, Value, option, Label) -} - -func RadioID[T comparable](c C, ID gfx.ID, Value *T, option T, Label string) Box { - useCheckbox() - return base.RadioID(c, ID, Value, option, Label) + return base.Radio(c, Value, option, Label, opts...) } func RadioBase[T comparable](c C, Value *T, option T, Label string) Box { @@ -223,14 +218,9 @@ func Tabs[T comparable](c C, Value *T, tabs []T, Label func(T) string) Box { return base.Tabs(c, Value, tabs, Label) } -func Select[T comparable](c C, Value *T, choices []T, Label func(T) string) Box { +func Select[T comparable](c C, Value *T, choices []T, Label func(T) string, opts ...Option) Box { useSelect() - return base.Select(c, Value, choices, Label) -} - -func SelectID[T comparable](c C, ID gfx.ID, Value *T, choices []T, Label func(T) string) Box { - useSelect() - return base.SelectID(c, ID, Value, choices, Label) + return base.Select(c, Value, choices, Label, opts...) } func SelectBase[T comparable](c C, Value *T, choices []T, Label func(T) string) Box { @@ -250,14 +240,9 @@ func ColorSwatch(c C, Color Color, selected bool, Label string) Box { return base.ColorSwatch(c, Color, selected, Label) } -func ColorPicker(c C, state *ColorPickerState, Color *Color, Label string) Box { +func ColorPicker(c C, state *ColorPickerState, Color *Color, Label string, opts ...Option) Box { useColor() - return base.ColorPicker(c, state, Color, Label) -} - -func ColorPickerID(c C, ID gfx.ID, state *ColorPickerState, Color *Color, Label string) Box { - useColor() - return base.ColorPickerID(c, ID, state, Color, Label) + return base.ColorPicker(c, state, Color, Label, opts...) } func Slider(c C, state *SliderState) Box { useSlider(); return base.Slider(c, state) } @@ -296,14 +281,10 @@ func Pagination(c C, Items []PaginationItem) Box { usePagination(); return base. // Fields and text entry. -func TextField[T TextValue](c C, Value T, Label, placeholder string) Box { - useField() - return base.TextField(c, Value, Label, placeholder) -} - -func TextFieldID[T TextValue](c C, ID gfx.ID, Value T, Label, placeholder string) Box { +func TextField[T TextValue](c C, Value T, Label, placeholder string, opts ...Option) Box { useField() - return base.TextFieldID(c, ID, Value, Label, placeholder) + useEditMenu() + return base.TextField(c, Value, Label, placeholder, opts...) } func TextFieldBase[T TextValue](c C, Value T, Label, placeholder string) Box { @@ -311,14 +292,10 @@ func TextFieldBase[T TextValue](c C, Value T, Label, placeholder string) Box { return base.TextFieldBase(c, Value, Label, placeholder) } -func TextArea[T TextValue](c C, Value T, Label, placeholder string) Box { +func TextArea[T TextValue](c C, Value T, Label, placeholder string, opts ...Option) Box { useField() - return base.TextArea(c, Value, Label, placeholder) -} - -func TextAreaID(c C, ID gfx.ID, field *Field, Label, placeholder string) Box { - useField() - return base.TextAreaID(c, ID, field, Label, placeholder) + useEditMenu() + return base.TextArea(c, Value, Label, placeholder, opts...) } func Fields(fields ...*Field) func(window.TextInputContext) *window.TextInput { @@ -350,24 +327,14 @@ func Drawer(c C, open *bool, title string, spec DrawerSpec, body, footer func()) return base.Drawer(c, open, title, spec, body, footer) } -func Modal(c C, open *bool, title string, body, footer func()) bool { - useDialog() - return base.Modal(c, open, title, body, footer) -} - -func ModalWith(c C, open *bool, title string, spec ModalSpec, body, footer func()) bool { +func Modal(c C, open *bool, title string, spec ModalSpec, body, footer func()) bool { useDialog() - return base.ModalWith(c, open, title, spec, body, footer) -} - -func Popover(c C, Anchor Box, open *bool, body func()) bool { - usePopover() - return base.Popover(c, Anchor, open, body) + return base.Modal(c, open, title, spec, body, footer) } -func PopoverWith(c C, Anchor Box, open *bool, spec PopoverSpec, body func()) bool { +func Popover(c C, Anchor Box, open *bool, spec PopoverSpec, body func()) bool { usePopover() - return base.PopoverWith(c, Anchor, open, spec, body) + return base.Popover(c, Anchor, open, spec, body) } func Menu(c C, Anchor Box, open *bool, body func(*MenuItems)) { @@ -456,6 +423,18 @@ func NavigateTree(items []TreeNavigationItem, current int, key gfx.Key, pageRows func ID(c C) gfx.ID { return base.ID(c) } +// WithID names a control with an identity the application holds; see base.WithID. +func WithID(id gfx.ID) Option { return base.WithID(id) } + +// SelectGroups puts group headings in a Select's list; see base.SelectGroups. +func SelectGroups(groups []SelectGroup) Option { return base.SelectGroups(groups) } + +// MaxLength caps a text control at n runes; see base.MaxLength. +func MaxLength(n int) Option { return base.MaxLength(n) } + +// ShowCount shows the rune count at the end of a text field; see base.ShowCount. +func ShowCount() Option { return base.ShowCount() } + func NewPage(config PageConfig) *Page { useTooltip(); return base.NewPage(config) } func Shortcut(c C, modifiers gfx.Modifiers, key string) bool { diff --git a/ui/field_alignment_test.go b/ui/field_alignment_test.go index c5c2b7b51..c0e4249f1 100644 --- a/ui/field_alignment_test.go +++ b/ui/field_alignment_test.go @@ -18,7 +18,7 @@ func TestFieldAlignmentPlacesTheValue(t *testing.T) { field := ui.Field{Alignment: align} field.Bind(&editor) d := openPage(t, func(c ui.C) { - ui.TextFieldID(c, ui.ID(c), &field, "Steps", "").Size(64, 32) + ui.TextField(c, &field, "Steps", "", ui.WithID(ui.ID(c))).Size(64, 32) }) for _, painted := range d.driver.Snapshot().Texts { if painted.Value == "30" { diff --git a/ui/field_limit_test.go b/ui/field_limit_test.go new file mode 100644 index 000000000..1478d4218 --- /dev/null +++ b/ui/field_limit_test.go @@ -0,0 +1,71 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/ui" +) + +// MaxLength cuts what is typed beyond the cap, and ShowCount shows how full the +// field is at its end. +func TestMaxLengthCapsTheFieldAndShowCountReportsIt(t *testing.T) { + var name string + d := openPage(t, func(c ui.C) { + ui.TextField(c, &name, "Name", "", ui.MaxLength(5), ui.ShowCount()) + }) + d.click("Name") + d.typeText("abcdefgh") + if name != "abcde" { + t.Fatalf("name = %q after typing eight runes into a field capped at five, want abcde", name) + } + d.repaint() + found := false + for _, text := range d.driver.Snapshot().Texts { + if text.Value == "5/5" { + found = true + } + } + if !found { + t.Fatal("the field does not show its count 5/5") + } +} + +// A field with no cap counts without a total, and one with no ShowCount shows no count. +func TestCountWithoutACapAndCapWithoutACount(t *testing.T) { + var a, b string + d := openPage(t, func(c ui.C) { + ui.TextField(c, &a, "Title", "", ui.ShowCount()) + ui.TextField(c, &b, "Body", "", ui.MaxLength(3)) + }) + d.click("Title") + d.typeText("hey") + d.click("Body") + d.typeText("abcdef") + d.repaint() + var counts []string + for _, text := range d.driver.Snapshot().Texts { + if text.Value == "3" || text.Value == "3/3" { + counts = append(counts, text.Value) + } + } + if len(counts) != 1 || counts[0] != "3" { + t.Fatalf("counts shown = %v, want only the uncapped field's 3", counts) + } + if b != "abc" { + t.Fatalf("body = %q, want abc", b) + } +} + +// A capped, counting field repaints without allocating: the count's words are made +// when the numbers change. +func TestCountedFieldRepaintsWithoutAllocating(t *testing.T) { + name := "abc" + d := openPage(t, func(c ui.C) { + ui.TextField(c, &name, "Name", "", ui.MaxLength(10), ui.ShowCount()) + }) + d.repaint() + d.repaint() + if allocs := testing.AllocsPerRun(100, d.repaint); allocs != 0 { + t.Fatalf("%v allocations a repaint", allocs) + } +} diff --git a/ui/field_multiselection_test.go b/ui/field_multiselection_test.go index 7267fdda8..352e8a93f 100644 --- a/ui/field_multiselection_test.go +++ b/ui/field_multiselection_test.go @@ -18,7 +18,7 @@ func TestFieldPaintsMultipleSelections(t *testing.T) { field.Bind(editor) search := gfx.Item(9) view := func(c ui.C) { - ui.TextFieldID(c, search, &field, "Search", "").Width(200) + ui.TextField(c, &field, "Search", "", ui.WithID(search)).Width(200) } d := openPage(t, view) bands := func() int { @@ -54,7 +54,7 @@ func TestFieldMultiSelectionPaintAllocatesNothing(t *testing.T) { field.Bind(editor) search := gfx.Item(9) d := openPage(t, func(c ui.C) { - ui.TextFieldID(c, search, &field, "Search", "").Width(200) + ui.TextField(c, &field, "Search", "", ui.WithID(search)).Width(200) }) d.repaint() if allocations := testing.AllocsPerRun(100, d.repaint); allocations != 0 { diff --git a/ui/field_paint.go b/ui/field_paint.go index d58738c8d..2989879be 100644 --- a/ui/field_paint.go +++ b/ui/field_paint.go @@ -11,7 +11,7 @@ import ( // // email := ui.ID(c) // ui.Label(c, "Work email").Required().LabelFor(email) -// ui.TextFieldID(c, email, &m.email, "Work email", "") +// ui.TextField(c, &m.email, "Work email", "", ui.WithID(email)) func Label(c C, Text string) Box { useField(); return base.Label(c, Text) } // FieldOrientation is a FormField's arrangement: the title above the control, diff --git a/ui/field_readonly_test.go b/ui/field_readonly_test.go index db6d53f62..662185818 100644 --- a/ui/field_readonly_test.go +++ b/ui/field_readonly_test.go @@ -77,8 +77,8 @@ func TestPageTextAreaStateAndReadOnly(t *testing.T) { disabled.Disabled = true view := func(c ui.C) { ui.Column(c).Pad(16).Gap(8).Children(func() { - ui.TextAreaID(c, gfx.Item(1), &invalid, "Invalid", "").Height(104) - ui.TextAreaID(c, gfx.Item(2), &disabled, "Disabled", "").Height(104) + ui.TextArea(c, &invalid, "Invalid", "", ui.WithID(gfx.Item(1))).Height(104) + ui.TextArea(c, &disabled, "Disabled", "", ui.WithID(gfx.Item(2))).Height(104) }) } page := ui.NewPage(ui.PageConfig{View: view}) diff --git a/ui/filedrop_test.go b/ui/filedrop_test.go new file mode 100644 index 000000000..8303546ea --- /dev/null +++ b/ui/filedrop_test.go @@ -0,0 +1,141 @@ +package ui_test + +import ( + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +type fileDropModel struct { + outer, inner ui.FileDropState + hidden bool +} + +func (m *fileDropModel) page(c ui.C) { + ui.Column(c).Fill().Pad(16).Gap(8).Children(func() { + if m.hidden { + return + } + ui.Column(c).Height(120).FillWidth().Hit(ui.ID(c), "Outer").DropFiles(&m.outer).Children(func() { + ui.Row(c).Height(40).FillWidth().Hit(ui.ID(c), "Inner").DropFiles(&m.inner) + }) + ui.Row(c).Height(30).FillWidth().Hit(ui.ID(c), "Elsewhere") + }) +} + +func dropAt(t *testing.T, d *pageDriver, phase gfx.FileDropPhase, label string, paths ...string) bool { + t.Helper() + x, y := center(d.hit(label).Bounds) + taken, err := d.driver.Drop(gfx.FileDropEvent{Phase: phase, X: x, Y: y, Paths: paths}) + if err != nil { + t.Fatal(err) + } + return taken +} + +func TestFileDropAreaTakesFilesOverIt(t *testing.T) { + m := &fileDropModel{} + d := openPage(t, m.page) + if !dropAt(t, d, gfx.FileDropOver, "Outer") { + t.Fatal("files over an area are not accepted") + } + if !m.outer.Over() { + t.Fatal("no area reports the files over it") + } + if dropAt(t, d, gfx.FileDropOver, "Elsewhere") { + t.Fatal("files over no area are accepted") + } + if m.outer.Over() || m.inner.Over() { + t.Fatal("an area still reports files after they moved away") + } +} + +func TestFileDropGoesToTheInnermostLastDeclaredArea(t *testing.T) { + if runtime.GOOS == "js" { + t.Skip("a browser gives dropped files without paths, so a test cannot drop them by path") + } + m := &fileDropModel{} + d := openPage(t, m.page) + dropAt(t, d, gfx.FileDropOver, "Inner") + if !m.inner.Over() || m.outer.Over() { + t.Fatalf("over: inner %v outer %v, want only the area declared last", m.inner.Over(), m.outer.Over()) + } + path := filepath.Join(t.TempDir(), "a.txt") + if err := os.WriteFile(path, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + if !dropAt(t, d, gfx.FileDropDrop, "Inner", path) { + t.Fatal("the drop is not accepted") + } + files, paths := m.inner.Dropped() + if len(files) != 1 || files[0].Name() != "a.txt" || len(paths) != 1 || paths[0] != path { + t.Fatalf("Dropped = %v, %v", files, paths) + } + if got := ui.FilePath(files[0]); got != path { + t.Fatalf("FilePath = %q, want %q", got, path) + } + if again, _ := m.inner.Dropped(); again != nil { + t.Fatal("Dropped returned the same drop twice") + } + if m.inner.Over() { + t.Fatal("an area still reports files after the drop") + } + if got, _ := m.outer.Dropped(); got != nil { + t.Fatal("the area underneath took the drop too") + } +} + +func TestFileDropLeaveClearsOver(t *testing.T) { + m := &fileDropModel{} + d := openPage(t, m.page) + dropAt(t, d, gfx.FileDropOver, "Outer") + if _, err := d.driver.Drop(gfx.FileDropEvent{Phase: gfx.FileDropLeave}); err != nil { + t.Fatal(err) + } + if m.outer.Over() || m.inner.Over() { + t.Fatal("leaving the window left an area over") + } +} + +func TestFileDropFallsThroughToTheWindowsOwnHandler(t *testing.T) { + m := &fileDropModel{} + var seen int + d := openPageWith(t, ui.PageConfig{View: m.page}, app.Config{OnFileDrop: func(e gfx.FileDropEvent) gfx.EventResult { + seen++ + return gfx.EventResult{Handled: true} + }}) + if !dropAt(t, d, gfx.FileDropOver, "Elsewhere") || seen != 1 { + t.Fatalf("the window's handler saw %d events and the area-less point was not its own", seen) + } + dropAt(t, d, gfx.FileDropOver, "Outer") + if seen != 1 { + t.Fatal("the window's handler saw a drop an area took") + } +} + +func TestFileDropAreaNotDeclaredAnymoreTakesNothing(t *testing.T) { + m := &fileDropModel{} + d := openPage(t, m.page) + m.hidden = true + d.invalidator.Invalidate() + if err := d.driver.Click(1, 1); err != nil { // paint again + t.Fatal(err) + } + if taken, err := d.driver.Drop(gfx.FileDropEvent{Phase: gfx.FileDropOver, X: 60, Y: 60}); err != nil || taken { + t.Fatalf("an undeclared area took files: %v %v", taken, err) + } +} + +func TestFileDropOverDoesNotAllocate(t *testing.T) { + m := &fileDropModel{} + d := openPage(t, m.page) + event := gfx.FileDropEvent{Phase: gfx.FileDropOver, X: 60, Y: 60} + if n := testing.AllocsPerRun(50, func() { d.driver.Drop(event) }); n != 0 { + t.Fatalf("a hover with files allocates %v times", n) + } +} diff --git a/ui/files_facade.go b/ui/files_facade.go new file mode 100644 index 000000000..5b8e0d5c1 --- /dev/null +++ b/ui/files_facade.go @@ -0,0 +1,51 @@ +package ui + +import ( + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" +) + +// OpenFileOptions and FileFilter describe the system's open-file picker: its +// title, the kinds of file it offers and whether it takes several. +type ( + OpenFileOptions = app.OpenFileOptions + FileFilter = app.FileFilter +) + +// ErrOpenCanceled is what OpenFiles reports when the user closes the picker +// without choosing. +var ErrOpenCanceled = app.ErrCanceled + +// OpenFiles presents the system's open-file picker and calls done once with the +// files the user chose, or with an error: ErrOpenCanceled when the picker was +// closed. The files read the same way as the ones dropped on a FileDropState. +// A native picker answers before OpenFiles returns; a browser's answers later, +// on the window's thread, and the window is painted again when it does, so done +// only has to record the result. A browser asks for the call to be made while a +// click is handled, so call it from the code that reacts to Clicked. +func OpenFiles(c C, options OpenFileOptions, done func([]gfx.FileDropFile, error)) error { + wake := c.GetPage().GetInvalidator() + return app.OpenFilesAsync(options, func(refs []app.FileRef, err error) { + if err != nil { + done(nil, err) + } else { + files := make([]gfx.FileDropFile, len(refs)) + for i, ref := range refs { + files[i] = ref + } + done(files, nil) + } + if wake != nil { + wake.Invalidate() + } + }) +} + +// FilePath is the absolute path of a file OpenFiles or a FileDropState gave, or +// the empty string where the platform does not give one (a browser). +func FilePath(file gfx.FileDropFile) string { + if located, ok := file.(interface{ Path() string }); ok { + return located.Path() + } + return "" +} diff --git a/ui/form_field_label_test.go b/ui/form_field_label_test.go index 1ef188e98..52ff3f66f 100644 --- a/ui/form_field_label_test.go +++ b/ui/form_field_label_test.go @@ -8,7 +8,7 @@ import ( // A form field's title labels the control its children declare, as an HTML // label labels the control inside it: pressing the title focuses the field. -// TextFieldID edits a model string under the application's own identity. +// A TextField given WithID edits a model string under the application's own identity. func TestAFormFieldTitleLabelsItsControl(t *testing.T) { var row ui.FormFieldState email := "" @@ -18,7 +18,7 @@ func TestAFormFieldTitleLabelsItsControl(t *testing.T) { id = ui.ID(c) } ui.FormField(c, &row, "Work email").FillWidth().Children(func() { - ui.TextFieldID(c, id, &email, "Email", "you@example.com").FillWidth() + ui.TextField(c, &email, "Email", "you@example.com", ui.WithID(id)).FillWidth() }) }) var title ui.Rect diff --git a/ui/imagepreview/imagepreview.go b/ui/imagepreview/imagepreview.go new file mode 100644 index 000000000..1fd9fc76c --- /dev/null +++ b/ui/imagepreview/imagepreview.go @@ -0,0 +1,269 @@ +// Package imagepreview is the opt-in page control for looking at a picture +// larger than the place it is shown in: a dialog with the image, zoom buttons +// and a pan by dragging. The thumbnail is the page's own (an image.View, a +// card, a button): the page opens the preview from whatever the user pressed, +// and declares the preview where the page is declared: +// +// m.preview = imagepreview.New() +// // in the page: +// if thumbnail.Clicked() { +// m.preview.Open() +// } +// m.preview.View(c, imagepreview.Spec{Bitmap: m.bitmap, Title: "Screenshot"}) +// +// The dialog opens with the whole image in view. The wheel, the buttons and the +// keys + and - zoom, 0 fits the image again, and a drag moves an image larger +// than the view. The Actual size button shows one image pixel for each device pixel. +// Escape, the close button and a press outside close the dialog, as for any +// Modal. +// +// The caller owns the decoded pixels and keeps them unchanged while the dialog +// is open (see image.State.Bitmap). +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Preview in the model; a warm paint allocates nothing. +// Do not copy a Preview after it has been declared. +package imagepreview + +import ( + "strconv" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/image" +) + +var ( + plusIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(5, 12), gfx.LineTo(19, 12), gfx.MoveTo(12, 5), gfx.LineTo(12, 19), + }} + minusIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(5, 12), gfx.LineTo(19, 12), + }} + fitIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(8, 3), gfx.LineTo(5, 3), gfx.QuadTo(3, 3, 3, 5), gfx.LineTo(3, 8), + gfx.MoveTo(21, 8), gfx.LineTo(21, 5), gfx.QuadTo(21, 3, 19, 3), gfx.LineTo(16, 3), + gfx.MoveTo(16, 21), gfx.LineTo(19, 21), gfx.QuadTo(21, 21, 21, 19), gfx.LineTo(21, 16), + gfx.MoveTo(3, 16), gfx.LineTo(3, 19), gfx.QuadTo(3, 21, 5, 21), gfx.LineTo(8, 21), + }} +) + +const ( + zoomStep = 1.25 + // maxZoom is the largest zoom: thirty-two device pixels for an image pixel. + maxZoom = 32 + // defaultWidth and defaultHeight are the view's size in the dialog. + defaultWidth, defaultHeight = 640, 420 + // chromeHeight is what the dialog's title, the buttons below the view and the + // room around them add to the view's height. + chromeHeight = 132 +) + +// Spec declares the dialog. +type Spec struct { + // Bitmap is the picture shown. + Bitmap gfx.Bitmap + // Title names the dialog for assistive technology and heads it; "Image + // preview" when empty. + Title string + // Width and Height are the size of the view in the dialog; 640 by 420 when + // zero or less. + Width, Height float32 + // Labels are the names of the zoom out, zoom in, fit and actual-size + // buttons: "Zoom out", "Zoom in", "Fit" and "Actual size" when empty. The + // first three are icons and name them for assistive technology; between + // the first two the zoom is shown as a percentage. + Labels [4]string +} + +// Preview is one dialog and the zoom and pan of its picture. +type Preview struct { + open bool + view image.State + zoom float32 // device pixels of the screen for an image pixel; zero fits the view + pan gfx.Point + last gfx.Point + dragging bool + size gfx.Size // the view's size in the last paint + bitmap gfx.Bitmap + scale float32 // the canvas's pixel scale in the last paint + percent [2]string + pct int + body func() + c ui.C + spec Spec +} + +// New returns a closed preview. +func New() *Preview { + p := &Preview{pct: -1} + p.view.Pointer = p.pointer + p.view.Scroll = p.scroll + p.view.Key = p.key + return p +} + +// Open shows the dialog with the whole picture in view. +func (p *Preview) Open() { + p.open = true + p.zoom, p.pan = 0, gfx.Point{} +} + +// Close hides the dialog. +func (p *Preview) Close() { p.open = false } + +// IsOpen reports whether the dialog is shown. +func (p *Preview) IsOpen() bool { return p.open } + +// fitZoom is the zoom at which the whole picture is in view. +func (p *Preview) fitZoom() float32 { + if p.bitmap.Width <= 0 || p.bitmap.Height <= 0 || p.size.Width <= 0 { + return 1 + } + return min(p.size.Width/float32(p.bitmap.Width), p.size.Height/float32(p.bitmap.Height)) * p.scale +} + +// current is the zoom in effect. +func (p *Preview) current() float32 { + if p.zoom > 0 { + return p.zoom + } + return p.fitZoom() +} + +func (p *Preview) zoomBy(factor float32) { + p.zoom = min(max(p.current()*factor, p.fitZoom()/4), maxZoom) + p.clampPan() +} + +// clampPan keeps the picture from leaving empty space in the view, as the +// component does when it paints, so a drag past the edge does not build up. +func (p *Preview) clampPan() { + if p.zoom <= 0 { + p.pan = gfx.Point{} + return + } + scale := p.zoom / p.scale + reachX := max((float32(p.bitmap.Width)*scale-p.size.Width)/2, 0) + reachY := max((float32(p.bitmap.Height)*scale-p.size.Height)/2, 0) + p.pan.X = max(min(p.pan.X, reachX), -reachX) + p.pan.Y = max(min(p.pan.Y, reachY), -reachY) +} + +func (p *Preview) pointer(event gfx.PointerEvent) gfx.EventResult { + switch event.Kind { + case gfx.PointerDown: + p.dragging = true + p.last = gfx.Point{X: event.X, Y: event.Y} + return gfx.EventResult{Handled: true} + case gfx.PointerMove: + if !p.dragging && !event.Captured { + return gfx.EventResult{} + } + p.pan.X += event.X - p.last.X + p.pan.Y += event.Y - p.last.Y + p.last = gfx.Point{X: event.X, Y: event.Y} + p.clampPan() + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.PointerUp: + p.dragging = false + return gfx.EventResult{Handled: true} + } + return gfx.EventResult{} +} + +func (p *Preview) scroll(event gfx.ScrollEvent) gfx.EventResult { + if event.DeltaY == 0 { + return gfx.EventResult{} + } + factor := float32(zoomStep) + if event.DeltaY > 0 { + factor = 1 / zoomStep + } + p.zoomBy(factor) + return gfx.EventResult{Handled: true, Repaint: true} +} + +func (p *Preview) key(event gfx.KeyEvent) gfx.EventResult { + if event.Release { + return gfx.EventResult{} + } + switch event.Text { + case "+", "=": + p.zoomBy(zoomStep) + case "-": + p.zoomBy(1 / zoomStep) + case "0": + p.zoom, p.pan = 0, gfx.Point{} + default: + return gfx.EventResult{} + } + return gfx.EventResult{Handled: true, Repaint: true} +} + +// View declares the dialog at c while it is open, and nothing while it is +// closed. Declare it on its own, not inside a Memo. +func (p *Preview) View(c ui.C, spec Spec) { + if p == nil { + panic("imagepreview: View needs its Preview") + } + if !p.open { + return + } + if spec.Title == "" { + spec.Title = "Image preview" + } + if spec.Width <= 0 || spec.Height <= 0 { + spec.Width, spec.Height = defaultWidth, defaultHeight + } + p.bitmap, p.size, p.scale = spec.Bitmap, gfx.Size{Width: spec.Width, Height: spec.Height}, c.Canvas().PixelScale() + p.c, p.spec = c, spec + if p.body == nil { + p.body = p.draw + } + pad := c.Theme().Metrics.PadSurface + ui.Modal(c, &p.open, spec.Title, ui.ModalSpec{Width: spec.Width + 2*pad, Height: spec.Height + chromeHeight}, p.body, nil) +} + +// label is the accessible name of a button, the caller's or the default. +func (s *Spec) label(i int) string { + if s.Labels[i] != "" { + return s.Labels[i] + } + return [4]string{"Zoom out", "Zoom in", "Fit", "Actual size"}[i] +} + +// percentText is the zoom as a percentage of the picture's own size. +func (p *Preview) percentText() string { + pct := int(p.current()*100 + 0.5) + if pct != p.pct || p.percent[0] == "" { + p.pct = pct + p.percent[0] = strconv.Itoa(pct) + "%" + } + return p.percent[0] +} + +func (p *Preview) draw() { + c, spec := p.c, &p.spec + p.clampPan() + ui.Column(c).Gap(c.Theme().Metrics.GapItem).Children(func() { + p.view.Reset().Bitmap(spec.Bitmap).Zoom(p.zoom).Pan(p.pan) + image.View(c, spec.Title, &p.view).Size(spec.Width, spec.Height) + ui.Row(c).Items(ui.Center).Justify(ui.Center).Gap(c.Theme().Metrics.GapItem).Children(func() { + if ui.Button(c, spec.label(0)).Icon(minusIcon).IconOnly().Outline().Clicked() { + p.zoomBy(1 / zoomStep) + } + ui.Text(c, p.percentText()).Muted().Width(48).Shrink(0) + if ui.Button(c, spec.label(1)).Icon(plusIcon).IconOnly().Outline().Clicked() { + p.zoomBy(zoomStep) + } + if ui.Button(c, spec.label(2)).Icon(fitIcon).IconOnly().Outline().Clicked() { + p.zoom, p.pan = 0, gfx.Point{} + } + if ui.Button(c, spec.label(3)).Outline().Clicked() { + p.zoom = 1 + p.clampPan() + } + }) + }) +} diff --git a/ui/imagepreview/imagepreview_test.go b/ui/imagepreview/imagepreview_test.go new file mode 100644 index 000000000..30f3d60cf --- /dev/null +++ b/ui/imagepreview/imagepreview_test.go @@ -0,0 +1,164 @@ +package imagepreview_test + +import ( + "strconv" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/imagepreview" +) + +func bitmap() gfx.Bitmap { + const w, h = 400, 300 + return gfx.Bitmap{Pix: make([]byte, w*h*4), Width: w, Height: h, Stride: w * 4, ID: 77, Version: 1} +} + +type model struct { + p *imagepreview.Preview + bmp gfx.Bitmap +} + +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(16).Children(func() { + ui.Text(c, "page") + m.p.View(c, imagepreview.Spec{Bitmap: m.bmp, Title: "Shot", Width: 400, Height: 240}) + }) +} + +type driver struct { + t *testing.T + *app.Driver + wake *app.Invalidator +} + +// repaint paints the page again, as the window does when the model changed. +func (d driver) repaint() { + d.t.Helper() + d.wake.Invalidate() + if err := d.Pump(); err != nil { + d.t.Fatal(err) + } +} + +func open(t *testing.T, m *model) driver { + t.Helper() + m.p, m.bmp = imagepreview.New(), bitmap() + page := ui.NewPage(ui.PageConfig{View: m.page}) + wake := new(app.Invalidator) + d, err := app.NewDriver(ui.Configure(page, app.Config{Width: 640, Height: 560, Invalidator: wake}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(d.Close) + return driver{t, d, wake} +} + +func (d driver) has(text string) bool { + for _, v := range d.Snapshot().Texts { + if v.Value == text { + return true + } + } + return false +} + +func (d driver) click(label string) { + d.t.Helper() + hits := d.Snapshot().Hits + for i := len(hits) - 1; i >= 0; i-- { + if h := hits[i]; h.Label == label && !h.IsLabel && !h.ID.IsZero() { + if err := d.Click(h.Bounds.X+h.Bounds.Width/2, h.Bounds.Y+h.Bounds.Height/2); err != nil { + d.t.Fatal(err) + } + return + } + } + d.t.Fatalf("no control labeled %q", label) +} + +func TestClosedPreviewDeclaresNothing(t *testing.T) { + d := open(t, &model{}) + for _, h := range d.Snapshot().Hits { + if h.Label == "Zoom in" { + t.Fatal("a closed preview shows its buttons") + } + } +} + +// percent is the zoom the dialog shows, as a number. +func (d driver) percent() int { + d.t.Helper() + for _, v := range d.Snapshot().Texts { + if n := len(v.Value); n > 1 && v.Value[n-1] == '%' { + p, err := strconv.Atoi(v.Value[:n-1]) + if err == nil { + return p + } + } + } + d.t.Fatal("the dialog shows no zoom") + return 0 +} + +func TestZoomButtonsChangeAndRestoreTheZoom(t *testing.T) { + m := &model{} + d := open(t, m) + m.p.Open() + d.repaint() + // The fitted zoom depends on the display's scale (a percentage of device + // pixels), so the test compares the zoom with itself. + fitted := d.percent() + d.click("Zoom in") + in := d.percent() + if in <= fitted { + t.Fatalf("zooming in went from %d%% to %d%%", fitted, in) + } + d.click("Zoom out") + if got := d.percent(); got != fitted { + t.Fatalf("zooming in and out ended at %d%%, want %d%%", got, fitted) + } + d.click("Zoom in") + d.click("Actual size") + if got := d.percent(); got != 100 { + t.Fatalf("Actual size is %d%%, want 100%%", got) + } + d.click("Fit") + if got := d.percent(); got != fitted { + t.Fatalf("Fit is %d%%, want %d%%", got, fitted) + } +} + +func TestEscapeClosesThePreview(t *testing.T) { + m := &model{} + d := open(t, m) + m.p.Open() + d.repaint() + if err := d.Key(gfx.KeyEscape, 0); err != nil { + t.Fatal(err) + } + if m.p.IsOpen() { + t.Fatal("Escape left the preview open") + } +} + +func TestWarmPaintDoesNotAllocate(t *testing.T) { + m := &model{p: imagepreview.New(), bmp: bitmap()} + m.p.Open() + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: m.page, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 640, Height: 560}, m.page) + canvas.EndFrame() + } + draw() + draw() + if n := testing.AllocsPerRun(100, draw); n != 0 { + t.Fatalf("a warm paint allocates %v times", n) + } +} diff --git a/ui/inputgroup/inputgroup.go b/ui/inputgroup/inputgroup.go index 5d29c05ec..364ccab29 100644 --- a/ui/inputgroup/inputgroup.go +++ b/ui/inputgroup/inputgroup.go @@ -51,6 +51,7 @@ type Group struct { blockEnd components.InputGroupSlot small bool + warning bool multiline bool readOnly bool actionID gfx.ID @@ -166,6 +167,13 @@ func (g *Group) Multiline() *Group { return g } +// Warning paints the group with the warning border, for a value that needs a look +// but did not fail; Warning(false) takes it away. The field's Invalid wins over it. +func (g *Group) Warning(warning bool) *Group { + g.warning = warning + return g +} + // ReadOnly paints the field as not editable without taking it out of the tab // order or the pointer's reach. func (g *Group) ReadOnly() *Group { @@ -282,7 +290,7 @@ func (g *Group) draw(d *ui.DrawContext) { input := g.field.Snapshot(d.Frame, id, g.label, g.placeholder) snapshot := components.InputGroupSnapshot{ ID: id, Label: g.label, Value: input.Value, Placeholder: g.placeholder, - Disabled: input.Disabled, Invalid: input.Invalid, Secure: input.Secure, + Disabled: input.Disabled, Invalid: input.Invalid, Warning: g.warning, Secure: input.Secure, Focused: input.Focused, Multiline: g.multiline, ReadOnly: g.readOnly, HideEditorText: true, ShowCaret: input.ShowCaret, Caret: input.Caret, SelectionStart: input.SelectionStart, SelectionEnd: input.SelectionEnd, diff --git a/ui/inputnumber/inputnumber.go b/ui/inputnumber/inputnumber.go new file mode 100644 index 000000000..96457cba8 --- /dev/null +++ b/ui/inputnumber/inputnumber.go @@ -0,0 +1,299 @@ +// Package inputnumber is the opt-in page control for a number field: a text +// field that holds a number, with a button on each side that steps it down and +// up. A page keeps an InputNumber in its model beside the number it edits: +// +// m.port = inputnumber.New().Min(1).Max(65535) +// // in the page: +// m.port.View(c, "Port", &m.portValue).Width(160) +// if m.port.Changed() { +// // the user entered or stepped to a new number; m.portValue holds it +// } +// +// The user types a number and it is taken when the field loses the focus or +// Enter is pressed; text that is not a number is put back to the number the +// field held. A number outside Min and Max is brought into range. Up and Down +// step the number by Step while the field has the focus, PageUp and PageDown by +// ten steps, and Home and End go to Min and Max when they are set. The buttons +// step it too, and are dimmed at the ends of the range. +// +// Precision is how many decimals the number is shown and kept with; it follows +// Step by default, so a step of 0.1 shows one decimal. The number is a float64: +// whole numbers up to 2^53 are exact. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an InputNumber in the model: it holds the field and the +// handlers, so a warm paint allocates nothing. Do not copy an InputNumber after +// it has been declared. +package inputnumber + +import ( + "math" + "strconv" + "strings" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +var ( + minusIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(5, 12), gfx.LineTo(19, 12), + }} + plusIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(5, 12), gfx.LineTo(19, 12), gfx.MoveTo(12, 5), gfx.LineTo(12, 19), + }} +) + +// InputNumber is one number field. Configure it with the chainable methods; they +// may be called before each View. +type InputNumber struct { + field ui.Field + keyFn func(gfx.KeyEvent) gfx.EventResult + + min, max float64 + step float64 + precision int // decimals; negative follows step + hint string + readOnly bool + decrease string + increase string + fieldID gfx.ID + fieldOpt [1]ui.Option + + value *float64 + shown float64 // the number the field's text was made from + shownSet bool + focused bool // the field had the focus in the last paint + changed bool + reported bool +} + +// New returns a number field with no range, a step of one and no decimals. +func New() *InputNumber { + n := &InputNumber{min: math.Inf(-1), max: math.Inf(1), step: 1, precision: -1, decrease: "Decrease", increase: "Increase"} + n.keyFn = n.key + return n +} + +// Min is the least number the field takes. +func (n *InputNumber) Min(min float64) *InputNumber { + n.min = min + return n +} + +// Max is the greatest number the field takes. +func (n *InputNumber) Max(max float64) *InputNumber { + n.max = max + return n +} + +// Step is how much the buttons and the arrow keys change the number; one by +// default. It must be above zero. +func (n *InputNumber) Step(step float64) *InputNumber { + if step > 0 { + n.step = step + } + return n +} + +// Precision is how many decimals the number is shown and kept with. By default it +// is as many as Step has. +func (n *InputNumber) Precision(decimals int) *InputNumber { + n.precision = max(decimals, 0) + return n +} + +// Placeholder is the text shown while the field is empty. +func (n *InputNumber) Placeholder(text string) *InputNumber { + n.hint = text + return n +} + +// ReadOnly shows the number and takes no input. +func (n *InputNumber) ReadOnly() *InputNumber { + n.readOnly = true + return n +} + +// Editable clears ReadOnly, for a page that enables editing later. +func (n *InputNumber) Editable() *InputNumber { + n.readOnly = false + return n +} + +// ButtonLabels are the accessible names of the two step buttons, "Decrease" and +// "Increase" by default, for a page in another language. +func (n *InputNumber) ButtonLabels(decrease, increase string) *InputNumber { + n.decrease, n.increase = decrease, increase + return n +} + +// FieldID gives the text field an identity of the application's own instead of the +// one its place gives it. It is for a runner that resolves the platform text +// service by an application identity, such as a component preview. +func (n *InputNumber) FieldID(id gfx.ID) *InputNumber { + n.fieldID, n.fieldOpt[0] = id, ui.WithID(id) + return n +} + +// Field is the text field behind the number, for a runner that binds the editor +// the platform edits to it with Field.Bind. A page does not need it. +func (n *InputNumber) Field() *ui.Field { return &n.field } + +// Changed reports whether the user entered or stepped to a new number in the +// paint that delivered it. +func (n *InputNumber) Changed() bool { return n.reported } + +// decimals is how many decimals the number carries. +func (n *InputNumber) decimals() int { + if n.precision >= 0 { + return n.precision + } + text := strconv.FormatFloat(n.step, 'f', -1, 64) + if dot := strings.IndexByte(text, '.'); dot >= 0 { + return len(text) - dot - 1 + } + return 0 +} + +// tidy is x in range and rounded to the decimals the field keeps. +func (n *InputNumber) tidy(x float64) float64 { + scale := math.Pow10(n.decimals()) + x = math.Round(x*scale) / scale + return math.Min(math.Max(x, n.min), n.max) +} + +func (n *InputNumber) format(x float64) string { + return strconv.FormatFloat(x, 'f', n.decimals(), 64) +} + +// parse is the number a text holds. A text with no digits, or one that is not a +// number, holds none. +func parse(text string) (float64, bool) { + text = strings.TrimSpace(text) + if text == "" { + return 0, false + } + x, err := strconv.ParseFloat(text, 64) + if err != nil || math.IsNaN(x) || math.IsInf(x, 0) { + return 0, false + } + return x, true +} + +// show puts x in the field's text. +func (n *InputNumber) show(x float64) { + n.field.SetText(n.format(x)) + n.shown, n.shownSet = x, true + n.field.Invalid = false +} + +// take makes x the number of the field and reports whether it changed. +func (n *InputNumber) take(x float64) { + x = n.tidy(x) + if x != *n.value { + *n.value, n.changed = x, true + } + n.show(*n.value) +} + +// commit takes the number the field's text holds, or puts the held one back. +func (n *InputNumber) commit() { + if x, ok := parse(n.field.Text()); ok { + n.take(x) + return + } + n.show(*n.value) +} + +// stepBy changes the number by delta steps, from what the field's text says. +func (n *InputNumber) stepBy(delta float64) { + from := *n.value + if x, ok := parse(n.field.Text()); ok { + from = n.tidy(x) + } + n.take(from + delta*n.step) +} + +func (n *InputNumber) key(event gfx.KeyEvent) gfx.EventResult { + if n.readOnly || n.value == nil { + return gfx.EventResult{} + } + switch event.Key { + case gfx.KeyUp: + n.stepBy(1) + case gfx.KeyDown: + n.stepBy(-1) + case gfx.KeyPageUp: + n.stepBy(10) + case gfx.KeyPageDown: + n.stepBy(-10) + case gfx.KeyHome: + if math.IsInf(n.min, 0) { + return gfx.EventResult{} + } + n.take(n.min) + case gfx.KeyEnd: + if math.IsInf(n.max, 0) { + return gfx.EventResult{} + } + n.take(n.max) + default: + return gfx.EventResult{} + } + return gfx.EventResult{Handled: true, Repaint: true} +} + +// View declares the field at c, showing and editing *value. label names it for +// assistive technology. The row is one control high; give it a Width. Declare the +// view on its own, not inside a Memo. +func (n *InputNumber) View(c ui.C, label string, value *float64) ui.Box { + if n == nil { + panic("inputnumber: View needs its InputNumber") + } + if value == nil { + panic("inputnumber: View needs the number") + } + n.reported, n.changed = n.changed, false + n.value = value + if math.IsNaN(*value) { + *value = 0 + } + *value = n.tidy(*value) + focused := n.focused + // Out of the field, the text follows the number the page holds. + if !n.shownSet || (!focused && *value != n.shown) { + n.show(*value) + } + n.field.ReadOnly = n.readOnly + row := ui.Row(c).Gap(4).Items(ui.Center) + row.Children(func() { + step := ui.Button(c, n.decrease).Icon(minusIcon).IconOnly().Outline().Disabled(n.readOnly || *value <= n.min) + if step.Clicked() { + n.stepBy(-1) + } + var options []ui.Option + if !n.fieldID.IsZero() { + options = n.fieldOpt[:] + } + field := ui.TextField(c, &n.field, label, n.hint, options...).Grow(1).TextCenter() + field.OnKey(n.keyFn) + if field.Submitted() { + n.commit() + } + step = ui.Button(c, n.increase).Icon(plusIcon).IconOnly().Outline().Disabled(n.readOnly || *value >= n.max) + if step.Clicked() { + n.stepBy(1) + } + now := c.Canvas().Focused() == n.field.ID && !n.field.ID.IsZero() + if n.focused && !now { + n.commit() + } else if now { + // While it is edited, text that is not a number is marked. + _, ok := parse(n.field.Text()) + n.field.Invalid = !ok && n.field.Text() != "" + } + n.focused = now + }) + return row +} diff --git a/ui/inputnumber/inputnumber_test.go b/ui/inputnumber/inputnumber_test.go new file mode 100644 index 000000000..dbcf6a3e9 --- /dev/null +++ b/ui/inputnumber/inputnumber_test.go @@ -0,0 +1,225 @@ +//go:build !js + +package inputnumber_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/inputnumber" +) + +// changes counts the paints that reported a change, as a page reads Changed. +var changes int + +// open runs a page holding one number field over *value and a button to move the +// focus to, headlessly. +func open(t *testing.T, n *inputnumber.InputNumber, value *float64) *headless.Session { + t.Helper() + changes = 0 + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Gap(8).Children(func() { + n.View(c, "Port", value).Width(200) + if n.Changed() { + changes++ + } + ui.Button(c, "Elsewhere") + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Number", Width: 360, Height: 200}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +func shown(t *testing.T, session *headless.Session) string { + t.Helper() + node, ok := session.AccessByName("Port") + if !ok { + t.Fatal("the field is not in the accessibility tree") + } + return node.Value +} + +// The buttons step the number, and the one at an end of the range is dimmed and +// cannot be pressed. +func TestButtonsStepWithinTheRange(t *testing.T) { + value := 8.0 + session := open(t, inputnumber.New().Min(0).Max(10).Step(2), &value) + if err := session.ClickLabel("Increase"); err != nil { + t.Fatal(err) + } + if value != 10 { + t.Fatalf("value = %v after Increase from 8 by 2, want 10", value) + } + if err := session.ClickLabel("Increase"); err == nil { + t.Fatal("Increase could be pressed at the top of the range") + } + if err := session.ClickLabel("Decrease"); err != nil { + t.Fatal(err) + } + if value != 8 { + t.Fatalf("value = %v after Decrease from 10, want 8", value) + } + if got := shown(t, session); got != "8" { + t.Fatalf("the field shows %q, want 8", got) + } + if changes == 0 { + t.Fatal("Changed was never reported for a step") + } +} + +// A number is typed in and taken on Enter; text that is not a number is put back +// to the number the field held. +func TestEnterTakesTheTypedNumber(t *testing.T) { + value := 22.0 + session := open(t, inputnumber.New().Min(1).Max(100), &value) + if err := session.ClickLabel("Port"); err != nil { + t.Fatal(err) + } + session.Keys("cmd+a") + if err := session.Type("42"); err != nil { + t.Fatal(err) + } + if err := session.Keys("enter"); err != nil { + t.Fatal(err) + } + if value != 42 { + t.Fatalf("value = %v after typing 42 and Enter, want 42", value) + } + session.Keys("cmd+a") + if err := session.Type("abc"); err != nil { + t.Fatal(err) + } + if err := session.Keys("enter"); err != nil { + t.Fatal(err) + } + if value != 42 || shown(t, session) != "42" { + t.Fatalf("value = %v, shown %q after text that is not a number, want 42 put back", value, shown(t, session)) + } +} + +// A number outside the range is brought in when the field loses the focus. +func TestLeavingTheFieldTakesTheNumberInRange(t *testing.T) { + value := 22.0 + session := open(t, inputnumber.New().Min(1).Max(100), &value) + if err := session.ClickLabel("Port"); err != nil { + t.Fatal(err) + } + session.Keys("cmd+a") + if err := session.Type("999"); err != nil { + t.Fatal(err) + } + if err := session.ClickLabel("Elsewhere"); err != nil { + t.Fatal(err) + } + if value != 100 || shown(t, session) != "100" { + t.Fatalf("value = %v, shown %q after leaving the field with 999, want 100", value, shown(t, session)) + } +} + +// Up and Down step the number while the field has the focus, PageUp by ten. +func TestArrowKeysStepTheNumber(t *testing.T) { + value := 5.0 + session := open(t, inputnumber.New(), &value) + if err := session.ClickLabel("Port"); err != nil { + t.Fatal(err) + } + for _, step := range []struct { + key string + want float64 + }{{"up", 6}, {"down", 5}, {"pageup", 15}, {"pagedown", 5}} { + if err := session.Keys(step.key); err != nil { + t.Fatal(err) + } + if value != step.want { + t.Fatalf("value = %v after %q, want %v", value, step.key, step.want) + } + } +} + +// The decimals follow the step, so a tenth steps without drifting. +func TestPrecisionFollowsTheStep(t *testing.T) { + value := 0.5 + session := open(t, inputnumber.New().Step(0.1), &value) + for range 3 { + if err := session.ClickLabel("Increase"); err != nil { + t.Fatal(err) + } + } + if value != 0.8 { + t.Fatalf("value = %v after three steps of 0.1 from 0.5, want exactly 0.8", value) + } + if got := shown(t, session); got != "0.8" { + t.Fatalf("the field shows %q, want 0.8", got) + } +} + +// A number the page changes shows in the field while it is not being edited. +func TestTheFieldFollowsThePage(t *testing.T) { + value := 1.0 + session := open(t, inputnumber.New(), &value) + value = 7 + if err := session.Frame(); err != nil { + t.Fatal(err) + } + if got := shown(t, session); got != "7" { + t.Fatalf("the field shows %q after the page set 7", got) + } +} + +// A read only field takes no input and offers no step. +func TestReadOnlyTakesNoInput(t *testing.T) { + value := 3.0 + session := open(t, inputnumber.New().ReadOnly(), &value) + session.ClickLabel("Increase") + if err := session.ClickLabel("Port"); err != nil { + t.Fatal(err) + } + session.Keys("up") + if value != 3 { + t.Fatalf("value = %v after input on a read only field, want 3", value) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + value := 12.5 + n := inputnumber.New().Step(0.5).Min(0).Max(100) + view := func(c ui.C) { n.View(c, "Port", &value).Width(200) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 360, Height: 200}, view) + canvas.EndFrame() + } + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + value := 12.5 + n := inputnumber.New().Step(0.5).Min(0).Max(100) + view := func(c ui.C) { n.View(c, "Port", &value).Width(200) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + b.ReportAllocs() + for range b.N { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 360, Height: 200}, view) + canvas.EndFrame() + } +} diff --git a/ui/label_test.go b/ui/label_test.go index d3b427542..1374d31a5 100644 --- a/ui/label_test.go +++ b/ui/label_test.go @@ -62,7 +62,7 @@ func TestPageLabelLabelsForItsControl(t *testing.T) { d := openPage(t, func(c ui.C) { ui.Column(c).Pad(16).Gap(8).Children(func() { ui.Label(c, "Work email").Required().LabelFor(control) - ui.TextFieldID(c, control, &field, "Work email", "") + ui.TextField(c, &field, "Work email", "", ui.WithID(control)) }) }) for _, hit := range d.driver.Snapshot().Hits { diff --git a/ui/leaves_paint.go b/ui/leaves_paint.go index 9dd9e8893..fc08ca305 100644 --- a/ui/leaves_paint.go +++ b/ui/leaves_paint.go @@ -7,8 +7,25 @@ import ( func paintProgress(f *Frame, n *Node) { r := n.Rect + palette := f.Palette + switch n.Status { + case StatusSuccess: + palette.Primary = palette.Success + case StatusWarning: + palette.Primary = palette.WarningColor() + case StatusDanger: + palette.Primary = palette.Danger + } + if n.Circle { + paintProgressRing(f, n, palette) + return + } + if n.Segments > 1 && n.Natural >= 0 { + paintProgressSegments(f, n, palette) + return + } if n.Natural >= 0 { - components.Progress(f.Surface, f.Palette, r, n.Natural) + components.Progress(f.Surface, palette, r, n.Natural) paintProgressHit(f, n, r, n.Natural) return } @@ -30,7 +47,7 @@ func paintProgress(f *Frame, n *Node) { } } canvas.Clip(r) - canvas.Rounded(Rect{X: x, Y: r.Y, Width: segment, Height: r.Height}, r.Height/2, f.Palette.Primary) + canvas.Rounded(Rect{X: x, Y: r.Y, Width: segment, Height: r.Height}, r.Height/2, palette.Primary) canvas.Unclip() paintProgressHit(f, n, r, -1) } @@ -63,3 +80,64 @@ func paintSpinner(f *Frame, n *Node) { } components.PaintSpinner(canvas, f.Palette, n.Rect, phase) } + +// paintProgressRing draws a circular Progress: a muted ring and over it the arc of the +// fraction, clockwise from twelve o'clock with round ends. An indeterminate one is an +// arc of a quarter turn that keeps going round, and holds still when the system asks +// for reduced motion. +func paintProgressRing(f *Frame, n *Node, palette Theme) { + canvas := f.Surface + r := n.Rect + side := min(r.Width, r.Height) + if side <= 0 { + return + } + box := Rect{X: r.X + (r.Width-side)/2, Y: r.Y + (r.Height-side)/2, Width: side, Height: side} + width := min(max(side*0.09, 3), 10) + radius := (side - width) / 2 + builder := canvas.PathBuilder() + builder.Arc(side/2, side/2, radius, -90, 360) + canvas.DrawPath(builder.Path(side, side), box, gfx.PathStyle{Stroke: palette.Muted, StrokeWidth: width}) + filled := min(n.Natural, 1) + start, sweep, fraction := float32(-90), filled*360, filled + if n.Natural < 0 { + sweep, fraction = 90, -1 + if !canvas.ReduceMotion() { + start += 360 * float32(canvas.Now()%IndeterminatePeriod) / float32(IndeterminatePeriod) + if f.Visible(n) { + canvas.RequestFrame() + } + } + } + if sweep > 0 { + builder = canvas.PathBuilder() + builder.Arc(side/2, side/2, radius, start, min(sweep, 359.9)) + canvas.DrawPath(builder.Path(side, side), box, gfx.PathStyle{Stroke: palette.Primary, StrokeWidth: width, Cap: gfx.CapRound}) + } + paintProgressHit(f, n, box, fraction) +} + +// paintProgressSegments draws a Progress as separate segments: the first of them +// filled, a segment from half of it. +func paintProgressSegments(f *Frame, n *Node, palette Theme) { + canvas := f.Surface + r := n.Rect + if r.Height <= 0 { + r.Height = ProgressHeight + } + count := int(n.Segments) + const gap = float32(3) + width := (r.Width - gap*float32(count-1)) / float32(count) + if width <= 0 { + return + } + filled := int(min(n.Natural, 1)*float32(count) + 0.5) + for i := range count { + color := palette.Muted + if i < filled { + color = palette.Primary + } + canvas.Rounded(Rect{X: r.X + float32(i)*(width+gap), Y: r.Y, Width: width, Height: r.Height}, r.Height/2, color) + } + paintProgressHit(f, n, r, min(n.Natural, 1)) +} diff --git a/ui/mentions/mentions.go b/ui/mentions/mentions.go new file mode 100644 index 000000000..fb39137b3 --- /dev/null +++ b/ui/mentions/mentions.go @@ -0,0 +1,303 @@ +// Package mentions is the opt-in page control for a text field that offers +// people, hosts or tags as the user types a trigger: typing "@" and a few +// letters opens a list under the field, and choosing one writes it in place of +// what was typed. A page keeps the field's value in a ui.Field and a Mentions in +// its model: +// +// m.mentions = mentions.New() +// // in the page: +// m.mentions.View(c, &m.message, "Message", "Write a message", mentions.Spec{Options: m.people}) +// if option, ok := m.mentions.Chosen(); ok { +// m.notify(option) // the field already holds "@Ada " +// } +// +// The list opens while the caret is at the end of a word that starts with the +// Trigger ("@" by default) at the start of the text or after a space, and closes +// when the word ends, the caret leaves it or the field loses the keyboard. Up +// and Down move through the options, Enter and Tab choose the highlighted one, +// and Escape closes the list until the word changes; the other keys type as +// usual. An option matches when the typed letters appear in its Label, without +// regard to case. A press on an option chooses it without taking the keyboard +// from the field. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Mentions in the model beside its field: its state is +// made once, and a paint allocates nothing while no mention is being typed. Do +// not copy a Mentions after it has been declared. +package mentions + +import ( + "strings" + "unicode" + "unicode/utf8" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" +) + +// Option is one thing that can be mentioned. +type Option struct { + // Label is what is written after the trigger and what the typed letters are + // matched against. + Label string + // Detail is a muted second line of the list, such as a role or an address; + // it is not matched. + Detail string +} + +// Spec declares the list. +type Spec struct { + // Options are everything that can be mentioned, in the order the list shows + // the ones that match. Keep the slice in the model. + Options []Option + // Trigger is the rune that starts a mention; '@' when zero. + Trigger rune + // MaxRows is how many options the list shows at most; 6 when zero. + MaxRows int + // Empty is the line of the list when nothing matches; the list stays closed + // when it is empty. + Empty string + // NoSuffix leaves out the space written after a chosen option. + NoSuffix bool +} + +// Mentions is one field's list. +type Mentions struct { + open bool + matches []int // indexes into Spec.Options of the rows shown + highlight int + wordStart int // the rune index of the trigger of the word being typed, or -1 + dismissed int // the wordStart Escape closed the list for, or -1 + chosen int // 1 + the option chosen since the last paint, or 0 + pending int // what a key or press chose, reported by the paint after it + spec Spec + field *ui.Field + key func(gfx.KeyEvent) gfx.EventResult + id gfx.ID + fieldID gfx.ID +} + +// New returns a closed list. +func New() *Mentions { + m := &Mentions{wordStart: -1, dismissed: -1} + m.key = m.onKey + return m +} + +// FieldID names the field with an identity the application already holds, in +// place of the one its place gives it. It is for a runner that resolves the +// platform text service by an application identity, such as a component +// preview; a page does not need it. +func (m *Mentions) FieldID(id gfx.ID) *Mentions { m.fieldID = id; return m } + +// Chosen reports the option the user chose since the paint before this one, +// by key or by press. +func (m *Mentions) Chosen() (Option, bool) { + if m.chosen == 0 { + return Option{}, false + } + return m.spec.Options[m.chosen-1], true +} + +func (s *Spec) trigger() rune { + if s.Trigger == 0 { + return '@' + } + return s.Trigger +} + +// word finds the mention being typed: the rune index of the trigger and the +// letters after it, when the caret (a rune index) is at the end of a word that +// starts with the trigger. It reads the text in place and allocates nothing. +func word(value string, caret int, trigger rune) (start int, query string, ok bool) { + end := 0 + for n := 0; n < caret && end < len(value); n++ { + _, size := utf8.DecodeRuneInString(value[end:]) + end += size + } + prefix := value[:end] + for i := len(prefix); i > 0; { + r, size := utf8.DecodeLastRuneInString(prefix[:i]) + i -= size + switch { + case r == trigger: + if i > 0 { + if before, _ := utf8.DecodeLastRuneInString(prefix[:i]); !unicode.IsSpace(before) { + return 0, "", false + } + } + return utf8.RuneCountInString(prefix[:i]), prefix[i+size:], true + case unicode.IsSpace(r): + return 0, "", false + } + } + return 0, "", false +} + +// containsFold reports whether s has query in it, without regard to case. +func containsFold(s, query string) bool { + if query == "" { + return true + } + for i := range s { + rest, q := s[i:], query + for q != "" && rest != "" { + a, as := utf8.DecodeRuneInString(rest) + b, bs := utf8.DecodeRuneInString(q) + if unicode.ToLower(a) != unicode.ToLower(b) { + break + } + rest, q = rest[as:], q[bs:] + } + if q == "" { + return true + } + } + return false +} + +// refresh finds the word at the caret and the options that match it, and +// reports whether the list is to be shown. +func (m *Mentions) refresh(c ui.C, spec Spec) bool { + m.matches = m.matches[:0] + editor := m.field.GetEditor() + if editor == nil || c.Canvas().Focused() != m.id { + m.wordStart = -1 + return false + } + selection := editor.Selection() + if selection.Start != selection.End { + m.wordStart = -1 + return false + } + start, query, ok := word(editor.String(), editor.Caret(), spec.trigger()) + if !ok { + m.wordStart, m.dismissed = -1, -1 + return false + } + if start != m.wordStart { + m.highlight = 0 + } + m.wordStart = start + if m.dismissed == start { + return false + } + limit := spec.MaxRows + if limit <= 0 { + limit = 6 + } + for i := range spec.Options { + if len(m.matches) == limit { + break + } + if containsFold(spec.Options[i].Label, query) { + m.matches = append(m.matches, i) + } + } + m.highlight = min(m.highlight, max(len(m.matches)-1, 0)) + return len(m.matches) > 0 || spec.Empty != "" +} + +func (m *Mentions) onKey(event gfx.KeyEvent) gfx.EventResult { + if !m.open || event.Release { + return gfx.EventResult{} + } + switch event.Key { + case gfx.KeyDown: + if len(m.matches) > 0 { + m.highlight = (m.highlight + 1) % len(m.matches) + } + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyUp: + if len(m.matches) > 0 { + m.highlight = (m.highlight + len(m.matches) - 1) % len(m.matches) + } + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyEnter, gfx.KeyTab: + if len(m.matches) == 0 { + return gfx.EventResult{} + } + m.insert(m.matches[m.highlight]) + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyEscape: + m.dismissed = m.wordStart + m.open = false + return gfx.EventResult{Handled: true, Repaint: true} + } + return gfx.EventResult{} +} + +// insert writes the option in place of the word being typed. +func (m *Mentions) insert(index int) { + editor := m.field.GetEditor() + if editor == nil || m.wordStart < 0 { + return + } + var b strings.Builder + b.WriteRune(m.spec.trigger()) + b.WriteString(m.spec.Options[index].Label) + if !m.spec.NoSuffix { + b.WriteByte(' ') + } + editor.SetSelection(text.Range{Start: m.wordStart, End: editor.Caret()}) + editor.Insert(b.String()) + m.pending = index + 1 + m.open = false + m.wordStart, m.dismissed = -1, -1 +} + +// View declares the field and, while a mention is being typed, the list under +// it. The field is a ui.TextField on field; label and placeholder are its. +// Declare the view on its own, not inside a Memo. +func (m *Mentions) View(c ui.C, field *ui.Field, label, placeholder string, spec Spec) ui.Box { + if m == nil { + panic("mentions: View needs its Mentions") + } + m.chosen, m.pending = m.pending, 0 + m.spec, m.field = spec, field + m.id = m.fieldID + if m.id.IsZero() { + m.id = ui.ID(c) + } + m.open = m.refresh(c, spec) + box := ui.TextField(c, field, label, placeholder, ui.WithID(m.id)).OnKey(m.key) + if m.open { + ui.Popover(c, box, &m.open, ui.PopoverSpec{ + Align: ui.Start, Padding: 4, Instant: true, + NoDismiss: true, KeepOpenOnAnchor: true, + }, func() { m.list(c) }) + } + return box +} + +// list declares the rows of the options that match. +func (m *Mentions) list(c ui.C) { + theme := c.Theme() + metrics := theme.Metrics + ui.Column(c).FillWidth().Children(func() { + if len(m.matches) == 0 { + ui.Text(c, m.spec.Empty).Muted().FontSize(metrics.FontSizeS).Pad(metrics.GapItem) + return + } + for row, index := range m.matches { + option := &m.spec.Options[index] + item := c.KeyInt(index) + box := ui.Row(item).FillWidth().Items(ui.Center).Gap(metrics.GapItem).Pad(metrics.GapItem).Radius(metrics.RadiusControl) + if row == m.highlight { + box = box.Background(theme.Accent) + } + box = box.HitWith(ui.ID(item), option.Label, gfx.HitOptions{Role: gfx.RoleOption, SkipFocus: true}) + box.Hover(ui.Look{}.Background(theme.Hover)) + box.Children(func() { + ui.Text(item, option.Label).Shrink(0) + if option.Detail != "" { + ui.Text(item, option.Detail).FontSize(metrics.FontSizeS).Muted().Ellipsis() + } + }) + if box.Clicked() { + m.insert(index) + } + } + }) +} diff --git a/ui/mentions/mentions_test.go b/ui/mentions/mentions_test.go new file mode 100644 index 000000000..6195330a4 --- /dev/null +++ b/ui/mentions/mentions_test.go @@ -0,0 +1,160 @@ +package mentions_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/mentions" +) + +var people = []mentions.Option{{Label: "Ada", Detail: "Engineer"}, {Label: "Grace", Detail: "Admiral"}, {Label: "Alan"}} + +type model struct { + m *mentions.Mentions + field ui.Field + chosen []string + options []mentions.Option +} + +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(16).Children(func() { + m.m.View(c, &m.field, "Message", "", mentions.Spec{Options: m.options, Empty: "No one"}).FillWidth() + if o, ok := m.m.Chosen(); ok { + m.chosen = append(m.chosen, o.Label) + } + }) +} + +type driver struct { + t *testing.T + *app.Driver +} + +func open(t *testing.T) (*model, driver) { + t.Helper() + m := &model{m: mentions.New(), options: people} + page := ui.NewPage(ui.PageConfig{View: m.page}) + d, err := app.NewDriver(ui.Configure(page, app.Config{Width: 400, Height: 320, Invalidator: new(app.Invalidator)}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(d.Close) + dr := driver{t, d} + dr.click("Message") + return m, dr +} + +func (d driver) click(label string) { + d.t.Helper() + hits := d.Snapshot().Hits + for i := len(hits) - 1; i >= 0; i-- { + if h := hits[i]; h.Label == label && !h.IsLabel && !h.ID.IsZero() { + if err := d.Click(h.Bounds.X+h.Bounds.Width/2, h.Bounds.Y+h.Bounds.Height/2); err != nil { + d.t.Fatal(err) + } + return + } + } + d.t.Fatalf("no control labeled %q", label) +} + +func (d driver) listed(label string) bool { + for _, h := range d.Snapshot().Hits { + if h.Label == label && h.Role == gfx.RoleOption { + return true + } + } + return false +} + +func (d driver) typeText(s string) { + d.t.Helper() + if err := d.Type(s); err != nil { + d.t.Fatal(err) + } +} + +func TestTypingTheTriggerOpensTheMatchingOptions(t *testing.T) { + _, d := open(t) + d.typeText("hi @gr") + if !d.listed("Grace") || d.listed("Ada") || d.listed("Alan") { + t.Fatalf("list after @gr: Grace %v Ada %v Alan %v", d.listed("Grace"), d.listed("Ada"), d.listed("Alan")) + } +} + +func TestATriggerInsideAWordOpensNothing(t *testing.T) { + _, d := open(t) + d.typeText("mail me at x@gr") + if d.listed("Grace") { + t.Fatal("an @ inside a word opened the list") + } +} + +func TestEnterChoosesTheHighlightedOption(t *testing.T) { + m, d := open(t) + d.typeText("hi @a") + if err := d.Key(gfx.KeyDown, 0); err != nil { + t.Fatal(err) + } + if err := d.Key(gfx.KeyEnter, 0); err != nil { + t.Fatal(err) + } + if got := m.field.GetEditor().String(); got != "hi @Grace " { + t.Fatalf("field = %q, want %q", got, "hi @Grace ") + } + if len(m.chosen) != 1 || m.chosen[0] != "Grace" { + t.Fatalf("chosen %v", m.chosen) + } + if d.listed("Ada") { + t.Fatal("the list stayed open after a choice") + } +} + +func TestPressingAnOptionChoosesItAndKeepsTheField(t *testing.T) { + m, d := open(t) + d.typeText("@") + d.click("Alan") + if got := m.field.GetEditor().String(); got != "@Alan " { + t.Fatalf("field = %q", got) + } +} + +func TestEscapeClosesTheListUntilTheWordChanges(t *testing.T) { + _, d := open(t) + d.typeText("@a") + if err := d.Key(gfx.KeyEscape, 0); err != nil { + t.Fatal(err) + } + if d.listed("Ada") { + t.Fatal("Escape left the list open") + } + d.typeText("d") + if d.listed("Ada") { + t.Fatal("the list came back while the same word was being typed") + } + d.typeText(" @a") + if !d.listed("Ada") { + t.Fatal("a new word did not open the list") + } +} + +func TestClosedFieldPaintsWithoutAllocating(t *testing.T) { + m := &model{m: mentions.New(), options: people} + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: m.page, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 400, Height: 320}, m.page) + canvas.EndFrame() + } + draw() + draw() + if n := testing.AllocsPerRun(100, draw); n != 0 { + t.Fatalf("a warm paint allocates %v times", n) + } +} diff --git a/ui/mentions/word_test.go b/ui/mentions/word_test.go new file mode 100644 index 000000000..5234a1900 --- /dev/null +++ b/ui/mentions/word_test.go @@ -0,0 +1,50 @@ +package mentions + +import "testing" + +func TestWordFindsTheMentionAtTheCaret(t *testing.T) { + cases := []struct { + value string + caret int + wantStart int + wantQuery string + wantOK bool + }{ + {"@", 1, 0, "", true}, + {"hi @gr", 6, 3, "gr", true}, + {"hi @gr there", 6, 3, "gr", true}, + {"hi @gr", 3, 0, "", false}, + {"x@gr", 4, 0, "", false}, + {"hi @gr ", 7, 0, "", false}, + {"你好 @张三", 6, 3, "张三", true}, + {"@a\n@b", 5, 3, "b", true}, + {"", 0, 0, "", false}, + {"@gr", 9, 0, "@gr"[1:], true}, // a caret past the end is the end + } + for _, c := range cases { + start, query, ok := word(c.value, c.caret, '@') + if ok != c.wantOK || (ok && (start != c.wantStart || query != c.wantQuery)) { + t.Errorf("word(%q, %d) = %d, %q, %v; want %d, %q, %v", c.value, c.caret, start, query, ok, c.wantStart, c.wantQuery, c.wantOK) + } + } +} + +func TestContainsFoldIgnoresCaseAndFindsInsideAWord(t *testing.T) { + for _, c := range []struct { + s, q string + want bool + }{ + {"Grace", "gr", true}, {"Grace", "ACE", true}, {"Grace", "x", false}, {"Grace", "", true}, + {"Ünal", "ün", true}, {"张三", "三", true}, {"Ada", "adam", false}, + } { + if got := containsFold(c.s, c.q); got != c.want { + t.Errorf("containsFold(%q, %q) = %v", c.s, c.q, got) + } + } +} + +func TestWordDoesNotAllocate(t *testing.T) { + if n := testing.AllocsPerRun(100, func() { word("hello @gra", 10, '@') }); n != 0 { + t.Fatalf("word allocates %v times", n) + } +} diff --git a/ui/menu_test.go b/ui/menu_test.go index 44a2465ba..ea91b7d1a 100644 --- a/ui/menu_test.go +++ b/ui/menu_test.go @@ -737,3 +737,35 @@ func TestMenuItemIDNamesItsRow(t *testing.T) { t.Fatalf("the row's hit is %v, ID says %v", hit.ID, row) } } + +type toggleModel struct { + open bool + a, b bool +} + +func (m *toggleModel) page(c ui.C) { + more := ui.Button(c, "More").Outline() + if more.Clicked() { + m.open = true + } + ui.Menu(c, more, &m.open, func(menu *ui.MenuItems) { + if menu.Item("Alpha").Checked(m.a).Toggled() { + m.a = !m.a + } + if menu.Item("Beta").Checked(m.b).Toggled() { + m.b = !m.b + } + }) +} + +// A Toggled item changes a setting and leaves the menu open for the next one. +func TestMenuToggledKeepsTheMenuOpen(t *testing.T) { + m := &toggleModel{} + d := openPage(t, m.page) + d.click("More") + d.click("Alpha") + d.click("Beta") + if !m.a || !m.b || !m.open { + t.Fatalf("a=%v b=%v open=%v", m.a, m.b, m.open) + } +} diff --git a/ui/overlay_test.go b/ui/overlay_test.go index 3eab4ad48..cfb8ffa69 100644 --- a/ui/overlay_test.go +++ b/ui/overlay_test.go @@ -74,7 +74,7 @@ func (m *dialogOverlayModel) View(c ui.C) { }).Children(func() { ui.Button(c, "Overlay") }) - ui.Modal(c, &m.open, "Settings", func() { + ui.Modal(c, &m.open, "Settings", ui.ModalSpec{}, func() { ui.Button(c, "Inside") }, nil) } diff --git a/ui/page_behavior_test.go b/ui/page_behavior_test.go index eb50df757..e4a2ba5a0 100644 --- a/ui/page_behavior_test.go +++ b/ui/page_behavior_test.go @@ -276,7 +276,7 @@ func TestPopoverClosesByEscapeAnchorAndOutside(t *testing.T) { if ui.Button(c, "Other").Clicked() { other++ } - ui.Popover(c, more, &open, func() { ui.Button(c, "Rename") }) + ui.Popover(c, more, &open, ui.PopoverSpec{Align: ui.Start}, func() { ui.Button(c, "Rename") }) }) }) d.click("More") @@ -305,7 +305,7 @@ func TestModalNeedsATitle(t *testing.T) { } }() drawPage(ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas(), func(c ui.C) { - ui.Modal(c, &open, "", func() {}, nil) + ui.Modal(c, &open, "", ui.ModalSpec{}, func() {}, nil) }) } @@ -373,8 +373,8 @@ func TestNativeViewTakesItsPlaceInThePage(t *testing.T) { ui.Scroll(c).Height(100).Children(func() { ui.Slot(c).Height(300).FillWidth().NativeView(1) }) - ui.Popover(c, anchor, &menu, func() { ui.Text(c, "over the page") }) - ui.Modal(c, &open, "Preview", func() { ui.Slot(c).Size(100, 80).NativeView(2) }, nil) + ui.Popover(c, anchor, &menu, ui.PopoverSpec{Align: ui.Start}, func() { ui.Text(c, "over the page") }) + ui.Modal(c, &open, "Preview", ui.ModalSpec{}, func() { ui.Slot(c).Size(100, 80).NativeView(2) }, nil) }) }) var inPage, inDialog gfx.NativeView diff --git a/ui/page_embed_test.go b/ui/page_embed_test.go index 9080d8232..88fe7bde4 100644 --- a/ui/page_embed_test.go +++ b/ui/page_embed_test.go @@ -46,7 +46,7 @@ func (m *paneModel) pane(c ui.C) { if more.Clicked() { m.menu = !m.menu } - ui.Popover(c, more, &m.menu, func() { ui.Text(c, "Menu item") }) + ui.Popover(c, more, &m.menu, ui.PopoverSpec{Align: ui.Start}, func() { ui.Text(c, "Menu item") }) ui.Select(c, &m.Size, []string{"S", "M", "L"}, nil).Placeholder("Size").Width(120) ui.Tabs(c, &m.tab, []string{"General", "Keys"}, nil) for _, row := range m.rows { diff --git a/ui/page_test.go b/ui/page_test.go index bb699764c..d4bfda025 100644 --- a/ui/page_test.go +++ b/ui/page_test.go @@ -190,12 +190,12 @@ func TestPagePopoverAndModal(t *testing.T) { if more.Clicked() { menu = !menu } - ui.Popover(c, more, &menu, func() { + ui.Popover(c, more, &menu, ui.PopoverSpec{Align: ui.Start}, func() { if ui.Button(c, "Delete…").Clicked() { menu, confirm = false, true } }) - ui.Modal(c, &confirm, "Delete host?", func() { + ui.Modal(c, &confirm, "Delete host?", ui.ModalSpec{}, func() { ui.Text(c, "This cannot be undone.") }, func() { if ui.Button(c, "Delete").Destructive().Clicked() { @@ -330,7 +330,7 @@ func combobox[T comparable](c ui.C, Value *T, options []T, Label func(T) string) if trigger.Clicked() { *open = !*open } - ui.Popover(c, trigger, open, func() { + ui.Popover(c, trigger, open, ui.PopoverSpec{Align: ui.Start}, func() { for i, option := range options { if ui.Button(c.KeyInt(i), Label(option)).Ghost().Clicked() { *Value, *open = option, false @@ -407,7 +407,7 @@ func TestPagePopoverMoves(t *testing.T) { if more.Clicked() { open = !open } - ui.Popover(c, more, &open, func() { ui.Button(c, "Rename") }) + ui.Popover(c, more, &open, ui.PopoverSpec{Align: ui.Start}, func() { ui.Button(c, "Rename") }) }) }}, app.Config{}) d.click("More") @@ -442,7 +442,7 @@ func BenchmarkPagePopoverOpen(b *testing.B) { view := func(c ui.C) { ui.Column(c).Pad(16).Children(func() { more := ui.Button(c, "More") - ui.Popover(c, more, &open, func() { + ui.Popover(c, more, &open, ui.PopoverSpec{Align: ui.Start}, func() { ui.Button(c, "Rename") ui.Button(c, "Delete") }) @@ -615,14 +615,14 @@ func TestSelectWithIconsMeasuresTheIconSpan(t *testing.T) { } } -// A TextAreaID is addressed by the identity the application gave it, and edits its +// A TextArea given WithID is addressed by the identity the application gave it, and edits its // Field in rows like a TextArea. -func TestPageTextAreaID(t *testing.T) { +func TestPageTextAreaWithID(t *testing.T) { var notes ui.Field id := gfx.Item(41) d := openPage(t, func(c ui.C) { ui.Column(c).Pad(16).Children(func() { - ui.TextAreaID(c, id, ¬es, "Notes", "").Width(300).Height(120) + ui.TextArea(c, ¬es, "Notes", "", ui.WithID(id)).Width(300).Height(120) }) }) d.click("Notes") diff --git a/ui/pagination/pagination.go b/ui/pagination/pagination.go new file mode 100644 index 000000000..d05d3d512 --- /dev/null +++ b/ui/pagination/pagination.go @@ -0,0 +1,238 @@ +// Package pagination is the opt-in page control for moving through pages of +// something: the page numbers with the previous and next controls, and +// optionally the total, a choice of page size and a field to jump to a page. A +// page keeps a State in its model and declares the row with a Spec: +// +// m.pager = pagination.State{PageSize: 20} +// // in the page: +// pagination.View(c, "Pages", &m.pager, pagination.Spec{Total: len(m.rows), SizeOptions: []int{10, 20, 50}, ShowTotal: true}) +// if m.pager.Changed() { +// // m.pager.Page or m.pager.PageSize moved: load the rows +// } +// +// Page is the current page, counted from one; PageSize is how many rows a page +// holds. The row shows the first and last page and a window around the current +// one, with an ellipsis for what is left out. Both are brought into range for +// Total before they are read, so a Total that shrinks never leaves the user on a +// page that no longer exists. A change of page size keeps the first row of the +// page in view. +// +// ui.Pagination, below this package, is the row of items a page assembles itself; +// this package assembles them from Total and keeps the state. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep the State in the model: it keeps its buffers across paints, +// so a warm paint allocates nothing. Do not copy a State after it has been +// declared. +package pagination + +import ( + "strconv" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Labels are the words of the row. +type Labels struct { + // Previous and Next name the two controls; Total precedes the number of rows; + // GoTo names the field that jumps to a page; PerPage names the page size choice. + Previous, Next, Total, GoTo, PerPage string +} + +// English is the default words. +var English = Labels{Previous: "Previous", Next: "Next", Total: "Total", GoTo: "Go to page", PerPage: "Rows per page"} + +// Spec declares the row. +type Spec struct { + // Total is the number of rows across all pages. + Total int + // SizeOptions, when it has more than one value, adds a choice of page size. + SizeOptions []int + // ShowTotal shows the total before the pages. + ShowTotal bool + // Jumper adds a field to type a page number into; Enter goes to it. + Jumper bool + // Labels are the words; English when zero. + Labels Labels + // JumperID gives the jump field an identity of the application's own instead of + // the one its place gives it, for a runner that resolves the platform text + // service by an application identity, such as a component preview. + JumperID gfx.ID +} + +// State is the position in the pages and what the row keeps between paints. +// Its zero value is the first page of ten rows. +type State struct { + // Page is the current page, from one. + Page int + // PageSize is how many rows a page holds; ten when zero or less. + PageSize int + + jump ui.Field + jumpOpt [1]ui.Option + changed bool + reported bool + items []ui.PaginationItem + numbers []string // the words of the page numbers, made once as they are first needed + sizes map[int]string + sizePick int // the page size the select edits, a field because its address is bound + sizeName func(int) string // sizeLabel, made once: a method value made in each paint allocates + total struct { + rows int + text string + } +} + +// Jumper is the field behind the jump box, for a runner that binds the editor the +// platform edits to it with Field.Bind. A page does not need it. +func (s *State) Jumper() *ui.Field { return &s.jump } + +// Changed reports whether the user moved to another page or page size in the +// paint that delivered it. +func (s *State) Changed() bool { return s.reported } + +// pages is how many pages Total rows make. +func (s *State) pages(total int) int { + return max((total+s.PageSize-1)/s.PageSize, 1) +} + +func (s *State) number(page int) string { + for len(s.numbers) <= page { + s.numbers = append(s.numbers, strconv.Itoa(len(s.numbers))) + } + return s.numbers[page] +} + +func (s *State) sizeLabel(size int) string { + if text, ok := s.sizes[size]; ok { + return text + } + if s.sizes == nil { + s.sizes = map[int]string{} + } + s.sizes[size] = strconv.Itoa(size) + return s.sizes[size] +} + +// window appends the items of the page row: the first page, the last page and +// the pages around the current one, with an ellipsis where pages are left out. +func (s *State) window(c ui.C, pages int, labels Labels) { + add := func(page int) { + s.items = append(s.items, ui.PaginationItem{ID: ui.ID(c), Label: s.number(page), Kind: ui.PaginationPage, Current: page == s.Page}) + } + s.items = append(s.items, ui.PaginationItem{ID: ui.ID(c), Label: labels.Previous, Kind: ui.PaginationPrevious, Disabled: s.Page <= 1}) + if pages <= 7 { + for page := 1; page <= pages; page++ { + add(page) + } + } else { + from, to := max(s.Page-1, 2), min(s.Page+1, pages-1) + // Near an end the window grows toward it, so the row keeps its length. + if s.Page <= 4 { + from, to = 2, 5 + } + if s.Page >= pages-3 { + from, to = pages-4, pages-1 + } + add(1) + if from > 2 { + s.items = append(s.items, ui.PaginationItem{Kind: ui.PaginationEllipsis}) + } + for page := from; page <= to; page++ { + add(page) + } + if to < pages-1 { + s.items = append(s.items, ui.PaginationItem{Kind: ui.PaginationEllipsis}) + } + add(pages) + } + s.items = append(s.items, ui.PaginationItem{ID: ui.ID(c), Label: labels.Next, Kind: ui.PaginationNext, Disabled: s.Page >= pages}) +} + +// View declares the row at c. label names the group for assistive technology. +// Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, state *State, spec Spec) ui.Box { + if state == nil { + panic("pagination: View needs its State") + } + state.reported, state.changed = state.changed, false + labels := spec.Labels + if labels == (Labels{}) { + labels = English + } + if state.PageSize <= 0 { + state.PageSize = 10 + } + total := max(spec.Total, 0) + pages := state.pages(total) + state.Page = min(max(state.Page, 1), pages) + theme := c.Theme() + metrics := theme.Metrics + row := ui.Flow(c).Items(ui.Center).Gap(metrics.GapItem * 1.5).LineGap(metrics.GapItem) + row = row.HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true}) + row.Children(func() { + if spec.ShowTotal { + if state.total.text == "" || state.total.rows != total { + state.total.rows = total + state.total.text = labels.Total + " " + strconv.Itoa(total) + } + ui.Text(c, state.total.text).Muted().Shrink(0) + } + state.items = state.items[:0] + state.window(c, pages, labels) + items := ui.Pagination(c, state.items) + if id, ok := items.Chosen(); ok { + for _, item := range state.items { + if item.ID != id || item.Disabled { + continue + } + switch item.Kind { + case ui.PaginationPrevious: + state.goTo(state.Page - 1) + case ui.PaginationNext: + state.goTo(state.Page + 1) + default: + if page, err := strconv.Atoi(item.Label); err == nil { + state.goTo(page) + } + } + } + } + if len(spec.SizeOptions) > 1 { + if state.sizeName == nil { + state.sizeName = state.sizeLabel + } + state.sizePick = state.PageSize + choice := ui.Select(c, &state.sizePick, spec.SizeOptions, state.sizeName).Width(88) + choice.Label(labels.PerPage) + if size := state.sizePick; size != state.PageSize { + first := (state.Page - 1) * state.PageSize + state.PageSize, state.changed = size, true + state.Page = min(first/size+1, state.pages(total)) + } + } + if spec.Jumper { + var options []ui.Option + if !spec.JumperID.IsZero() { + state.jumpOpt[0] = ui.WithID(spec.JumperID) + options = state.jumpOpt[:] + } + field := ui.TextField(c, &state.jump, labels.GoTo, labels.GoTo, options...).Width(112) + if field.Submitted() { + if page, err := strconv.Atoi(state.jump.Text()); err == nil { + state.goTo(min(max(page, 1), pages)) + } + state.jump.SetText("") + } + } + }) + return row +} + +// goTo moves to a page, and notes it when that is another page. +func (s *State) goTo(page int) { + if page != s.Page { + s.Page, s.changed = page, true + } +} diff --git a/ui/pagination/pagination_test.go b/ui/pagination/pagination_test.go new file mode 100644 index 000000000..054992228 --- /dev/null +++ b/ui/pagination/pagination_test.go @@ -0,0 +1,172 @@ +//go:build !js + +package pagination_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/pagination" +) + +var changes int + +func open(t *testing.T, state *pagination.State, spec pagination.Spec) *headless.Session { + t.Helper() + changes = 0 + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + pagination.View(c, "Pages", state, spec) + if state.Changed() { + changes++ + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Pages", Width: 900, Height: 160}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +// Next and Previous move one page, and the numbers jump; each change is reported +// once. +func TestControlsMoveThroughThePages(t *testing.T) { + state := &pagination.State{PageSize: 10} + session := open(t, state, pagination.Spec{Total: 95}) + if state.Page != 1 { + t.Fatalf("Page = %d at the start, want 1", state.Page) + } + if err := session.ClickLabel("Next"); err != nil { + t.Fatal(err) + } + if err := session.ClickLabel("5"); err != nil { + t.Fatal(err) + } + if state.Page != 5 || changes != 2 { + t.Fatalf("Page = %d after Next and 5, changes %d; want 5 and 2", state.Page, changes) + } + if err := session.ClickLabel("Previous"); err != nil { + t.Fatal(err) + } + if state.Page != 4 { + t.Fatalf("Page = %d after Previous, want 4", state.Page) + } +} + +// Previous is dimmed on the first page and Next on the last. +func TestEndsOfTheRangeCannotBePressed(t *testing.T) { + state := &pagination.State{PageSize: 10, Page: 1} + session := open(t, state, pagination.Spec{Total: 25}) + if err := session.ClickLabel("Previous"); err == nil { + t.Fatal("Previous could be pressed on the first page") + } + state.Page = 3 + session.Frame() + if err := session.ClickLabel("Next"); err == nil { + t.Fatal("Next could be pressed on the last page") + } +} + +// A Total that shrinks brings the page back into range; the row of a long run of +// pages keeps the first and last page and a window around the current one. +func TestPageIsKeptInRangeAndLongRunsCollapse(t *testing.T) { + state := &pagination.State{PageSize: 10, Page: 9} + session := open(t, state, pagination.Spec{Total: 30}) + if state.Page != 3 { + t.Fatalf("Page = %d after Total shrank to 3 pages, want 3", state.Page) + } + long := &pagination.State{PageSize: 10, Page: 10} + session = open(t, long, pagination.Spec{Total: 200}) + buttons := map[string]bool{} + for _, node := range session.Access() { + if node.Role == gfx.RoleButton { + buttons[node.Label] = true + } + } + for _, shown := range []string{"1", "9", "10", "11", "20"} { + if !buttons[shown] { + t.Fatalf("page %s is not in the row", shown) + } + } + for _, hidden := range []string{"2", "5", "15"} { + if buttons[hidden] { + t.Fatalf("page %s is in the row though it collapsed", hidden) + } + } +} + +// Changing the page size keeps the first row of the page in view. +func TestPageSizeChangeKeepsTheFirstRow(t *testing.T) { + state := &pagination.State{PageSize: 10, Page: 5} // rows 40..49 + session := open(t, state, pagination.Spec{Total: 200, SizeOptions: []int{10, 20, 50}}) + if err := session.ClickLabel("Rows per page"); err != nil { + t.Fatal(err) + } + if err := session.ClickLabel("20"); err != nil { + t.Fatal(err) + } + if state.PageSize != 20 || state.Page != 3 { + t.Fatalf("PageSize %d, Page %d after choosing 20 on page 5 of 10, want 20 and 3", state.PageSize, state.Page) + } +} + +// The jumper takes a page number and goes to it, clamped. +func TestJumperGoesToThePage(t *testing.T) { + state := &pagination.State{PageSize: 10} + session := open(t, state, pagination.Spec{Total: 95, Jumper: true}) + if err := session.ClickLabel("Go to page"); err != nil { + t.Fatal(err) + } + if err := session.Type("7"); err != nil { + t.Fatal(err) + } + if err := session.Keys("enter"); err != nil { + t.Fatal(err) + } + if state.Page != 7 { + t.Fatalf("Page = %d after typing 7 and Enter, want 7", state.Page) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + state := &pagination.State{PageSize: 10, Page: 5} + spec := pagination.Spec{Total: 500, ShowTotal: true, SizeOptions: []int{10, 20, 50}, Jumper: true} + view := func(c ui.C) { pagination.View(c, "Pages", state, spec) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 900, Height: 160}, view) + canvas.EndFrame() + } + draw() + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + state := &pagination.State{PageSize: 10, Page: 5} + spec := pagination.Spec{Total: 500, ShowTotal: true} + view := func(c ui.C) { pagination.View(c, "Pages", state, spec) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + b.ReportAllocs() + for range b.N { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 900, Height: 160}, view) + canvas.EndFrame() + } +} diff --git a/ui/paint_parity_test.go b/ui/paint_parity_test.go index f00aebaca..1988a7728 100644 --- a/ui/paint_parity_test.go +++ b/ui/paint_parity_test.go @@ -354,7 +354,8 @@ func TestTablePaintParity(t *testing.T) { pageView := func(c ui.C) { ui.Column(c).Pad(16).Children(func() { element = ui.Table(c, &state, ui.TableSpec{ - Columns: columns, Headers: headers, Source: &rows, + Columns: titledColumns(columns, headers, nil), + Source: &rows, }).Width(240) }) } diff --git a/ui/popconfirm/popconfirm.go b/ui/popconfirm/popconfirm.go new file mode 100644 index 000000000..ae1e045a0 --- /dev/null +++ b/ui/popconfirm/popconfirm.go @@ -0,0 +1,126 @@ +// Package popconfirm is the opt-in page control for a small confirmation next to +// what it confirms: a popover over the button that was pressed, with a question, +// an optional line of detail and the two answers. It is for a cheap, local +// question; a consequence that cannot be undone, or one the user must not click +// through, belongs in ui.AlertDialog. A page keeps a Popconfirm in its model and +// opens it from the button: +// +// m.remove = popconfirm.New() +// // in the page: +// trigger := ui.Button(c, "Remove").Outline() +// if trigger.Clicked() { +// m.remove.Open() +// } +// m.remove.View(c, trigger, popconfirm.Spec{Title: "Remove build-01?", Danger: true, OkLabel: "Remove"}) +// if m.remove.Confirmed() { +// m.removeHost() +// } +// +// Confirmed is true in the paint that delivers a press on the confirming button, +// Cancelled in the one that delivers the other; both close it. Escape and a press +// outside close it without either, as they do a ui.Popover. Danger paints the +// confirming button destructive. The popover opens below the button and flips +// above it when there is no room. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Popconfirm in the model: it holds the open state, so a +// warm paint allocates nothing. Do not copy a Popconfirm after it has been +// declared. +package popconfirm + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Spec declares the question. +type Spec struct { + // Title is the question; Description is the line under it. + Title, Description string + // OkLabel and CancelLabel are the answers, "OK" and "Cancel" when empty. + OkLabel, CancelLabel string + // Danger paints the confirming button destructive, for a question about + // removing something. + Danger bool + // Width is the popover's width, 280 when zero. + Width float32 +} + +// Popconfirm is one question and what the user answered. +type Popconfirm struct { + open bool + confirmed bool + cancelled bool + // spec and the closures are kept so the body is made once: a closure made in + // each paint allocates in each paint. + spec Spec + c ui.C + body func() +} + +// New returns a closed Popconfirm. +func New() *Popconfirm { + p := &Popconfirm{} + p.body = p.declare + return p +} + +// Open shows the question. Call it from the press on the button it belongs to. +func (p *Popconfirm) Open() { p.open = true } + +// Close hides it without answering. +func (p *Popconfirm) Close() { p.open = false } + +// IsOpen reports whether the question is showing. +func (p *Popconfirm) IsOpen() bool { return p.open } + +// Confirmed reports whether the confirming button was pressed in the paint just made. +func (p *Popconfirm) Confirmed() bool { return p.confirmed } + +// Cancelled reports whether the cancelling button was pressed in the paint just made. +func (p *Popconfirm) Cancelled() bool { return p.cancelled } + +// View declares the question over anchor, the button it belongs to, while it is open. +// Declare the view on its own, not inside a Memo. +func (p *Popconfirm) View(c ui.C, anchor ui.Box, spec Spec) { + if p == nil { + panic("popconfirm: View needs its Popconfirm") + } + p.confirmed, p.cancelled = false, false + if spec.OkLabel == "" { + spec.OkLabel = "OK" + } + if spec.CancelLabel == "" { + spec.CancelLabel = "Cancel" + } + width := spec.Width + if width <= 0 { + width = 280 + } + p.spec, p.c = spec, c + ui.Popover(c, anchor, &p.open, ui.PopoverSpec{Align: ui.Start, Width: width}, p.body) +} + +// declare is the body of the popover: the words and the two answers. +func (p *Popconfirm) declare() { + c, spec := p.c, p.spec + metrics := c.Theme().Metrics + ui.Column(c).Gap(metrics.GapItem).Children(func() { + ui.Text(c, spec.Title).Weight(gfx.WeightSemibold) + if spec.Description != "" { + ui.Wrap(c, spec.Description).FontSize(metrics.FontSizeS).Muted() + } + ui.Row(c).Justify(ui.End).Gap(metrics.GapItem).MarginSides(metrics.GapItem, 0, 0, 0).Children(func() { + if ui.Button(c, spec.CancelLabel).Outline().Small().Clicked() { + p.cancelled, p.open = true, false + } + ok := ui.Button(c, spec.OkLabel).Small() + if spec.Danger { + ok = ok.Destructive() + } + if ok.Clicked() { + p.confirmed, p.open = true, false + } + }) + }) +} diff --git a/ui/popconfirm/popconfirm_test.go b/ui/popconfirm/popconfirm_test.go new file mode 100644 index 000000000..398ddffaf --- /dev/null +++ b/ui/popconfirm/popconfirm_test.go @@ -0,0 +1,120 @@ +//go:build !js + +package popconfirm_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/popconfirm" +) + +type model struct { + pc *popconfirm.Popconfirm + danger bool + confirmed, cancelled int +} + +func (m *model) open(t *testing.T) *headless.Session { + t.Helper() + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + trigger := ui.Button(c, "Remove").Outline() + if trigger.Clicked() { + m.pc.Open() + } + m.pc.View(c, trigger, popconfirm.Spec{Title: "Remove build-01?", Description: "It cannot be undone.", OkLabel: "Yes", Danger: m.danger}) + if m.pc.Confirmed() { + m.confirmed++ + } + if m.pc.Cancelled() { + m.cancelled++ + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Pop", Width: 480, Height: 320}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +// The question shows only after the trigger opens it; confirming reports once and +// closes it. +func TestConfirmReportsOnceAndCloses(t *testing.T) { + m := &model{pc: popconfirm.New()} + session := m.open(t) + if err := session.Expect("text", "Remove build-01?"); err == nil { + t.Fatal("the question shows before it was opened") + } + if err := session.ClickLabel("Remove"); err != nil { + t.Fatal(err) + } + if err := session.Expect("text", "Remove build-01?"); err != nil { + t.Fatal(err) + } + if err := session.ClickLabel("Yes"); err != nil { + t.Fatal(err) + } + if m.confirmed != 1 || m.cancelled != 0 { + t.Fatalf("confirmed %d, cancelled %d after pressing Yes, want 1, 0", m.confirmed, m.cancelled) + } + if m.pc.IsOpen() { + t.Fatal("the question stayed open after an answer") + } +} + +func TestCancelReportsAndCloses(t *testing.T) { + m := &model{pc: popconfirm.New()} + session := m.open(t) + session.ClickLabel("Remove") + if err := session.ClickLabel("Cancel"); err != nil { + t.Fatal(err) + } + if m.cancelled != 1 || m.confirmed != 0 || m.pc.IsOpen() { + t.Fatalf("cancelled %d, confirmed %d, open %v after Cancel", m.cancelled, m.confirmed, m.pc.IsOpen()) + } +} + +// Escape closes the question without answering it. +func TestEscapeClosesWithoutAnswering(t *testing.T) { + m := &model{pc: popconfirm.New()} + session := m.open(t) + session.ClickLabel("Remove") + if err := session.Keys("escape"); err != nil { + t.Fatal(err) + } + if m.pc.IsOpen() || m.confirmed != 0 || m.cancelled != 0 { + t.Fatalf("open %v, confirmed %d, cancelled %d after Escape", m.pc.IsOpen(), m.confirmed, m.cancelled) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + pc := popconfirm.New() + pc.Open() + var c0 ui.C + _ = c0 + view := func(c ui.C) { + trigger := ui.Button(c, "Remove") + pc.View(c, trigger, popconfirm.Spec{Title: "Remove?", Description: "No undo.", Danger: true}) + } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 480, Height: 320}, view) + canvas.EndFrame() + } + draw() + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} diff --git a/ui/popover_test.go b/ui/popover_test.go index 32ed3d267..5ee89838e 100644 --- a/ui/popover_test.go +++ b/ui/popover_test.go @@ -18,7 +18,7 @@ func TestPopoverHeaderAndFixedBody(t *testing.T) { var body ui.Box d := openPage(t, func(c ui.C) { more := ui.Button(c, "More") - ui.PopoverWith(c, more, &open, ui.PopoverSpec{Width: 200, Title: "Transfers", Description: long}, func() { + ui.Popover(c, more, &open, ui.PopoverSpec{Width: 200, Title: "Transfers", Description: long}, func() { body = ui.Column(c).FillWidth().Height(120).Children(func() { ui.Text(c, "Body") }) }) }) @@ -60,7 +60,7 @@ func TestPopoverHeaderToBodyFollowsSurfacePadding(t *testing.T) { var body ui.Box d := openPageWith(t, ui.PageConfig{Theme: &theme, View: func(c ui.C) { more := ui.Button(c, "More") - ui.PopoverWith(c, more, &open, ui.PopoverSpec{Width: 300, Title: "Transfers", Description: "Active transfers"}, func() { + ui.Popover(c, more, &open, ui.PopoverSpec{Width: 300, Title: "Transfers", Description: "Active transfers"}, func() { body = ui.Column(c).FillWidth().Height(40).Children(func() { ui.Text(c, "Body") }) }) }}, app.Config{}) @@ -89,7 +89,7 @@ func TestPopoverAlignOffset(t *testing.T) { d := openPage(t, func(c ui.C) { ui.Column(c).Pad(20).Children(func() { more := ui.Button(c, "More").Width(200) - ui.PopoverWith(c, more, &open, ui.PopoverSpec{Side: components.PopoverBottom, Align: ui.Start, AlignOffset: shift, Width: 100}, func() { + ui.Popover(c, more, &open, ui.PopoverSpec{Side: components.PopoverBottom, Align: ui.Start, AlignOffset: shift, Width: 100}, func() { body = ui.Column(c).FillWidth().Height(40) }) }) @@ -110,7 +110,7 @@ func TestPopoverCanBeAHoverPreview(t *testing.T) { open := true d := openPage(t, func(c ui.C) { anchor := ui.Button(c, "Anchor") - ui.PopoverWith(c, anchor, &open, ui.PopoverSpec{Title: "Details", Width: 200, Radius: 10, NoDismiss: true}, func() { + ui.Popover(c, anchor, &open, ui.PopoverSpec{Title: "Details", Width: 200, Radius: 10, NoDismiss: true}, func() { ui.Text(c, "Body") }) }) @@ -136,7 +136,7 @@ func TestPopoverMarginKeepsClearOfTheWindowEdge(t *testing.T) { openPage(t, func(c ui.C) { ui.Row(c).FillWidth().Justify(ui.End).Children(func() { anchor := ui.Button(c, "Anchor").Width(100) - ui.PopoverWith(c, anchor, &open, ui.PopoverSpec{Side: components.PopoverBottom, Align: ui.Start, Width: 200, Margin: margin}, func() { + ui.Popover(c, anchor, &open, ui.PopoverSpec{Side: components.PopoverBottom, Align: ui.Start, Width: 200, Margin: margin}, func() { body = ui.Column(c).FillWidth().Height(40) }) }) @@ -156,7 +156,7 @@ func TestPopoverPaddingInsetsTheBody(t *testing.T) { var body ui.Box openPage(t, func(c ui.C) { anchor := ui.Button(c, "Anchor") - ui.PopoverWith(c, anchor, &open, ui.PopoverSpec{Width: 200, Padding: padding}, func() { + ui.Popover(c, anchor, &open, ui.PopoverSpec{Width: 200, Padding: padding}, func() { body = ui.Column(c).FillWidth().Height(40) }) }) @@ -175,7 +175,7 @@ func TestPopoverInstantKeepsTheLayout(t *testing.T) { var body ui.Box openPage(t, func(c ui.C) { anchor := ui.Button(c, "Anchor") - ui.PopoverWith(c, anchor, &open, ui.PopoverSpec{Width: 200, Instant: instant}, func() { + ui.Popover(c, anchor, &open, ui.PopoverSpec{Width: 200, Instant: instant}, func() { body = ui.Column(c).FillWidth().Height(40) }) }) diff --git a/ui/popover_wheel_test.go b/ui/popover_wheel_test.go index e95967c88..4ffa34bac 100644 --- a/ui/popover_wheel_test.go +++ b/ui/popover_wheel_test.go @@ -23,7 +23,7 @@ func TestAWheelOverAPopoverStaysInThePanel(t *testing.T) { d := openPage(t, func(c ui.C) { ui.Column(c).Fill().Children(func() { projects := ui.Button(c, "Projects") - ui.PopoverWith(c, projects, &open, ui.PopoverSpec{Width: 200}, func() { + ui.Popover(c, projects, &open, ui.PopoverSpec{Width: 200}, func() { list = ui.Scroll(c).FillWidth().MaxHeight(150).Children(func() { for range 20 { ui.Slot(c).Height(30) @@ -89,7 +89,7 @@ func TestATableInAPopoverTakesTheWheelAndTheTableUnderItDoesNot(t *testing.T) { d := openPage(t, func(c ui.C) { ui.Column(c).Fill().Children(func() { projects := ui.Button(c, "Projects") - ui.PopoverWith(c, projects, &open, ui.PopoverSpec{Width: 200}, func() { + ui.Popover(c, projects, &open, ui.PopoverSpec{Width: 200}, func() { panelTable = ui.Table(c, &inner, ui.TableSpec{ Columns: []components.TableColumn{{}}, Rows: gfx.Item(1).Scope(), Source: &rows, }).FillWidth().Height(150) @@ -139,7 +139,7 @@ func TestAWheelOverAModalLeavesThePageUnderIt(t *testing.T) { } }) }) - ui.Modal(c, &open, "Rename", func() { ui.Text(c, "A short body") }, nil) + ui.Modal(c, &open, "Rename", ui.ModalSpec{}, func() { ui.Text(c, "A short body") }, nil) }) page := area.ScrollState() r := area.Rect() @@ -300,7 +300,7 @@ func TestDialogKeepsTheWheelFromIndependentRoutesBehindIt(t *testing.T) { open := true d := openPage(t, func(c ui.C) { boxes[0] = declare(c, 0).Fill() - ui.Modal(c, &open, "Details", func() { + ui.Modal(c, &open, "Details", ui.ModalSpec{}, func() { boxes[1] = declare(c, 1).FillWidth().Height(150).Shrink(0) }, nil) }) @@ -350,7 +350,7 @@ func TestPopoverWheelFallbackBelongsOnlyToScrollAt(t *testing.T) { d := openPageWith(t, ui.PageConfig{View: func(c ui.C) { ui.Column(c).Fill().Children(func() { anchor := ui.Button(c, "Projects") - ui.Popover(c, anchor, &open, func() { + ui.Popover(c, anchor, &open, ui.PopoverSpec{Align: ui.Start}, func() { if manual { area = ui.ScrollAt(c, 0) } else { diff --git a/ui/presence_parity_test.go b/ui/presence_parity_test.go index 01871ccee..907daedc4 100644 --- a/ui/presence_parity_test.go +++ b/ui/presence_parity_test.go @@ -96,7 +96,7 @@ func TestPagePopoverAnimatesLikeTheComponentsPopover(t *testing.T) { newClock := newParityClock() view := func(c ui.C) { slot := ui.Slot(c).Absolute().Left(anchor.X).Top(anchor.Y).Size(anchor.Width, anchor.Height) - ui.PopoverWith(c, slot, &open, ui.PopoverSpec{ + ui.Popover(c, slot, &open, ui.PopoverSpec{ Scope: gfx.Item(7), Side: components.PopoverBottom, Align: ui.Start, Offset: 2, Width: width, }, func() { ui.Slot(c).FillWidth().Height(bodyHeight) @@ -150,13 +150,13 @@ func TestPagePopoverAnimatesLikeTheComponentsPopover(t *testing.T) { // Instant is the one difference kept from the components options: a list that // appears under the cursor as the user types has no entrance, so the page // paints it at its place on the first frame and asks for no next frame. -func TestPagePopoverWithInstantAppearsAtOnce(t *testing.T) { +func TestPagePopoverInstantAppearsAtOnce(t *testing.T) { theme := gfx.LightTheme() open := true clock := newParityClock() view := func(c ui.C) { slot := ui.Slot(c).Absolute().Left(100).Top(100).Size(40, 20) - ui.PopoverWith(c, slot, &open, ui.PopoverSpec{ + ui.Popover(c, slot, &open, ui.PopoverSpec{ Scope: gfx.Item(7), Side: components.PopoverBottom, Align: ui.Start, Offset: 2, Width: 200, Instant: true, }, func() { ui.Slot(c).FillWidth().Height(120) diff --git a/ui/progress_ring_test.go b/ui/progress_ring_test.go new file mode 100644 index 000000000..83907b53c --- /dev/null +++ b/ui/progress_ring_test.go @@ -0,0 +1,97 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +func ringTriangles(d *pageDriver, color gfx.Color) int { + n := 0 + for _, triangle := range d.driver.Snapshot().Primitives { + if triangle.Color == color { + n++ + } + } + return n +} + +// A circular Progress is a ring that keeps its size in a Column instead of +// stretching like a bar, fills with its fraction, and takes its status color. +func TestProgressCircleKeepsItsSizeAndFillsWithItsFraction(t *testing.T) { + var box ui.Box + fraction := float32(0.25) + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(8).Children(func() { box = ui.Progress(c, fraction).Circle().Status(ui.StatusSuccess) }) + }) + r := box.Rect() + if r.Width != 64 || r.Height != 64 { + t.Fatalf("a ring given no size is %vx%v, want 64x64", r.Width, r.Height) + } + quarter := ringTriangles(d, pageTheme.Success) + if quarter == 0 { + t.Fatal("the ring's fill is not painted in the status color") + } + fraction = 0.75 + d.repaint() + if three := ringTriangles(d, pageTheme.Success); three <= quarter { + t.Fatalf("a ring three quarters full has %d fill triangles, not above a quarter full (%d)", three, quarter) + } + fraction = 0 + d.repaint() + if ringTriangles(d, pageTheme.Success) != 0 { + t.Fatal("an empty ring paints a fill") + } +} + +// The ring is a progress bar to assistive technology, with the fraction as its value. +func TestProgressCircleIsAProgressBar(t *testing.T) { + d := openPage(t, func(c ui.C) { ui.Progress(c, 0.5).Circle().Label("Upload") }) + hit := d.hit("Upload") + if hit.Role != gfx.RoleProgressBar || hit.Range.Now != 50 || hit.Range.Max != 100 { + t.Fatalf("hit = role %v, range %+v; want a progress bar at 50 of 100", hit.Role, hit.Range) + } +} + +func TestProgressCircleRepaintsWithoutAllocating(t *testing.T) { + d := openPage(t, func(c ui.C) { ui.Progress(c, 0.6).Circle().Size(80, 80) }) + d.repaint() + d.repaint() + if allocs := testing.AllocsPerRun(100, d.repaint); allocs != 0 { + t.Fatalf("%v allocations a repaint", allocs) + } +} + +// A segmented Progress is separate segments with the first of them filled for the +// fraction, in the status color, and still one progress bar to assistive technology. +func TestProgressSegmentsFillTheFirstOnes(t *testing.T) { + filled := func(fraction float32) int { + d := openPage(t, func(c ui.C) { ui.Progress(c, fraction).Segments(5).Status(ui.StatusSuccess).Width(200).Label("Stages") }) + n := 0 + for _, primitive := range d.driver.Snapshot().Primitives { + if primitive.Color == pageTheme.Success { + n++ + } + } + return n + } + for fraction, want := range map[float32]int{0: 0, 0.2: 1, 0.6: 3, 1: 5} { + if got := filled(fraction); got != want { + t.Fatalf("a fraction of %v fills %d segments, want %d", fraction, got, want) + } + } + d := openPage(t, func(c ui.C) { ui.Progress(c, 0.6).Segments(5).Width(200).Label("Stages") }) + if hit := d.hit("Stages"); hit.Role != gfx.RoleProgressBar { + t.Fatalf("a segmented bar is a %v, want a progress bar", hit.Role) + } +} + +func TestProgressSegmentsRepaintWithoutAllocating(t *testing.T) { + d := openPage(t, func(c ui.C) { ui.Progress(c, 0.6).Segments(5).Width(200) }) + d.repaint() + d.repaint() + if allocs := testing.AllocsPerRun(100, d.repaint); allocs != 0 { + t.Fatalf("%v allocations a repaint", allocs) + } +} diff --git a/ui/radio_test.go b/ui/radio_test.go index 99d71b76d..0c2e06382 100644 --- a/ui/radio_test.go +++ b/ui/radio_test.go @@ -30,13 +30,13 @@ func TestRadioGroupChoosesByClickAndArrows(t *testing.T) { } } -func TestRadioIDKeepsTheApplicationsIdentity(t *testing.T) { +func TestRadioWithIDKeepsTheApplicationsIdentity(t *testing.T) { id := gfx.Item(41) ungroup := false d := openPage(t, func(c ui.C) { ui.RadioGroup(c).Children(func() { - ui.RadioID(c, gfx.Item(40), &ungroup, false, "Keep") - ui.RadioID(c, id, &ungroup, true, "Ungroup") + ui.Radio(c, &ungroup, false, "Keep", ui.WithID(gfx.Item(40))) + ui.Radio(c, &ungroup, true, "Ungroup", ui.WithID(id)) }) }) d.click("Ungroup") diff --git a/ui/rate/rate.go b/ui/rate/rate.go new file mode 100644 index 000000000..353796ece --- /dev/null +++ b/ui/rate/rate.go @@ -0,0 +1,322 @@ +// Package rate is the opt-in page control for a star rating: a row of stars +// that shows a score and, unless it is read only, lets the user choose one. A +// page keeps a Rate in its model beside the score it edits: +// +// m.rate = rate.New().AllowHalf() +// // in the page: +// m.rate.View(c, "Rating", &m.score) +// if m.rate.Changed() { +// // the user chose a new score; m.score already holds it +// } +// +// The score is a number of stars from zero to Count, a whole number or, with +// AllowHalf, a multiple of one half. A click on a star chooses it, on the left +// half of a star chooses the half with AllowHalf, and a click on the score +// already chosen clears it unless KeepScore is set. While the pointer is over +// the stars they show the score a click would choose. +// +// The stars are one tab stop. The arrow keys change the score by one star, or +// one half with AllowHalf, and Home and End choose none and all of the stars. A +// ReadOnly rating shows the score and takes no input. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Rate in the model: its handlers and draw function are +// made once, so a warm paint allocates nothing. Do not copy a Rate after it has +// been declared. +package rate + +import ( + "math" + "strconv" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// DefaultColor is the color of a chosen star unless Color gives another. +var DefaultColor = gfx.RGB(245, 183, 0) + +// starPath is Lucide's star, as a closed outline. +var starPath = []gfx.PathCommand{ + gfx.MoveTo(12, 2), gfx.LineTo(15.09, 8.26), gfx.LineTo(22, 9.27), gfx.LineTo(17, 14.14), + gfx.LineTo(18.18, 21.02), gfx.LineTo(12, 17.77), gfx.LineTo(5.82, 21.02), gfx.LineTo(7, 14.14), + gfx.LineTo(2, 9.27), gfx.LineTo(8.91, 8.26), gfx.ClosePath(), +} + +var ( + solidStar = gfx.Icon{ViewBox: 24, Commands: starPath} + outlineStar = gfx.Icon{ViewBox: 24, Stroke: 1.5, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: starPath} +) + +// names are the accessible names of the stars, made once. +var names [16]string + +func init() { + for i := range names { + names[i] = strconv.Itoa(i + 1) + } +} + +func name(i int) string { + if i < len(names) { + return names[i] + } + return strconv.Itoa(i + 1) +} + +// Rate is one rating control. Configure it with the chainable methods; they may +// be called before each View. +type Rate struct { + handlers ui.Handlers + drawFn func(*ui.DrawContext) + + count int + half bool + keep bool + readOnly bool + size float32 + color gfx.Color + + value *float32 + origin gfx.Rect // where the control was drawn last + hover float32 // the score the pointer would choose; zero when it is elsewhere + changed bool // the score changed since the last View + reported bool // the score changed since the paint before this one +} + +// New returns a rating of five stars. +func New() *Rate { + r := &Rate{count: 5, size: 20} + r.handlers.Key = r.key + r.handlers.Pointer = r.pointer + r.drawFn = r.draw + return r +} + +// Count is the number of stars; five by default. +func (r *Rate) Count(count int) *Rate { + r.count = max(count, 1) + return r +} + +// AllowHalf lets the score be a multiple of one half. +func (r *Rate) AllowHalf() *Rate { + r.half = true + return r +} + +// KeepScore makes a click on the chosen score keep it, instead of clearing it. +func (r *Rate) KeepScore() *Rate { + r.keep = true + return r +} + +// ReadOnly shows the score and takes no input. +func (r *Rate) ReadOnly() *Rate { + r.readOnly = true + return r +} + +// Editable clears ReadOnly, for a page that enables editing later. +func (r *Rate) Editable() *Rate { + r.readOnly = false + return r +} + +// Size is the width and height of a star in pixels; 20 by default. +func (r *Rate) Size(size float32) *Rate { + r.size = max(size, 8) + return r +} + +// Color is the color of the chosen stars; DefaultColor by default. +func (r *Rate) Color(color gfx.Color) *Rate { + r.color = color + return r +} + +// Changed reports whether the user chose a new score since the last paint. +func (r *Rate) Changed() bool { return r.reported } + +const gap = 4 + +// step is the smallest change of the score. +func (r *Rate) step() float32 { + if r.half { + return 0.5 + } + return 1 +} + +// View declares the rating at c, showing and editing *score. label names it for +// assistive technology. Declare the view on its own, not inside a Memo. +func (r *Rate) View(c ui.C, label string, score *float32) ui.Box { + if r == nil { + panic("rate: View needs its Rate") + } + if score == nil { + panic("rate: View needs the score") + } + r.reported, r.changed = r.changed, false + r.value = score + *score = r.clamp(*score) + r.handlers.Role = gfx.RoleGroup + if r.readOnly { + r.handlers.Role = gfx.RoleStatus + } + width := float32(r.count)*r.size + float32(r.count-1)*gap + return ui.Control(c, label, &r.handlers).Size(width, r.size).Shrink(0).Draw(r.drawFn) +} + +// clamp is score as one the rating can show: from zero to Count, in whole +// stars or halves. +func (r *Rate) clamp(score float32) float32 { + if score != score { // NaN + return 0 + } + step := r.step() + score = float32(math.Round(float64(score/step))) * step + return min(max(score, 0), float32(r.count)) +} + +// choose makes score the chosen one and reports whether it changed. +func (r *Rate) choose(score float32) bool { + score = r.clamp(score) + if score == *r.value { + return false + } + *r.value, r.changed = score, true + return true +} + +// pointedScore is the score a click at x on star i would choose. +func (r *Rate) pointedScore(i int, x float32) float32 { + score := float32(i + 1) + if r.half && x < r.starRect(r.origin, i).X+r.size/2 { + score -= 0.5 + } + return score +} + +// starRect is the rectangle of star i within origin, the control's rectangle. +func (r *Rate) starRect(origin gfx.Rect, i int) gfx.Rect { + return gfx.Rect{X: origin.X + float32(i)*(r.size+gap), Y: origin.Y, Width: r.size, Height: r.size} +} + +// focusPart is the star the keyboard rests on: the one that holds the score, or +// the first when there is none. +func (r *Rate) focusPart(score float32) int { + return min(max(int(math.Ceil(float64(score)))-1, 0), r.count-1) +} + +func (r *Rate) pointer(event gfx.PointerEvent) gfx.EventResult { + if r.readOnly || r.value == nil { + return gfx.EventResult{} + } + i, onStar := event.Target.In(r.handlers.Parts()) + switch event.Kind { + case gfx.PointerExit: + if r.hover == 0 { + return gfx.EventResult{} + } + r.hover = 0 + return gfx.EventResult{Repaint: true} + case gfx.PointerMove: + if !onStar { + return gfx.EventResult{} + } + hover := r.pointedScore(i, event.X) + if hover == r.hover { + return gfx.EventResult{} + } + r.hover = hover + return gfx.EventResult{Repaint: true} + case gfx.PointerDown: + if !onStar || event.Button != gfx.PointerButtonPrimary { + return gfx.EventResult{} + } + score := r.pointedScore(i, event.X) + if score == *r.value && !r.keep { + score = 0 + } + r.choose(score) + r.hover = 0 + return gfx.EventResult{Handled: true, Repaint: true, Focus: r.handlers.Parts().At(r.focusPart(*r.value)), FocusVisible: false} + } + return gfx.EventResult{} +} + +func (r *Rate) key(event gfx.KeyEvent) gfx.EventResult { + if r.readOnly || r.value == nil || event.Text != "" { + return gfx.EventResult{} + } + score := *r.value + switch event.Key { + case gfx.KeyLeft, gfx.KeyDown: + score -= r.step() + case gfx.KeyRight, gfx.KeyUp: + score += r.step() + case gfx.KeyHome: + score = 0 + case gfx.KeyEnd: + score = float32(r.count) + default: + return gfx.EventResult{} + } + r.choose(score) + return gfx.EventResult{Handled: true, Repaint: true, Focus: r.handlers.Parts().At(r.focusPart(*r.value)), FocusVisible: true} +} + +// draw paints the stars and declares each as a part of the control. A star is +// painted empty, then filled over the score the pointer or the user's choice +// shows, with the half star clipped to its left half. +func (r *Rate) draw(d *ui.DrawContext) { + if r.value == nil { + return + } + r.origin = d.Rect + canvas, theme := d.Canvas, d.Theme + parts := r.handlers.Parts() + shown := *r.value + if r.hover > 0 && !r.readOnly { + shown = r.hover + } + color := r.color + if color == (gfx.Color{}) { + color = DefaultColor + } + rest := r.focusPart(*r.value) + for i := range r.count { + star := r.starRect(d.Rect, i) + canvas.DrawIcon(solidStar, star, theme.Border) + switch filled := min(max(shown-float32(i), 0), 1); { + case filled >= 1: + canvas.DrawIcon(solidStar, star, color) + case filled > 0: + canvas.Clip(gfx.Rect{X: star.X, Y: star.Y, Width: star.Width * filled, Height: star.Height}) + canvas.DrawIcon(solidStar, star, color) + canvas.Unclip() + } + if r.readOnly { + continue + } + if canvas.FocusVisible() == parts.At(i) { + ring(canvas, theme, gfx.Rect{X: star.X - 2, Y: star.Y - 2, Width: star.Width + 4, Height: star.Height + 4}) + } + // The stars are one radio group and one tab stop: the one that holds the + // score is checked and takes the focus, and the arrow keys move it. + canvas.HitWithOptions(parts.At(i), star, name(i), gfx.HitOptions{ + Role: gfx.RoleRadio, Checked: *r.value > 0 && i == rest, SkipFocus: i != rest, SkipTab: i != rest, + PosInSet: int32(i + 1), SetSize: int32(r.count), + }) + } +} + +// ring paints the focus ring around a star. +func ring(canvas *gfx.Canvas, theme *gfx.Theme, b gfx.Rect) { + const width = float32(2) + canvas.Fill(gfx.Rect{X: b.X, Y: b.Y, Width: b.Width, Height: width}, theme.Ring) + canvas.Fill(gfx.Rect{X: b.X, Y: b.Y + b.Height - width, Width: b.Width, Height: width}, theme.Ring) + canvas.Fill(gfx.Rect{X: b.X, Y: b.Y, Width: width, Height: b.Height}, theme.Ring) + canvas.Fill(gfx.Rect{X: b.X + b.Width - width, Y: b.Y, Width: width, Height: b.Height}, theme.Ring) +} diff --git a/ui/rate/rate_test.go b/ui/rate/rate_test.go new file mode 100644 index 000000000..0a176222d --- /dev/null +++ b/ui/rate/rate_test.go @@ -0,0 +1,200 @@ +//go:build !js + +package rate_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/rate" +) + +// changes counts the paints that reported a change, as a page reads Changed. +var changes int + +// open runs a page holding one rating over *score, headlessly. +func open(t *testing.T, r *rate.Rate, score *float32) *headless.Session { + t.Helper() + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + r.View(c, "Rating", score) + if r.Changed() { + changes++ + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Rate", Width: 320, Height: 120}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +// star is the center of the left or right half of star n, as the page drew it. +func star(t *testing.T, session *headless.Session, n string, right bool) (x, y float32) { + t.Helper() + hit, err := session.Locate(n) + if err != nil { + t.Fatal(err) + } + b := hit.Bounds + x = b.X + b.Width/4 + if right { + x = b.X + b.Width*3/4 + } + return x, b.Y + b.Height/2 +} + +// A click on a star chooses it, a click on the chosen one clears it, and the +// page learns of each change once. +func TestClickChoosesAndClears(t *testing.T) { + var score float32 + changes = 0 + session := open(t, rate.New(), &score) + x, y := star(t, session, "4", true) + if err := session.Click(x, y); err != nil { + t.Fatal(err) + } + if score != 4 { + t.Fatalf("score = %v after a click on star 4, want 4", score) + } + if changes != 1 { + t.Fatalf("Changed was reported in %d paints after one choice, want 1", changes) + } + if err := session.Click(x, y); err != nil { + t.Fatal(err) + } + if score != 0 { + t.Fatalf("score = %v after a second click on the chosen star, want it cleared", score) + } +} + +func TestKeepScoreKeepsTheChosenOne(t *testing.T) { + score := float32(4) + session := open(t, rate.New().KeepScore(), &score) + x, y := star(t, session, "4", true) + if err := session.Click(x, y); err != nil { + t.Fatal(err) + } + if score != 4 { + t.Fatalf("score = %v, want the chosen score kept", score) + } +} + +// With AllowHalf the left half of a star chooses the half, the right half the whole. +func TestAllowHalfChoosesHalfStars(t *testing.T) { + var score float32 + session := open(t, rate.New().AllowHalf(), &score) + x, y := star(t, session, "2", false) + if err := session.Click(x, y); err != nil { + t.Fatal(err) + } + if score != 1.5 { + t.Fatalf("score = %v after a click on the left half of star 2, want 1.5", score) + } + x, y = star(t, session, "2", true) + if err := session.Click(x, y); err != nil { + t.Fatal(err) + } + if score != 2 { + t.Fatalf("score = %v after a click on the right half of star 2, want 2", score) + } +} + +// The stars are one tab stop and the arrow keys change the score from there. +func TestKeysChangeTheScore(t *testing.T) { + score := float32(2) + session := open(t, rate.New(), &score) + for _, step := range []struct { + key string + want float32 + }{{"tab", 2}, {"right", 3}, {"up", 4}, {"left", 3}, {"down", 2}, {"end", 5}, {"right", 5}, {"home", 0}, {"left", 0}} { + if err := session.Keys(step.key); err != nil { + t.Fatal(err) + } + if score != step.want { + t.Fatalf("score = %v after %q, want %v", score, step.key, step.want) + } + } +} + +// A read only rating shows the score and answers to nothing. +func TestReadOnlyTakesNoInput(t *testing.T) { + score := float32(3) + session := open(t, rate.New().ReadOnly(), &score) + if _, err := session.Locate("5"); err == nil { + t.Fatal("a read only rating declares stars to click") + } + if err := session.Keys("tab"); err != nil { + t.Fatal(err) + } + if err := session.Keys("right"); err != nil { + t.Fatal(err) + } + if score != 3 { + t.Fatalf("score = %v after a key on a read only rating, want 3", score) + } +} + +// A score the rating cannot show is brought into range: a whole number of +// stars, or of halves, from none to all. +func TestScoreIsKeptInRange(t *testing.T) { + for _, test := range []struct { + rate *rate.Rate + score float32 + want float32 + }{ + {rate.New(), 9, 5}, + {rate.New(), -2, 0}, + {rate.New(), 2.6, 3}, + {rate.New().AllowHalf(), 2.6, 2.5}, + {rate.New().Count(3), 4, 3}, + } { + score := test.score + open(t, test.rate, &score) + if score != test.want { + t.Fatalf("score %v became %v, want %v", test.score, score, test.want) + } + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + score := float32(3.5) + r := rate.New().AllowHalf() + view := func(c ui.C) { r.View(c, "Rating", &score) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 320, Height: 120}, view) + canvas.EndFrame() + } + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + score := float32(3.5) + r := rate.New().AllowHalf() + view := func(c ui.C) { r.View(c, "Rating", &score) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + b.ReportAllocs() + for range b.N { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 320, Height: 120}, view) + canvas.EndFrame() + } +} diff --git a/ui/result/result.go b/ui/result/result.go new file mode 100644 index 000000000..b640550af --- /dev/null +++ b/ui/result/result.go @@ -0,0 +1,95 @@ +// Package result is the opt-in page control for the outcome of a task, shown as +// the whole content of a page or a dialog: a large status icon, a title, a +// description and the next steps. A page declares it with a Spec and, optionally, +// the actions under the words: +// +// result.View(c, result.Spec{ +// Status: ui.StatusSuccess, +// Title: "Key imported", +// Description: "The key is now in your vault.", +// }, func() { +// ui.Button(c, "Done") +// }).Fill() +// +// Status picks the icon and its color in the shared ui.Status vocabulary: +// ui.StatusDefault is an information result, and success, warning and danger +// carry a check, a triangle and a cross. Icon replaces it. It is the large +// counterpart of an alert: an alert sits in a page beside other content, a result +// is the content. +// +// It is a separate package so an application that does not import it pays +// nothing for it, and it depends only on the public gfx and ui packages. +package result + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +const maxWidth = 440 + +var circle = []gfx.PathCommand{ + gfx.MoveTo(22, 12), gfx.CubicTo(22, 17.52, 17.52, 22, 12, 22), gfx.CubicTo(6.48, 22, 2, 17.52, 2, 12), + gfx.CubicTo(2, 6.48, 6.48, 2, 12, 2), gfx.CubicTo(17.52, 2, 22, 6.48, 22, 12), +} + +func icon(extra ...gfx.PathCommand) gfx.Icon { + return gfx.Icon{ViewBox: 24, Stroke: 1.5, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: append(append([]gfx.PathCommand(nil), circle...), extra...)} +} + +var ( + infoIcon = icon(gfx.MoveTo(12, 16), gfx.LineTo(12, 12), gfx.MoveTo(12, 8), gfx.LineTo(12.01, 8)) + successIcon = icon(gfx.MoveTo(8.5, 12.5), gfx.LineTo(11, 15), gfx.LineTo(15.5, 9.5)) + dangerIcon = icon(gfx.MoveTo(15, 9), gfx.LineTo(9, 15), gfx.MoveTo(9, 9), gfx.LineTo(15, 15)) + warningIcon = gfx.Icon{ViewBox: 24, Stroke: 1.5, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(10.29, 3.86), gfx.LineTo(1.82, 18), gfx.QuadTo(1, 20, 3, 20), gfx.LineTo(21, 20), gfx.QuadTo(23, 20, 22.18, 18), + gfx.LineTo(13.71, 3.86), gfx.QuadTo(12, 2, 10.29, 3.86), + gfx.MoveTo(12, 9), gfx.LineTo(12, 13), gfx.MoveTo(12, 17), gfx.LineTo(12.01, 17), + }} +) + +// Spec declares a result. +type Spec struct { + // Status picks the icon and its color; an information result by default. + Status ui.Status + // Icon replaces the icon of the status. A zero icon keeps it. + Icon gfx.Icon + // Title says how it went; Description says more. Either may be empty. + Title, Description string +} + +// View declares the result at c, with actions, when not nil, declaring the next +// steps under the words. It is centered in the room it is given: give it Fill, or +// a size. Declare the view on its own, not inside a Memo. +func View(c ui.C, spec Spec, actions func()) ui.Box { + theme := c.Theme() + metrics := theme.Metrics + ink := theme.MutedForeground + glyph := infoIcon + switch spec.Status { + case ui.StatusSuccess: + ink, glyph = theme.Success, successIcon + case ui.StatusWarning: + ink, glyph = theme.WarningColor(), warningIcon + case ui.StatusDanger: + ink, glyph = theme.Danger, dangerIcon + } + if spec.Icon.ViewBox > 0 { + glyph = spec.Icon + } + root := ui.Column(c).Center().Gap(metrics.GapItem).Pad(metrics.PadSurface * 2) + root = root.HitWith(ui.ID(c), spec.Title, gfx.HitOptions{Role: gfx.RoleStatus, SkipFocus: true}) + root.Children(func() { + ui.Icon(c, glyph).Size(64, 64).Color(ink) + if spec.Title != "" { + ui.Text(c, spec.Title).FontSize(metrics.FontSizeL).Weight(gfx.WeightSemibold).TextCenter().MaxWidth(maxWidth) + } + if spec.Description != "" { + ui.Wrap(c, spec.Description).Muted().TextCenter().MaxWidth(maxWidth) + } + if actions != nil { + ui.Row(c).Gap(metrics.GapItem).MarginSides(metrics.GapItem, 0, 0, 0).Items(ui.Center).Children(actions) + } + }) + return root +} diff --git a/ui/result/result_test.go b/ui/result/result_test.go new file mode 100644 index 000000000..b35a6eb6c --- /dev/null +++ b/ui/result/result_test.go @@ -0,0 +1,113 @@ +//go:build !js + +package result_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/result" +) + +func measure(value string, size, weight float32) float32 { return float32(len(value)) * size * 0.55 } + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 600, Height: 400}, view) + canvas.EndFrame() +} + +func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { + t.Helper() + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetMeasurer(measure) + canvas.SetReduceMotion(true) + draw(page, canvas, view) + return page, canvas +} + +// The icon takes the color of the status, and the result is announced as a +// status named by its title. +func TestStatusColorsTheIconAndNamesTheResult(t *testing.T) { + theme := gfx.LightTheme() + for name, test := range map[string]struct { + status ui.Status + want gfx.Color + }{ + "success": {ui.StatusSuccess, theme.Success}, + "warning": {ui.StatusWarning, theme.Warning}, + "danger": {ui.StatusDanger, theme.Danger}, + "info": {ui.StatusDefault, theme.MutedForeground}, + } { + view := func(c ui.C) { result.View(c, result.Spec{Status: test.status, Title: "Done"}, nil).Fill() } + _, canvas := open(t, view) + found := false + for _, triangle := range canvas.Triangles() { + if triangle.Color == test.want { + found = true + break + } + } + if !found { + t.Fatalf("%s: no part of the icon is painted in %+v", name, test.want) + } + } + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + result.View(c, result.Spec{Status: ui.StatusSuccess, Title: "Key imported"}, nil).Fill() + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Result", Width: 480, Height: 320}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + if node, ok := session.AccessByName("Key imported"); !ok || node.Role != gfx.RoleStatus { + t.Fatalf("access node = %+v, %v; want a status named by the title", node, ok) + } +} + +// The actions sit under the words and are page controls of their own. +func TestActionsSitUnderTheWords(t *testing.T) { + var c0 ui.C + actions := func() { ui.Button(c0, "Done") } + view := func(c ui.C) { + c0 = c + result.View(c, result.Spec{Title: "Key imported", Description: "In your vault."}, actions).Fill() + } + _, canvas := open(t, view) + y := map[string]float32{} + for _, text := range canvas.Texts() { + y[text.Value] = text.Bounds.Y + } + if !(y["Key imported"] < y["In your vault."] && y["In your vault."] < y["Done"]) { + t.Fatalf("title %v, description %v, action %v are not in order", y["Key imported"], y["In your vault."], y["Done"]) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + var c0 ui.C + actions := func() { ui.Button(c0, "Done") } + view := func(c ui.C) { + c0 = c + result.View(c, result.Spec{Status: ui.StatusWarning, Title: "Check", Description: "Look again."}, actions).Fill() + } + page, canvas := open(t, view) + if allocations := testing.AllocsPerRun(100, func() { draw(page, canvas, view) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + view := func(c ui.C) { result.View(c, result.Spec{Status: ui.StatusSuccess, Title: "Done"}, nil).Fill() } + page, canvas := open(b, view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, view) + } +} diff --git a/ui/select_disabled_test.go b/ui/select_disabled_test.go index 48ddee46b..31f140604 100644 --- a/ui/select_disabled_test.go +++ b/ui/select_disabled_test.go @@ -124,7 +124,7 @@ func TestFieldInvalidChangesTheLook(t *testing.T) { look := func(invalid bool) string { var f ui.Field f.Invalid = invalid - d := openPage(t, page(func(c ui.C) { ui.TextFieldID(c, gfx.Item(5), &f, "Name", "") })) + d := openPage(t, page(func(c ui.C) { ui.TextField(c, &f, "Name", "", ui.WithID(gfx.Item(5))) })) return fmt.Sprint(d.driver.Snapshot().Primitives) } if look(false) == look(true) { @@ -139,7 +139,7 @@ func TestFormFieldErrorInvalidAndFor(t *testing.T) { state.Error, state.Invalid, state.For = "Not valid.", true, gfx.Item(9) d := openPage(t, page(func(c ui.C) { ui.FormField(c, &state, "Name").FillWidth().Height(90).Children(func() { - ui.TextFieldID(c, gfx.Item(9), new(ui.Field), "Name", "") + ui.TextField(c, new(ui.Field), "Name", "", ui.WithID(gfx.Item(9))) }) })) snap := d.driver.Snapshot() @@ -163,7 +163,7 @@ func TestFieldDisabledIsDimmedAndInert(t *testing.T) { look := func(disabled bool) (string, gfx.Hit) { var f ui.Field f.Disabled = disabled - d := openPage(t, page(func(c ui.C) { ui.TextFieldID(c, gfx.Item(5), &f, "Name", "") })) + d := openPage(t, page(func(c ui.C) { ui.TextField(c, &f, "Name", "", ui.WithID(gfx.Item(5))) })) snap := d.driver.Snapshot() for _, h := range snap.Hits { if h.Role == gfx.RoleTextField { @@ -237,7 +237,7 @@ func TestFormFieldDescriptionAndFieldHint(t *testing.T) { f.Hint = "Locked while connected." d := openPage(t, page(func(c ui.C) { ui.FormField(c, &state, "Port").FillWidth().Height(90).Children(func() { - ui.TextFieldID(c, gfx.Item(9), &f, "Port", "") + ui.TextField(c, &f, "Port", "", ui.WithID(gfx.Item(9))) }) })) snap := d.driver.Snapshot() diff --git a/ui/select_groups_test.go b/ui/select_groups_test.go new file mode 100644 index 000000000..ba1a22cc2 --- /dev/null +++ b/ui/select_groups_test.go @@ -0,0 +1,107 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +var groupedHosts = []string{"alpha", "beta", "gamma", "delta"} +var hostGroupHeads = []ui.SelectGroup{{Label: "Recent", From: 0}, {Label: "All hosts", From: 2}} + +func groupedSelect(t *testing.T, host *string, disabled []bool) *pageDriver { + t.Helper() + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + ui.Select(c, host, groupedHosts, nil, ui.SelectGroups(hostGroupHeads)).Placeholder("Host").DisabledOptions(disabled) + }) + }) + d.click("Host") + return d +} + +// An open list has a heading before the first option of each group, and a heading is +// no option: it is painted, but it is not a control to press. +func TestSelectGroupsPaintHeadingsThatAreNotOptions(t *testing.T) { + host := "" + d := groupedSelect(t, &host, nil) + for _, heading := range []string{"Recent", "All hosts"} { + found := false + for _, text := range d.driver.Snapshot().Texts { + found = found || text.Value == heading + } + if !found { + t.Fatalf("the list did not paint the heading %q", heading) + } + if d.has(heading) { + t.Fatalf("the heading %q is a control", heading) + } + } + for _, option := range groupedHosts { + if !d.has(option) { + t.Fatalf("the option %q is not in the list", option) + } + } +} + +// A press on an option reports the choice's own index, whatever headings come +// before it. +func TestSelectGroupsPickByTheChoicesIndex(t *testing.T) { + host := "" + d := groupedSelect(t, &host, nil) + d.click("gamma") + if host != "gamma" { + t.Fatalf("host = %q after a press on gamma, want gamma", host) + } +} + +// The arrow keys skip the headings and go option to option across groups. +func TestSelectGroupsKeysSkipHeadings(t *testing.T) { + host := "" + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + ui.Select(c, &host, groupedHosts, nil, ui.SelectGroups(hostGroupHeads)).Placeholder("Host") + }) + }) + d.key(gfx.KeyTab) + d.key(gfx.KeyEnter) + if got := d.Focused(); got != "alpha" { + t.Fatalf("Enter opened the list on %q, want the first option", got) + } + d.key(gfx.KeyDown) + d.key(gfx.KeyDown) + if got := d.Focused(); got != "gamma" { + t.Fatalf("two Downs reached %q, want gamma, past the second heading", got) + } + d.key(gfx.KeyEnter) + if host != "gamma" { + t.Fatalf("Enter chose %q", host) + } +} + +// DisabledOptions keeps indexing the choices: a disabled option cannot be pressed +// and its neighbors can. +func TestSelectGroupsDisabledOptionsFollowTheChoices(t *testing.T) { + host := "" + d := groupedSelect(t, &host, []bool{false, true, false, false}) + d.click("beta") + if host != "" { + t.Fatalf("a disabled option was chosen: %q", host) + } + d.click("gamma") + if host != "gamma" { + t.Fatalf("host = %q, want gamma chosen", host) + } +} + +// The chosen option shows on the trigger, and the grouped list repaints without allocating. +func TestSelectGroupsRepaintWithoutAllocating(t *testing.T) { + host := "beta" + d := groupedSelect(t, &host, nil) + d.repaint() + d.repaint() + if allocs := testing.AllocsPerRun(100, d.repaint); allocs != 0 { + t.Fatalf("%v allocations a repaint", allocs) + } +} diff --git a/ui/select_keys_test.go b/ui/select_keys_test.go index 3e774ed4c..387c1d453 100644 --- a/ui/select_keys_test.go +++ b/ui/select_keys_test.go @@ -79,16 +79,16 @@ func TestSelectEscapeClosesTheListFromTheKeyboard(t *testing.T) { } } -// SelectID names the trigger with the application's identity, so a row's words +// A Select given WithID names the trigger with the application's identity, so a row's words // can be its label and the click still opens and chooses. -func TestSelectIDNamesTheTrigger(t *testing.T) { +func TestSelectWithIDNamesTheTrigger(t *testing.T) { size := "" var trigger gfx.ID d := openPage(t, func(c ui.C) { if trigger.IsZero() { trigger = ui.ID(c) } - ui.SelectID(c, trigger, &size, []string{"S", "M"}, nil).Label("Size") + ui.Select(c, &size, []string{"S", "M"}, nil, ui.WithID(trigger)).Label("Size") }) if hit := d.hit("Size"); hit.ID != trigger { t.Fatalf("the trigger's hit is %v, want %v", hit.ID, trigger) diff --git a/ui/select_paint.go b/ui/select_paint.go index 24dd36876..efca6aa9f 100644 --- a/ui/select_paint.go +++ b/ui/select_paint.go @@ -132,13 +132,17 @@ func paintSelect(f *Frame, n *Node) { base.WidgetsOf(f).SetRows(append(base.WidgetsOf(f).GetRows(), Rect{})) } for index := first; index < first+visible && index < count; index++ { - item := components.SelectItem{ID: d.GetScope().At(index), Label: d.GetLabels()[index], Selected: index == d.GetSelected(), Disabled: base.OptionDisabled(d.GetDisabled(), index)} - if index < len(d.GetIcons()) { - item.Icon = d.GetIcons()[index] + item := components.SelectItem{ID: d.GetScope().At(index), Label: d.GetLabels()[index], Selected: index == d.GetSelected(), Disabled: base.OptionDisabled(d.GetDisabled(), index), Heading: d.IsHeading(index)} + if option := d.OptionAt(index); option >= 0 && option < len(d.GetIcons()) { + item.Icon = d.GetIcons()[option] } base.WidgetsOf(f).GetRows()[int(d.GetRects())+index] = control.AddItem(item) } if visible < count { control.AddScrollDown(d.GetScope().At(count+4), first+visible >= count) } + // End closes the popup's entrance and paints its scrollbar: without it the + // popup's presence stays open and the next EndPresence of an enclosing dialog, + // drawer or popover closes the select's in its place. + control.End() } diff --git a/ui/select_presence_test.go b/ui/select_presence_test.go new file mode 100644 index 000000000..b5e562d55 --- /dev/null +++ b/ui/select_presence_test.go @@ -0,0 +1,65 @@ +package ui_test + +import ( + "testing" + "time" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// An open Select inside an enclosing presence (a dialog, drawer or popover) +// closes only its own popup: what is painted after the select is still the +// enclosing surface's, not the popup's entrance. +func TestOpenSelectInsideAPresenceLeavesTheRestOfThePageAlone(t *testing.T) { + var now time.Duration + canvas := &gfx.Canvas{} + canvas.SetClock(func() time.Duration { return now }) + canvas.SetMeasurer(func(value string, size, _ float32) float32 { return float32(len(value)) * size / 2 }) + theme := gfx.LightTheme() + choice := 0 + choices := []int{0, 1, 2} + label := func(index int) string { return [...]string{"A", "B", "C"}[index] } + view := func(c ui.C) { ui.Select(c, &choice, choices, label).Size(120, 32) } + page := ui.NewPage(ui.PageConfig{Theme: &theme, View: view}) + bounds := gfx.Rect{Width: 320, Height: 240} + outer, presence := gfx.Item(1), gfx.Presence{Motion: gfx.Motion{Duration: 100 * time.Millisecond}, Fade: true} + sentinel := gfx.Rect{X: 280, Y: 200, Width: 10, Height: 10} + + canvas.BeginFrame() + canvas.BeginPresence(outer, 0, presence, gfx.Point{}) + page.Draw(canvas, bounds, view) + canvas.EndPresence() + canvas.EndFrame() + var trigger gfx.ID + for _, hit := range canvas.Hits() { + if hit.Role == gfx.RoleCombobox { + trigger = hit.ID + } + } + if trigger.IsZero() { + t.Fatal("the select painted no trigger") + } + + // The enclosing presence has settled; the select opens in an event pass. + now = time.Second + canvas.Reset() + canvas.BeginEventPass(trigger, gfx.ClickInfo{}) + page.Draw(canvas, bounds, view) + canvas.EndEventPass() + + canvas.Reset() + canvas.BeginFrame() + canvas.BeginPresence(outer, 0, presence, gfx.Point{}) + page.Draw(canvas, bounds, view) + canvas.Fill(sentinel, gfx.Color{Red: 1, Alpha: 1}) + canvas.EndPresence() + canvas.EndFrame() + rects := canvas.Rectangles() + if len(rects) == 0 { + t.Fatal("nothing was painted") + } + if last := rects[len(rects)-1]; last.Bounds != sentinel || last.Color.Alpha != 1 { + t.Fatalf("the rectangle painted after the open select = %+v, want the settled sentinel at full alpha", last) + } +} diff --git a/ui/shortcut_test.go b/ui/shortcut_test.go index 66ecccfff..08a46be95 100644 --- a/ui/shortcut_test.go +++ b/ui/shortcut_test.go @@ -42,7 +42,7 @@ func (m *shortcutModel) page(c ui.C) { if more.Clicked() { m.menu = !m.menu } - ui.Popover(c, more, &m.menu, func() { ui.Button(c, "Rename") }) + ui.Popover(c, more, &m.menu, ui.PopoverSpec{Align: ui.Start}, func() { ui.Button(c, "Rename") }) }) } diff --git a/ui/slider_marks_test.go b/ui/slider_marks_test.go new file mode 100644 index 000000000..ae5ca789b --- /dev/null +++ b/ui/slider_marks_test.go @@ -0,0 +1,79 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/ui" +) + +var qualityMarks = []ui.SliderMark{{Value: 0, Label: "Low"}, {Value: 50, Label: "Medium"}, {Value: 100, Label: "High"}} + +// The words of the marks are painted under the track, in order across it, and the +// slider is taller by the room they take. +func TestSliderMarksPaintTheirWordsAndMakeRoom(t *testing.T) { + var s ui.SliderState + var plain, marked ui.Box + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(8).Gap(8).Children(func() { + plain = ui.Slider(c, &s).Width(300) + marked = ui.Slider(c, &s).Width(300).Marks(qualityMarks) + }) + }) + if marked.Rect().Height <= plain.Rect().Height { + t.Fatalf("a slider with labelled marks is %v high, not above a plain one (%v)", marked.Rect().Height, plain.Rect().Height) + } + // The dots sit on the track at the values they mark: the first where the thumb's + // center rests at the minimum, the last at the maximum, the middle one half way. + var centers []float32 + for _, primitive := range d.driver.Snapshot().Primitives { + if primitive.Radius == 2 && primitive.Bounds.Width == 4 { + centers = append(centers, primitive.Bounds.X+2) + } + } + r := marked.Rect() + want := []float32{r.X + 8, r.X + r.Width/2, r.X + r.Width - 8} + if len(centers) != 3 { + t.Fatalf("dots = %v, want one for each of the 3 marks", centers) + } + for i := range want { + if centers[i] < want[i]-0.5 || centers[i] > want[i]+0.5 { + t.Fatalf("dot %d is at %v, want %v", i, centers[i], want[i]) + } + } + at := map[string]float32{} + for _, text := range d.driver.Snapshot().Texts { + at[text.Value] = text.Bounds.X + } + if !(at["Low"] < at["Medium"] && at["Medium"] < at["High"]) { + t.Fatalf("label origins %v, %v, %v are not in order across the track", at["Low"], at["Medium"], at["High"]) + } +} + +// Marks do not move the thumb's travel: a press at the far end still takes the +// maximum. +func TestSliderWithMarksStillTakesThePointer(t *testing.T) { + var s ui.SliderState + var box ui.Box + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(8).Children(func() { + box = ui.Slider(c, &s).Width(300).Marks(qualityMarks).Label("Quality") + }) + }) + r := box.Rect() + if err := d.driver.Click(r.X+r.Width-2, r.Y+8); err != nil { + t.Fatal(err) + } + if s.Value < 99 { + t.Fatalf("value = %v after a press at the far end of a marked slider, want 100", s.Value) + } +} + +func TestMarkedSliderRepaintsWithoutAllocating(t *testing.T) { + var s ui.SliderState + d := openPage(t, func(c ui.C) { ui.Slider(c, &s).Width(300).Marks(qualityMarks) }) + d.repaint() + d.repaint() + if allocs := testing.AllocsPerRun(100, d.repaint); allocs != 0 { + t.Fatalf("%v allocations a repaint", allocs) + } +} diff --git a/ui/slider_paint.go b/ui/slider_paint.go index 59dd2083d..9ae6c59d2 100644 --- a/ui/slider_paint.go +++ b/ui/slider_paint.go @@ -10,7 +10,12 @@ func paintSlider(f *Frame, n *Node) { f.SettleSlider(n) d := &base.WidgetsOf(f).GetSliders()[n.Aux] s := d.GetState() - s.SetArea(n.Rect) + area := n.Rect + if n.Natural <= 0 && hasLabelledMark(d.GetMarks()) { + // The words of the marks hang below the track, in the room measure gave them. + area.Height = min(area.Height, 16) + } + s.SetArea(area) if n.Flags&FlagThemed == 0 { // A SliderBase paints nothing of its own: it is the slider to the pointer, the // keyboard and assistive technology, over the element's whole rectangle. @@ -28,7 +33,7 @@ func paintSlider(f *Frame, n *Node) { }) return } - slider := components.BeginSlider(f.Surface, f.Palette, n.ID, n.Rect, s.Value).Range(s.GetMin(), s.GetMax()).Step(s.GetStep()).ValueText(s.ValueText()) + slider := components.BeginSlider(f.Surface, f.Palette, n.ID, area, s.Value).Range(s.GetMin(), s.GetMax()).Step(s.GetStep()).ValueText(s.ValueText()).Marks(d.GetMarks()) if n.Natural > 0 { slider = slider.Vertical() } @@ -42,6 +47,16 @@ func paintSlider(f *Frame, n *Node) { slider.Paint(label) } +// hasLabelledMark reports whether any mark has a word. +func hasLabelledMark(marks []base.SliderMark) bool { + for _, mark := range marks { + if mark.Label != "" { + return true + } + } + return false +} + // sliderPointer moves the slider under the pointer. func sliderPointer(f *Frame, n *Node, s *SliderState) { event, _ := f.Surface.PointerOn(n.ID) diff --git a/ui/steps/steps.go b/ui/steps/steps.go new file mode 100644 index 000000000..41b47c71c --- /dev/null +++ b/ui/steps/steps.go @@ -0,0 +1,329 @@ +// Package steps is the opt-in page control for a step bar: the stages of a +// task laid out in order, with the finished ones behind the current one and the +// ones to come after it. A page keeps the current step in its model and +// declares the stages with a Spec: +// +// steps.View(c, "Checkout", &m.step, steps.Spec{Steps: m.stages, Clickable: true}) +// // m.stages is a []steps.Step kept in the model, so a warm paint allocates +// // nothing: {Title: "Account", Description: "Create a login"}, ... +// +// current is the zero-based index of the step being worked on: the steps before +// it are finished and the ones after it wait. Spec.Status says how the current +// step stands, Process while it is under way or Error when it failed. With +// Clickable a click, or Enter or Space on a focused step, makes it the current +// one; without it the bar only shows where the task is. +// +// The step bar is horizontal by default and vertical for Direction: Vertical; +// Type: Dot replaces the numbered markers with dots, and Size: Small makes the +// markers and the text smaller. It composes the page's own primitives, so it +// takes the page's theme and density. +// +// It is a separate package so an application that does not import it pays +// nothing for it, and it depends only on the public gfx and ui packages. +package steps + +import ( + "strconv" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Status is how a step stands. +type Status uint8 + +const ( + // Process is the step under way: the zero value, and what the current step + // shows unless Spec.Status says otherwise. + Process Status = iota + // Wait is a step not reached yet. + Wait + // Finish is a step done. + Finish + // Error is a step that failed. + Error +) + +// Type is the look of a step's marker. +type Type uint8 + +const ( + // Numbered marks each step with a circle holding its number, a check once + // it is finished and a cross when it failed. It is the zero value. + Numbered Type = iota + // Dot marks each step with a small dot. + Dot +) + +// Direction is the way the steps run. +type Direction uint8 + +const ( + // Horizontal lays the steps out in a row, joined by lines. It is the zero + // value. + Horizontal Direction = iota + // Vertical stacks the steps in a column. + Vertical +) + +// Size is how large the markers and the text are. +type Size uint8 + +const ( + // Default is the zero value. + Default Size = iota + // Small is the compact bar. + Small +) + +// Step is one stage of the task. +type Step struct { + // Title names the stage. + Title string + // Description is an optional line under the title. + Description string + // Icon replaces the number of a numbered marker while the step is not + // finished or failed. A zero icon keeps the number. + Icon gfx.Icon +} + +// Spec declares the step bar. Its zero value is a horizontal, default sized bar +// of numbered markers that only shows where the task is. +type Spec struct { + // Steps are the stages, in order. Keep the slice in the model: a slice made in + // each paint allocates in each paint. + Steps []Step + // Status is how the current step stands; Process by default. + Status Status + // Type is the look of the markers. + Type Type + // Direction is the way the steps run. + Direction Direction + // Size is how large the markers and the text are. + Size Size + // Clickable lets a click on a step make it the current one. + Clickable bool +} + +var ( + checkIcon = gfx.Icon{ViewBox: 24, Stroke: 2.5, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(20, 6), gfx.LineTo(9, 17), gfx.LineTo(4, 12), + }} + crossIcon = gfx.Icon{ViewBox: 24, Stroke: 2.5, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(18, 6), gfx.LineTo(6, 18), gfx.MoveTo(6, 6), gfx.LineTo(18, 18), + }} +) + +// numbers are the words of the markers of the first steps, made once. +var numbers [20]string + +func init() { + for i := range numbers { + numbers[i] = strconv.Itoa(i + 1) + } +} + +func number(i int) string { + if i < len(numbers) { + return numbers[i] + } + return strconv.Itoa(i + 1) +} + +// View declares the step bar at c. label names it for assistive technology; +// current is the index of the current step, and a click on a Clickable bar sets +// it. The bar is as tall as its steps and, horizontally, as wide as the room it +// is given: give it FillWidth. Declare the view on its own, not inside a Memo. +func View(c ui.C, label string, current *int, spec Spec) ui.Box { + if c == nil { + panic("steps: View needs a page") + } + if current == nil { + panic("steps: View needs the current step") + } + var root ui.Box + if spec.Direction == Vertical { + root = ui.Column(c) + } else { + root = ui.Row(c).Items(ui.Start) + } + if spec.Clickable { + // The steps are the control's hits, and a hit over them would overlap theirs. + root = root.Label(label) + } else { + root = root.HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true}) + } + look := newLook(c, spec) + last := len(spec.Steps) - 1 + root.Children(func() { + for i := range spec.Steps { + status := statusOf(i, *current, spec.Status) + var step ui.Box + if spec.Direction == Vertical { + step = ui.Row(c).Items(ui.Stretch).Gap(look.gap) + } else { + step = ui.Row(c).Items(ui.Start).Gap(look.gap).Shrink(0) + } + if spec.Clickable { + step.HitWith(ui.ID(c), spec.Steps[i].Title, gfx.HitOptions{Role: gfx.RoleButton}) + } + step.Children(func() { + if spec.Direction == Vertical { + look.rail(c, spec.Steps[i], i, status, i < last, i < *current) + look.text(c, spec.Steps[i], status, i < last) + } else { + look.marker(c, spec.Steps[i], i, status) + look.text(c, spec.Steps[i], status, false) + } + }) + if spec.Clickable && step.Clicked() { + *current = i + } + if spec.Direction != Vertical && i < last { + look.line(c, i < *current) + } + } + }) + return root +} + +// statusOf is how step i stands with the current one at current. +func statusOf(i, current int, now Status) Status { + switch { + case i < current: + return Finish + case i == current: + return now + } + return Wait +} + +// look is what a bar paints with: the page's theme and the spec's size and type. +type look struct { + theme *gfx.Theme + markerSize float32 + dot float32 + gap float32 + title float32 + detail float32 + numbered bool + vertical bool +} + +func newLook(c ui.C, spec Spec) look { + theme := c.Theme() + metrics := theme.Metrics + l := look{ + theme: theme, markerSize: 24, dot: 8, gap: metrics.GapItem, + title: metrics.FontSizeM, detail: metrics.FontSizeS, + numbered: spec.Type == Numbered, vertical: spec.Direction == Vertical, + } + if spec.Size == Small { + l.markerSize, l.dot, l.title = 20, 6, metrics.FontSizeS + } + return l +} + +// tone is the colors of a marker in a status: its fill, and what is drawn on it. +func (l look) tone(status Status) (fill, ink gfx.Color) { + switch status { + case Finish: + return l.theme.Secondary, l.theme.Primary + case Process: + return l.theme.Primary, l.theme.PrimaryForeground + case Error: + return l.theme.Danger, l.theme.DangerForeground + } + return l.theme.Muted, l.theme.MutedForeground +} + +// marker declares the circle or the dot of a step. +func (l look) marker(c ui.C, step Step, i int, status Status) ui.Box { + fill, ink := l.tone(status) + if !l.numbered { + // A dot is centered on the first line of the title, where a number sits. + slot := ui.Row(c).Size(l.dot, l.markerSize).Shrink(0).Justify(ui.Center).Items(ui.Center) + slot.Children(func() { + ui.Spacer(c).Size(l.dot, l.dot).Shrink(0).Radius(l.dot / 2).Background(dotFill(l.theme, status)) + }) + return slot + } + circle := ui.Row(c).Size(l.markerSize, l.markerSize).Shrink(0).Radius(l.markerSize / 2).Background(fill).Center() + circle.Children(func() { + glyph := l.markerSize * 0.55 + switch { + case status == Finish: + ui.Icon(c, checkIcon).Size(glyph, glyph).Color(ink) + case status == Error: + ui.Icon(c, crossIcon).Size(glyph, glyph).Color(ink) + case step.Icon.ViewBox > 0: + ui.Icon(c, step.Icon).Size(glyph, glyph).Color(ink) + default: + ui.Text(c, number(i)).FontSize(l.detail).Weight(gfx.WeightMedium).Color(ink) + } + }) + return circle +} + +// dotFill is the color of a dot in a status. +func dotFill(theme *gfx.Theme, status Status) gfx.Color { + switch status { + case Finish, Process: + return theme.Primary + case Error: + return theme.Danger + } + return theme.Border +} + +// text declares the title and the description of a step. +func (l look) text(c ui.C, step Step, status Status, padded bool) { + column := ui.Column(c).Gap(2) + if padded { + column = column.PadBottom(l.gap * 2) + } + column.Children(func() { + title := ui.Text(c, step.Title).FontSize(l.title).LineHeight(l.markerSize) + switch status { + case Wait: + title.Muted() + case Error: + title.Color(l.theme.Danger).Weight(gfx.WeightMedium) + case Process: + title.Weight(gfx.WeightMedium) + } + if step.Description != "" { + ui.Text(c, step.Description).FontSize(l.detail).Muted() + } + }) +} + +// line declares the line that joins two steps of a horizontal bar; done is +// whether the step it leaves is behind the current one. +func (l look) line(c ui.C, done bool) { + color := l.theme.Border + if done { + color = l.theme.Primary + } + holder := ui.Row(c).Grow(1).Height(l.markerSize).MinWidth(16).Items(ui.Center) + holder.MarginSides(0, l.gap, 0, l.gap) + holder.Children(func() { + ui.Spacer(c).FillWidth().Height(1).Background(color) + }) +} + +// rail declares the marker of a step of a vertical bar and the line that runs +// down from it to the next step. +func (l look) rail(c ui.C, step Step, i int, status Status, joined, done bool) { + rail := ui.Column(c).Items(ui.Center).Shrink(0).Width(l.markerSize) + rail.Children(func() { + l.marker(c, step, i, status) + if joined { + color := l.theme.Border + if done { + color = l.theme.Primary + } + ui.Spacer(c).Width(1).Grow(1).MinHeight(8).Margin(4).Background(color) + } + }) +} diff --git a/ui/steps/steps_test.go b/ui/steps/steps_test.go new file mode 100644 index 000000000..7031fff89 --- /dev/null +++ b/ui/steps/steps_test.go @@ -0,0 +1,185 @@ +//go:build !js + +package steps_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/steps" +) + +var items = []steps.Step{ + {Title: "Account", Description: "Create a login"}, + {Title: "Profile"}, + {Title: "Done"}, +} + +func measure(value string, size, weight float32) float32 { + return float32(len(value)) * size * 0.55 +} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 480, Height: 240}, view) + canvas.EndFrame() +} + +func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { + t.Helper() + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetMeasurer(measure) + canvas.SetReduceMotion(true) + draw(page, canvas, view) + return page, canvas +} + +func hitByLabel(canvas *gfx.Canvas, label string) (gfx.Hit, bool) { + hits := canvas.Hits() + for i := len(hits) - 1; i >= 0; i-- { + if hits[i].Label == label && !hits[i].IsLabel && !hits[i].Backdrop { + return hits[i], true + } + } + return gfx.Hit{}, false +} + +func click(page *ui.Page, canvas *gfx.Canvas, view func(ui.C), id gfx.ID) { + canvas.BeginEventPass(id, gfx.ClickInfo{}) + draw(page, canvas, view) + canvas.EndEventPass() + draw(page, canvas, view) +} + +// markerFills counts the circles of the markers by the color they are filled +// with, so a test can say which step stands how without knowing its position. +func markerFills(canvas *gfx.Canvas, color gfx.Color) int { + count := 0 + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color == color && rectangle.Radius >= 8 && rectangle.Bounds.Width == rectangle.Bounds.Height { + count++ + } + } + return count +} + +// The steps behind the current one are finished, the current one is under way +// and the rest wait, each painted in the tone of its status. +func TestStepsStandByTheirPlaceFromTheCurrentOne(t *testing.T) { + theme := gfx.LightTheme() + current := 1 + view := func(c ui.C) { + steps.View(c, "Checkout", ¤t, steps.Spec{Steps: items}).FillWidth() + } + _, canvas := open(t, view) + for name, want := range map[string]struct { + color gfx.Color + count int + }{ + "finished": {theme.Secondary, 1}, + "current": {theme.Primary, 1}, + "waiting": {theme.Muted, 1}, + "failed": {theme.Danger, 0}, + } { + if got := markerFills(canvas, want.color); got != want.count { + t.Fatalf("%s markers = %d, want %d", name, got, want.count) + } + } +} + +// The status says how the current step stands: a failed one is painted in the +// danger color and the steps around it are unchanged. +func TestStepsShowAFailedCurrentStep(t *testing.T) { + theme := gfx.LightTheme() + current := 1 + view := func(c ui.C) { + steps.View(c, "Checkout", ¤t, steps.Spec{Steps: items, Status: steps.Error}).FillWidth() + } + _, canvas := open(t, view) + if got := markerFills(canvas, theme.Danger); got != 1 { + t.Fatalf("failed markers = %d, want 1", got) + } + if got := markerFills(canvas, theme.Primary); got != 0 { + t.Fatalf("under-way markers = %d, want 0 while the current step failed", got) + } +} + +// A clickable bar makes the clicked step the current one; a bar that is not +// clickable offers no step to click. +func TestStepsClickMovesTheCurrentStep(t *testing.T) { + current := 0 + view := func(c ui.C) { + steps.View(c, "Checkout", ¤t, steps.Spec{Steps: items, Clickable: true}).FillWidth() + } + page, canvas := open(t, view) + hit, ok := hitByLabel(canvas, "Done") + if !ok { + t.Fatal("a clickable bar has no step named Done to click") + } + click(page, canvas, view, hit.ID) + if current != 2 { + t.Fatalf("current = %d after a click on the last step, want 2", current) + } + + still := 0 + fixed := func(c ui.C) { + steps.View(c, "Checkout", &still, steps.Spec{Steps: items}).FillWidth() + } + _, canvas = open(t, fixed) + if _, ok := hitByLabel(canvas, "Done"); ok { + t.Fatal("a bar that is not clickable offers a step to click") + } +} + +// A clickable step is a button for the keyboard too: Tab reaches it and Enter +// chooses it. +func TestStepsChooseWithTheKeyboard(t *testing.T) { + current := 0 + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + steps.View(c, "Checkout", ¤t, steps.Spec{Steps: items, Clickable: true}).FillWidth() + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Steps", Width: 480, Height: 200}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + session.Keys("tab") + session.Keys("tab") + session.Keys("enter") + if current != 1 { + t.Fatalf("current = %d after Tab, Tab and Enter, want the second step", current) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + for name, spec := range map[string]steps.Spec{ + "horizontal": {Steps: items, Clickable: true}, + "vertical": {Steps: items, Direction: steps.Vertical, Type: steps.Dot, Size: steps.Small}, + } { + t.Run(name, func(t *testing.T) { + current := 1 + view := func(c ui.C) { steps.View(c, "Checkout", ¤t, spec).FillWidth() } + page, canvas := open(t, view) + if allocations := testing.AllocsPerRun(100, func() { draw(page, canvas, view) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } + }) + } +} + +func BenchmarkViewPaint(b *testing.B) { + current := 1 + view := func(c ui.C) { steps.View(c, "Checkout", ¤t, steps.Spec{Steps: items}).FillWidth() } + page, canvas := open(b, view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, view) + } +} diff --git a/ui/table_checked_test.go b/ui/table_checked_test.go new file mode 100644 index 000000000..28d63b83b --- /dev/null +++ b/ui/table_checked_test.go @@ -0,0 +1,156 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// rowChecks are the checkboxes of the rows of the last paint, top to bottom. +func (d *pageDriver) rowChecks() []gfx.Hit { + var out []gfx.Hit + for _, hit := range d.driver.Snapshot().Hits { + if hit.Label == "Select row" && !hit.IsLabel { + out = append(out, hit) + } + } + return out +} + +func (d *pageDriver) clickHit(hit gfx.Hit) { + d.t.Helper() + if err := d.driver.Click(hit.Bounds.X+hit.Bounds.Width/2, hit.Bounds.Y+hit.Bounds.Height/2); err != nil { + d.t.Fatal(err) + } +} + +// A table given Checked has a checkbox for each row and one in the header: the +// row's ticks are the keys of the Selection, the header ticks or clears them all, +// and it is mixed while only some are ticked. +func TestTableCheckedTicksRowsAndHeader(t *testing.T) { + var state ui.TableState + var checked ui.Selection + changes := 0 + d := openPage(t, func(c ui.C) { + ui.Table(c, &state, ui.TableSpec{ + Source: wholeRows{}, Checked: &checked, + Columns: titledColumns(nil, []string{"Host", "Port"}, nil), + }).Width(400).Height(200) + if state.CheckedChanged() { + changes++ + } + }) + boxes := d.rowChecks() + if len(boxes) != 3 { + t.Fatalf("row checkboxes = %d, want one for each of the 3 rows", len(boxes)) + } + d.clickHit(boxes[1]) + if !checked.Has(1) || checked.Len() != 1 || changes != 1 { + t.Fatalf("after a tick on row 1: checked %v (len %d), changes %d", checked.Has(1), checked.Len(), changes) + } + if state.Selected() != -1 { + t.Fatalf("a tick selected row %d; ticks and the selected row are separate", state.Selected()) + } + header := d.hit("Select all rows") + if header.Checked || !header.Mixed { + t.Fatalf("header with one of three ticked: checked %v, mixed %v; want mixed", header.Checked, header.Mixed) + } + d.clickHit(header) + if checked.Len() != 3 { + t.Fatalf("%d rows ticked after the header was pressed with some ticked, want all 3", checked.Len()) + } + if h := d.hit("Select all rows"); !h.Checked || h.Mixed { + t.Fatalf("header with every row ticked: checked %v, mixed %v", h.Checked, h.Mixed) + } + d.clickHit(d.hit("Select all rows")) + if checked.Len() != 0 { + t.Fatalf("%d rows ticked after the header was pressed with all ticked, want none", checked.Len()) + } +} + +// The column of checkboxes is in front of the application's columns and is not +// one of them: Source.Cell and CellRect keep the application's indexes, and the +// first column's text starts after the checkboxes. +func TestTableCheckedKeepsTheApplicationsColumnIndexes(t *testing.T) { + var state ui.TableState + var checked ui.Selection + d := openPage(t, func(c ui.C) { + ui.Table(c, &state, ui.TableSpec{ + Source: wholeRows{}, Checked: &checked, + Columns: titledColumns(nil, []string{"Host", "Port"}, nil), + }).Width(400).Height(200) + }) + at := map[string]float32{} + for _, label := range d.driver.Snapshot().Labels { + at[label.Value] = label.Bounds.X + } + if at["alpha"] < 40 { + t.Fatalf("the first column's text starts at %v, inside the 40 pixel column of checkboxes", at["alpha"]) + } + cell, ok := state.CellRect(0, 0) + if !ok || cell.X < 40 { + t.Fatalf("CellRect(0, 0) = %+v, %v; want the application's first column, after the checkboxes", cell, ok) + } + port, ok := state.CellRect(0, 1) + if !ok || port.X <= cell.X { + t.Fatalf("CellRect(0, 1) = %+v, %v; want the second column right of the first", port, ok) + } +} + +// A sortable column is sorted by its own index, with a column of checkboxes in front. +func TestTableCheckedSortsByTheApplicationsColumn(t *testing.T) { + var state ui.TableState + var checked ui.Selection + clicked := -1 + d := openPage(t, func(c ui.C) { + table := ui.Table(c, &state, ui.TableSpec{ + Source: wholeRows{}, Checked: &checked, + Columns: titledColumns(nil, []string{"Host", "Port"}, []bool{true, true}), + }).Width(400).Height(200) + if column, ok := table.HeaderClicked(); ok { + clicked = column + } + }) + d.click("Port") + if clicked != 1 { + t.Fatalf("a click on the Port heading reported column %d, want 1", clicked) + } +} + +// Checked rows repaint without allocating. +func TestTableCheckedRepaintsWithoutAllocating(t *testing.T) { + var state ui.TableState + var checked ui.Selection + checked.Add(1) + rows := ui.TableRows{{"alpha", ""}, {"beta", ":22"}, {"gamma", ""}} // cells made once: wholeRows builds them in each call + columns := titledColumns(nil, []string{"Host", "Port"}, nil) + d := openPage(t, func(c ui.C) { + ui.Table(c, &state, ui.TableSpec{Source: &rows, Checked: &checked, Columns: columns}).Width(400).Height(200) + }) + d.repaint() + d.repaint() + if allocs := testing.AllocsPerRun(100, d.repaint); allocs != 0 { + t.Fatalf("%v allocations a repaint", allocs) + } +} + +// With frozen columns and sideways scrolling the rows are painted in two passes; +// the checkbox of a row still ticks once for one click. +func TestTableCheckedWithFrozenColumnsTicksOnce(t *testing.T) { + var state ui.TableState + var checked ui.Selection + rows := ui.TableRows{{"alpha", "a", "b"}, {"beta", "c", "d"}, {"gamma", "e", "f"}} + columns := titledColumns([]ui.TableColumn{{Width: 120}, {Width: 160}, {Width: 160}}, []string{"Host", "Port", "User"}, nil) + d := openPage(t, func(c ui.C) { + ui.Table(c, &state, ui.TableSpec{Source: &rows, Checked: &checked, Columns: columns, FrozenColumns: 1}).Width(300).Height(200) + }) + boxes := d.rowChecks() + if len(boxes) == 0 { + t.Fatal("no row checkboxes painted") + } + d.clickHit(boxes[len(boxes)-1]) + if checked.Len() != 1 { + t.Fatalf("%d rows ticked after one click in a table painted in two passes, want 1", checked.Len()) + } +} diff --git a/ui/table_columns_test.go b/ui/table_columns_test.go new file mode 100644 index 000000000..800ed450a --- /dev/null +++ b/ui/table_columns_test.go @@ -0,0 +1,18 @@ +package ui_test + +import "github.com/vivaui/viva/ui" + +// titledColumns is columns with the titles and the sortable flags a test keeps in +// slices of their own, one per column; a nil columns is one column of no width for +// each title. +func titledColumns(columns []ui.TableColumn, titles []string, sortable []bool) []ui.TableColumn { + out := make([]ui.TableColumn, max(len(columns), len(titles))) + copy(out, columns) + for i, title := range titles { + out[i].Title = title + } + for i := range min(len(sortable), len(out)) { + out[i].Sortable = sortable[i] + } + return out +} diff --git a/ui/table_filter_test.go b/ui/table_filter_test.go new file mode 100644 index 000000000..68443a15e --- /dev/null +++ b/ui/table_filter_test.go @@ -0,0 +1,62 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/ui" +) + +// A filterable column has a button at the end of its heading, separate from the +// heading's own press: a press on it is reported as the column's index in Columns +// (with or without a column of checkboxes in front), and does not sort. +func TestFilterButtonReportsItsColumn(t *testing.T) { + for _, checkedTable := range []bool{false, true} { + var state ui.TableState + var checked ui.Selection + filtered, sorted := -1, -1 + columns := titledColumns(nil, []string{"Host", "Port"}, []bool{true, true}) + columns[1].Filterable = true + spec := ui.TableSpec{Source: wholeRows{}, Columns: columns} + if checkedTable { + spec.Checked = &checked + } + d := openPage(t, func(c ui.C) { + table := ui.Table(c, &state, spec).Width(400).Height(200) + if column, ok := table.FilterClicked(); ok { + filtered = column + } + if column, ok := table.HeaderClicked(); ok { + sorted = column + } + }) + d.clickHit(d.hit("Filter")) + if filtered != 1 || sorted != -1 { + t.Fatalf("checked=%v: filter reported column %d and the heading sorted %d; want 1 and none", checkedTable, filtered, sorted) + } + if node := d.hit("Filter"); node.Selected { + t.Fatal("a column that is not filtered paints its filter button as on") + } + } +} + +// Filtered paints the button as one that is on, and HeaderRect says where the heading +// is so the application can anchor its choice there. +func TestFilteredColumnAndHeaderRect(t *testing.T) { + var state ui.TableState + columns := titledColumns(nil, []string{"Host", "Port"}, nil) + columns[0].Filterable, columns[0].Filtered = true, true + d := openPage(t, func(c ui.C) { + ui.Table(c, &state, ui.TableSpec{Source: wholeRows{}, Columns: columns}).Width(400).Height(200) + }) + if !d.hit("Filter").Selected { + t.Fatal("a filtered column's button is not painted as on") + } + rect, ok := state.HeaderRect(0) + filter := d.hit("Filter") + if !ok || filter.Bounds.X < rect.X || filter.Bounds.X+filter.Bounds.Width > rect.X+rect.Width+0.5 || filter.Bounds.Y < rect.Y { + t.Fatalf("HeaderRect(0) = %+v, %v; the filter button %+v is not inside it", rect, ok, filter.Bounds) + } + if _, ok := state.HeaderRect(5); ok { + t.Fatal("HeaderRect answered for a column that does not exist") + } +} diff --git a/ui/table_paint.go b/ui/table_paint.go index 1f2283c61..559a6f9f3 100644 --- a/ui/table_paint.go +++ b/ui/table_paint.go @@ -22,9 +22,14 @@ func paintTableRows(f *Frame, t *TableDecl, rows Rect, First, Last int, top, con w.SetCells(make([]string, len(t.GetSpec().Columns))) } cells := w.GetCells()[:len(t.GetSpec().Columns)] + lead := t.GetLead() for row := First; row < Last; row++ { for column := range cells { - cells[column] = t.GetSpec().Source.Cell(row, column) + if column < lead { + cells[column] = "" // the column of checkboxes has no text + continue + } + cells[column] = t.GetSpec().Source.Cell(row, column-lead) } if t.GetSpec().Striped && row%2 == 1 { stripe := f.Palette.Muted @@ -38,6 +43,9 @@ func paintTableRows(f *Frame, t *TableDecl, rows Rect, First, Last int, top, con id = gfx.ID{} } table.RowState(id, cells, components.TableRowState{Selected: row == t.GetState().Selected()}) + if lead > 0 && !id.IsZero() { + paintRowCheckbox(f, t, row, Rect{X: rows.X, Y: top + float32(row)*rowHeight, Width: t.GetSpec().Columns[0].Width, Height: rowHeight}) + } } } @@ -108,8 +116,9 @@ func paintTableHeaderRow(f *Frame, t *TableDecl, r Rect, headerHeight, rowHeight cells := components.TableCellBounds(t.GetSpec().Columns, bounds, base.WidgetsOf(f).GetRects()[:0]) base.WidgetsOf(f).SetRectsCells(cells[:0]) hover := f.Palette.Hover + lead := t.GetLead() for column, cell := range cells { - if column < len(t.GetSpec().Sortable) && t.GetSpec().Sortable[column] && !t.GetSpec().Header.IsZero() && canvas.Hovered() == t.GetSpec().Header.At(column) { + if column >= lead && column < len(t.GetSpec().Columns) && t.GetSpec().Columns[column].Sortable && !t.GetSpec().Header.IsZero() && canvas.Hovered() == t.GetSpec().Header.At(column-lead) { canvas.Fill(cell, hover) } } @@ -122,7 +131,7 @@ func paintTableHeaderRow(f *Frame, t *TableDecl, r Rect, headerHeight, rowHeight if t.GetForegroundSet() { table = table.Foreground(t.GetForeground()) } - table.Header(t.GetSpec().Headers) + table.Header(t.GetTitles()) sorted, descending, isSorted := t.GetState().Sort() metrics := f.Palette.Metrics @@ -130,15 +139,15 @@ func paintTableHeaderRow(f *Frame, t *TableDecl, r Rect, headerHeight, rowHeight if fontSize <= 0 { fontSize = metrics.FontSizeM } + if lead > 0 && len(cells) > 0 { + paintHeaderCheckbox(f, t, cells[0]) + } for column, cell := range cells { - if column >= len(t.GetSpec().Sortable) || !t.GetSpec().Sortable[column] || t.GetSpec().Header.IsZero() { + if column < lead || column >= len(t.GetSpec().Columns) || !t.GetSpec().Columns[column].Sortable || t.GetSpec().Header.IsZero() { continue } - title := "" - if column < len(t.GetSpec().Headers) { - title = t.GetSpec().Headers[column] - } - if isSorted && sorted == column { + title := t.GetSpec().Columns[column].Title + if isSorted && sorted == column-lead { arrow := "↑" if descending { arrow = "↓" @@ -154,6 +163,72 @@ func paintTableHeaderRow(f *Frame, t *TableDecl, r Rect, headerHeight, rowHeight } canvas.LabelCenter(arrow, Rect{X: x, Y: cell.Y, Width: 12, Height: cell.Height}, gfx.TextStyle{Size: fontSize, Weight: gfx.WeightMedium, Color: f.Palette.MutedForeground}) } - canvas.HitWithLabel(t.GetSpec().Header.At(column), cell, title) + canvas.HitWithLabel(t.GetSpec().Header.At(column-lead), cell, title) + } + for column, cell := range cells { + if column >= lead && column < len(t.GetSpec().Columns) && t.GetSpec().Columns[column].Filterable { + paintFilterButton(f, t, column, cell) + } + } +} + +// funnelIcon is Lucide's filter. +var funnelIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(22, 3), gfx.LineTo(2, 3), gfx.LineTo(10, 12.46), gfx.LineTo(10, 19), gfx.LineTo(14, 21), gfx.LineTo(14, 12.46), gfx.ClosePath(), +}} + +// paintFilterButton paints the funnel at the end of a column's heading, in the +// primary color while the column is filtered, and declares its hit. It is declared +// after the heading's own, inside it, so a press on it is not a press on the heading. +func paintFilterButton(f *Frame, t *TableDecl, column int, cell Rect) { + canvas := f.Surface + const side = 20 + button := Rect{X: cell.X + cell.Width - side - f.Palette.Metrics.PadControlX/2, Y: cell.Y + (cell.Height-side)/2, Width: side, Height: side} + id := base.FilterID(canvas, t.GetSpec().Header, column-t.GetLead()) + ink := f.Palette.MutedForeground + if t.GetSpec().Columns[column].Filtered { + ink = f.Palette.Primary + } + if canvas.Hovered() == id { + canvas.Rounded(button, f.Palette.Metrics.RadiusControl, f.Palette.Hover) + } + canvas.DrawIcon(funnelIcon, Rect{X: button.X + 4, Y: button.Y + 4, Width: side - 8, Height: side - 8}, ink) + label := t.GetSpec().FilterLabel + if label == "" { + label = "Filter" + } + canvas.HitWithOptions(id, button, label, gfx.HitOptions{Role: gfx.RoleButton, Description: t.GetSpec().Columns[column].Title, Selected: t.GetSpec().Columns[column].Filtered}) +} + +// checkSize is the side of a table's checkbox. +const checkSize = 16 + +// paintRowCheckbox paints the checkbox of a row in the cell of the column of +// checkboxes; a click on it was applied where the table was declared. +func paintRowCheckbox(f *Frame, t *TableDecl, row int, cell Rect) { + canvas := f.Surface + id := base.CheckID(canvas, t.GetSpec().Rows, row) + label := t.GetSpec().SelectRowLabel + if label == "" { + label = "Select row" + } + box := Rect{X: cell.X + (cell.Width-checkSize)/2, Y: cell.Y + (cell.Height-checkSize)/2, Width: checkSize, Height: checkSize} + components.BeginCheckbox(canvas, f.Palette, id, box, t.GetSpec().Checked.Has(row)).Label(label).Paint() +} + +// paintHeaderCheckbox paints the checkbox of the header: ticked when every row is, +// mixed when some are. +func paintHeaderCheckbox(f *Frame, t *TableDecl, cell Rect) { + canvas := f.Surface + id := base.HeaderCheckID(canvas, t.GetSpec().Rows) + label := t.GetSpec().SelectAllLabel + if label == "" { + label = "Select all rows" + } + box := Rect{X: cell.X + (cell.Width-checkSize)/2, Y: cell.Y + (cell.Height-checkSize)/2, Width: checkSize, Height: checkSize} + checkbox := components.BeginCheckbox(canvas, f.Palette, id, box, t.AllChecked()).Label(label) + if t.SomeChecked() && !t.AllChecked() { + checkbox = checkbox.Indeterminate() } + checkbox.Paint() } diff --git a/ui/table_scrollbars_test.go b/ui/table_scrollbars_test.go index cc8a1dee2..1b4d620b5 100644 --- a/ui/table_scrollbars_test.go +++ b/ui/table_scrollbars_test.go @@ -115,9 +115,11 @@ func TestTableHideHoverScrollbarsOmitsOnlyTheAnonymousVerticalThumb(t *testing.T view := func(c ui.C) { ui.Column(c).Children(func() { table = ui.Table(c, &state, ui.TableSpec{ - Columns: []components.TableColumn{{Width: 120}, {Width: 120}, {Width: 120}, {Width: 120}}, - Headers: []string{"A", "B", "C", "D"}, Rows: gfx.Item(1).Scope(), Source: &rows, - ScrollbarSize: 10, ScrollbarGutter: test.gutter, + Columns: titledColumns([]components.TableColumn{{Width: 120}, {Width: 120}, {Width: 120}, {Width: 120}}, []string{"A", "B", "C", "D"}, nil), + Rows: gfx.Item(1).Scope(), + Source: &rows, + ScrollbarSize: 10, + ScrollbarGutter: test.gutter, HideHoverScrollbars: test.hide, }).Size(320, 200) }) @@ -212,11 +214,14 @@ func TestTableScrollsItselfWithAHoverBarInItsGutter(t *testing.T) { view := func(c ui.C) { ui.Column(c).Fill().Pad(20).Children(func() { table = ui.Table(c, &tableState, ui.TableSpec{ - Rows: rowScope, Header: gfx.Item(2).Scope(), - Columns: []components.TableColumn{{Width: 200}, {Width: 0}}, - Headers: []string{"Name", "State"}, Source: &rows, - Scrollbar: gfx.Item(900), ScrollbarLabel: "Table rows", - ScrollbarSize: 10, ScrollbarGutter: 10, + Rows: rowScope, + Header: gfx.Item(2).Scope(), + Columns: titledColumns([]components.TableColumn{{Width: 200}, {Width: 0}}, []string{"Name", "State"}, nil), + Source: &rows, + Scrollbar: gfx.Item(900), + ScrollbarLabel: "Table rows", + ScrollbarSize: 10, + ScrollbarGutter: 10, }).Size(400, 160) }) } diff --git a/ui/table_whole_test.go b/ui/table_whole_test.go index 1e5fb2d30..57c3e778d 100644 --- a/ui/table_whole_test.go +++ b/ui/table_whole_test.go @@ -21,7 +21,7 @@ func TestATableIsWholeAsDeclared(t *testing.T) { var state ui.TableState chosen := -1 d := openPage(t, func(c ui.C) { - ui.Table(c, &state, ui.TableSpec{Headers: []string{"Host", "Port"}, Source: wholeRows{}}).Width(400).Height(200) + ui.Table(c, &state, ui.TableSpec{Source: wholeRows{}, Columns: titledColumns(nil, []string{"Host", "Port"}, nil)}).Width(400).Height(200) if state.Changed() { chosen = state.Selected() } diff --git a/ui/tag/tag.go b/ui/tag/tag.go new file mode 100644 index 000000000..bda025a9e --- /dev/null +++ b/ui/tag/tag.go @@ -0,0 +1,143 @@ +// Package tag is the opt-in page control for a tag: a short label in a small +// rounded box that classifies something, and optionally can be ticked on and off +// or removed. It keeps no state of its own: a page passes what it knows, as for a +// button, and reads what the user did from the result: +// +// for i, host := range m.tags { +// result := tag.View(c.Key(host.Name), host.Name, tag.Spec{Closable: true}) +// if result.Closed { +// m.removeTag(i) +// } +// } +// +// A checkable tag is a toggle: the page gives it Checked and flips it when the +// result says Toggled. +// +// result := tag.View(c, "production", tag.Spec{Checkable: true, Checked: m.production}) +// if result.Toggled { +// m.production = !m.production +// } +// +// Status colors the tag in the shared ui.Status vocabulary, Outlined draws only a +// rim, and Size is Small, Default or Large. Name each tag of a loop with c.Key before +// View, by something that stays with the tag when others are removed, not by its +// index. +// +// It is a separate package so an application that does not import it pays +// nothing for it. A tag allocates nothing in a warm paint. +package tag + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Size is how large the tag is. +type Size uint8 + +const ( + // Default is the zero value. + Default Size = iota + // Small is the compact tag. + Small + // Large is the roomy tag. + Large +) + +var closeIcon = gfx.Icon{ViewBox: 24, Stroke: 2.5, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(18, 6), gfx.LineTo(6, 18), gfx.MoveTo(6, 6), gfx.LineTo(18, 18), +}} + +// Spec declares one tag. +type Spec struct { + // Status colors the tag; ui.StatusDefault is the neutral tag. + Status ui.Status + // Icon is drawn before the label. A zero icon draws none. + Icon gfx.Icon + // Outlined draws only a rim, with no fill. + Outlined bool + // Size is how large the tag is. + Size Size + // Closable adds a close button; Closed reports a press on it. + Closable bool + // CloseLabel is the accessible name of the close button, "Remove" when empty. + CloseLabel string + // Checkable makes the tag a toggle that is on while Checked is set; Toggled + // reports a press on it. A checked tag takes the theme's primary color. + Checkable, Checked bool +} + +// Result is what the user did to the tag in the paint just made. +type Result struct { + // Box is the tag, for the page to place: Grow, Margin and the rest. + Box ui.Box + // Closed is true in the paint that delivers a press on the close button. + Closed bool + // Toggled is true in the paint that delivers a press on a checkable tag. + Toggled bool +} + +func tint(color gfx.Color, alpha float32) gfx.Color { + color.Alpha *= alpha + return color +} + +// View declares the tag at c. Declare it on its own, not inside a Memo. +func View(c ui.C, label string, spec Spec) Result { + theme := c.Theme() + metrics := theme.Metrics + size, padX, padY := metrics.FontSizeS, float32(8), float32(2) + switch spec.Size { + case Small: + size, padX, padY = metrics.FontSizeS-1, 6, 1 + case Large: + size, padX, padY = metrics.FontSizeM, 10, 4 + } + ink, fill, rim := theme.SecondaryForeground, theme.Secondary, theme.Border + switch spec.Status { + case ui.StatusSuccess: + ink = theme.Success + fill, rim = tint(ink, 0.12), tint(ink, 0.4) + case ui.StatusWarning: + ink = theme.WarningColor() + fill, rim = tint(ink, 0.12), tint(ink, 0.4) + case ui.StatusDanger: + ink = theme.Danger + fill, rim = tint(ink, 0.12), tint(ink, 0.4) + } + if spec.Checkable && spec.Checked { + ink, fill, rim = theme.PrimaryForeground, theme.Primary, theme.Primary + } + if spec.Outlined && !(spec.Checkable && spec.Checked) { + fill = gfx.Color{} + if spec.Status == ui.StatusDefault { + ink = theme.Foreground + } + } + id := ui.ID(c) + box := ui.Row(c).Items(ui.Center).Gap(4).Shrink(0).PadSides(padY, padX, padY, padX). + Radius(metrics.RadiusControl).Background(fill).Border(1, rim) + var result Result + if spec.Checkable { + box = box.HitWith(id, label, gfx.HitOptions{Role: gfx.RoleCheckbox, Checked: spec.Checked}) + } + box.Children(func() { + if spec.Icon.ViewBox > 0 { + ui.Icon(c, spec.Icon).Size(size, size).Color(ink) + } + ui.Text(c, label).FontSize(size).Weight(gfx.WeightMedium).Color(ink) + if spec.Closable { + name := spec.CloseLabel + if name == "" { + name = "Remove" + } + closeID := ui.ID(c) + button := ui.Row(c).Size(size+2, size+2).Shrink(0).Center().HitWith(closeID, name, gfx.HitOptions{Role: gfx.RoleButton}) + button.Children(func() { ui.Icon(c, closeIcon).Size(size-1, size-1).Color(ink) }) + result.Closed = button.Clicked() + } + }) + result.Box = box + result.Toggled = spec.Checkable && box.Clicked() + return result +} diff --git a/ui/tag/tag_test.go b/ui/tag/tag_test.go new file mode 100644 index 000000000..18bd4274f --- /dev/null +++ b/ui/tag/tag_test.go @@ -0,0 +1,149 @@ +//go:build !js + +package tag_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/tag" +) + +// open runs a page of one tag and reports what the page read from it. +func open(t *testing.T, spec tag.Spec, closed, toggled *int) *headless.Session { + t.Helper() + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + result := tag.View(c, "production", spec) + if result.Closed { + *closed++ + } + if result.Toggled { + *toggled++ + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Tag", Width: 320, Height: 120}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +// A press on the close button is reported as Closed once, and not as a toggle. +func TestCloseButtonIsReported(t *testing.T) { + var closed, toggled int + session := open(t, tag.Spec{Closable: true}, &closed, &toggled) + if err := session.ClickLabel("Remove"); err != nil { + t.Fatal(err) + } + if closed != 1 || toggled != 0 { + t.Fatalf("closed %d, toggled %d after a press on the close button, want 1, 0", closed, toggled) + } +} + +// A checkable tag is a checkbox that reports each press, and shows its state to +// assistive technology. +func TestCheckableTagToggles(t *testing.T) { + var closed, toggled int + session := open(t, tag.Spec{Checkable: true, Checked: true}, &closed, &toggled) + node, ok := session.AccessByName("production") + if !ok || node.Role != gfx.RoleCheckbox || !node.Checked { + t.Fatalf("access node = %+v, %v; want a checked checkbox", node, ok) + } + if err := session.ClickLabel("production"); err != nil { + t.Fatal(err) + } + if toggled != 1 { + t.Fatalf("toggled %d after one press, want 1", toggled) + } +} + +// A plain tag takes no input: no control to press. +func TestPlainTagOffersNothingToPress(t *testing.T) { + var closed, toggled int + session := open(t, tag.Spec{}, &closed, &toggled) + for _, name := range []string{"production", "Remove"} { + if _, err := session.Locate(name); err == nil { + t.Fatalf("a plain tag offers %q as a control", name) + } + } +} + +// Each status paints its words in its color, and a checked tag takes the primary. +func TestStatusAndCheckColorTheLabel(t *testing.T) { + theme := gfx.LightTheme() + for name, test := range map[string]struct { + spec tag.Spec + want gfx.Color + }{ + "success": {tag.Spec{Status: ui.StatusSuccess}, theme.Success}, + "warning": {tag.Spec{Status: ui.StatusWarning}, theme.Warning}, + "danger": {tag.Spec{Status: ui.StatusDanger}, theme.Danger}, + "checked": {tag.Spec{Checkable: true, Checked: true}, theme.PrimaryForeground}, + } { + view := func(c ui.C) { tag.View(c, "label", test.spec) } + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.BeginFrame() + page.Draw(canvas, gfx.Rect{Width: 200, Height: 60}, view) + canvas.EndFrame() + found := false + for _, text := range canvas.Texts() { + if text.Value == "label" { + found = true + if text.Style.Color != test.want { + t.Fatalf("%s: label color = %+v, want %+v", name, text.Style.Color, test.want) + } + } + } + if !found { + t.Fatalf("%s: the tag did not paint its label", name) + } + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + for name, spec := range map[string]tag.Spec{ + "plain": {}, + "closable": {Closable: true, Status: ui.StatusWarning, Size: tag.Small}, + "checkbox": {Checkable: true, Checked: true, Outlined: true, Size: tag.Large}, + } { + t.Run(name, func(t *testing.T) { + view := func(c ui.C) { tag.View(c, "production", spec) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 320, Height: 120}, view) + canvas.EndFrame() + } + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } + }) + } +} + +func BenchmarkViewPaint(b *testing.B) { + view := func(c ui.C) { tag.View(c, "production", tag.Spec{Closable: true, Status: ui.StatusSuccess}) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + b.ReportAllocs() + for range b.N { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 320, Height: 120}, view) + canvas.EndFrame() + } +} diff --git a/ui/text_field_id_test.go b/ui/text_field_with_id_test.go similarity index 57% rename from ui/text_field_id_test.go rename to ui/text_field_with_id_test.go index 88eb95723..97d18f6ff 100644 --- a/ui/text_field_id_test.go +++ b/ui/text_field_with_id_test.go @@ -8,16 +8,16 @@ import ( "github.com/vivaui/viva/ui" ) -// TextFieldID edits an editor the application keeps, under the identity the +// A TextField given WithID edits an editor the application keeps, under the identity the // application gave it: the page's input routing and a test address that name, // and what is typed reaches the same editor the application reads. -func TestTextFieldIDEditsTheBoundEditorUnderItsExplicitName(t *testing.T) { +func TestTextFieldWithIDEditsTheBoundEditorUnderItsExplicitName(t *testing.T) { editor := text.NewEditor("") var field ui.Field field.Bind(editor) search := gfx.Item(9) d := openPage(t, func(c ui.C) { - ui.TextFieldID(c, search, &field, "Search", "").NavigationKeys() + ui.TextField(c, &field, "Search", "", ui.WithID(search)).NavigationKeys() }) hit := d.hit("Search") if hit.ID != search { @@ -38,14 +38,14 @@ func TestTextFieldIDEditsTheBoundEditorUnderItsExplicitName(t *testing.T) { // A bound field kept in the model repaints without allocating, and reports a change // only for an edit. -func TestTextFieldIDKeptInTheModelIsStable(t *testing.T) { +func TestTextFieldWithIDKeptInTheModelIsStable(t *testing.T) { editor := text.NewEditor("") var field ui.Field field.Bind(editor) search := gfx.Item(9) changed := 0 d := openPage(t, func(c ui.C) { - if ui.TextFieldID(c, search, &field, "Search", "").Changed() { + if ui.TextField(c, &field, "Search", "", ui.WithID(search)).Changed() { changed++ } }) @@ -74,7 +74,7 @@ func TestFieldBindIsNotAnEdit(t *testing.T) { search := gfx.Item(9) changed := 0 d := openPage(t, func(c ui.C) { - if ui.TextFieldID(c, search, &field, "Search", "").Changed() { + if ui.TextField(c, &field, "Search", "", ui.WithID(search)).Changed() { changed++ } }) @@ -88,3 +88,39 @@ func TestFieldBindIsNotAnEdit(t *testing.T) { t.Fatalf("changed %d, editor %q", changed, editor.String()) } } + +// A string of the model takes the application's name too, and an unnamed field +// beside it keeps the name its place gives it. +func TestTextFieldWithIDNamesAModelString(t *testing.T) { + var query, other string + search := gfx.Item(9) + d := openPage(t, func(c ui.C) { + ui.TextField(c, &query, "Search", "", ui.WithID(search)) + ui.TextField(c, &other, "Other", "") + }) + if hit := d.hit("Search"); hit.ID != search { + t.Fatalf("hit identity = %v, want the explicit %v", hit.ID, search) + } + if hit := d.hit("Other"); hit.ID == search || hit.ID.IsZero() { + t.Fatalf("unnamed field identity = %v", hit.ID) + } + d.click("Search") + d.typeText("hi") + if query != "hi" { + t.Fatalf("query = %q", query) + } +} + +// A control has one name: a second WithID is a mistake in the call, not a +// choice between two. +func TestTextFieldTakesOneWithID(t *testing.T) { + defer func() { + if recover() == nil { + t.Fatal("two WithID did not panic") + } + }() + var query string + openPage(t, func(c ui.C) { + ui.TextField(c, &query, "Search", "", ui.WithID(gfx.Item(1)), ui.WithID(gfx.Item(2))) + }) +} diff --git a/ui/timeline/timeline.go b/ui/timeline/timeline.go new file mode 100644 index 000000000..dfa9e4d7a --- /dev/null +++ b/ui/timeline/timeline.go @@ -0,0 +1,168 @@ +// Package timeline is the opt-in page control for a timeline: events in the +// order they happened, joined by a line down the side. A page keeps the events +// in its model and declares the line with a Spec: +// +// timeline.View(c, "History", timeline.Spec{Items: m.events, Pending: "Waiting for review"}) +// // m.events is a []timeline.Item kept in the model: +// // {Title: "Connected", Description: "build-01 accepted the key", Label: "09:41"} +// +// An item has a Title, an optional Description under it and an optional Label, +// the time or date of the event, shown muted beside it. Its Tone colors the dot +// and the line after it: Default is the theme's primary color, Success and +// Danger say how the event ended and Muted is a quiet one. Pending, when set, +// ends the line with an open dot for what comes next. +// +// With LabelWidth the labels line up in a column before the line, as a log +// does; without it a label sits under its title. It composes the page's own +// primitives, so it takes the page's theme and density. +// +// It is a separate package so an application that does not import it pays +// nothing for it, and it depends only on the public gfx and ui packages. +package timeline + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Tone is the color of an event's dot and of the line after it. +type Tone uint8 + +const ( + // Default is the theme's primary color: the zero value. + Default Tone = iota + // Success is the event ended well. + Success + // Danger is the event failed. + Danger + // Muted is a quiet event. + Muted +) + +// Item is one event. +type Item struct { + // Title names the event. + Title string + // Description is an optional line under the title. + Description string + // Label is the time or date of the event, shown muted. It is not drawn when + // empty. + Label string + // Tone colors the dot. + Tone Tone +} + +// Spec declares the timeline. +type Spec struct { + // Items are the events, in order. Keep the slice in the model: a slice made + // in each paint allocates in each paint. + Items []Item + // Pending ends the line with an open dot and these words, for what is still to + // come. It is not drawn when empty. + Pending string + // LabelWidth puts the labels in a column of this width before the line, so + // they line up; zero puts each under its title. + LabelWidth float32 +} + +// View declares the timeline at c. label names it for assistive technology. The +// timeline is as tall as its events; give it FillWidth. Declare the view on its +// own, not inside a Memo. +func View(c ui.C, label string, spec Spec) ui.Box { + if c == nil { + panic("timeline: View needs a page") + } + theme := c.Theme() + look := look{theme: theme, gap: theme.Metrics.GapItem, size: theme.Metrics.FontSizeM, detail: theme.Metrics.FontSizeS} + root := ui.Column(c).HitWith(ui.ID(c), label, gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true}) + root.Children(func() { + for i := range spec.Items { + look.event(c, spec, spec.Items[i], i < len(spec.Items)-1 || spec.Pending != "") + } + if spec.Pending != "" { + look.pending(c, spec) + } + }) + return root +} + +// look is what a timeline paints with: the page's theme. +type look struct { + theme *gfx.Theme + gap float32 + size float32 + detail float32 +} + +const dotSize = 10 + +// ink is the color of a tone. +func (l look) ink(tone Tone) gfx.Color { + switch tone { + case Success: + return l.theme.Success + case Danger: + return l.theme.Danger + case Muted: + return l.theme.MutedForeground + } + return l.theme.Primary +} + +// event declares one event: its label column, its dot and line, and its words. +func (l look) event(c ui.C, spec Spec, item Item, joined bool) { + row := ui.Row(c).Items(ui.Stretch).Gap(l.gap) + row.Children(func() { + if spec.LabelWidth > 0 { + ui.Row(c).Width(spec.LabelWidth).Shrink(0).Justify(ui.End).Items(ui.Start).Children(func() { + ui.Text(c, item.Label).FontSize(l.detail).Muted().LineHeight(l.size * 1.5) + }) + } + l.rail(c, l.ink(item.Tone), true, joined) + column := ui.Column(c).Gap(2).Grow(1).Basis(0) + if joined { + column = column.PadBottom(l.gap * 2) + } + column.Children(func() { + ui.Text(c, item.Title).FontSize(l.size).LineHeight(l.size * 1.5) + if item.Description != "" { + ui.Text(c, item.Description).FontSize(l.detail).Muted() + } + if item.Label != "" && spec.LabelWidth <= 0 { + ui.Text(c, item.Label).FontSize(l.detail).Muted() + } + }) + }) +} + +// pending declares the open dot that ends a timeline and its words. +func (l look) pending(c ui.C, spec Spec) { + row := ui.Row(c).Items(ui.Stretch).Gap(l.gap) + row.Children(func() { + if spec.LabelWidth > 0 { + ui.Spacer(c).Width(spec.LabelWidth).Grow(0).Shrink(0) + } + l.rail(c, l.theme.Border, false, false) + ui.Text(c, spec.Pending).FontSize(l.size).Muted().LineHeight(l.size * 1.5) + }) +} + +// rail declares a dot and, when joined, the line that runs down from it. A filled +// dot is solid; an open one is a ring. +func (l look) rail(c ui.C, ink gfx.Color, filled, joined bool) { + rail := ui.Column(c).Items(ui.Center).Shrink(0).Width(dotSize) + rail.Children(func() { + slot := ui.Row(c).Size(dotSize, l.size*1.5).Shrink(0).Center() + slot.Children(func() { + dot := ui.Spacer(c).Size(dotSize, dotSize).Grow(0).Shrink(0).Radius(dotSize / 2) + if filled { + dot.Background(ink) + } else { + dot.Background(l.theme.Background).Border(2, ink) + } + }) + if joined { + ui.Spacer(c).Width(1).Grow(1).MinHeight(8).Background(l.theme.Border) + } + }) +} diff --git a/ui/timeline/timeline_test.go b/ui/timeline/timeline_test.go new file mode 100644 index 000000000..da3a7efc4 --- /dev/null +++ b/ui/timeline/timeline_test.go @@ -0,0 +1,134 @@ +package timeline_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/timeline" +) + +var events = []timeline.Item{ + {Title: "Connected", Description: "accepted the key", Label: "09:41"}, + {Title: "Uploaded", Label: "09:42", Tone: timeline.Success}, + {Title: "Failed", Label: "09:44", Tone: timeline.Danger}, + {Title: "Rolled back", Label: "09:45", Tone: timeline.Muted}, +} + +func measure(value string, size, weight float32) float32 { + return float32(len(value)) * size * 0.55 +} + +func draw(page *ui.Page, canvas *gfx.Canvas, view func(ui.C)) { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 400, Height: 400}, view) + canvas.EndFrame() +} + +func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { + t.Helper() + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetMeasurer(measure) + canvas.SetReduceMotion(true) + draw(page, canvas, view) + return page, canvas +} + +func textAt(canvas *gfx.Canvas, value string) (gfx.Text, bool) { + for _, text := range canvas.Texts() { + if text.Value == value { + return text, true + } + } + return gfx.Text{}, false +} + +// dots counts the round dots filled with a color. +func dots(canvas *gfx.Canvas, color gfx.Color) int { + count := 0 + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color == color && rectangle.Radius > 0 && rectangle.Bounds.Width == rectangle.Bounds.Height { + count++ + } + } + return count +} + +// Each event paints its words and a dot in the color of its tone. +func TestEventsPaintTheirWordsAndToneDots(t *testing.T) { + theme := gfx.LightTheme() + view := func(c ui.C) { timeline.View(c, "History", timeline.Spec{Items: events}) } + _, canvas := open(t, view) + for _, value := range []string{"Connected", "accepted the key", "09:41", "Uploaded", "Failed", "Rolled back"} { + if _, ok := textAt(canvas, value); !ok { + t.Fatalf("the timeline did not paint %q", value) + } + } + for name, color := range map[string]gfx.Color{ + "default": theme.Primary, "success": theme.Success, "danger": theme.Danger, "muted": theme.MutedForeground, + } { + if dots(canvas, color) != 1 { + t.Fatalf("%s dots = %d, want 1", name, dots(canvas, color)) + } + } +} + +// Events follow one another down the page, and Pending comes after the last. +func TestEventsRunDownAndPendingComesLast(t *testing.T) { + view := func(c ui.C) { timeline.View(c, "History", timeline.Spec{Items: events, Pending: "Waiting"}) } + _, canvas := open(t, view) + previous := float32(-1) + for _, title := range []string{"Connected", "Uploaded", "Failed", "Rolled back", "Waiting"} { + text, ok := textAt(canvas, title) + if !ok { + t.Fatalf("the timeline did not paint %q", title) + } + if text.Bounds.Y <= previous { + t.Fatalf("%q is at %v, not below the event before it (%v)", title, text.Bounds.Y, previous) + } + previous = text.Bounds.Y + } +} + +// With a label column the labels line up and sit beside their titles. +func TestLabelWidthLinesUpTheLabels(t *testing.T) { + view := func(c ui.C) { timeline.View(c, "History", timeline.Spec{Items: events, LabelWidth: 60}) } + _, canvas := open(t, view) + first, _ := textAt(canvas, "09:41") + other, _ := textAt(canvas, "09:44") + if first.Bounds.X+first.Bounds.Width != other.Bounds.X+other.Bounds.Width { + t.Fatalf("labels end at %v and %v, want one right edge", first.Bounds.X+first.Bounds.Width, other.Bounds.X+other.Bounds.Width) + } + title, _ := textAt(canvas, "Connected") + if first.Bounds.X+first.Bounds.Width > title.Bounds.X { + t.Fatal("a label overlaps the title beside it") + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + for name, spec := range map[string]timeline.Spec{ + "plain": {Items: events, Pending: "Waiting"}, + "labels": {Items: events, LabelWidth: 60}, + } { + t.Run(name, func(t *testing.T) { + view := func(c ui.C) { timeline.View(c, "History", spec) } + page, canvas := open(t, view) + if allocations := testing.AllocsPerRun(100, func() { draw(page, canvas, view) }); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } + }) + } +} + +func BenchmarkViewPaint(b *testing.B) { + view := func(c ui.C) { timeline.View(c, "History", timeline.Spec{Items: events, Pending: "Waiting"}) } + page, canvas := open(b, view) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + draw(page, canvas, view) + } +} diff --git a/ui/timepicker/timepicker.go b/ui/timepicker/timepicker.go new file mode 100644 index 000000000..ceb02264e --- /dev/null +++ b/ui/timepicker/timepicker.go @@ -0,0 +1,371 @@ +// Package timepicker is the opt-in page control for choosing a time of day: a +// button that shows the time and opens columns of hours and minutes, and +// seconds with Seconds, to choose it from. A page keeps a TimePicker in its model +// beside the time it edits: +// +// m.start = timepicker.New().Placeholder("Pick a time").MinuteStep(5) +// // in the page: +// m.start.View(c, "Start", &m.startAt).Width(160) +// if m.start.Changed() { +// // the user chose a time; m.startAt holds it +// } +// +// A Value is a time on the 24 hour clock; Valid is false while there is none. +// Choosing a number in a column sets that part of the time at once, so the +// value follows what the user points at. The wheel scrolls a column, Up and Down +// change the part the focus is in by one step and Left and Right move between the +// columns; Enter closes the columns and Escape does too. +// +// MinuteStep and SecondStep limit the minutes and seconds to multiples of a +// step, and a time the page sets between two steps is brought to the one below. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a TimePicker in the model: its handlers and draw function +// are made once, so a warm paint allocates nothing. Do not copy a TimePicker after +// it has been declared. +package timepicker + +import ( + "strconv" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Value is a time of day. +type Value struct { + Hour, Minute, Second int + // Valid is whether there is a time at all. + Valid bool +} + +var clockIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(12, 6), gfx.LineTo(12, 12), gfx.LineTo(16, 14), + gfx.MoveTo(22, 12), gfx.CubicTo(22, 17.52, 17.52, 22, 12, 22), gfx.CubicTo(6.48, 22, 2, 17.52, 2, 12), + gfx.CubicTo(2, 6.48, 6.48, 2, 12, 2), gfx.CubicTo(17.52, 2, 22, 6.48, 22, 12), +}} + +// pad is the two digit words of the numbers of a column, made once. +var pad [60]string + +func init() { + for i := range pad { + pad[i] = strconv.Itoa(i/10) + strconv.Itoa(i%10) + } +} + +const ( + columnWidth = 56 + rowHeight = 32 + visibleRows = 7 + padding = 8 + hourColumn = 0 +) + +// TimePicker is one time field and its columns. Configure it with the chainable +// methods; they may be called before each View. +type TimePicker struct { + handlers ui.Handlers + drawFn func(*ui.DrawContext) + + placeholder string + minuteStep int + secondStep int + seconds bool + units [3]string + + value *Value + open bool + active int // the column the keyboard is in + offsets [3]float32 // how far each column is scrolled, in pixels + focusOnOpen bool + changed bool + reported bool + + shown Value + shownText string +} + +// New returns a time field of hours and minutes in steps of one. +func New() *TimePicker { + t := &TimePicker{minuteStep: 1, secondStep: 1, units: [3]string{"Hours", "Minutes", "Seconds"}} + t.handlers.Key = t.key + t.handlers.Pointer = t.pointer + t.handlers.Scroll = t.scroll + t.drawFn = t.draw + return t +} + +// Placeholder is the text shown while there is no time. +func (t *TimePicker) Placeholder(text string) *TimePicker { + t.placeholder, t.shownText = text, "" + return t +} + +// MinuteStep limits the minutes to multiples of step; one by default. +func (t *TimePicker) MinuteStep(step int) *TimePicker { + t.minuteStep = max(step, 1) + return t +} + +// SecondStep limits the seconds to multiples of step; one by default. +func (t *TimePicker) SecondStep(step int) *TimePicker { + t.secondStep = max(step, 1) + return t +} + +// Seconds adds a column of seconds. +func (t *TimePicker) Seconds() *TimePicker { + t.seconds = true + t.shownText = "" + return t +} + +// Units are the names of the columns for assistive technology, "Hours", +// "Minutes" and "Seconds" by default, for a page in another language. +func (t *TimePicker) Units(hours, minutes, seconds string) *TimePicker { + t.units = [3]string{hours, minutes, seconds} + return t +} + +// Changed reports whether the user chose a new time in the paint that delivered it. +func (t *TimePicker) Changed() bool { return t.reported } + +func (t *TimePicker) columns() int { + if t.seconds { + return 3 + } + return 2 +} + +// size is the number of rows of a column, and step the distance between them. +func (t *TimePicker) size(column int) (rows, step int) { + switch column { + case hourColumn: + return 24, 1 + case 1: + return (59 + t.minuteStep) / t.minuteStep, t.minuteStep + } + return (59 + t.secondStep) / t.secondStep, t.secondStep +} + +// part is the number a column holds. +func (v Value) part(column int) int { + switch column { + case hourColumn: + return v.Hour + case 1: + return v.Minute + } + return v.Second +} + +// with is v with a part of it changed. +func (v Value) with(column, number int) Value { + switch column { + case hourColumn: + v.Hour = number + case 1: + v.Minute = number + default: + v.Second = number + } + v.Valid = true + return v +} + +// tidy is v as a time the columns can show: in range, on the steps, with the +// seconds dropped when there is no column for them. +func (t *TimePicker) tidy(v Value) Value { + if !v.Valid { + return Value{} + } + v.Hour = min(max(v.Hour, 0), 23) + v.Minute = min(max(v.Minute, 0), 59) / t.minuteStep * t.minuteStep + v.Second = min(max(v.Second, 0), 59) / t.secondStep * t.secondStep + if !t.seconds { + v.Second = 0 + } + return v +} + +func (t *TimePicker) text(v Value) string { + if !v.Valid { + return t.placeholder + } + text := pad[v.Hour] + ":" + pad[v.Minute] + if t.seconds { + text += ":" + pad[v.Second] + } + return text +} + +// choose sets a part of the value and scrolls the column to it. +func (t *TimePicker) choose(column, number int) { + next := t.tidy(t.value.with(column, number)) + if !t.value.Valid { + // A first choice makes a time: the other parts start at zero. + next = t.tidy(Value{Valid: true}.with(column, number)) + } + if next != *t.value { + *t.value, t.changed = next, true + } + t.reveal(column) +} + +// reveal scrolls a column so the number it holds is in the middle of its rows. +func (t *TimePicker) reveal(column int) { + rows, step := t.size(column) + index := t.value.part(column) / step + total := float32(rows * rowHeight) + view := float32(visibleRows * rowHeight) + offset := float32(index)*rowHeight + rowHeight/2 - view/2 + t.offsets[column] = min(max(offset, 0), max(total-view, 0)) +} + +func (t *TimePicker) scroll(event gfx.ScrollEvent) gfx.EventResult { + if t.value == nil { + return gfx.EventResult{} + } + column, ok := event.Target.In(t.handlers.Parts()) + if !ok { + return gfx.EventResult{} + } + column /= 64 + if column >= t.columns() { + return gfx.EventResult{} + } + rows, _ := t.size(column) + limit := max(float32(rows*rowHeight)-visibleRows*rowHeight, 0) + t.offsets[column] = min(max(t.offsets[column]-event.DeltaY, 0), limit) + return gfx.EventResult{Handled: true, Repaint: true} +} + +func (t *TimePicker) pointer(event gfx.PointerEvent) gfx.EventResult { + if t.value == nil || event.Kind != gfx.PointerDown || event.Button != gfx.PointerButtonPrimary { + return gfx.EventResult{} + } + index, ok := event.Target.In(t.handlers.Parts()) + if !ok { + return gfx.EventResult{} + } + column, row := index/64, index%64 + _, step := t.size(column) + t.active = column + t.choose(column, row*step) + return gfx.EventResult{Handled: true, Repaint: true, Focus: t.handlers.Parts().At(t.focusIndex())} +} + +// focusIndex is the part the keyboard rests on: the chosen number of the active +// column. +func (t *TimePicker) focusIndex() int { + _, step := t.size(t.active) + return t.active*64 + t.value.part(t.active)/step +} + +func (t *TimePicker) key(event gfx.KeyEvent) gfx.EventResult { + if t.value == nil || event.Text != "" { + return gfx.EventResult{} + } + rows, step := t.size(t.active) + number := t.value.part(t.active) + switch event.Key { + case gfx.KeyUp: + t.choose(t.active, (number/step+rows-1)%rows*step) + case gfx.KeyDown: + t.choose(t.active, (number/step+1)%rows*step) + case gfx.KeyLeft: + t.active = (t.active + t.columns() - 1) % t.columns() + case gfx.KeyRight: + t.active = (t.active + 1) % t.columns() + case gfx.KeyEnter: + t.open = false + return gfx.EventResult{Handled: true, Repaint: true} + default: + return gfx.EventResult{} + } + return gfx.EventResult{Handled: true, Repaint: true, Focus: t.handlers.Parts().At(t.focusIndex()), FocusVisible: true} +} + +// View declares the field at c, showing and editing *value. label names it for +// assistive technology. The button is one control high; give it a Width. Declare +// the view on its own, not inside a Memo. +func (t *TimePicker) View(c ui.C, label string, value *Value) ui.Box { + if t == nil { + panic("timepicker: View needs its TimePicker") + } + if value == nil { + panic("timepicker: View needs the time") + } + t.reported, t.changed = t.changed, false + t.value = value + *value = t.tidy(*value) + if *value != t.shown || t.shownText == "" { + t.shown = *value + t.shownText = t.text(*value) + } + trigger := ui.Button(c, t.shownText).Outline().Icon(clockIcon) + if !value.Valid { + trigger.Muted() + } + if trigger.Clicked() { + t.open = !t.open + if t.open { + t.active, t.focusOnOpen = hourColumn, true + for column := range t.columns() { + t.reveal(column) + } + } + } + width := float32(t.columns()*columnWidth + 2*padding) + ui.Popover(c, trigger, &t.open, ui.PopoverSpec{Align: ui.Start, Padding: padding, Width: width}, func() { + ui.Control(c, label, &t.handlers).Size(float32(t.columns()*columnWidth), visibleRows*rowHeight).Shrink(0).Draw(t.drawFn) + }) + return trigger +} + +// draw paints the columns and declares each number as a part of the control. +func (t *TimePicker) draw(d *ui.DrawContext) { + if t.value == nil { + return + } + canvas, theme := d.Canvas, d.Theme + parts := t.handlers.Parts() + if t.focusOnOpen { + t.focusOnOpen = false + canvas.RequestFocus(parts.At(t.focusIndex())) + } + size := theme.Metrics.FontSizeM + rest := t.focusIndex() + for column := range t.columns() { + area := gfx.Rect{X: d.Rect.X + float32(column*columnWidth), Y: d.Rect.Y, Width: columnWidth, Height: visibleRows * rowHeight} + rows, step := t.size(column) + chosen := t.value.part(column) + canvas.Clip(area) + first := int(t.offsets[column] / rowHeight) + for row := first; row < min(rows, first+visibleRows+1); row++ { + bounds := gfx.Rect{X: area.X, Y: area.Y + float32(row)*rowHeight - t.offsets[column], Width: columnWidth, Height: rowHeight} + inner := gfx.Rect{X: bounds.X + 4, Y: bounds.Y + 2, Width: columnWidth - 8, Height: rowHeight - 4} + index := column*64 + row + number := row * step + ink := theme.Foreground + selected := t.value.Valid && number == chosen + switch { + case selected: + canvas.Rounded(inner, theme.Metrics.RadiusControl, theme.Primary) + ink = theme.PrimaryForeground + case canvas.Hovered() == parts.At(index): + canvas.Rounded(inner, theme.Metrics.RadiusControl, theme.Hover) + } + canvas.LabelCenter(pad[number], bounds, gfx.TextStyle{Size: size, Weight: gfx.WeightRegular, Color: ink}) + if canvas.FocusVisible() == parts.At(index) { + canvas.RoundedBorder(inner, theme.Metrics.RadiusControl, 2, theme.Ring, gfx.Color{}) + } + canvas.HitWithOptions(parts.At(index), bounds, pad[number], gfx.HitOptions{ + Role: gfx.RoleButton, Selected: selected, SkipFocus: index != rest, SkipTab: index != rest, + Description: t.units[column], + }) + } + canvas.Unclip() + } +} diff --git a/ui/timepicker/timepicker_test.go b/ui/timepicker/timepicker_test.go new file mode 100644 index 000000000..7a792b570 --- /dev/null +++ b/ui/timepicker/timepicker_test.go @@ -0,0 +1,177 @@ +//go:build !js + +package timepicker_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/timepicker" +) + +// changes counts the paints that reported a change, as a page reads Changed. +var changes int + +// open runs a page holding one time field over *value, headlessly. +func open(t *testing.T, p *timepicker.TimePicker, value *timepicker.Value) *headless.Session { + t.Helper() + changes = 0 + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + p.View(c, "Start", value).Width(220) + if p.Changed() { + changes++ + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Time", Width: 420, Height: 420}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +func at(hour, minute, second int) timepicker.Value { + return timepicker.Value{Hour: hour, Minute: minute, Second: second, Valid: true} +} + +// A click on a number sets that part of the time at once. +func TestClickingANumberSetsThatPart(t *testing.T) { + value := at(9, 30, 0) + session := open(t, timepicker.New().MinuteStep(5), &value) + if err := session.ClickLabel("09:30"); err != nil { + t.Fatal(err) + } + if err := session.ClickLabel("45"); err != nil { + t.Fatal(err) + } + if value != at(9, 45, 0) { + t.Fatalf("value = %+v after a click on 45, want 09:45", value) + } + if changes != 1 { + t.Fatalf("Changed was reported in %d paints, want 1", changes) + } +} + +// Up and Down change the part the focus is in, wrapping at the ends, and Left +// and Right move between the columns; Enter closes the columns. +func TestKeysChangeTheActivePart(t *testing.T) { + value := at(23, 55, 0) + session := open(t, timepicker.New().MinuteStep(5), &value) + if err := session.ClickLabel("23:55"); err != nil { + t.Fatal(err) + } + for _, step := range []struct { + key string + want timepicker.Value + }{ + {"down", at(0, 55, 0)}, // the hours wrap + {"right", at(0, 55, 0)}, + {"down", at(0, 0, 0)}, // the minutes wrap in steps of five + {"up", at(0, 55, 0)}, + {"left", at(0, 55, 0)}, + {"up", at(23, 55, 0)}, + } { + if err := session.Keys(step.key); err != nil { + t.Fatal(err) + } + if value != step.want { + t.Fatalf("value = %+v after %q, want %+v", value, step.key, step.want) + } + } + if err := session.Keys("enter"); err != nil { + t.Fatal(err) + } + if _, err := session.Locate("Start"); err == nil { + t.Fatal("the columns stayed open after Enter") + } +} + +// With no time yet, the first choice makes one and the other parts start at zero. +func TestFirstChoiceMakesATime(t *testing.T) { + var value timepicker.Value + session := open(t, timepicker.New().Placeholder("Pick a time"), &value) + if err := session.ClickLabel("Pick a time"); err != nil { + t.Fatal(err) + } + if err := session.Keys("down"); err != nil { + t.Fatal(err) + } + if value != at(1, 0, 0) { + t.Fatalf("value = %+v after the first Down, want 01:00", value) + } +} + +// A time the page sets between two steps is brought to the one below, and seconds +// are dropped when there is no column for them. +func TestTimesAreKeptOnTheSteps(t *testing.T) { + value := at(9, 33, 41) + open(t, timepicker.New().MinuteStep(5), &value) + if value != at(9, 30, 0) { + t.Fatalf("value = %+v, want 09:30 with no seconds column", value) + } + value = at(9, 33, 41) + open(t, timepicker.New().Seconds().SecondStep(10), &value) + if value != at(9, 33, 40) { + t.Fatalf("value = %+v, want 09:33:40 on steps of ten seconds", value) + } + value = at(31, 70, 0) + open(t, timepicker.New(), &value) + if value != at(23, 59, 0) { + t.Fatalf("value = %+v, want an out of range time brought to 23:59", value) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + value := at(9, 30, 0) + p := timepicker.New().Seconds() + view := func(c ui.C) { p.View(c, "Start", &value).Width(220) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 420, Height: 420}, view) + canvas.EndFrame() + } + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +// Open columns repaint without allocating too. +func TestOpenColumnsAllocateNothing(t *testing.T) { + value := at(9, 30, 0) + session := open(t, timepicker.New().Seconds(), &value) + if err := session.ClickLabel("09:30:00"); err != nil { + t.Fatal(err) + } + session.Frame() + if allocations := testing.AllocsPerRun(50, func() { session.Frame() }); allocations != 0 { + t.Fatalf("open columns allocated %v times a frame, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + value := at(9, 30, 0) + p := timepicker.New().Seconds() + view := func(c ui.C) { p.View(c, "Start", &value).Width(220) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + b.ReportAllocs() + for range b.N { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 420, Height: 420}, view) + canvas.EndFrame() + } +} diff --git a/ui/toast_paint.go b/ui/toast_paint.go index 184b7e671..05438a6ee 100644 --- a/ui/toast_paint.go +++ b/ui/toast_paint.go @@ -5,6 +5,7 @@ import ( "unsafe" "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" ) // Toasts paints the toasts of t where t.Position says, over everything @@ -19,6 +20,9 @@ func Toasts(c C, t *Toaster) { if canvas == nil || len(t.GetToasts()) == 0 { return } + // The Toaster owns the policy; the queue below is its running state. + queue := t.QueuePtr() + queue.Timeout, queue.Limit = t.Timeout, t.Limit now := ClockEpoch.Add(canvas.Now()) // A press on a close or an action button, delivered here. if id, ok := canvas.ClickTarget(); ok { @@ -30,7 +34,7 @@ func Toasts(c C, t *Toaster) { } } for { - id, ok := t.QueuePtr().Expire(now) + id, ok := queue.Expire(now) if !ok { break } @@ -42,7 +46,7 @@ func Toasts(c C, t *Toaster) { if item.GetShown() { continue } - evicted, ok := t.QueuePtr().Add(t.ID(item.GetN()), now, item.Kind == ToastLoading) + evicted, ok := queue.AddFor(t.ID(item.GetN()), now, item.Kind == ToastLoading, item.GetTimeout()) item.SetShown(ok) if at, inside := evicted.In(t.GetScope()); inside { // The queue was full: the oldest goes, which is ahead of this one. @@ -62,16 +66,20 @@ func Toasts(c C, t *Toaster) { for i := len(t.GetToasts()) - 1; i >= 0; i-- { item := &t.GetToasts()[i] if held { - t.QueuePtr().Pause(t.ID(item.GetN()), now) + queue.Pause(t.ID(item.GetN()), now) } else { - t.QueuePtr().Resume(t.ID(item.GetN()), now) + queue.Resume(t.ID(item.GetN()), now) + } + var dismiss gfx.ID + if !item.GetHideClose() { + dismiss = t.GetScope().At(int(item.GetN())*3 + ToastClose) } toast := components.SonnerToast{ Snapshot: components.ToastSnapshot{ Title: item.GetTitle(), Description: item.GetDescription(), Type: toastKindComponent(item.Kind), SwipeX: t.SwipeX(ToastID(item.GetN())), }, - Scope: t.ID(item.GetN()), DismissID: t.GetScope().At(int(item.GetN())*3 + ToastClose), + Scope: t.ID(item.GetN()), DismissID: dismiss, } if item.GetAction() != "" { toast.ActionID, toast.ActionLabel = t.GetScope().At(int(item.GetN())*3+ToastAction), item.GetAction() @@ -79,9 +87,9 @@ func Toasts(c C, t *Toaster) { t.SetStack(append(t.GetStack(), toast)) } components.PaintSonner(canvas, c.GetF().Palette, c.GetF().GetBounds(), t.GetStack(), components.SonnerOptions{ - Layer: ToastLayer, Expanded: held || t.Expanded, Position: components.ToastPosition(t.Position), + Layer: ToastLayer, Expanded: held || t.Expanded, Position: components.ToastPosition(t.Position), Limit: t.Limit, }) - if deadline, ok := t.QueuePtr().NextDeadline(); ok { + if deadline, ok := queue.NextDeadline(); ok { canvas.RequestFrameIn(max(deadline.Sub(now), time.Millisecond)) } } diff --git a/ui/toast_test.go b/ui/toast_test.go index fe7e7ec6b..2233dd3d4 100644 --- a/ui/toast_test.go +++ b/ui/toast_test.go @@ -138,6 +138,74 @@ func TestToastActionAndLoading(t *testing.T) { } } +// A toast can hide its close button and set its own lifetime; the close button +// is there by default and the Toaster's Timeout is the default lifetime. +func TestToastConfigHidesItsCloseButtonAndSetsItsOwnTime(t *testing.T) { + m := &toastModel{} + d := openPage(t, m.page) + m.toaster.ShowConfig("Quiet", "", ui.ToastInfo, ui.ToastConfig{HideClose: true, Timeout: 2 * time.Second}) + d.repaint() + if d.has("Close toast") { + t.Fatal("a toast that hides its close button has one") + } + if !tooltipShown(d, "Quiet") { + t.Fatal("the toast is not shown") + } + if err := d.driver.Advance(1500 * time.Millisecond); err != nil { + t.Fatal(err) + } + if !tooltipShown(d, "Quiet") { + t.Fatal("the toast went before its own time") + } + if err := d.driver.Advance(600 * time.Millisecond); err != nil { + t.Fatal(err) + } + if err := d.driver.Advance(time.Second); err != nil { // its exit + t.Fatal(err) + } + if tooltipShown(d, "Quiet") || m.toaster.Len() != 0 { + t.Fatal("the toast is still up after its own time") + } +} + +// The Toaster's Timeout is the lifetime of a toast that does not name one. +func TestToasterTimeoutSetsTheDefaultLifetime(t *testing.T) { + m := &toastModel{} + m.toaster.Timeout = 2 * time.Second + d := openPage(t, m.page) + m.toaster.Show("Quick", "", ui.ToastInfo) + d.repaint() + if err := d.driver.Advance(1500 * time.Millisecond); err != nil { + t.Fatal(err) + } + if !tooltipShown(d, "Quick") { + t.Fatal("the toast went before the Toaster's time") + } + if err := d.driver.Advance(600 * time.Millisecond); err != nil { + t.Fatal(err) + } + if err := d.driver.Advance(time.Second); err != nil { + t.Fatal(err) + } + if tooltipShown(d, "Quick") || m.toaster.Len() != 0 { + t.Fatal("the toast is still up after the Toaster's time") + } +} + +// The Toaster's Limit is how many toasts it keeps up. +func TestToasterLimitSetsTheVisibleCount(t *testing.T) { + m := &toastModel{} + m.toaster.Limit = 1 + d := openPage(t, m.page) + m.toaster.Show("a", "", ui.ToastInfo) + d.repaint() + m.toaster.Show("b", "", ui.ToastInfo) + d.repaint() + if m.toaster.Len() != 1 || !tooltipShown(d, "b") || tooltipShown(d, "a") { + t.Fatalf("%d toasts, a shown %v, b shown %v", m.toaster.Len(), tooltipShown(d, "a"), tooltipShown(d, "b")) + } +} + func BenchmarkToasts(b *testing.B) { m := &toastModel{} m.toaster.Show("Saved", "The host list was written", ui.ToastSuccess) diff --git a/ui/tooltip_test.go b/ui/tooltip_test.go index 87cb97d3e..26fdab27e 100644 --- a/ui/tooltip_test.go +++ b/ui/tooltip_test.go @@ -214,6 +214,21 @@ func tooltipShown(d *pageDriver, Text string) bool { return false } +func TestIdleTooltipPaintAllocatesNothing(t *testing.T) { + d := openPage(t, func(c ui.C) { + ui.Column(c).Children(func() { + ui.Button(c, "Info").Tooltip("More information") + ui.Button(c, "Plain") + }) + }) + if err := d.driver.Move(center(d.hit("Plain").Bounds)); err != nil { + t.Fatal(err) + } + if allocs := testing.AllocsPerRun(100, d.repaint); allocs != 0 { + t.Fatalf("idle tooltip paint: %v allocations per repaint, want zero", allocs) + } +} + // A Tooltip appears while the pointer rests on its control, is the control's // description, hides on a press until the pointer leaves, and a Memo's copy keeps it. func TestTooltip(t *testing.T) { diff --git a/ui/tour/tour.go b/ui/tour/tour.go new file mode 100644 index 000000000..94b7e20d5 --- /dev/null +++ b/ui/tour/tour.go @@ -0,0 +1,223 @@ +// Package tour is the opt-in page control for a guided tour: a note beside one +// control of the page at a time, with the rest of the window dimmed around it, +// that the user steps through. A page keeps a Tour in its model, names the +// controls the steps point at as it declares them, and declares the tour last: +// +// m.tour = tour.New() +// // in the page: +// save := ui.Button(c, "Save") +// m.tour.Target(0, save) +// sync := ui.Button(c, "Sync") +// m.tour.Target(1, sync) +// m.tour.View(c, tour.Spec{Steps: m.steps}) +// if m.tour.Finished() { +// m.settings.TourSeen = true +// } +// +// Start opens the tour at its first step. The note has Previous and Next +// buttons, Finish on the last step, and Skip to leave early; Escape and a press +// outside the note leave it too. Only Finish counts as finishing: Finished +// reports it, so a page can remember that the tour was seen. A step whose +// target was not declared in the paint is shown without a pointer at a +// control and without a hole in the dimming, so a tour survives a page whose +// controls come and go. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Tour in the model; a warm paint allocates nothing +// while it is closed. Do not copy a Tour after it has been declared. +package tour + +import ( + "strconv" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Step is one note of the tour. +type Step struct { + // Title heads the note and Description is the text under it; either may be + // empty. + Title, Description string +} + +// Spec declares the tour. +type Spec struct { + // Steps are the notes, in order. Keep the slice in the model. + Steps []Step + // Labels are the words of the buttons: Previous, Next, Finish and Skip; + // "Previous", "Next", "Finish" and "Skip" when empty. + Labels [4]string + // NoMask leaves the window undimmed. + NoMask bool + // Width is the note's width, 288 when zero. + Width float32 +} + +// Tour is one tour and where it is. +type Tour struct { + open bool + step int + targets []ui.Box // the controls of this paint, by step; a zero Box is none + declared []bool + finished bool + pending bool // Finish was pressed, reported by the next paint + counter struct { + step, total int + text string + } + mask func(*ui.DrawContext) + note func() + spec Spec + c ui.C + target ui.Box + has bool +} + +// New returns a closed tour. +func New() *Tour { + t := &Tour{} + t.mask = t.drawMask + t.note = t.draw + return t +} + +// Start opens the tour at its first step. +func (t *Tour) Start() { t.open, t.step = true, 0 } + +// Close leaves the tour. +func (t *Tour) Close() { t.open = false } + +// IsOpen reports whether the tour is shown. +func (t *Tour) IsOpen() bool { return t.open } + +// Step is the index of the step shown. +func (t *Tour) Step() int { return t.step } + +// Finished reports whether the user pressed Finish since the paint before this +// one. +func (t *Tour) Finished() bool { return t.finished } + +// Target says which control step i points at: the Box its declaration returned, +// in the paint being declared. +func (t *Tour) Target(step int, anchor ui.Box) { + if step < 0 { + panic("tour: Target needs a step index of zero or more") + } + for len(t.targets) <= step { + t.targets = append(t.targets, ui.Box{}) + t.declared = append(t.declared, false) + } + t.targets[step], t.declared[step] = anchor, true +} + +func (s *Spec) label(i int) string { + if s.Labels[i] != "" { + return s.Labels[i] + } + return [4]string{"Previous", "Next", "Finish", "Skip"}[i] +} + +func (t *Tour) counterText(step, total int) string { + if t.counter.text == "" || t.counter.step != step || t.counter.total != total { + t.counter.step, t.counter.total = step, total + t.counter.text = strconv.Itoa(step+1) + " / " + strconv.Itoa(total) + } + return t.counter.text +} + +// View declares the tour at c, after the controls its steps point at. It +// declares nothing while the tour is closed. Declare it on its own, not inside a +// Memo. +func (t *Tour) View(c ui.C, spec Spec) { + if t == nil { + panic("tour: View needs its Tour") + } + t.finished, t.pending = t.pending, false + defer t.forget() + if !t.open || len(spec.Steps) == 0 { + return + } + t.step = min(max(t.step, 0), len(spec.Steps)-1) + t.has = t.step < len(t.declared) && t.declared[t.step] + t.target = ui.Box{} + if t.has { + t.target = t.targets[t.step] + } + t.spec, t.c = spec, c + if t.has && !spec.NoMask { + ui.Overlay(c, ui.OverlaySpec{Band: ui.LayerPaneChrome, Bounds: c.Bounds()}).Children(func() { + ui.Column(c).Fill().Draw(t.mask) + }) + } + width := spec.Width + if width <= 0 { + width = 288 + } + step := spec.Steps[t.step] + pop := ui.PopoverSpec{Align: ui.Center, Width: width, Title: step.Title, Description: step.Description} + if !t.has { + // No control to hang the note on: it is a note in the middle of the window. + ui.Modal(c, &t.open, orDefault(step.Title, "Tour"), ui.ModalSpec{Description: step.Description, Width: width}, nil, t.note) + return + } + ui.Popover(c, t.target, &t.open, pop, t.note) +} + +func orDefault(s, fallback string) string { + if s == "" { + return fallback + } + return s +} + +// forget drops the controls of this paint; the next declares its own. +func (t *Tour) forget() { + clear(t.targets) + clear(t.declared) +} + +// drawMask dims the window around the control the step points at. +func (t *Tour) drawMask(d *ui.DrawContext) { + hole := t.target.Rect() + if hole.Width <= 0 || hole.Height <= 0 { + return + } + const gap = 4 + hole = gfx.Rect{X: hole.X - gap, Y: hole.Y - gap, Width: hole.Width + 2*gap, Height: hole.Height + 2*gap} + dim := gfx.Color{Alpha: 0.5} + whole := d.Rect + canvas := d.Canvas + canvas.Fill(gfx.Rect{X: whole.X, Y: whole.Y, Width: whole.Width, Height: max(hole.Y-whole.Y, 0)}, dim) + canvas.Fill(gfx.Rect{X: whole.X, Y: hole.Y + hole.Height, Width: whole.Width, Height: max(whole.Y+whole.Height-hole.Y-hole.Height, 0)}, dim) + canvas.Fill(gfx.Rect{X: whole.X, Y: hole.Y, Width: max(hole.X-whole.X, 0), Height: hole.Height}, dim) + canvas.Fill(gfx.Rect{X: hole.X + hole.Width, Y: hole.Y, Width: max(whole.X+whole.Width-hole.X-hole.Width, 0), Height: hole.Height}, dim) + canvas.Border(hole, 2, d.Theme.Primary, gfx.Color{}) +} + +// draw declares the buttons of the note. +func (t *Tour) draw() { + c, spec := t.c, &t.spec + metrics := c.Theme().Metrics + last := t.step == len(spec.Steps)-1 + ui.Row(c).FillWidth().Items(ui.Center).Gap(metrics.GapItem).Children(func() { + ui.Text(c, t.counterText(t.step, len(spec.Steps))).FontSize(metrics.FontSizeS).Muted().Grow(1) + if !last { + if ui.Button(c, spec.label(3)).Ghost().Small().Clicked() { + t.open = false + } + } + if t.step > 0 { + if ui.Button(c, spec.label(0)).Outline().Small().Clicked() { + t.step-- + } + } + if last { + if ui.Button(c, spec.label(2)).Small().Clicked() { + t.open, t.pending = false, true + } + } else if ui.Button(c, spec.label(1)).Small().Clicked() { + t.step++ + } + }) +} diff --git a/ui/tour/tour_test.go b/ui/tour/tour_test.go new file mode 100644 index 000000000..58e9d33ed --- /dev/null +++ b/ui/tour/tour_test.go @@ -0,0 +1,167 @@ +package tour_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/tour" +) + +var steps = []tour.Step{ + {Title: "Save", Description: "Saves the file."}, + {Title: "Sync", Description: "Sends it to the host."}, + {Title: "Done", Description: "That is all."}, +} + +type model struct { + t *tour.Tour + hideSync bool + finished int +} + +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(16).Gap(12).Children(func() { + save := ui.Button(c, "Save File") + m.t.Target(0, save) + if !m.hideSync { + sync := ui.Button(c, "Sync Now") + m.t.Target(1, sync) + } + m.t.View(c, tour.Spec{Steps: steps}) + if m.t.Finished() { + m.finished++ + } + }) +} + +type driver struct { + t *testing.T + *app.Driver + wake *app.Invalidator +} + +func open(t *testing.T, m *model) driver { + t.Helper() + m.t = tour.New() + page := ui.NewPage(ui.PageConfig{View: m.page}) + wake := new(app.Invalidator) + d, err := app.NewDriver(ui.Configure(page, app.Config{Width: 480, Height: 360, Invalidator: wake}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(d.Close) + return driver{t, d, wake} +} + +func (d driver) repaint() { + d.t.Helper() + d.wake.Invalidate() + if err := d.Pump(); err != nil { + d.t.Fatal(err) + } +} + +func (d driver) shown(text string) bool { + for _, v := range d.Snapshot().Texts { + if v.Value == text { + return true + } + } + return false +} + +func (d driver) click(label string) { + d.t.Helper() + hits := d.Snapshot().Hits + for i := len(hits) - 1; i >= 0; i-- { + if h := hits[i]; h.Label == label && !h.IsLabel && !h.ID.IsZero() { + if err := d.Click(h.Bounds.X+h.Bounds.Width/2, h.Bounds.Y+h.Bounds.Height/2); err != nil { + d.t.Fatal(err) + } + return + } + } + d.t.Fatalf("no control labeled %q", label) +} + +func TestClosedTourDeclaresNothing(t *testing.T) { + d := open(t, &model{}) + if d.shown("1 / 3") { + t.Fatal("a closed tour shows its counter") + } +} + +func TestTourStepsForwardAndBackAndFinishes(t *testing.T) { + m := &model{} + d := open(t, m) + m.t.Start() + d.repaint() + if !d.shown("Save") || !d.shown("1 / 3") { + t.Fatal("the first step is not shown") + } + d.click("Next") + if !d.shown("2 / 3") || !d.shown("Sync") { + t.Fatal("Next did not show the second step") + } + d.click("Previous") + if !d.shown("1 / 3") { + t.Fatal("Previous did not go back") + } + d.click("Next") + d.click("Next") + if !d.shown("3 / 3") { + t.Fatal("the last step is not shown") + } + d.click("Finish") + d.repaint() + if m.t.IsOpen() { + t.Fatal("Finish left the tour open") + } + if m.finished != 1 { + t.Fatalf("Finished was reported %d times, want 1", m.finished) + } +} + +func TestSkipLeavesWithoutFinishing(t *testing.T) { + m := &model{} + d := open(t, m) + m.t.Start() + d.repaint() + d.click("Skip") + d.repaint() + if m.t.IsOpen() || m.finished != 0 { + t.Fatalf("after Skip: open %v, finished %d", m.t.IsOpen(), m.finished) + } +} + +func TestStepWithoutATargetIsStillShown(t *testing.T) { + m := &model{hideSync: true} + d := open(t, m) + m.t.Start() + d.repaint() + d.click("Next") + if !d.shown("Sync") || !d.shown("2 / 3") { + t.Fatal("a step whose control is not on the page is not shown") + } +} + +func TestClosedWarmPaintDoesNotAllocate(t *testing.T) { + m := &model{t: tour.New()} + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: m.page, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 480, Height: 360}, m.page) + canvas.EndFrame() + } + draw() + draw() + if n := testing.AllocsPerRun(100, draw); n != 0 { + t.Fatalf("a warm paint allocates %v times", n) + } +} diff --git a/ui/transfer/transfer.go b/ui/transfer/transfer.go new file mode 100644 index 000000000..0d01308b7 --- /dev/null +++ b/ui/transfer/transfer.go @@ -0,0 +1,225 @@ +// Package transfer is the opt-in page control for moving items between two +// lists: the ones on the left are available, the ones on the right are chosen. +// A page keeps the items in its model and declares the two lists with a Spec: +// +// m.moves = transfer.New() +// // in the page: +// m.moves.View(c, "Groups", transfer.Spec{Items: m.groups, Titles: [2]string{"Available", "Selected"}}) +// if m.moves.Changed() { +// // items moved; m.groups[i].Target says which side each is on +// } +// +// An Item says on which side it is (Target is true for the right list) and whether +// it is ticked (Checked); the control moves the ticked items of a list to the +// other list with the button between them, and writes Target and Checked in the +// caller's slice, so the page reads the result where it keeps the items. A +// Disabled item can be neither ticked nor moved. The tick above a list ticks or +// clears every item in it. Each list scrolls when it is longer than its Height. +// +// Every item of a list is declared in each paint, so it is for lists of some +// hundreds of items, not for a table of thousands. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Transfer in the model: it holds the state of the two +// ticks above the lists, so a warm paint allocates nothing. Do not copy a Transfer +// after it has been declared. +package transfer + +import ( + "strconv" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +var ( + rightIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(9, 18), gfx.LineTo(15, 12), gfx.LineTo(9, 6), + }} + leftIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(15, 18), gfx.LineTo(9, 12), gfx.LineTo(15, 6), + }} +) + +// Item is one thing that is in one of the two lists. +type Item struct { + // Title is what the list shows. + Title string + // Target is whether the item is in the right list; false is the left one. + Target bool + // Checked is whether the item is ticked, to be moved with the button. + Checked bool + // Disabled makes the item neither tickable nor movable. + Disabled bool +} + +// Spec declares the two lists. +type Spec struct { + // Items are everything, on either side, in the order the lists show them. + // Keep the slice in the model: the control writes Target and Checked in it. + Items []Item + // Titles head the left and the right list; they are not drawn when empty. + Titles [2]string + // Height is the height of a list; 240 when zero or less. + Height float32 + // MoveLabels are the accessible names of the buttons that move the ticked + // items to the right and to the left; "Move right" and "Move left" when empty. + MoveLabels [2]string +} + +// Transfer is one pair of lists. +type Transfer struct { + all [2]bool // the tick above each list, as of the last paint + counts [2]countText + changed bool + reported bool +} + +// countText is the "ticked/total" words above a list, made when the counts change. +type countText struct { + ticked, total int + text string +} + +// New returns a pair of lists. +func New() *Transfer { return &Transfer{} } + +// Changed reports whether items moved in the paint that delivered it. +func (t *Transfer) Changed() bool { return t.reported } + +func (c *countText) set(ticked, total int) string { + if c.text == "" || c.ticked != ticked || c.total != total { + c.ticked, c.total = ticked, total + c.text = strconv.Itoa(ticked) + "/" + strconv.Itoa(total) + } + return c.text +} + +// stats counts the items of a side and how many of them are ticked, and whether +// every tickable one is. +func stats(items []Item, target bool) (total, ticked int, every bool) { + tickable := 0 + for i := range items { + item := &items[i] + if item.Target != target { + continue + } + total++ + if item.Disabled { + continue + } + tickable++ + if item.Checked { + ticked++ + } + } + return total, ticked, tickable > 0 && ticked == tickable +} + +// move moves the ticked items of a side to the other and unticks them. +func (t *Transfer) move(items []Item, from bool) { + for i := range items { + item := &items[i] + if item.Target == from && item.Checked && !item.Disabled { + item.Target, item.Checked = !from, false + t.changed = true + } + } +} + +// View declares the two lists and the buttons between them at c. label names the +// control for assistive technology. The control is as wide as the room it is given +// and as tall as Height plus the heads; give it FillWidth. Declare the view on its +// own, not inside a Memo. +func (t *Transfer) View(c ui.C, label string, spec Spec) ui.Box { + if t == nil { + panic("transfer: View needs its Transfer") + } + t.reported, t.changed = t.changed, false + height := spec.Height + if height <= 0 { + height = 240 + } + moves := spec.MoveLabels + if moves[0] == "" { + moves[0] = "Move right" + } + if moves[1] == "" { + moves[1] = "Move left" + } + theme := c.Theme() + root := ui.Row(c).Items(ui.Center).Gap(theme.Metrics.GapItem) + // The lists are made of controls of their own, so the row names the group + // without a hit that would overlap theirs. + root = root.Label(label) + root.Children(func() { + t.panel(c, spec, false, height) + ui.Column(c).Gap(theme.Metrics.GapItem).Shrink(0).Children(func() { + _, leftTicked, _ := stats(spec.Items, false) + _, rightTicked, _ := stats(spec.Items, true) + if ui.Button(c, moves[0]).Icon(rightIcon).IconOnly().Outline().Disabled(leftTicked == 0).Clicked() { + t.move(spec.Items, false) + } + if ui.Button(c, moves[1]).Icon(leftIcon).IconOnly().Outline().Disabled(rightTicked == 0).Clicked() { + t.move(spec.Items, true) + } + }) + t.panel(c, spec, true, height) + }) + return root +} + +// panel declares one list: its head with the tick for all, the title and the +// count, and the scrolling rows. +func (t *Transfer) panel(c ui.C, spec Spec, target bool, height float32) { + theme := c.Theme() + side := 0 + if target { + side = 1 + } + total, ticked, every := stats(spec.Items, target) + t.all[side] = every + box := ui.Column(c).Grow(1).Basis(0).Border(1, theme.Border).Radius(theme.Metrics.RadiusControl).Clip() + box.Children(func() { + head := ui.Row(c).FillWidth().Items(ui.Center).Gap(theme.Metrics.GapItem).Pad(theme.Metrics.GapItem) + head.Children(func() { + // The title is a label of the tick, as a row of words beside a control is. + id := ui.ID(c) + all := ui.Checkbox(c, &t.all[side], "").Hit(id, spec.Titles[side]) + if spec.Titles[side] != "" { + ui.Text(c, spec.Titles[side]).LabelFor(id) + } + if all.Changed() { + for i := range spec.Items { + item := &spec.Items[i] + if item.Target == target && !item.Disabled { + item.Checked = t.all[side] + } + } + } + ui.Spacer(c).Grow(1) + ui.Text(c, t.counts[side].set(ticked, total)).FontSize(theme.Metrics.FontSizeS).Muted() + }) + ui.Spacer(c).FillWidth().Height(1).Grow(0).Shrink(0).Background(theme.Border) + ui.Scroll(c).FillWidth().Height(height).Children(func() { + ui.Column(c).FillWidth().Pad(theme.Metrics.GapItem).Gap(theme.Metrics.GapItem).Children(func() { + for i := range spec.Items { + item := &spec.Items[i] + if item.Target != target { + continue + } + // Keyed by the item's place in the caller's slice, so an item that moves + // to the other list keeps its name. + id := ui.ID(c.KeyInt(i)) + ui.Row(c).FillWidth().Items(ui.Center).Gap(theme.Metrics.GapItem).Children(func() { + ui.Checkbox(c, &item.Checked, "").Hit(id, item.Title).Disabled(item.Disabled) + title := ui.Text(c, item.Title).LabelFor(id).Grow(1) + if item.Disabled { + title.Muted() + } + }) + } + }) + }) + }) +} diff --git a/ui/transfer/transfer_test.go b/ui/transfer/transfer_test.go new file mode 100644 index 000000000..2cf59434b --- /dev/null +++ b/ui/transfer/transfer_test.go @@ -0,0 +1,159 @@ +//go:build !js + +package transfer_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/transfer" +) + +// changes counts the paints that reported a change, as a page reads Changed. +var changes int + +func open(t *testing.T, tr *transfer.Transfer, items []transfer.Item) *headless.Session { + t.Helper() + changes = 0 + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + tr.View(c, "Groups", transfer.Spec{Items: items, Titles: [2]string{"Available", "Selected"}}).FillWidth() + if tr.Changed() { + changes++ + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Transfer", Width: 640, Height: 420}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +func sides(items []transfer.Item) (left, right []string) { + for _, item := range items { + if item.Target { + right = append(right, item.Title) + } else { + left = append(left, item.Title) + } + } + return left, right +} + +func equal(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +// The button moves the ticked items of a list to the other and unticks them; an +// item nobody ticked stays where it is. +func TestButtonMovesTheTickedItems(t *testing.T) { + items := []transfer.Item{{Title: "alpha"}, {Title: "beta"}, {Title: "gamma"}, {Title: "delta", Target: true}} + session := open(t, transfer.New(), items) + if err := session.ClickLabel("alpha"); err != nil { + t.Fatal(err) + } + if err := session.ClickLabel("gamma"); err != nil { + t.Fatal(err) + } + if err := session.ClickLabel("Move right"); err != nil { + t.Fatal(err) + } + left, right := sides(items) + if !equal(left, []string{"beta"}) || !equal(right, []string{"alpha", "gamma", "delta"}) { + t.Fatalf("lists = %v | %v after moving alpha and gamma right, want [beta] | [alpha gamma delta]", left, right) + } + if items[0].Checked || items[2].Checked { + t.Fatal("a moved item stayed ticked") + } + if changes != 1 { + t.Fatalf("Changed was reported in %d paints, want 1", changes) + } + if err := session.ClickLabel("Move left"); err == nil { + t.Fatal("Move left could be pressed with nothing ticked on the right") + } +} + +// A disabled item is neither ticked by the tick for all nor moved. +func TestTickForAllSkipsDisabledItems(t *testing.T) { + items := []transfer.Item{{Title: "alpha"}, {Title: "beta", Disabled: true}, {Title: "gamma"}} + session := open(t, transfer.New(), items) + if err := session.ClickLabel("Available"); err != nil { + t.Fatal(err) + } + if !items[0].Checked || items[1].Checked || !items[2].Checked { + t.Fatalf("ticks = %v %v %v after the tick for all, want true false true", items[0].Checked, items[1].Checked, items[2].Checked) + } + if err := session.ClickLabel("Move right"); err != nil { + t.Fatal(err) + } + left, right := sides(items) + if !equal(left, []string{"beta"}) || !equal(right, []string{"alpha", "gamma"}) { + t.Fatalf("lists = %v | %v, want the disabled item left behind", left, right) + } +} + +// The tick for all follows the items: it is ticked once every tickable item is, +// and clears them when it is cleared. +func TestTickForAllFollowsTheItems(t *testing.T) { + items := []transfer.Item{{Title: "alpha", Checked: true}, {Title: "beta", Checked: true}} + session := open(t, transfer.New(), items) + if err := session.ClickLabel("Available"); err != nil { + t.Fatal(err) + } + if items[0].Checked || items[1].Checked { + t.Fatalf("items stayed ticked after the tick for all was cleared: %v %v", items[0].Checked, items[1].Checked) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + items := []transfer.Item{{Title: "alpha"}, {Title: "beta", Checked: true}, {Title: "gamma", Target: true}} + tr := transfer.New() + view := func(c ui.C) { tr.View(c, "Groups", transfer.Spec{Items: items}).FillWidth() } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 640, Height: 420}, view) + canvas.EndFrame() + } + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + items := make([]transfer.Item, 200) + for i := range items { + items[i] = transfer.Item{Title: "host", Target: i%3 == 0, Checked: i%5 == 0} + } + tr := transfer.New() + view := func(c ui.C) { tr.View(c, "Groups", transfer.Spec{Items: items}).FillWidth() } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + b.ReportAllocs() + for range b.N { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 640, Height: 420}, view) + canvas.EndFrame() + } +} diff --git a/ui/tree_paint.go b/ui/tree_paint.go index 1627a7577..94c454105 100644 --- a/ui/tree_paint.go +++ b/ui/tree_paint.go @@ -19,6 +19,7 @@ func treeStateRow(s *TreeState, i int, rowBox Box) { item := components.TreeItem{ ID: s.GetRows().At(key), Label: s.GetRowLabel()(i), Depth: uint8(min(max(depth, 0), 31)), Branch: node.Branch, Expanded: node.Expanded, Selected: node.Selected, Disabled: node.Disabled, + Loading: node.Branch && node.Loading, } if node.Branch { item.DisclosureID = s.GetChevrons().At(key) @@ -27,7 +28,7 @@ func treeStateRow(s *TreeState, i int, rowBox Box) { if canvas.Clicked(item.ID) { s.SetChosenIndex(i) } - if node.Branch && canvas.Clicked(item.DisclosureID) { + if node.Branch && !node.Loading && canvas.Clicked(item.DisclosureID) { s.SetToggledIndex(i) } } @@ -65,10 +66,27 @@ func treeStateDraw(s *TreeState, d *DrawContext) { if s.Disclosure != nil { tree = tree.Disclosure(*s.Disclosure) } - tree.Item(row.GetItem()) + item := row.GetItem() + if item.Loading { + item.Phase = spinnerPhase(d) + } + tree.Item(item) if s.DragPtr().GetActive() { s.DragOver(row, d) } return } } + +// spinnerPhase is the frame of the indicator of a branch whose children are being +// fetched: it turns while the row is on screen and holds still when the system asks +// for reduced motion. +func spinnerPhase(d *DrawContext) uint8 { + if d.Canvas.ReduceMotion() { + return 0 + } + if d.Frame.Visible(d.Node) { + d.Canvas.RequestFrameIn(SpinnerStep) + } + return uint8(d.Canvas.Now() / SpinnerStep % 8) +} diff --git a/ui/typography/typography.go b/ui/typography/typography.go new file mode 100644 index 000000000..d7569aa19 --- /dev/null +++ b/ui/typography/typography.go @@ -0,0 +1,148 @@ +// Package typography is the opt-in page control for a piece of text that can be +// cut to a few lines with a way to read the rest, and copied: a description, a +// fingerprint, a command. A page keeps a Text in its model, because it remembers +// whether the user expanded it: +// +// m.about = typography.New() +// // in the page: +// m.about.View(c, m.description, typography.Spec{Rows: 3, Expandable: true, Copyable: true}).FillWidth() +// if m.about.Copied() { +// // the text went to the clipboard; say so, for instance with a toast +// } +// +// Rows is how many lines the text shows before it ends in an ellipsis; zero shows +// all of it. When the text needs more lines than Rows at the width it has, Expandable +// adds a button after it that shows the rest and takes it away again. Copyable adds a +// button that puts the whole text on the system clipboard; Copied reports a press on +// it. Whether the text is cut is known from the width it had in the paint before, so +// the button appears one paint after the text first does. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep a Text in the model: it holds the expanded state and the +// width the last paint measured, so a warm paint allocates nothing. Do not copy a +// Text after it has been declared. +package typography + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +var copyIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(9, 9), gfx.LineTo(20, 9), gfx.LineTo(20, 20), gfx.LineTo(9, 20), gfx.ClosePath(), + gfx.MoveTo(5, 15), gfx.LineTo(4, 15), gfx.LineTo(4, 4), gfx.LineTo(15, 4), gfx.LineTo(15, 5), +}} + +// Labels are the words of the buttons. +type Labels struct { + // More and Less are the expand button's two states; Copy names the copy button. + More, Less, Copy string +} + +// English is the default words. +var English = Labels{More: "More", Less: "Less", Copy: "Copy"} + +// Spec declares the text. +type Spec struct { + // Rows is how many lines show before the ellipsis; zero shows all. Up to seven are + // told apart. + Rows int + // Expandable adds the button that shows the rest of a text cut to Rows. + Expandable bool + // Copyable adds the copy button. + Copyable bool + // Muted paints the text in the muted color. + Muted bool + // Labels are the words; English when zero. + Labels Labels +} + +// Text is one text and whether it is expanded. +type Text struct { + expanded bool + copied bool + width float32 // the width the paragraph had in the last paint + cut bool // whether the text needs more than Rows lines at that width + measure func(*ui.DrawContext) +} + +// New returns a collapsed text. +func New() *Text { + t := &Text{} + t.measure = t.noteWidth + return t +} + +// noteWidth keeps the width the paragraph was laid out at. A change asks for one more +// paint, which decides again whether the text is cut; the width only changes when the +// window or the layout does, so an idle text asks for nothing. +func (t *Text) noteWidth(d *ui.DrawContext) { + if d.Rect.Width != t.width { + t.width = d.Rect.Width + d.Canvas.RequestFrame() + } +} + +// Copied reports whether the copy button was pressed in the paint just made. +func (t *Text) Copied() bool { return t.copied } + +// Expanded reports whether the text shows all of itself. +func (t *Text) Expanded() bool { return t.expanded } + +// View declares the text at c. The text is as tall as its lines; give it FillWidth. +// Declare the view on its own, not inside a Memo. +func (t *Text) View(c ui.C, value string, spec Spec) ui.Box { + if t == nil { + panic("typography: View needs its Text") + } + t.copied = false + labels := spec.Labels + if labels == (Labels{}) { + labels = English + } + rows := min(max(spec.Rows, 0), 7) + theme := c.Theme() + metrics := theme.Metrics + // Whether the text is cut, from the width the paragraph had last paint. + t.cut = false + if rows > 0 && t.width > 0 { + var scratch [8]string + lines := c.Canvas().WrapLines(scratch[:0], value, metrics.FontSizeM, gfx.WeightRegular, t.width, rows+1) + t.cut = len(lines) > rows + } + maxLines := rows + if t.expanded { + maxLines = 0 + } + root := ui.Column(c).Gap(metrics.GapItem * 0.5) + root.Children(func() { + var paragraph ui.Box + if spec.Copyable { + ui.Row(c).FillWidth().Items(ui.Start).Gap(metrics.GapItem).Children(func() { + paragraph = ui.Paragraph(c, value, maxLines).Grow(1).Basis(0).Draw(t.measure) + if spec.Muted { + paragraph.Muted() + } + if ui.Button(c, labels.Copy).Icon(copyIcon).IconOnly().Ghost().Shrink(0).Clicked() { + _ = ui.SetClipboardText(value) + t.copied = true + } + }) + } else { + paragraph = ui.Paragraph(c, value, maxLines).Draw(t.measure) + if spec.Muted { + paragraph.Muted() + } + } + if spec.Expandable && (t.cut || t.expanded) { + label := labels.More + if t.expanded { + label = labels.Less + } + if ui.Button(c, label).Link().Small().Clicked() { + t.expanded = !t.expanded + } + } + }) + return root +} diff --git a/ui/typography/typography_test.go b/ui/typography/typography_test.go new file mode 100644 index 000000000..0a03daf7b --- /dev/null +++ b/ui/typography/typography_test.go @@ -0,0 +1,122 @@ +//go:build !js + +package typography_test + +import ( + "strings" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/typography" +) + +var long = strings.Repeat("Keeps scene nodes and repaints only when the content changes. ", 8) + +func open(t *testing.T, tx *typography.Text, value string, spec typography.Spec) *headless.Session { + t.Helper() + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { tx.View(c, value, spec).FillWidth() }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Text", Width: 420, Height: 360}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + session.Frame() // the second paint knows the width and so whether the text is cut + return session +} + +func lines(session *headless.Session) int { + n := 0 + for _, text := range session.Driver().Snapshot().Texts { + if len(text.Value) > 20 { + n++ + } + } + return n +} + +// A text longer than Rows is cut to Rows lines with a button to read the rest, and +// the button takes the rest away again. +func TestLongTextIsCutAndExpands(t *testing.T) { + tx := typography.New() + session := open(t, tx, long, typography.Spec{Rows: 2, Expandable: true}) + if got := lines(session); got != 2 { + t.Fatalf("lines shown = %d, want 2", got) + } + if err := session.ClickLabel("More"); err != nil { + t.Fatal(err) + } + if !tx.Expanded() || lines(session) <= 2 { + t.Fatalf("expanded %v, lines %d after More; want all the lines", tx.Expanded(), lines(session)) + } + if err := session.ClickLabel("Less"); err != nil { + t.Fatal(err) + } + if tx.Expanded() || lines(session) != 2 { + t.Fatalf("expanded %v, lines %d after Less; want cut to 2", tx.Expanded(), lines(session)) + } +} + +// A text that fits in Rows offers nothing to expand. +func TestShortTextHasNoMoreButton(t *testing.T) { + session := open(t, typography.New(), "A short line.", typography.Spec{Rows: 2, Expandable: true}) + if _, err := session.Locate("More"); err == nil { + t.Fatal("a text that fits offers More") + } +} + +// The copy button puts the whole text, not the cut one, on the clipboard, and +// Copied is reported in the paint that delivers the press. +func TestCopyPutsTheWholeTextOnTheClipboard(t *testing.T) { + tx := typography.New() + copied := 0 + spec := typography.Spec{Rows: 2, Copyable: true} + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + tx.View(c, long, spec).FillWidth() + if tx.Copied() { + copied++ + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Text", Width: 420, Height: 360}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + if err := session.ClickLabel("Copy"); err != nil { + t.Fatal(err) + } + if copied != 1 { + t.Fatalf("Copied was reported in %d paints after one press, want 1", copied) + } + if got := session.Driver().Clipboard(); got != long { + t.Fatalf("clipboard holds %d characters, want the whole text (%d)", len(got), len(long)) + } +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + tx := typography.New() + spec := typography.Spec{Rows: 2, Expandable: true, Copyable: true} + view := func(c ui.C) { tx.View(c, long, spec).FillWidth() } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 420, Height: 360}, view) + canvas.EndFrame() + } + draw() + draw() + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} diff --git a/ui/upload/upload.go b/ui/upload/upload.go new file mode 100644 index 000000000..cc41e4036 --- /dev/null +++ b/ui/upload/upload.go @@ -0,0 +1,389 @@ +// Package upload is the opt-in page control for choosing files to send: an area +// that takes files dragged from the system or chosen with the system's picker, +// and the list of the files chosen so far, each with its progress and a button +// to remove it. A page keeps an Upload in its model beside the list: +// +// m.upload = upload.New() +// // in the page: +// m.upload.View(c, "Attachments", upload.Spec{ +// Items: m.files, Multiple: true, Accept: []string{".png", ".jpg"}, +// }).FillWidth() +// for _, file := range m.upload.Added() { +// m.files = append(m.files, upload.Item{Name: file.Name(), Size: file.Size()}) +// // start sending file; set the item's Status and Progress as it goes +// } +// if i, ok := m.upload.Removed(); ok { +// m.files = slices.Delete(m.files, i, i+1) // and stop sending it +// } +// +// The control sends nothing: the page owns the files and the transfer, and says +// how far each Item is (Status, Progress, Error). The control reports what the +// user did: Added the files that passed the checks, Rejected the ones that did +// not, Removed and Retried the item of a button pressed. +// +// A file is added when it is a file and not a folder, its name ends in one of +// Accept when that is set, and, unless Multiple is set, it is the first of its +// batch. With Limit set, a batch is cut where the list would be longer. A +// browser gives files without paths; ui.FilePath says whether a file has one. +// +// The picker is the Choose button, which is the keyboard's way to the picker +// too. Dropping on the area adds the same way. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an Upload in the model: its state and handlers are made +// once, so a warm paint allocates nothing. Do not copy an Upload after it has +// been declared. +package upload + +import ( + "strconv" + "strings" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +var ( + uploadIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(21, 15), gfx.LineTo(21, 19), gfx.QuadTo(21, 21, 19, 21), gfx.LineTo(5, 21), gfx.QuadTo(3, 21, 3, 19), gfx.LineTo(3, 15), + gfx.MoveTo(17, 8), gfx.LineTo(12, 3), gfx.LineTo(7, 8), + gfx.MoveTo(12, 3), gfx.LineTo(12, 15), + }} + fileIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(14.5, 2), gfx.LineTo(6, 2), gfx.QuadTo(4, 2, 4, 4), gfx.LineTo(4, 20), gfx.QuadTo(4, 22, 6, 22), gfx.LineTo(18, 22), + gfx.QuadTo(20, 22, 20, 20), gfx.LineTo(20, 7.5), gfx.LineTo(14.5, 2), + gfx.MoveTo(14, 2), gfx.LineTo(14, 8), gfx.LineTo(20, 8), + }} + removeIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(18, 6), gfx.LineTo(6, 18), gfx.MoveTo(6, 6), gfx.LineTo(18, 18), + }} + retryIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(21, 12), gfx.CubicTo(21, 16.97, 16.97, 21, 12, 21), gfx.CubicTo(9.5, 21, 7.24, 19.98, 5.6, 18.3), + gfx.MoveTo(3, 12), gfx.CubicTo(3, 7.03, 7.03, 3, 12, 3), gfx.CubicTo(14.5, 3, 16.76, 4.02, 18.4, 5.7), + gfx.MoveTo(21, 3), gfx.LineTo(21, 8), gfx.LineTo(16, 8), + gfx.MoveTo(3, 21), gfx.LineTo(3, 16), gfx.LineTo(8, 16), + }} +) + +// Status is how far the sending of an item has got. +type Status uint8 + +const ( + // Pending is an item chosen and not yet sent: the zero value. + Pending Status = iota + // Uploading is an item being sent; Progress says how far. + Uploading + // Done is an item that was sent. + Done + // Failed is an item that could not be sent; it offers Retry. + Failed +) + +// Item is one file of the list, as the page keeps it. +type Item struct { + Name string + // Size is the file's length in bytes; not shown when zero or less. + Size int64 + Status Status + // Progress is the fraction, 0 to 1, of an Uploading item that was sent. + Progress float32 + // Error is the words that say why a Failed item failed, in place of its size. + Error string +} + +// Spec declares the area and the list. +type Spec struct { + // Items are the files chosen so far, in the order the list shows them. + Items []Item + // Title is the line in the area, "Drag files here" when empty; Hint is a muted + // line under it, for what the area accepts ("PNG or JPEG, up to 5 MB"), and is + // not drawn when empty. Choose is the picker button's label, "Choose files" + // when empty. + Title, Hint, Choose string + // Accept are the file name endings the area takes, with the dot (".png"), + // matched without regard to case. Empty takes every file. AcceptName names + // them in the picker, "Supported files" when empty. + Accept []string + AcceptName string + // Multiple lets one batch add several files; otherwise only the first is added. + Multiple bool + // Limit is how many items the list may have; zero is no limit. + Limit int + // Disabled leaves the area and the buttons inert. + Disabled bool + // RemoveLabel and RetryLabel are the accessible names of the buttons of a row, + // before the file's name: "Remove" and "Retry" when empty. + RemoveLabel, RetryLabel string +} + +// Upload is one area and its list. +type Upload struct { + drop ui.FileDropState + + added, rejected []gfx.FileDropFile + removed int + retried int + picked []gfx.FileDropFile + pickedFn func([]gfx.FileDropFile, error) + rows []rowText +} + +// rowText is the words of a row that are made from the item and kept while it +// does not change. +type rowText struct { + name string + size int64 + sizeAt string + remove string + retry string + labels [2]string // the button labels the words were made with +} + +// New returns an empty upload. +func New() *Upload { + u := &Upload{removed: -1, retried: -1} + u.pickedFn = u.onPicked + return u +} + +// Added are the files the user chose or dropped in the paint just made that +// passed the checks, in order; the page adds them to its list and starts sending +// them. +func (u *Upload) Added() []gfx.FileDropFile { return u.added } + +// Rejected are the files chosen or dropped in the paint just made that were not +// added: a folder, a file whose name is not in Accept, or one past Limit or past +// the first of a single-file batch. +func (u *Upload) Rejected() []gfx.FileDropFile { return u.rejected } + +// Removed reports the index in Spec.Items of the item whose remove button was +// pressed in the paint just made. +func (u *Upload) Removed() (index int, ok bool) { return u.removed, u.removed >= 0 } + +// Retried reports the index in Spec.Items of the failed item whose retry button +// was pressed in the paint just made. +func (u *Upload) Retried() (index int, ok bool) { return u.retried, u.retried >= 0 } + +func (u *Upload) onPicked(files []gfx.FileDropFile, err error) { + if err == nil { + u.picked = files + } +} + +// View declares the area and the list at c. label names the area for assistive +// technology. The control is as wide as the room it is given and as tall as its +// content; give it FillWidth. Declare the view on its own, not inside a Memo. +func (u *Upload) View(c ui.C, label string, spec Spec) ui.Box { + if u == nil { + panic("upload: View needs its Upload") + } + u.added, u.rejected = u.added[:0], u.rejected[:0] + u.removed, u.retried = -1, -1 + if files, _ := u.drop.Dropped(); len(files) > 0 { + u.take(files, spec) + } + if len(u.picked) > 0 { + u.take(u.picked, spec) + u.picked = nil + } + theme := c.Theme() + root := ui.Column(c).Gap(theme.Metrics.GapItem).Label(label) + root.Children(func() { + u.area(c, spec) + if len(spec.Items) > 0 { + u.list(c, spec) + } + }) + return root +} + +// take checks a batch of files against the spec and sorts them into Added and +// Rejected. +func (u *Upload) take(files []gfx.FileDropFile, spec Spec) { + if spec.Disabled { + return + } + room := len(files) + if spec.Limit > 0 { + room = max(spec.Limit-len(spec.Items)-len(u.added), 0) + } + if !spec.Multiple { + room = min(room, 1-len(u.added)) + } + for _, file := range files { + if file.IsDir() || !accepts(spec.Accept, file.Name()) || room <= 0 { + u.rejected = append(u.rejected, file) + continue + } + u.added = append(u.added, file) + room-- + } +} + +// accepts reports whether the name ends in one of the endings, or there are none. +func accepts(endings []string, name string) bool { + if len(endings) == 0 { + return true + } + for _, ending := range endings { + if len(name) >= len(ending) && strings.EqualFold(name[len(name)-len(ending):], ending) { + return true + } + } + return false +} + +// area declares the place files are dropped on, with the picker's button. +func (u *Upload) area(c ui.C, spec Spec) { + theme := c.Theme() + metrics := theme.Metrics + title, choose := spec.Title, spec.Choose + if title == "" { + title = "Drag files here" + } + if choose == "" { + choose = "Choose files" + } + box := ui.Column(c).FillWidth().Center().Gap(metrics.GapItem).Pad(metrics.PadSurface * 1.5) + box = box.Radius(metrics.RadiusSurface).Border(1, theme.Border).Dashed() + if !spec.Disabled { + box = box.DropFiles(&u.drop) + if u.drop.Over() { + tint := theme.Primary + tint.Alpha *= 0.08 + box = box.Background(tint).Border(1, theme.Primary) + } + } + box.Children(func() { + ink := theme.MutedForeground + ui.Icon(c, uploadIcon).Size(24, 24).Color(ink) + ui.Text(c, title) + if spec.Hint != "" { + ui.Text(c, spec.Hint).FontSize(metrics.FontSizeS).Muted() + } + if ui.Button(c, choose).Outline().Small().Disabled(spec.Disabled).Clicked() { + u.choose(c, spec) + } + }) +} + +// choose opens the picker. A native picker answers at once, so its files are +// checked in this paint; a browser's arrive in a later one. +func (u *Upload) choose(c ui.C, spec Spec) { + options := ui.OpenFileOptions{AllowMultiple: spec.Multiple} + if len(spec.Accept) > 0 { + name := spec.AcceptName + if name == "" { + name = "Supported files" + } + var pattern strings.Builder + for i, ending := range spec.Accept { + if i > 0 { + pattern.WriteByte(';') + } + pattern.WriteByte('*') + pattern.WriteString(ending) + } + options.Filters = []ui.FileFilter{{Name: name, Pattern: pattern.String()}} + } + if err := ui.OpenFiles(c, options, u.pickedFn); err != nil { + return + } + if len(u.picked) > 0 { + u.take(u.picked, spec) + u.picked = nil + } +} + +// list declares one row for each item. +func (u *Upload) list(c ui.C, spec Spec) { + theme := c.Theme() + metrics := theme.Metrics + for len(u.rows) < len(spec.Items) { + u.rows = append(u.rows, rowText{}) + } + removeLabel, retryLabel := spec.RemoveLabel, spec.RetryLabel + if removeLabel == "" { + removeLabel = "Remove" + } + if retryLabel == "" { + retryLabel = "Retry" + } + ui.Column(c).FillWidth().Gap(metrics.GapItem).Children(func() { + for i := range spec.Items { + item := &spec.Items[i] + text := u.rows[i].refresh(item, removeLabel, retryLabel) + row := c.KeyInt(i) + ink := theme.MutedForeground + switch item.Status { + case Done: + ink = theme.Success + case Failed: + ink = theme.Danger + } + ui.Column(row).FillWidth().Gap(4).Pad(metrics.GapItem).Radius(metrics.RadiusControl).Border(1, theme.Border).Children(func() { + ui.Row(row).FillWidth().Items(ui.Center).Gap(metrics.GapItem).Children(func() { + ui.Icon(row, fileIcon).Size(16, 16).Color(ink).Shrink(0) + ui.Text(row, item.Name).Grow(1).Basis(0).Ellipsis() + meta := text.sizeAt + if item.Status == Failed && item.Error != "" { + meta = item.Error + } + if meta != "" { + note := ui.Text(row, meta).FontSize(metrics.FontSizeS).Shrink(0) + if item.Status == Failed { + note.Color(theme.Danger) + } else { + note.Muted() + } + } + if item.Status == Failed { + if ui.Button(row, text.retry).Icon(retryIcon).IconOnly().Ghost().Disabled(spec.Disabled).Shrink(0).Clicked() { + u.retried = i + } + } + if ui.Button(row, text.remove).Icon(removeIcon).IconOnly().Ghost().Disabled(spec.Disabled).Shrink(0).Clicked() { + u.removed = i + } + }) + if item.Status == Uploading { + ui.Progress(row, item.Progress).FillWidth().Height(4) + } + }) + } + }) +} + +// refresh remakes the words of a row that depend on the item when they changed. +func (r *rowText) refresh(item *Item, removeLabel, retryLabel string) *rowText { + if r.size != item.Size || r.sizeAt == "" && item.Size > 0 { + r.size, r.sizeAt = item.Size, "" + if item.Size > 0 { + r.sizeAt = formatSize(item.Size) + } + } + if r.name != item.Name || r.labels != [2]string{removeLabel, retryLabel} { + r.name, r.labels = item.Name, [2]string{removeLabel, retryLabel} + r.remove = removeLabel + " " + item.Name + r.retry = retryLabel + " " + item.Name + } + return r +} + +// formatSize writes a length in bytes in the largest unit that keeps it above +// one, with one decimal for kilobytes and up. +func formatSize(n int64) string { + const unit = 1024 + if n < unit { + return strconv.FormatInt(n, 10) + " B" + } + value, suffix := float64(n), "" + for _, s := range [...]string{"KB", "MB", "GB", "TB"} { + value /= unit + suffix = s + if value < unit { + break + } + } + return strconv.FormatFloat(value, 'f', 1, 64) + " " + suffix +} diff --git a/ui/upload/upload_test.go b/ui/upload/upload_test.go new file mode 100644 index 000000000..43f81ae13 --- /dev/null +++ b/ui/upload/upload_test.go @@ -0,0 +1,254 @@ +package upload_test + +import ( + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/upload" +) + +type model struct { + up *upload.Upload + spec upload.Spec + added []string + rejected []string + removed []int + retried []int +} + +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(16).Children(func() { + m.up.View(c, "Attachments", m.spec).FillWidth() + for _, f := range m.up.Added() { + m.added = append(m.added, f.Name()) + } + for _, f := range m.up.Rejected() { + m.rejected = append(m.rejected, f.Name()) + } + if i, ok := m.up.Removed(); ok { + m.removed = append(m.removed, i) + } + if i, ok := m.up.Retried(); ok { + m.retried = append(m.retried, i) + } + }) +} + +type driver struct { + t *testing.T + *app.Driver +} + +func open(t *testing.T, m *model) driver { + t.Helper() + m.up = upload.New() + page := ui.NewPage(ui.PageConfig{View: m.page}) + d, err := app.NewDriver(ui.Configure(page, app.Config{Width: 480, Height: 480, Invalidator: new(app.Invalidator)}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(d.Close) + return driver{t, d} +} + +func (d driver) areaPoint() (float32, float32) { + d.t.Helper() + for _, text := range d.Snapshot().Texts { + if text.Value == "Drag files here" { + return text.Bounds.X + text.Bounds.Width/2, text.Bounds.Y + text.Bounds.Height/2 + } + } + d.t.Fatal("the area's title is not painted") + return 0, 0 +} + +func (d driver) drop(paths ...string) { + d.t.Helper() + x, y := d.areaPoint() + if _, err := d.Drop(gfx.FileDropEvent{Phase: gfx.FileDropOver, X: x, Y: y}); err != nil { + d.t.Fatal(err) + } + if taken, err := d.Drop(gfx.FileDropEvent{Phase: gfx.FileDropDrop, X: x, Y: y, Paths: paths}); err != nil || !taken { + d.t.Fatalf("the area did not take the drop: %v %v", taken, err) + } + if err := d.Pump(); err != nil { + d.t.Fatal(err) + } +} + +func (d driver) click(label string) { + d.t.Helper() + hits := d.Snapshot().Hits + for i := len(hits) - 1; i >= 0; i-- { + if h := hits[i]; h.Label == label && !h.IsLabel && !h.ID.IsZero() { + if err := d.Click(h.Bounds.X+h.Bounds.Width/2, h.Bounds.Y+h.Bounds.Height/2); err != nil { + d.t.Fatal(err) + } + return + } + } + d.t.Fatalf("no control labeled %q", label) +} + +func files(t *testing.T, names ...string) []string { + t.Helper() + if runtime.GOOS == "js" { + t.Skip("a browser gives dropped files without paths, so a test cannot drop them by path") + } + dir := t.TempDir() + var paths []string + for _, name := range names { + path := filepath.Join(dir, name) + if filepath.Ext(name) == "" && name[len(name)-1] == '/' { + path = filepath.Join(dir, name) + if err := os.Mkdir(path, 0o700); err != nil { + t.Fatal(err) + } + } else if err := os.WriteFile(path, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + paths = append(paths, path) + } + return paths +} + +func equal(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func TestDroppedFilesAreAddedOrRejectedByAccept(t *testing.T) { + m := &model{spec: upload.Spec{Multiple: true, Accept: []string{".png", ".jpg"}}} + d := open(t, m) + d.drop(files(t, "a.PNG", "b.txt", "c.jpg")...) + if want := []string{"a.PNG", "c.jpg"}; !equal(m.added, want) { + t.Errorf("added %v, want %v", m.added, want) + } + if want := []string{"b.txt"}; !equal(m.rejected, want) { + t.Errorf("rejected %v, want %v", m.rejected, want) + } +} + +func TestSingleBatchTakesOnlyTheFirstFile(t *testing.T) { + m := &model{} + d := open(t, m) + d.drop(files(t, "a.txt", "b.txt")...) + if !equal(m.added, []string{"a.txt"}) || !equal(m.rejected, []string{"b.txt"}) { + t.Errorf("added %v rejected %v", m.added, m.rejected) + } +} + +func TestLimitCountsTheItemsAlreadyInTheList(t *testing.T) { + m := &model{spec: upload.Spec{Multiple: true, Limit: 3, Items: []upload.Item{{Name: "x"}, {Name: "y"}}}} + d := open(t, m) + d.drop(files(t, "a.txt", "b.txt")...) + if !equal(m.added, []string{"a.txt"}) || !equal(m.rejected, []string{"b.txt"}) { + t.Errorf("added %v rejected %v", m.added, m.rejected) + } +} + +func TestFoldersAreRejected(t *testing.T) { + m := &model{spec: upload.Spec{Multiple: true}} + d := open(t, m) + d.drop(files(t, "dir/", "a.txt")...) + if !equal(m.added, []string{"a.txt"}) || !equal(m.rejected, []string{"dir"}) { + t.Errorf("added %v rejected %v", m.added, m.rejected) + } +} + +func TestDisabledAreaTakesNothing(t *testing.T) { + m := &model{spec: upload.Spec{Disabled: true}} + d := open(t, m) + x, y := d.areaPoint() + if taken, err := d.Drop(gfx.FileDropEvent{Phase: gfx.FileDropOver, X: x, Y: y}); err != nil || taken { + t.Fatalf("a disabled area took files: %v %v", taken, err) + } +} + +func TestRemoveAndRetryReportTheRow(t *testing.T) { + m := &model{spec: upload.Spec{Items: []upload.Item{ + {Name: "a.txt", Size: 10, Status: upload.Done}, + {Name: "b.txt", Size: 2048, Status: upload.Failed, Error: "Network error"}, + {Name: "c.txt", Status: upload.Uploading, Progress: 0.5}, + }}} + d := open(t, m) + d.click("Retry b.txt") + d.click("Remove c.txt") + if len(m.retried) != 1 || m.retried[0] != 1 { + t.Errorf("retried %v, want [1]", m.retried) + } + if len(m.removed) != 1 || m.removed[0] != 2 { + t.Errorf("removed %v, want [2]", m.removed) + } +} + +func TestOnlyFailedItemsOfferRetry(t *testing.T) { + m := &model{spec: upload.Spec{Items: []upload.Item{{Name: "a.txt", Status: upload.Done}}}} + d := open(t, m) + for _, h := range d.Snapshot().Hits { + if h.Label == "Retry a.txt" { + t.Fatal("a finished item offers retry") + } + } +} + +func warmView() (func(), *model) { + m := &model{up: upload.New(), spec: upload.Spec{Multiple: true, Hint: "PNG", Items: []upload.Item{ + {Name: "a.txt", Size: 10, Status: upload.Done}, + {Name: "b.txt", Size: 2048, Status: upload.Failed, Error: "Network error"}, + {Name: "c.txt", Size: 1 << 20, Status: upload.Uploading, Progress: 0.5}, + }}} + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: m.page, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + return func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 480, Height: 480}, m.page) + canvas.EndFrame() + }, m +} + +func TestWarmPaintDoesNotAllocate(t *testing.T) { + draw, _ := warmView() + draw() + if n := testing.AllocsPerRun(100, draw); n != 0 { + t.Fatalf("a warm paint allocates %v times", n) + } +} + +func BenchmarkViewPaint(b *testing.B) { + draw, _ := warmView() + draw() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + draw() + } +} + +func TestFormatSizeGrowsByUnit(t *testing.T) { + m := &model{spec: upload.Spec{Items: []upload.Item{{Name: "a", Size: 512}, {Name: "b", Size: 1536}, {Name: "c", Size: 5 << 20}}}} + d := open(t, m) + seen := map[string]bool{} + for _, text := range d.Snapshot().Texts { + seen[text.Value] = true + } + for _, want := range []string{"512 B", "1.5 KB", "5.0 MB"} { + if !seen[want] { + t.Errorf("no %q among the painted texts", want) + } + } +} diff --git a/ui/validate/validate.go b/ui/validate/validate.go new file mode 100644 index 000000000..840704a55 --- /dev/null +++ b/ui/validate/validate.go @@ -0,0 +1,156 @@ +// Package validate is the opt-in set of rules a form checks a text value +// against: required, length, range, pattern, e-mail and URL, each with the +// message the field shows when the rule fails. A rule is a function from the +// value to a message, empty when the value passes, so an application's own rule +// is a plain function of the same shape. A page builds its rules once, in the +// model, and checks them when the value changes or the form is submitted: +// +// m.nameRules = []validate.Rule{ +// validate.Required("Enter a name"), +// validate.MaxLength(32, "At most 32 characters"), +// } +// // when the value changes, or on submit: +// ok := validate.Apply(&m.nameField, m.name, m.nameRules) +// +// Check returns the message of the first failing rule, in the order given; +// Apply puts it in a FormFieldState's Error and Invalid, so the field shows the +// message under the control. Lengths count characters (runes), as the text +// field's MaxLength does, and the rules other than Required pass an empty value: +// an optional field is checked only once something is entered. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Rules are closures made once; checking a value with them, URL +// aside, does not allocate. +package validate + +import ( + "net/url" + "regexp" + "strconv" + "strings" + "unicode/utf8" + + "github.com/vivaui/viva/ui" +) + +// Rule checks a value and returns the message to show when it fails, or the +// empty string when it passes. +type Rule func(value string) string + +// Required fails a value that is empty after trimming white space. +func Required(message string) Rule { + return func(value string) string { + if strings.TrimSpace(value) == "" { + return message + } + return "" + } +} + +// MinLength fails a non-empty value shorter than n characters. +func MinLength(n int, message string) Rule { + return func(value string) string { + if value != "" && utf8.RuneCountInString(value) < n { + return message + } + return "" + } +} + +// MaxLength fails a value longer than n characters. +func MaxLength(n int, message string) Rule { + return func(value string) string { + if utf8.RuneCountInString(value) > n { + return message + } + return "" + } +} + +// Min fails a non-empty value that is not a number or is less than n. +func Min(n float64, message string) Rule { + return func(value string) string { + if value == "" { + return "" + } + if v, err := strconv.ParseFloat(strings.TrimSpace(value), 64); err != nil || v < n { + return message + } + return "" + } +} + +// Max fails a non-empty value that is not a number or is greater than n. +func Max(n float64, message string) Rule { + return func(value string) string { + if value == "" { + return "" + } + if v, err := strconv.ParseFloat(strings.TrimSpace(value), 64); err != nil || v > n { + return message + } + return "" + } +} + +// Pattern fails a non-empty value that does not match re. +func Pattern(re *regexp.Regexp, message string) Rule { + return func(value string) string { + if value != "" && !re.MatchString(value) { + return message + } + return "" + } +} + +// Email fails a non-empty value that is not a bare e-mail address: a local +// part, one "@" and a dotted host, with no white space or angle brackets. +func Email(message string) Rule { + return func(value string) string { + if value == "" { + return "" + } + at := strings.IndexByte(value, '@') + if at <= 0 || strings.ContainsAny(value, " \t\r\n<>,;\"") || strings.IndexByte(value[at+1:], '@') >= 0 { + return message + } + host := value[at+1:] + if !strings.Contains(host, ".") || strings.HasPrefix(host, ".") || strings.HasSuffix(host, ".") || strings.Contains(host, "..") { + return message + } + return "" + } +} + +// URL fails a non-empty value that is not an absolute URL with a scheme and a +// host. +func URL(message string) Rule { + return func(value string) string { + if value == "" { + return "" + } + if u, err := url.Parse(value); err != nil || u.Scheme == "" || u.Host == "" { + return message + } + return "" + } +} + +// Check returns the message of the first rule that fails value, or the empty +// string when all pass. +func Check(value string, rules []Rule) string { + for _, rule := range rules { + if message := rule(value); message != "" { + return message + } + } + return "" +} + +// Apply checks value and puts the result in the field's Error and Invalid. It +// reports whether the value passed. +func Apply(field *ui.FormFieldState, value string, rules []Rule) bool { + field.Error = Check(value, rules) + field.Invalid = field.Error != "" + return !field.Invalid +} diff --git a/ui/validate/validate_test.go b/ui/validate/validate_test.go new file mode 100644 index 000000000..7673fd9e2 --- /dev/null +++ b/ui/validate/validate_test.go @@ -0,0 +1,79 @@ +package validate_test + +import ( + "regexp" + "testing" + + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/validate" +) + +func TestRules(t *testing.T) { + re := regexp.MustCompile(`^[a-z]+$`) + cases := []struct { + name string + rule validate.Rule + pass []string + fails []string + }{ + {"required", validate.Required("m"), []string{"a"}, []string{"", " \t"}}, + {"minlength", validate.MinLength(3, "m"), []string{"", "abc", "你好吗"}, []string{"ab", "你好"}}, + {"maxlength", validate.MaxLength(2, "m"), []string{"", "ab", "你好"}, []string{"abc", "你好吗"}}, + {"min", validate.Min(1, "m"), []string{"", "1", " 2.5 "}, []string{"0", "x"}}, + {"max", validate.Max(10, "m"), []string{"", "10", "-3"}, []string{"11", "x"}}, + {"pattern", validate.Pattern(re, "m"), []string{"", "abc"}, []string{"ab1"}}, + {"email", validate.Email("m"), []string{"", "a@b.co"}, []string{"a", "A ", "a@"}}, + {"url", validate.URL("m"), []string{"", "https://x.dev/p?q=1"}, []string{"x.dev", "https://", "/p"}}, + } + for _, c := range cases { + for _, v := range c.pass { + if got := c.rule(v); got != "" { + t.Errorf("%s(%q) = %q, want pass", c.name, v, got) + } + } + for _, v := range c.fails { + if got := c.rule(v); got != "m" { + t.Errorf("%s(%q) = %q, want failure", c.name, v, got) + } + } + } +} + +func TestCheckReportsFirstFailureInOrder(t *testing.T) { + rules := []validate.Rule{validate.Required("req"), validate.MinLength(3, "short")} + if got := validate.Check("", rules); got != "req" { + t.Errorf("empty = %q, want req", got) + } + if got := validate.Check("ab", rules); got != "short" { + t.Errorf("ab = %q, want short", got) + } + if got := validate.Check("abc", rules); got != "" { + t.Errorf("abc = %q, want pass", got) + } +} + +func TestApplySetsAndClearsTheField(t *testing.T) { + var f ui.FormFieldState + rules := []validate.Rule{validate.Required("req")} + if validate.Apply(&f, "", rules) || f.Error != "req" || !f.Invalid { + t.Fatalf("failing value left the field %+v", f) + } + if !validate.Apply(&f, "x", rules) || f.Error != "" || f.Invalid { + t.Fatalf("passing value left the field %+v", f) + } +} + +func TestCheckDoesNotAllocate(t *testing.T) { + rules := []validate.Rule{validate.Required("r"), validate.MaxLength(8, "l"), validate.Email("e")} + if n := testing.AllocsPerRun(100, func() { validate.Check("a@b.co", rules) }); n != 0 { + t.Fatalf("Check allocates %v times", n) + } +} + +func BenchmarkCheck(b *testing.B) { + rules := []validate.Rule{validate.Required("r"), validate.MaxLength(32, "l"), validate.Email("e")} + b.ReportAllocs() + for i := 0; i < b.N; i++ { + validate.Check("user@example.com", rules) + } +} diff --git a/ui/validation_options_test.go b/ui/validation_options_test.go index 9a3769bd1..5ae990fac 100644 --- a/ui/validation_options_test.go +++ b/ui/validation_options_test.go @@ -68,9 +68,9 @@ func TestInvalidPageControlsCarryTheSemanticState(t *testing.T) { case "select": ui.Select(c, &size, []string{"S", "M"}, nil).Placeholder("Size").Invalid(true) case "text field": - ui.TextFieldID(c, gfx.Item(1), &field, "Email", "") + ui.TextField(c, &field, "Email", "", ui.WithID(gfx.Item(1))) case "text area": - ui.TextAreaID(c, gfx.Item(1), &field, "Notes", "") + ui.TextArea(c, &field, "Notes", "", ui.WithID(gfx.Item(1))) case "combobox": ui.Combobox(c, &framework, []string{"Go", "Rust"}, func(value string) string { return value }, "Framework").Invalid(true) } diff --git a/ui/vocab.go b/ui/vocab.go index 2b09d7d27..6d7bb2142 100644 --- a/ui/vocab.go +++ b/ui/vocab.go @@ -25,11 +25,31 @@ const ( ExtraLarge = base.ExtraLarge // from 1600: wide screens ) +// Status is the outcome a control reports through color, one vocabulary for an +// alert, a tag and a field. +type Status = style.Status + +const ( + StatusDefault = style.StatusDefault + StatusSuccess = style.StatusSuccess + StatusWarning = style.StatusWarning + StatusDanger = style.StatusDanger +) + type Rect = base.Rect type Size = base.Size type Point = base.Point type Theme = base.Theme +// SelectGroup is a group of a Select's options with a heading; see Box.OptionGroups. +type SelectGroup = base.SelectGroup + +// SliderMark is a value of a Slider's range marked on its track; see Box.Marks. +type SliderMark = base.SliderMark + +// Option is a setting a control takes after its fixed arguments, as WithID. +type Option = base.Option + // LightTheme is the light theme. func LightTheme() Theme { return base.LightTheme() } diff --git a/ui/warning_test.go b/ui/warning_test.go new file mode 100644 index 000000000..ab8813078 --- /dev/null +++ b/ui/warning_test.go @@ -0,0 +1,89 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// hasColor reports whether any primitive of the page is painted in color. +func hasColor(d *pageDriver, color gfx.Color) bool { + for _, primitive := range d.driver.Snapshot().Primitives { + if primitive.Color == color { + return true + } + } + return false +} + +// A TextField or TextArea marked Warning takes the warning border; a field that is +// also Invalid brings the destructive one, which wins; Warning(false) takes it away. +func TestWarningBorderOfTextControls(t *testing.T) { + warning := pageTheme.Warning + for _, kind := range []string{"text field", "text area"} { + t.Run(kind, func(t *testing.T) { + var field ui.Field + warn, invalid := false, false + d := openPage(t, func(c ui.C) { + field.Invalid = invalid + var box ui.Box + if kind == "text field" { + box = ui.TextField(c, &field, "Name", "") + } else { + box = ui.TextArea(c, &field, "Name", "").Height(80) + } + box.Warning(warn) + }) + if hasColor(d, warning) { + t.Fatal("a control that is not marked paints the warning color") + } + warn = true + d.repaint() + if !hasColor(d, warning) || hasColor(d, pageTheme.Danger) { + t.Fatalf("a warned control: warning painted %v, danger painted %v; want true, false", hasColor(d, warning), hasColor(d, pageTheme.Danger)) + } + invalid = true + d.repaint() + if hasColor(d, warning) || !hasColor(d, pageTheme.Danger) { + t.Fatalf("a control both warned and invalid: warning painted %v, danger painted %v; want false, true", hasColor(d, warning), hasColor(d, pageTheme.Danger)) + } + warn, invalid = false, false + d.repaint() + if hasColor(d, warning) || hasColor(d, pageTheme.Danger) { + t.Fatal("Warning(false) left a warning border") + } + }) + } +} + +// A *Field takes Warning where the model is made, as it takes Invalid. +func TestFieldWarning(t *testing.T) { + var field ui.Field + field.Warning = true + d := openPage(t, func(c ui.C) { ui.TextField(c, &field, "Name", "") }) + if !hasColor(d, pageTheme.Warning) { + t.Fatal("a Field with Warning set paints no warning border") + } +} + +// A Progress takes the color of its status for its fill, and the primary without one. +func TestProgressStatusColorsTheFill(t *testing.T) { + for name, test := range map[string]struct { + status ui.Status + want gfx.Color + }{ + "default": {ui.StatusDefault, pageTheme.Primary}, + "success": {ui.StatusSuccess, pageTheme.Success}, + "warning": {ui.StatusWarning, pageTheme.Warning}, + "danger": {ui.StatusDanger, pageTheme.Danger}, + } { + d := openPage(t, func(c ui.C) { ui.Progress(c, 0.5).Status(test.status).Width(200) }) + if !hasColor(d, test.want) { + t.Fatalf("%s: the fill is not painted in %+v", name, test.want) + } + if test.status != ui.StatusDefault && hasColor(d, pageTheme.Primary) { + t.Fatalf("%s: the fill kept the primary color", name) + } + } +} diff --git a/update/install_windows.go b/update/install_windows.go index 9baf81fa9..1e88f195a 100644 --- a/update/install_windows.go +++ b/update/install_windows.go @@ -154,8 +154,9 @@ func install(options InstallOptions, quit func()) error { // installPayload replaces the application's files from a staged payload: the // executable and the folders beside it that a patch wrote. The installer and -// its uninstaller are not run, so shortcuts, registry entries and anything -// else the installer owns stay as they are. A writable install directory is +// its uninstaller are not run, so shortcuts and the other registry entries the +// installer owns stay as they are; only its Add or Remove Programs entry is +// brought up to date with the new version. A writable install directory is // required; a machine-wide installation under Program Files is refused before // anything changes. func installPayload(options InstallOptions, quit func()) error { @@ -195,7 +196,7 @@ func installPayload(options InstallOptions, quit func()) error { return fmt.Errorf("update: staging the payload: %w", err) } options.report("replacing") - if err := startPayload(os.Getpid(), staged, installDir, executable, options.Args); err != nil { + if err := startPayload(os.Getpid(), staged, installDir, executable, options.Version, options.Args); err != nil { _ = os.RemoveAll(staged) return fmt.Errorf("update: start the update helper: %w", err) } @@ -224,8 +225,8 @@ var startPayload = startPayloadHelper // process to exit, copies the staged files over the installation and starts // the new program. It moves every file it replaces to a same-volume backup until // the new version has started, and restores them if it fails. -func startPayloadHelper(parentPID int, payload, installDir, executable string, args []string) error { - name, arguments := helperCommand(payloadHelperScript(parentPID, payload, installDir, executable, args)) +func startPayloadHelper(parentPID int, payload, installDir, executable, version string, args []string) error { + name, arguments := helperCommand(payloadHelperScript(parentPID, payload, installDir, executable, version, args)) command := exec.Command(name, arguments...) command.SysProcAttr = helperSysProcAttr() if err := command.Start(); err != nil { @@ -236,14 +237,17 @@ func startPayloadHelper(parentPID int, payload, installDir, executable string, a } // payloadHelperScript builds the script the payload helper runs. Every path is -// a PowerShell single-quoted literal. -func payloadHelperScript(parentPID int, payload, installDir, executable string, args []string) string { +// a PowerShell single-quoted literal. A version, when there is one, is written +// to the installer's Add or Remove Programs entry once the new files are in +// place. +func payloadHelperScript(parentPID int, payload, installDir, executable, version string, args []string) string { var script strings.Builder script.WriteString("$ErrorActionPreference = 'Stop'\n") fmt.Fprintf(&script, "$parent = %d\n", parentPID) fmt.Fprintf(&script, "$payload = %s\n", powerShellQuote(payload)) fmt.Fprintf(&script, "$dir = %s\n", powerShellQuote(installDir)) fmt.Fprintf(&script, "$exe = %s\n", powerShellQuote(executable)) + fmt.Fprintf(&script, "$version = %s\n", powerShellQuote(strings.TrimLeft(version, "vV"))) script.WriteString("$backup = Join-Path $dir ('.viva-update-' + [guid]::NewGuid().ToString('N'))\n") script.WriteString("$created = New-Object System.Collections.ArrayList\n") script.WriteString("$temps = New-Object System.Collections.ArrayList\n") @@ -260,6 +264,30 @@ func payloadHelperScript(parentPID int, payload, installDir, executable string, script.WriteString(" foreach ($rel in $created) { Remove-Item -LiteralPath (Join-Path $dir $rel) -Force -ErrorAction SilentlyContinue }\n") script.WriteString(" foreach ($tmp in $temps) { Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue }\n") script.WriteString("}\n") + // The NSIS installer wrote DisplayVersion and EstimatedSize once and the + // payload path never runs it, so a package manager that detects the + // installed version through that entry (winget) would offer the update + // again. The entry is found by its InstallLocation, in the user hive and the + // machine hive alike; one that cannot be written, as a machine-wide + // installation's cannot be by a user process, is left alone, and a failure + // here never undoes an update that has already worked. + script.WriteString("function Register {\n") + script.WriteString(" if (-not $version) { return }\n") + script.WriteString(" try {\n") + script.WriteString(" $bytes = (Get-ChildItem -LiteralPath $dir -Recurse -File -Force | Where-Object { -not $_.FullName.StartsWith($backup, [StringComparison]::OrdinalIgnoreCase) } | Measure-Object -Property Length -Sum).Sum\n") + script.WriteString(" $kilobytes = [int][math]::Ceiling($bytes / 1024)\n") + script.WriteString(" foreach ($hive in 'HKCU:', 'HKLM:') {\n") + script.WriteString(" Get-ChildItem -LiteralPath ($hive + '\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall') -ErrorAction SilentlyContinue | ForEach-Object {\n") + script.WriteString(" if (([string]$_.GetValue('InstallLocation')).TrimEnd('\\') -ieq $dir.TrimEnd('\\')) {\n") + script.WriteString(" try {\n") + script.WriteString(" Set-ItemProperty -LiteralPath $_.PSPath -Name 'DisplayVersion' -Value $version -ErrorAction Stop\n") + script.WriteString(" Set-ItemProperty -LiteralPath $_.PSPath -Name 'EstimatedSize' -Value $kilobytes -Type DWord -ErrorAction Stop\n") + script.WriteString(" } catch {}\n") + script.WriteString(" }\n") + script.WriteString(" }\n") + script.WriteString(" }\n") + script.WriteString(" } catch {}\n") + script.WriteString("}\n") // The payload is the helper's own copy (stagePayloadDir): it is deleted on every // way out, so a failed update leaves nothing behind either. script.WriteString("function Discard { Remove-Item -LiteralPath $payload -Recurse -Force -ErrorAction SilentlyContinue }\n") @@ -312,6 +340,7 @@ func payloadHelperScript(parentPID int, payload, installDir, executable string, script.WriteString("\n") script.WriteString(" Start-Sleep -Seconds 2\n") script.WriteString(" if ($p.HasExited -and $p.ExitCode -ne 0) { Restore; Launch; Discard; exit 1 }\n") + script.WriteString(" Register\n") script.WriteString("} catch { Restore; Launch; Discard; exit 1 }\n") script.WriteString("Remove-Item -Recurse -Force $backup -ErrorAction SilentlyContinue\n") script.WriteString("Discard\n") diff --git a/update/install_windows_test.go b/update/install_windows_test.go index d82dca3b5..9f0d1bd21 100644 --- a/update/install_windows_test.go +++ b/update/install_windows_test.go @@ -14,6 +14,8 @@ import ( "testing" "time" "unsafe" + + "golang.org/x/sys/windows/registry" ) func TestInstallRejectsNonNSISFormat(t *testing.T) { @@ -216,7 +218,7 @@ func TestWinTrustStructLayout(t *testing.T) { } func TestPayloadHelperScriptKeepsABackupAndRestores(t *testing.T) { - script := payloadHelperScript(1234, `C:\Temp\O'Brien\payload`, `C:\Apps\Motty`, `C:\Apps\Motty\motty.exe`, []string{"--flag", "a b"}) + script := payloadHelperScript(1234, `C:\Temp\O'Brien\payload`, `C:\Apps\Motty`, `C:\Apps\Motty\motty.exe`, "v1.2.3", []string{"--flag", "a b"}) for _, want := range []string{ "$parent = 1234", `$payload = 'C:\Temp\O''Brien\payload'`, @@ -286,7 +288,7 @@ func TestInstallPayloadHandsTheHelperACopyTheCallerMayDelete(t *testing.T) { } var started string previous := startPayload - startPayload = func(_ int, staged, _, _ string, _ []string) error { + startPayload = func(_ int, staged, _, _, _ string, _ []string) error { started = staged return nil } @@ -325,7 +327,7 @@ func TestInstallPayloadDeletesItsCopyWhenTheHelperDoesNotStart(t *testing.T) { copyWindowsFile(t, systemExecutable(t, "whoami.exe"), filepath.Join(payload, filepath.Base(executable))) var started string previous := startPayload - startPayload = func(_ int, staged, _, _ string, _ []string) error { + startPayload = func(_ int, staged, _, _, _ string, _ []string) error { started = staged return errors.New("no helper") } @@ -359,7 +361,7 @@ func TestPayloadHelperRelaunchesTheOldVersionWithoutAPayload(t *testing.T) { marker := filepath.Join(t.TempDir(), "started") t.Setenv("VIVA_UPDATE_START_MARKER", marker) missing := filepath.Join(t.TempDir(), "gone") - script := payloadHelperScript(999999, missing, install, filepath.Join(install, "app.exe"), []string{"-test.run=^TestPayloadHelperProcess$"}) + script := payloadHelperScript(999999, missing, install, filepath.Join(install, "app.exe"), "", []string{"-test.run=^TestPayloadHelperProcess$"}) runPayloadHelper(t, script, 1) waitForMarker(t, marker) got, err := os.ReadFile(filepath.Join(install, "app.exe")) @@ -448,7 +450,7 @@ func TestPayloadHelperReplacesTheApplication(t *testing.T) { if err := os.WriteFile(filepath.Join(stale, "app.exe"), []byte("stale"), 0o644); err != nil { t.Fatal(err) } - script := payloadHelperScript(999999, payload, install, filepath.Join(install, "app.exe"), nil) + script := payloadHelperScript(999999, payload, install, filepath.Join(install, "app.exe"), "", nil) runPayloadHelper(t, script, 0) if _, err := os.Stat(stale); !os.IsNotExist(err) { t.Errorf("a previous update's backup survived the next update: %v", err) @@ -475,12 +477,72 @@ func TestPayloadHelperReplacesTheApplication(t *testing.T) { } } +// uninstallEntry creates a per-user Add or Remove Programs entry the way the +// NSIS installer writes one and removes it when the test ends. +func uninstallEntry(t *testing.T, name, location string) registry.Key { + t.Helper() + path := `Software\Microsoft\Windows\CurrentVersion\Uninstall\` + name + key, _, err := registry.CreateKey(registry.CURRENT_USER, path, registry.SET_VALUE|registry.QUERY_VALUE) + if err != nil { + t.Skipf("the per-user registry is not writable: %v", err) + } + t.Cleanup(func() { + _ = key.Close() + _ = registry.DeleteKey(registry.CURRENT_USER, path) + }) + if err := key.SetStringValue("DisplayVersion", "1.0.0"); err != nil { + t.Fatal(err) + } + if err := key.SetStringValue("InstallLocation", location); err != nil { + t.Fatal(err) + } + if err := key.SetDWordValue("EstimatedSize", 1); err != nil { + t.Fatal(err) + } + return key +} + +func TestPayloadHelperBringsTheInstallersRegistrationUpToDate(t *testing.T) { + payload := t.TempDir() + install := t.TempDir() + copyWindowsFile(t, systemExecutable(t, "cmd.exe"), filepath.Join(install, "app.exe")) + copyWindowsFile(t, systemExecutable(t, "whoami.exe"), filepath.Join(payload, "app.exe")) + ours := uninstallEntry(t, "viva-update-test-ours", install+`\`) + other := uninstallEntry(t, "viva-update-test-other", filepath.Join(t.TempDir(), "elsewhere")) + + runPayloadHelper(t, payloadHelperScript(999999, payload, install, filepath.Join(install, "app.exe"), "v2.0.0", nil), 0) + + if version, _, err := ours.GetStringValue("DisplayVersion"); err != nil || version != "2.0.0" { + t.Errorf("DisplayVersion = %q, %v; want the installed version 2.0.0", version, err) + } + if size, _, err := ours.GetIntegerValue("EstimatedSize"); err != nil || size <= 1 { + t.Errorf("EstimatedSize = %d, %v; want the size of the new files", size, err) + } + if version, _, err := other.GetStringValue("DisplayVersion"); err != nil || version != "1.0.0" { + t.Errorf("an entry for another installation changed: %q, %v", version, err) + } +} + +func TestPayloadHelperWithoutAVersionLeavesTheRegistrationAlone(t *testing.T) { + payload := t.TempDir() + install := t.TempDir() + copyWindowsFile(t, systemExecutable(t, "cmd.exe"), filepath.Join(install, "app.exe")) + copyWindowsFile(t, systemExecutable(t, "whoami.exe"), filepath.Join(payload, "app.exe")) + ours := uninstallEntry(t, "viva-update-test-unversioned", install) + + runPayloadHelper(t, payloadHelperScript(999999, payload, install, filepath.Join(install, "app.exe"), "", nil), 0) + + if version, _, err := ours.GetStringValue("DisplayVersion"); err != nil || version != "1.0.0" { + t.Errorf("DisplayVersion = %q, %v; want it untouched without a version", version, err) + } +} + func TestStartPayloadHelperInstallsWithoutOutputPipes(t *testing.T) { payload, install := t.TempDir(), t.TempDir() executable := filepath.Join(install, "app.exe") copyWindowsFile(t, systemExecutable(t, "cmd.exe"), executable) want := copyWindowsFile(t, systemExecutable(t, "whoami.exe"), filepath.Join(payload, "app.exe")) - if err := startPayloadHelper(999999, payload, install, executable, nil); err != nil { + if err := startPayloadHelper(999999, payload, install, executable, "", nil); err != nil { t.Fatal(err) } deadline := time.Now().Add(15 * time.Second) @@ -531,7 +593,7 @@ func TestPayloadHelperReplacesARunningExecutable(t *testing.T) { } } - script := payloadHelperScript(999999, payload, install, filepath.Join(install, "app.exe"), nil) + script := payloadHelperScript(999999, payload, install, filepath.Join(install, "app.exe"), "", nil) runPayloadHelper(t, script, 0) got, err := os.ReadFile(filepath.Join(install, "app.exe")) if err != nil { @@ -571,7 +633,7 @@ func TestPayloadHelperRollsBackAFailedStart(t *testing.T) { if err := os.WriteFile(filepath.Join(payload, "new.dll"), []byte("new"), 0o644); err != nil { t.Fatal(err) } - script := payloadHelperScript(999999, payload, install, filepath.Join(install, "app.exe"), []string{"-test.run=^TestPayloadHelperProcess$"}) + script := payloadHelperScript(999999, payload, install, filepath.Join(install, "app.exe"), "", []string{"-test.run=^TestPayloadHelperProcess$"}) runPayloadHelper(t, script, 1) if data, err := os.ReadFile(marker); err != nil || string(data) != "started" { t.Fatalf("updated application did not start: marker=%q, %v", data, err) diff --git a/website/content/guides/en/components.md b/website/content/guides/en/components.md index db6f605dd..a6eaca8c7 100644 --- a/website/content/guides/en/components.md +++ b/website/content/guides/en/components.md @@ -27,7 +27,7 @@ A page control for a heavy or stateful component lives in its own package under - Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid` - Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard` -- Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup` +- Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer` `ui/textview` displays read-only text that the user can select and copy, such as logs and process output. Keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`; `textview.Strings` adapts a string slice. The caller owns the lines, styles and actions. The view owns selection and drawing without an editing or undo model. diff --git a/website/content/guides/en/declarative-layout.md b/website/content/guides/en/declarative-layout.md index d16d78bf7..c397f7065 100644 --- a/website/content/guides/en/declarative-layout.md +++ b/website/content/guides/en/declarative-layout.md @@ -338,11 +338,13 @@ func (m *model) page(c ui.C) { ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { ui.Text(c, "Servers").FontSize(20).Bold() table := ui.Table(c, &m.table, ui.TableSpec{ - Headers: []string{"Name", "State", "Region"}, - Sortable: []bool{true, true, true}, - Source: &m.rows, - Striped: true, - Columns: []ui.TableColumn{{Width: 200}, {Width: 120}, {}}, + Source: &m.rows, + Striped: true, + Columns: []ui.TableColumn{ + {Title: "Name", Width: 200, Sortable: true}, + {Title: "State", Width: 120, Sortable: true}, + {Title: "Region", Sortable: true}, + }, }) if column, ok := table.HeaderClicked(); ok { m.table.SortBy(column) diff --git a/website/content/guides/en/getting-started.md b/website/content/guides/en/getting-started.md index d17452c6b..d626db121 100644 --- a/website/content/guides/en/getting-started.md +++ b/website/content/guides/en/getting-started.md @@ -22,7 +22,7 @@ go mod init example.com/hello go get github.com/vivaui/viva ``` -`go get` without a version resolves to the latest tagged release, which is `v0.6.7`. Pin it by naming the version: `go get github.com/vivaui/viva@v0.6.7`. Viva is not yet at 1.0, so the API in `go.mod` can still change between minor releases; read the release notes before upgrading. +`go get` without a version resolves to the latest tagged release, which is `v0.6.8`. Pin it by naming the version: `go get github.com/vivaui/viva@v0.6.8`. Viva is not yet at 1.0, so the API in `go.mod` can still change between minor releases; read the release notes before upgrading. If you are working on Viva itself rather than using it, `replace` it with your checkout instead: diff --git a/website/content/guides/en/overlays.md b/website/content/guides/en/overlays.md index f4502a395..16b5a55b4 100644 --- a/website/content/guides/en/overlays.md +++ b/website/content/guides/en/overlays.md @@ -41,7 +41,7 @@ func (m *model) page(c ui.C) { // A popover hangs off its anchor while menuOpen is true. A press outside it // or Escape closes it, and the press goes on to what is under the pointer; // the focus goes back to the anchor. - ui.PopoverWith(c, actions, &m.menuOpen, ui.PopoverSpec{Width: 180, Align: ui.Start}, func() { + ui.Popover(c, actions, &m.menuOpen, ui.PopoverSpec{Width: 180, Align: ui.Start}, func() { if ui.Button(c, "New file").Ghost().Clicked() { m.menuOpen, m.status = false, "Created" } @@ -52,7 +52,7 @@ func (m *model) page(c ui.C) { // A modal dims the page and keeps the keyboard while dialogOpen is true: // Escape, a press on the dim and the close button set it to false. - ui.ModalWith(c, &m.dialogOpen, "Delete file?", ui.ModalSpec{Description: "This cannot be undone.", Width: 400}, nil, func() { + ui.Modal(c, &m.dialogOpen, "Delete file?", ui.ModalSpec{Description: "This cannot be undone.", Width: 400}, nil, func() { if ui.Button(c, "Cancel").Outline().Clicked() { m.dialogOpen = false } @@ -73,7 +73,7 @@ func main() { ## Popovers -`ui.Popover(c, anchor, &open, body)` shows the panel `body` declares, hanging off `anchor`, while `open` is true, with shadcn's popover look. `ui.PopoverWith` takes a `ui.PopoverSpec` for the side, the alignment, the width, the padding of its content and the margin it keeps from the window's edges (8 unless set) and `Instant` to open without the entrance motion, as a list appearing under the cursor as the user types. It opens below the anchor and flips above it when there is no room. Keep the trigger's `Box` (`actions := ui.Button(c, ...)`) to anchor to it. +`ui.Popover(c, anchor, &open, spec, body)` shows the panel `body` declares, hanging off `anchor`, while `open` is true, with shadcn's popover look. `spec` is a `ui.PopoverSpec`, whose zero value is the plain panel, for the side, the alignment, the width, the padding of its content and the margin it keeps from the window's edges (8 unless set) and `Instant` to open without the entrance motion, as a list appearing under the cursor as the user types. It opens below the anchor and flips above it when there is no room. Keep the trigger's `Box` (`actions := ui.Button(c, ...)`) to anchor to it. A press outside the panel or Escape sets `open` to false. The press then goes on to what is under the pointer, as a web popover's does, so one click on another button both closes the menu and presses that button. A press on the anchor only closes the panel, so a trigger that toggles `open` does not open it again in the same click. The focus goes back to where it was when the panel opened. `Popover` reports the paint that closed it; a panel that must stay open sets `open` back to true there. @@ -87,7 +87,7 @@ The example's test checks all of it: a press at the far corner closes the menu, ## Dialogs -`ui.Modal(c, &open, title, body, footer)` dims the window, paints a centered surface with the title and a close button, and keeps the keyboard while `open` is true. The title is required: it is the dialog's name for assistive technology. `body` declares the content and `footer` the buttons, which sit against the right edge in the order given; either may be nil, and the surface is as tall as the body needs. Escape, a press on the dim and the close button set `open` to false. The first control in the body takes the focus as the dialog opens (`ModalSpec.InitialFocus` names another), and the focus goes back to the control that opened it as it closes. `ui.ModalWith` takes a `ui.ModalSpec` for a description, a size or no close button. +`ui.Modal(c, &open, title, spec, body, footer)` dims the window, paints a centered surface with the title and a close button, and keeps the keyboard while `open` is true. The title is required: it is the dialog's name for assistive technology. `body` declares the content and `footer` the buttons, which sit against the right edge in the order given; either may be nil, and the surface is as tall as the body needs. Escape, a press on the dim and the close button set `open` to false. The first control in the body takes the focus as the dialog opens (`ModalSpec.InitialFocus` names another), and the focus goes back to the control that opened it as it closes. `spec` is a `ui.ModalSpec`, whose zero value is the plain dialog, for a description, a size or no close button. `ui.Dialog(c, ui.DialogSpec{...})` is the application-named form of the same dialog: `Scope` is the focus scope, `DismissID` the identity the dim and Escape report, `CloseID` the corner button's, and `InitialFocusID` the control that takes the focus. `dialog.Header(fn)` declares controls in the title row, `Body` the content and `Footer` the buttons; `Dismissed()` is true in the paint that delivers one of those clicks. diff --git a/website/content/guides/en/system-integration.md b/website/content/guides/en/system-integration.md index 278d3a3aa..5ff1165a0 100644 --- a/website/content/guides/en/system-integration.md +++ b/website/content/guides/en/system-integration.md @@ -125,7 +125,7 @@ func (m *model) page(c ui.C) { m.menuOpen = !m.menuOpen } ui.Text(c, m.status).Muted() - ui.PopoverWith(c, menu, &m.menuOpen, ui.PopoverSpec{Width: 220, Align: ui.Start}, func() { + ui.Popover(c, menu, &m.menuOpen, ui.PopoverSpec{Width: 220, Align: ui.Start}, func() { if ui.Button(c, "Say hello to the page").Ghost().Clicked() && m.view != nil { m.view.PostMessage("hello from Viva") m.menuOpen = false diff --git a/website/content/guides/en/text-input.md b/website/content/guides/en/text-input.md index bc0f87b1d..2d30bd64f 100644 --- a/website/content/guides/en/text-input.md +++ b/website/content/guides/en/text-input.md @@ -58,7 +58,11 @@ The text geometry the field declared, its bounds, font size and color, fills in ## Painting a field -A field the application already names, and whose editor it keeps, is `ui.TextFieldID(c, id, &m.searchField, label, placeholder)`, with `m.searchField.Bind(&m.search)` called once where the model is made (the `ui.Field` lives in the model, as for any field): the id is the field's identity in the page's Tree, so the window's own `TextInput` routing, an initial focus and a test address it, while the editor is the one the application reads and moves. `.NavigationKeys()` leaves Up, Down, PageUp and PageDown to the application instead of moving the caret, for a search box whose arrows move a list's selection. `.OnKey(fn)` gives the field a handler for the keys pressed while it has the keyboard, before the page routes them anywhere else: returning `Handled` claims one, and returning an empty `EventResult` leaves it to the page, so Enter can still submit. Keys that type text are never offered and always reach the field. `OnKey` implies `NavigationKeys`, since Up and Down have to reach the application for the field to claim them. +A field the application already names, and whose editor it keeps, is `ui.TextField(c, &m.searchField, label, placeholder, ui.WithID(id))`, with `m.searchField.Bind(&m.search)` called once where the model is made (the `ui.Field` lives in the model, as for any field): the id is the field's identity in the page's Tree, so the window's own `TextInput` routing, an initial focus and a test address it, while the editor is the one the application reads and moves. `.NavigationKeys()` leaves Up, Down, PageUp and PageDown to the application instead of moving the caret, for a search box whose arrows move a list's selection. `.OnKey(fn)` gives the field a handler for the keys pressed while it has the keyboard, before the page routes them anywhere else: returning `Handled` claims one, and returning an empty `EventResult` leaves it to the page, so Enter can still submit. Keys that type text are never offered and always reach the field. `OnKey` implies `NavigationKeys`, since Up and Down have to reach the application for the field to claim them. + +`ui.MaxLength(n)` caps a `TextField` or `TextArea` at n runes: what is typed, pasted or composed beyond it is cut off the end, and text already longer is left alone. `ui.ShowCount()` shows how many runes the field holds, and of how many when it is capped ("12/32"), at the end of a `TextField`; it takes the place of an `Action`. Both are options after the fixed arguments, as `ui.WithID` is: `ui.TextField(c, &m.title, "Title", "", ui.MaxLength(80), ui.ShowCount())`. A `*Field` kept in the model takes `Field.Restrict(accept, maxRunes)` instead, which also limits which runes it accepts. + +A `TextField` or `TextArea` opens a menu of Cut, Copy, Paste and Select All on a secondary press, and the field takes the keyboard as it does. On macOS and Windows it is the system's own menu, shown by the window for any text field with an editor (also one the application paints itself); elsewhere the page draws one, and `PageConfig.CanvasMenus` asks for that everywhere. Cut and Copy act on the selection and are off for a `Secure` field, as with the keyboard; the commands run as the chords do, so a `TextField` folds a pasted text into one line and a `TextArea` keeps its lines. The words are English until the page names them, by pointer as it does its theme, so a change of language reaches the next menu: `ui.PageConfig{EditMenu: &ui.EditMenuLabels{Cut: "Couper", Copy: "Copier", Paste: "Coller", SelectAll: "Tout sélectionner"}}`. A field with a `ContextMenu` of its own takes `ui.WithoutEditMenu()`, and a field in a `Memo` has the system's menu only. A read-only field has no editor, so it has the page's menu only. `ui.TextField(c, &m.name, label, placeholder)` takes the snapshot from the field, so there is nothing to build; `Changed` reports the first paint after the user edited it, not an assignment or `SetText` of yours; `.Secure()` makes it a password field. Components that paint your own field take an `InputSnapshot` instead, and it is one frame's view of the field: `Value`, `Placeholder`, `Invalid`, `Disabled`, `ReadOnly` and `Secure`, plus `Focused` and `PlatformEditing`. The page's field sets the last one for you. While the platform's editor is on screen it draws the text, the caret and the selection itself, and the static label must not paint underneath it. So `PlatformEditing` is true only while the field is focused and has text, and when focus leaves, the next frame paints the current text again as an ordinary label. The example tests exactly that: after the click on Save, the native editor is gone. diff --git a/website/content/guides/en/windows.md b/website/content/guides/en/windows.md index 154666ea4..da6563297 100644 --- a/website/content/guides/en/windows.md +++ b/website/content/guides/en/windows.md @@ -79,7 +79,7 @@ Hosts without the capability return an error wrapping `app.ErrUnsupported`. ## A complete example -The program below opens a custom-title-bar window with a Settings button that opens a second window, and refuses to close while a note is unsaved. The strip along the top is an ordinary `ui.Row` padded by `c.TitlebarInsets()`, so the title never runs under the window buttons, and the confirmation is a `ui.ModalWith` declared only while a close is pending: +The program below opens a custom-title-bar window with a Settings button that opens a second window, and refuses to close while a note is unsaved. The strip along the top is an ordinary `ui.Row` padded by `c.TitlebarInsets()`, so the title never runs under the window buttons, and the confirmation is a `ui.Modal` declared only while a close is pending: ```go @@ -115,7 +115,7 @@ func (state *notes) page(c ui.C) { ui.PageConfig{View: func(c ui.C) { ui.Text(c, "Settings").FontSize(20).Bold() }}) } }) - ui.ModalWith(c, &state.confirmClosing, "Discard changes?", ui.ModalSpec{ + ui.Modal(c, &state.confirmClosing, "Discard changes?", ui.ModalSpec{ Description: "The note has not been saved.", Width: 400, NoClose: true, }, nil, func() { if ui.Button(c, "Keep editing").Outline().Clicked() { diff --git a/website/content/guides/zh/components.md b/website/content/guides/zh/components.md index c544bac8e..c33368507 100644 --- a/website/content/guides/zh/components.md +++ b/website/content/guides/zh/components.md @@ -27,7 +27,7 @@ components.BeginButton(canvas, theme, hitSave, bounds).Outline("Save") - 编辑器与可视化:`ui/codeeditor`、`ui/textview`、`ui/chart`、`ui/markdown`、`ui/image`、`ui/calendar`、`ui/carousel`、`ui/columnresize`、`ui/reordergrid` - 导航与浮层:`ui/command`、`ui/menubar`、`ui/navigationmenu`、`ui/sidebar`、`ui/hovercard` -- 数据与输入:`ui/avatar`、`ui/avatareditor`、`ui/attachment`、`ui/metriccard`、`ui/marker`、`ui/skeleton`、`ui/aspectratio`、`ui/questionnaire`、`ui/messagescroller`、`ui/message`、`ui/inputgroup`、`ui/inputotp`、`ui/multiselect`、`ui/hierarchypicker`、`ui/buttongroup`、`ui/togglegroup` +- 数据与输入:`ui/avatar`、`ui/avatareditor`、`ui/attachment`、`ui/metriccard`、`ui/marker`、`ui/skeleton`、`ui/aspectratio`、`ui/questionnaire`、`ui/messagescroller`、`ui/message`、`ui/inputgroup`、`ui/inputotp`、`ui/multiselect`、`ui/hierarchypicker`、`ui/buttongroup`、`ui/togglegroup`、`ui/steps`、`ui/descriptions`、`ui/timeline`、`ui/rate`、`ui/inputnumber`、`ui/datepicker`、`ui/timepicker`、`ui/transfer`、`ui/alert`、`ui/tag`、`ui/breadcrumb`、`ui/card`、`ui/empty`、`ui/result`、`ui/pagination`、`ui/editabletabs`、`ui/popconfirm`、`ui/divider`、`ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour` `ui/textview` 用来显示可选择、可复制的只读文本,例如日志和进程输出。在 model 中保留 `textview.View`,调用 `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`;`textview.Strings` 可以把字符串切片适配成数据源。调用方拥有文本、样式和动作,视图负责选择与绘制,不带编辑或撤销模型。 diff --git a/website/content/guides/zh/declarative-layout.md b/website/content/guides/zh/declarative-layout.md index 2646a4e7c..cbfffb66e 100644 --- a/website/content/guides/zh/declarative-layout.md +++ b/website/content/guides/zh/declarative-layout.md @@ -339,11 +339,13 @@ func (m *model) page(c ui.C) { ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { ui.Text(c, "Servers").FontSize(20).Bold() table := ui.Table(c, &m.table, ui.TableSpec{ - Headers: []string{"Name", "State", "Region"}, - Sortable: []bool{true, true, true}, - Source: &m.rows, - Striped: true, - Columns: []ui.TableColumn{{Width: 200}, {Width: 120}, {}}, + Source: &m.rows, + Striped: true, + Columns: []ui.TableColumn{ + {Title: "Name", Width: 200, Sortable: true}, + {Title: "State", Width: 120, Sortable: true}, + {Title: "Region", Sortable: true}, + }, }) if column, ok := table.HeaderClicked(); ok { m.table.SortBy(column) diff --git a/website/content/guides/zh/getting-started.md b/website/content/guides/zh/getting-started.md index 56f9f7559..b710f80b5 100644 --- a/website/content/guides/zh/getting-started.md +++ b/website/content/guides/zh/getting-started.md @@ -22,7 +22,7 @@ go mod init example.com/hello go get github.com/vivaui/viva ``` -`go get` 不带版本号时取最新的正式版本,目前就是 `v0.6.7`。要固定版本就写明:`go get github.com/vivaui/viva@v0.6.7`。Viva 还没有到 1.0,所以小版本之间 `go.mod` 的 API 仍可能变化;升级前看一眼发版说明。 +`go get` 不带版本号时取最新的正式版本,目前就是 `v0.6.8`。要固定版本就写明:`go get github.com/vivaui/viva@v0.6.8`。Viva 还没有到 1.0,所以小版本之间 `go.mod` 的 API 仍可能变化;升级前看一眼发版说明。 如果你是在 Viva 仓库里改框架本身、而不是使用它,改用 `replace` 指向检出目录: diff --git a/website/content/guides/zh/overlays.md b/website/content/guides/zh/overlays.md index 3d06ce1a2..1f96a40e9 100644 --- a/website/content/guides/zh/overlays.md +++ b/website/content/guides/zh/overlays.md @@ -41,7 +41,7 @@ func (m *model) page(c ui.C) { // A popover hangs off its anchor while menuOpen is true. A press outside it // or Escape closes it, and the press goes on to what is under the pointer; // the focus goes back to the anchor. - ui.PopoverWith(c, actions, &m.menuOpen, ui.PopoverSpec{Width: 180, Align: ui.Start}, func() { + ui.Popover(c, actions, &m.menuOpen, ui.PopoverSpec{Width: 180, Align: ui.Start}, func() { if ui.Button(c, "New file").Ghost().Clicked() { m.menuOpen, m.status = false, "Created" } @@ -52,7 +52,7 @@ func (m *model) page(c ui.C) { // A modal dims the page and keeps the keyboard while dialogOpen is true: // Escape, a press on the dim and the close button set it to false. - ui.ModalWith(c, &m.dialogOpen, "Delete file?", ui.ModalSpec{Description: "This cannot be undone.", Width: 400}, nil, func() { + ui.Modal(c, &m.dialogOpen, "Delete file?", ui.ModalSpec{Description: "This cannot be undone.", Width: 400}, nil, func() { if ui.Button(c, "Cancel").Outline().Clicked() { m.dialogOpen = false } @@ -73,7 +73,7 @@ func main() { ## 弹出框 -`ui.Popover(c, anchor, &open, body)` 在 `open` 为真时显示 `body` 声明的面板,挂在 `anchor` 上,外观与 shadcn 的 Popover 一致。`ui.PopoverWith` 接受 `ui.PopoverSpec`,可以指定方向、对齐、宽度、内容内边距、与窗口边缘保持的边距(未设置时为 8),以及 `Instant`:无入场动画地打开,适合随用户输入在光标下出现的列表。它默认在锚点下方打开,下方放不下时翻到上方。要锚定到触发控件,就保留它的 `Box`(`actions := ui.Button(c, ...)`)。 +`ui.Popover(c, anchor, &open, spec, body)` 在 `open` 为真时显示 `body` 声明的面板,挂在 `anchor` 上,外观与 shadcn 的 Popover 一致。`spec` 是 `ui.PopoverSpec`,零值就是普通面板,可以指定方向、对齐、宽度、内容内边距、与窗口边缘保持的边距(未设置时为 8),以及 `Instant`:无入场动画地打开,适合随用户输入在光标下出现的列表。它默认在锚点下方打开,下方放不下时翻到上方。要锚定到触发控件,就保留它的 `Box`(`actions := ui.Button(c, ...)`)。 在面板外按下或按 Escape 会把 `open` 设为 false。这次按下随后会传给指针下方的控件,与网页里的 popover 一致:一次点击另一个按钮,既关闭菜单,也按下那个按钮。在锚点上按下只会关闭面板,所以切换 `open` 的触发按钮不会在同一次点击里又把它打开。焦点回到面板打开前的位置。`Popover` 报告关闭它的那一遍绘制;必须保持打开的面板在那里把 `open` 改回 true。 @@ -87,7 +87,7 @@ func main() { ## 对话框 -`ui.Modal(c, &open, title, body, footer)` 在 `open` 为真时把窗口变暗,画出居中的表面,带标题和关闭按钮,并占住键盘。标题是必填的:它是对话框给辅助技术的名字。`body` 声明正文,`footer` 声明按钮,按钮按给定顺序靠右排列;两者都可以为 nil,表面高度正好等于正文所需。Escape、点击变暗的背景和关闭按钮都会把 `open` 设为 false。对话框打开时,正文里的第一个控件获得焦点(`ModalSpec.InitialFocus` 可以指定另一个);关闭时,焦点回到打开它的那个控件。`ui.ModalWith` 接受 `ui.ModalSpec`,用来加描述、指定大小或去掉关闭按钮。 +`ui.Modal(c, &open, title, spec, body, footer)` 在 `open` 为真时把窗口变暗,画出居中的表面,带标题和关闭按钮,并占住键盘。标题是必填的:它是对话框给辅助技术的名字。`body` 声明正文,`footer` 声明按钮,按钮按给定顺序靠右排列;两者都可以为 nil,表面高度正好等于正文所需。Escape、点击变暗的背景和关闭按钮都会把 `open` 设为 false。对话框打开时,正文里的第一个控件获得焦点(`ModalSpec.InitialFocus` 可以指定另一个);关闭时,焦点回到打开它的那个控件。`spec` 是 `ui.ModalSpec`,零值就是普通对话框,用来加描述、指定大小或去掉关闭按钮。 `ui.Dialog(c, ui.DialogSpec{...})` 是同一个对话框由应用命名目标的形式:`Scope` 是焦点范围,`DismissID` 是背景和 Escape 报告的标识,`CloseID` 是右上角按钮的,`InitialFocusID` 是获得焦点的控件。`dialog.Header(fn)` 在标题行声明控件,`Body` 声明正文,`Footer` 声明按钮;`Dismissed()` 在递送其中任一点击的那一遍绘制里为真。 diff --git a/website/content/guides/zh/system-integration.md b/website/content/guides/zh/system-integration.md index 95bac7c4a..60131b5b0 100644 --- a/website/content/guides/zh/system-integration.md +++ b/website/content/guides/zh/system-integration.md @@ -125,7 +125,7 @@ func (m *model) page(c ui.C) { m.menuOpen = !m.menuOpen } ui.Text(c, m.status).Muted() - ui.PopoverWith(c, menu, &m.menuOpen, ui.PopoverSpec{Width: 220, Align: ui.Start}, func() { + ui.Popover(c, menu, &m.menuOpen, ui.PopoverSpec{Width: 220, Align: ui.Start}, func() { if ui.Button(c, "Say hello to the page").Ghost().Clicked() && m.view != nil { m.view.PostMessage("hello from Viva") m.menuOpen = false diff --git a/website/content/guides/zh/text-input.md b/website/content/guides/zh/text-input.md index af7df9ede..0ba602286 100644 --- a/website/content/guides/zh/text-input.md +++ b/website/content/guides/zh/text-input.md @@ -58,7 +58,11 @@ func main() { ## 绘制字段 -应用自己命名、并且自己持有 editor 的字段写成 `ui.TextFieldID(c, id, &m.searchField, label, placeholder)`,其中 `m.searchField.Bind(&m.search)` 在创建模型时调用一次(`ui.Field` 和其他字段一样放在模型里):id 是字段在页面 Tree 里的身份,窗口自己的 `TextInput` 路由、初始焦点和测试都用它定位,而 editor 就是应用自己读取和移动的那一个。`.NavigationKeys()` 把 Up、Down、PageUp、PageDown 交给应用而不是移动光标,用于方向键移动列表选择项的搜索框。`.OnKey(fn)` 给字段一个处理函数,在它持有键盘时接收按键,先于页面把它们路由到别处:返回 `Handled` 就是认领这个键,返回空的 `EventResult` 则把它留给页面,所以 Enter 仍然可以提交。会输入文字的键从不交给它,总是到达字段。`OnKey` 同时启用 `NavigationKeys`,因为字段要认领 Up 和 Down,这两个键必须先到达应用。 +应用自己命名、并且自己持有 editor 的字段写成 `ui.TextField(c, &m.searchField, label, placeholder, ui.WithID(id))`,其中 `m.searchField.Bind(&m.search)` 在创建模型时调用一次(`ui.Field` 和其他字段一样放在模型里):id 是字段在页面 Tree 里的身份,窗口自己的 `TextInput` 路由、初始焦点和测试都用它定位,而 editor 就是应用自己读取和移动的那一个。`.NavigationKeys()` 把 Up、Down、PageUp、PageDown 交给应用而不是移动光标,用于方向键移动列表选择项的搜索框。`.OnKey(fn)` 给字段一个处理函数,在它持有键盘时接收按键,先于页面把它们路由到别处:返回 `Handled` 就是认领这个键,返回空的 `EventResult` 则把它留给页面,所以 Enter 仍然可以提交。会输入文字的键从不交给它,总是到达字段。`OnKey` 同时启用 `NavigationKeys`,因为字段要认领 Up 和 Down,这两个键必须先到达应用。 + +`ui.MaxLength(n)` 把 `TextField` 或 `TextArea` 限制在 n 个字符:超出的输入、粘贴和输入法组合内容会从末尾截掉,已有的更长文本不受影响。`ui.ShowCount()` 在 `TextField` 末尾显示已输入的字符数,设了上限时显示为“12/32”,它会占用 `Action` 的位置。两者和 `ui.WithID` 一样是固定参数之后的选项:`ui.TextField(c, &m.title, "Title", "", ui.MaxLength(80), ui.ShowCount())`。保存在模型里的 `*Field` 则用 `Field.Restrict(accept, maxRunes)`,它还能限制可输入的字符。 + +`TextField` 和 `TextArea` 在次键按下时打开剪切、复制、粘贴、全选菜单,字段同时取得键盘。macOS 和 Windows 上是系统自己的菜单,由窗口为任何带编辑器的文本框弹出(应用自己画的输入框也一样);其他平台由页面画一个,`PageConfig.CanvasMenus` 可以要求所有平台都用页面的。剪切和复制作用于选区,`Secure` 字段与键盘一样没有这两项;各命令与对应快捷键走同一条路径,所以 `TextField` 把粘贴的文本折成一行,`TextArea` 保留换行。文字默认是英文,由页面像主题一样以指针给出自己的语言,切换语言后下一次打开的菜单生效:`ui.PageConfig{EditMenu: &ui.EditMenuLabels{Cut: "Couper", Copy: "Copier", Paste: "Coller", SelectAll: "Tout sélectionner"}}`。自己带 `ContextMenu` 的字段用 `ui.WithoutEditMenu()`;`Memo` 里的字段只有系统菜单。只读字段没有编辑器,只有页面的菜单。 `ui.TextField(c, &m.name, label, placeholder)` 直接从字段取得快照,不需要自己构造;`Changed` 报告用户编辑之后的第一次绘制,你自己赋值或调用 `SetText` 不算;`.Secure()` 让它成为密码字段。自己绘制字段的组件则接受 `InputSnapshot`,它是字段某一帧的视图:`Value`、`Placeholder`、`Invalid`、`Disabled`、`ReadOnly` 和 `Secure`,以及 `Focused` 和 `PlatformEditing`。页面的字段会替你设置最后一个。平台编辑器显示在屏幕上时,文本、光标和选区都由它自己绘制,静态标签不能画在它下面。所以 `PlatformEditing` 只在字段获得焦点且有文本时为真;焦点离开后,下一帧会把当前文本重新画成普通标签。示例的测试检查的正是这一点:点击 Save 之后,原生编辑器就消失了。 diff --git a/website/content/guides/zh/windows.md b/website/content/guides/zh/windows.md index 81f13ee09..b8b1e9165 100644 --- a/website/content/guides/zh/windows.md +++ b/website/content/guides/zh/windows.md @@ -45,7 +45,7 @@ Windows 使用整个显示器而不是任务栏工作区,并保存之前的位 ## 完整示例 -下面的程序打开一个自定义标题栏窗口,其中的“Settings”按钮会打开第二个窗口,并且在有未保存的笔记时拒绝关闭。顶部条带是一个普通的 `ui.Row`,用 `c.TitlebarInsets()` 留出内边距,所以标题不会压到窗口按钮下面;确认框是 `ui.ModalWith`,只在有关闭请求挂起时才声明: +下面的程序打开一个自定义标题栏窗口,其中的“Settings”按钮会打开第二个窗口,并且在有未保存的笔记时拒绝关闭。顶部条带是一个普通的 `ui.Row`,用 `c.TitlebarInsets()` 留出内边距,所以标题不会压到窗口按钮下面;确认框是 `ui.Modal`,只在有关闭请求挂起时才声明: ```go @@ -81,7 +81,7 @@ func (state *notes) page(c ui.C) { ui.PageConfig{View: func(c ui.C) { ui.Text(c, "Settings").FontSize(20).Bold() }}) } }) - ui.ModalWith(c, &state.confirmClosing, "Discard changes?", ui.ModalSpec{ + ui.Modal(c, &state.confirmClosing, "Discard changes?", ui.ModalSpec{ Description: "The note has not been saved.", Width: 400, NoClose: true, }, nil, func() { if ui.Button(c, "Keep editing").Outline().Clicked() { diff --git a/website/src/components/APIDescription.astro b/website/src/components/APIDescription.astro new file mode 100644 index 000000000..614838bbe --- /dev/null +++ b/website/src/components/APIDescription.astro @@ -0,0 +1,13 @@ +--- +import { type DocBlock } from '../lib/api'; +import type { Locale } from '../lib/i18n'; +import DocInline from './DocInline.astro'; + +// One API row's description: a hand-written translation when the page has +// one, otherwise the first paragraph of the generated English doc comment. +interface Props { text?: string; blocks: DocBlock[]; locale: Locale } +const { text, blocks, locale } = Astro.props; +const parts = blocks.find(block => block.kind === 'paragraph')?.text ?? []; +--- + +{text ? text : } diff --git a/website/src/components/ComponentAPI.astro b/website/src/components/ComponentAPI.astro new file mode 100644 index 000000000..cf75f11ea --- /dev/null +++ b/website/src/components/ComponentAPI.astro @@ -0,0 +1,58 @@ +--- +import { readAPI, resolveAPISymbol, type APIFunc, type APIType } from '../lib/api'; +import { apiZh } from '../lib/api-zh'; +import { siteText } from '../lib/site'; +import type { Locale } from '../lib/i18n'; +import ComponentAPIGroup from './ComponentAPIGroup.astro'; + +// The API table under a component page. The page's catalog entry names the +// symbols; every name, type and description here comes from the generated +// api.json, so a renamed argument or a stale default cannot survive the build. +// The page API (ui.*) is the primary table; the canvas recipe (components) is +// folded below it, because the documentation's first call surface is the page. +interface Props { symbols: string[]; locale: Locale } +const { symbols, locale } = Astro.props; +const text = siteText(locale); +const data = readAPI(); +const zh = (key: string) => (locale === 'zh' ? apiZh[key] : undefined); + +type FunctionEntry = { func: APIFunc; owner?: APIType; kind: 'function' | 'constructor' | 'method' }; +type TypeEntry = { type: APIType; synopsis: string }; +type Group = { pkg: string; types: TypeEntry[]; funcs: FunctionEntry[] }; +const groups: Group[] = []; +for (const symbol of symbols) { + const resolved = resolveAPISymbol(data, symbol); + if (!resolved) { + throw new Error(`The component page names unknown API symbol ${symbol}`); + } + let group = groups.find(entry => entry.pkg === resolved.pkg.name); + if (!group) { + group = { pkg: resolved.pkg.name, types: [], funcs: [] }; + groups.push(group); + } + if (resolved.type) { + group.types.push({ + type: resolved.type, + synopsis: zh(`${resolved.pkg.name}.${resolved.type.name}`) ?? resolved.type.synopsis, + }); + } + if (resolved.func) group.funcs.push({ func: resolved.func, owner: resolved.owner, kind: resolved.kind as 'function' | 'constructor' | 'method' }); +} +const pageGroups = groups.filter(group => group.pkg !== 'components'); +const canvasGroups = groups.filter(group => group.pkg === 'components'); +--- + +
+

{text.apiTable}

+ {pageGroups.map(group =>
+

{group.pkg}{text.apiPageGroup}

+ +
)} + {canvasGroups.length > 0 &&
+ components{text.apiCanvasGroup} +

{text.apiCanvasNote}

+ {canvasGroups.map(group =>
+ +
)} +
} +
diff --git a/website/src/components/ComponentAPIGroup.astro b/website/src/components/ComponentAPIGroup.astro new file mode 100644 index 000000000..0fdedd8ed --- /dev/null +++ b/website/src/components/ComponentAPIGroup.astro @@ -0,0 +1,54 @@ +--- +import { apiPath } from '../lib/routes'; +import { readAPI, typeHref, type APIFunc, type APIType } from '../lib/api'; +import { apiZh } from '../lib/api-zh'; +import { siteText } from '../lib/site'; +import type { Locale } from '../lib/i18n'; +import APIDescription from './APIDescription.astro'; + +interface GroupEntry { + pkg: string; + types: { type: APIType; synopsis: string }[]; + funcs: { func: APIFunc; owner?: APIType; kind?: 'function' | 'constructor' | 'method' }[]; +} +interface Props { group: GroupEntry; locale: Locale } +const { group, locale } = Astro.props; +const text = siteText(locale); +const data = readAPI(); +const zh = (key: string) => (locale === 'zh' ? apiZh[key] : undefined); +--- + +{group.types.map(({ type, synopsis }) =>
+

{type.name}

+ {synopsis &&

{synopsis}

} + {type.fields && type.fields.length > 0 && + + {type.fields.map(field => + + + + )} +
{text.apiField}{text.apiType}{text.apiDescription}
{field.name}{(() => { + const href = typeHref(data, group.pkg, field.type, locale); + return href ? {field.type} : {field.type}; + })()}
} + {type.methods.length > 0 && + + {type.methods.map(method => + + + + )} +
{text.apiMethods}{text.apiSignature}{text.apiDescription}
{method.name}{method.signature ?? method.name}
} +
)} +{group.funcs.length > 0 && <> +

{text.apiFunctions}

+ + + {group.funcs.map(({ func, owner, kind }) => + + + + )} +
{text.apiFunctions}{text.apiSignature}{text.apiDescription}
{func.name}{func.signature ?? func.name}
+} diff --git a/website/src/components/DocInline.astro b/website/src/components/DocInline.astro new file mode 100644 index 000000000..b3dab66cd --- /dev/null +++ b/website/src/components/DocInline.astro @@ -0,0 +1,14 @@ +--- +import { apiHref, type DocInline as Inline } from '../lib/api'; +import type { Locale } from '../lib/i18n'; + +// One paragraph's inline runs, for a table cell. The full block renderer +// (ApiDoc) is for prose; a cell holds at most one sentence. +interface Props { parts: Inline[]; locale: Locale } +const { parts, locale } = Astro.props; +--- + +{parts.map(part => { + const content = part.code ? {part.text} : part.italic ? {part.text} : part.text; + return part.href ? {content} : content; +})} diff --git a/website/src/lib/api-zh.ts b/website/src/lib/api-zh.ts new file mode 100644 index 000000000..d36b966b5 --- /dev/null +++ b/website/src/lib/api-zh.ts @@ -0,0 +1,66 @@ +// Chinese descriptions for the API tables on component pages. The Go doc +// comments remain the English source of truth and fill any key missing here; +// this dictionary only translates the pages that have tables today. Keys are +// "package.Symbol" for a type or function, and "package.Symbol.Field" or +// "package.Symbol.Method" for one row. +export const apiZh: Record = { + 'ui.Toaster': 'Toaster 保存一个窗口的通知栈,放在模型里,用法与 shadcn 的 Sonner 相同:Show 放上一条通知,页面里声明一次的 ui.Toasts 负责绘制。', + 'ui.Toaster.Position': '通知栈的位置;零值是右下角。', + 'ui.Toaster.Expanded': '让通知栈保持展开,效果等同于指针停在栈上或焦点进入栈内:由调用方持有的标志,用于无法悬停的静态页面。零值是折叠。', + 'ui.Toaster.Timeout': '没有单独设置时长的通知使用这个时长;零值为 5 秒,与 Base UI 一致。', + 'ui.Toaster.Limit': '同时可见的通知条数上限;零值为 3,与 Base UI 一致。', + 'ui.Toaster.Acted': 'Acted 报告本次绘制中按下的是哪条通知的操作按钮;在 ui.Toasts 之后读取。', + 'ui.Toaster.Close': 'Close 在通知到期前把它收起。', + 'ui.Toaster.Done': 'Done 把一条 ToastLoading 通知替换成它最终的结果:立即更新标题、描述和类型,并从现在开始重新计时。', + 'ui.Toaster.ID': 'ID 返回第 n 条通知的标识;Toaster 首次绘制前为零。', + 'ui.Toaster.Len': 'Len 是当前通知条数。', + 'ui.Toaster.Show': 'Show 放上一条通知:一个标题,以及标题下方可选的描述(传空字符串表示没有)。相同标题和描述已在栈上时不重复显示,只重新计时。', + 'ui.Toaster.ShowAction': 'ShowAction 是带操作按钮的 Show,按钮文字由 action 指定;按下后 Acted 会报告,并把通知收起,例如 Undo、Retry、Open。操作按钮不是唯一入口:通知会自己到期,所以它提供的内容在窗口里还应有别处可访问。', + 'ui.Toaster.ShowConfig': 'ShowConfig 是 Show 加上这条通知单独的设置:操作按钮、自己的时长,或隐藏关闭按钮。隐藏关闭按钮的通知仍会按时到期、被操作按钮收起,或由应用调用 Close 收起。', + 'ui.Toaster.Swipe': 'Swipe 让第 id 条通知在本次及之后的绘制中水平移动 x 像素:这是调用方提供的拖拽快照,ui.Toasts 会原样绘制。正数向右,零复位。它不读取指针、不解释手势、不调度帧;拖拽和阈值由调用方负责。通知不在栈上时什么也不做。', + 'ui.Toaster.SwipeX': 'SwipeX 返回 Swipe 会让第 id 条通知在下次绘制中移动的距离;通知不在栈上时为零。', + + 'ui.ToastConfig': 'ToastConfig 是一次 show 调用为单条通知设置的额外内容:操作按钮、自己的时长,或隐藏关闭按钮。', + 'ui.ToastConfig.Action': '操作按钮的文字;为空表示没有按钮。', + 'ui.ToastConfig.Timeout': '覆盖 Toaster 的 Timeout,只作用于这条通知;零或负数表示沿用 Toaster 的时长。', + 'ui.ToastConfig.HideClose': '隐藏关闭按钮。通知仍会按时到期、被操作按钮收起,或由应用调用 Close 收起。', + + 'ui.Toasts': 'Toasts 在 t.Position 指定的位置绘制 t 的通知栈,盖在其他内容之上,并在到期时收起。它只在需要下一帧时请求一帧,没有通知时不调度任何帧。在页面里声明一次,放在最后。', + + 'components.PaintToast': 'PaintToast 在 options 指定的位置绘制一条通知快照,默认右下角。宽度跟随文字,最宽 384px;高度跟随描述,描述在该宽度内换行。它不调度工作,也不保留生命周期状态;唯一的例外是 loading 通知每 100ms 请求一帧来转动 spinner,直到它不再被绘制。', + + 'components.ToastOptions': 'ToastOptions 保存稳定的操作和浮层标识。', + 'components.ToastOptions.Layer': '通知绘制的画布图层。', + 'components.ToastOptions.Scope': '把通知的标识和焦点归入同一作用域。', + 'components.ToastOptions.DismissID': '关闭按钮和 Escape 目标的标识。为零时不绘制关闭按钮,Escape 交给页面处理。', + 'components.ToastOptions.ActionID': '操作按钮的标识;为零时不绘制操作按钮。', + 'components.ToastOptions.ActionLabel': '操作按钮的文字;为空时不绘制操作按钮。', + 'components.ToastOptions.Disabled': '让通知变暗,并禁用操作和关闭按钮。', + 'components.ToastOptions.Position': '通知的位置;零值是右下角。', + + 'components.ToastSnapshot': 'ToastSnapshot 是一帧里绘制的完整调用方状态。计时、过期、滑动解释和栈成员关系都在组件之外。', + 'components.ToastSnapshot.Title': '通知的第一行文字。', + 'components.ToastSnapshot.Description': '标题下方较小的一行文字;为空时不绘制。', + 'components.ToastSnapshot.Type': '选择图标、图标颜色和 spinner。', + 'components.ToastSnapshot.Index': '通知在栈中位于最前面之后的第几层。', + 'components.ToastSnapshot.Expanded': '展开通知栈时用间隙而不是堆叠露出。', + 'components.ToastSnapshot.Limited': '标记超出可见上限的通知;它不会被绘制。', + 'components.ToastSnapshot.OffsetY': '调用方提供的纵向快照偏移。', + 'components.ToastSnapshot.SwipeX': '调用方提供的横向拖拽快照。', + 'components.ToastSnapshot.SwipeY': '调用方提供的纵向拖拽快照。', + + 'components.PaintSonner': 'PaintSonner 使用官方的主题化 Toast 配方绘制一个完整的调用方通知栈。它不保留条目、不运行计时器、不调度帧,也不解释滑动手势。', + 'components.SonnerOptions': 'SonnerOptions 配置调用方通知栈的一次无状态绘制。通知按最新在前排序。Layer 是栈中最旧一条的图层,更新的一条依次加一,折叠卡片才能正确合成。', + 'components.SonnerOptions.Layer': '栈中最旧一条通知的图层;更新的通知依次加一。', + 'components.SonnerOptions.Expanded': '展开通知栈时用间隙而不是堆叠露出。', + 'components.SonnerOptions.Limit': '只显示最新的几条通知;零值为 Base UI 的 3,更旧的不会被绘制。', + 'components.SonnerOptions.Position': '通知栈增长的位置;零值是右下角。', + + 'components.SonnerToast': 'SonnerToast 是调用方通知栈里的一条通知:它的快照,以及关闭和操作按钮的标识。', + 'components.SonnerToast.Snapshot': '通知的文字、类型和位置。', + 'components.SonnerToast.Scope': '把通知的标识和焦点归入同一作用域。', + 'components.SonnerToast.DismissID': '关闭按钮的标识;为零时不绘制关闭按钮。', + 'components.SonnerToast.ActionID': '操作按钮的标识;为零时不绘制操作按钮。', + 'components.SonnerToast.ActionLabel': '操作按钮的文字;为空时不绘制操作按钮。', + 'components.SonnerToast.Disabled': '让通知变暗,并禁用操作和关闭按钮。', +}; diff --git a/website/src/lib/api.ts b/website/src/lib/api.ts index 90c432c3b..0c3236b17 100644 --- a/website/src/lib/api.ts +++ b/website/src/lib/api.ts @@ -6,8 +6,9 @@ import { apiPath } from './routes'; export interface DocInline { text: string; italic?: boolean; code?: boolean; href?: string } export interface DocBlock { kind: 'paragraph' | 'heading' | 'code' | 'list'; text?: DocInline[]; items?: DocBlock[][]; code?: string; ordered?: boolean } export interface APIValue { names: string[]; decl: string; doc: DocBlock[] } -export interface APIFunc { name: string; receiver?: string; decl: string; synopsis: string; doc: DocBlock[] } -export interface APIType { name: string; decl: string; synopsis: string; doc: DocBlock[]; constants: APIValue[]; variables: APIValue[]; constructors: APIFunc[]; methods: APIFunc[] } +export interface APIFunc { name: string; receiver?: string; decl: string; signature?: string; synopsis: string; doc: DocBlock[] } +export interface APIField { name: string; type: string; doc: DocBlock[] } +export interface APIType { name: string; decl: string; synopsis: string; doc: DocBlock[]; fields?: APIField[]; constants: APIValue[]; variables: APIValue[]; constructors: APIFunc[]; methods: APIFunc[] } export interface APIPackage { name: string; importPath: string; synopsis: string; doc: DocBlock[]; constants: APIValue[]; variables: APIValue[]; functions: APIFunc[]; types: APIType[] } export interface APIData { packages: APIPackage[] } @@ -36,6 +37,55 @@ export function packageNamed(data: APIData, name: string): APIPackage { return found; } +export type APISymbolKind = 'type' | 'function' | 'constructor' | 'method'; + +export interface ResolvedAPISymbol { + pkg: APIPackage; + type?: APIType; + func?: APIFunc; + // owner is the type whose page anchors a constructor's or method's entry. + owner?: APIType; + kind: APISymbolKind; +} + +// resolveAPISymbol finds "package.Name" in the generated API data. A name may +// be a type, a package function, or a constructor that go/doc attached to the +// type it returns (PaintToast belongs to ToastLayout). +export function resolveAPISymbol(data: APIData, symbol: string): ResolvedAPISymbol | undefined { + const cut = symbol.indexOf('.'); + if (cut <= 0 || cut === symbol.length - 1) return undefined; + const pkg = data.packages.find(entry => entry.name === symbol.slice(0, cut)); + if (!pkg) return undefined; + const name = symbol.slice(cut + 1); + const type = pkg.types.find(entry => entry.name === name); + if (type) return { pkg, type, kind: 'type' }; + const fn = pkg.functions.find(entry => entry.name === name); + if (fn) return { pkg, func: fn, kind: 'function' }; + for (const owner of pkg.types) { + const constructor = owner.constructors.find(entry => entry.name === name); + if (constructor) return { pkg, func: constructor, owner, kind: 'constructor' }; + const method = owner.methods.find(entry => entry.name === name); + if (method) return { pkg, func: method, owner, kind: 'method' }; + } + return undefined; +} + +// typeHref links a field's Go type to its generated type page when it is a Viva +// type the API documents. Slices and pointers look through to their element +// type; primitives, time.Duration and other packages stay plain. +export function typeHref(data: APIData, pkgName: string, value: string, locale: Locale): string | undefined { + let name = value.trim(); + while (name.startsWith('[]')) name = name.slice(2); + while (name.startsWith('*')) name = name.slice(1); + const parts = name.split('.'); + const targetPkg = parts.length === 2 ? parts[0] : pkgName; + const typeName = parts.length === 2 ? parts[1] : name; + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(typeName)) return undefined; + const pkg = data.packages.find(entry => entry.name === targetPkg); + if (!pkg || !pkg.types.some(entry => entry.name === typeName)) return undefined; + return apiPath(locale, targetPkg, typeName); +} + // A generated link such as "ui/Canvas#method-Hovered" or "app#func-RunCanvas" // becomes a route under //api/. External URLs pass through unchanged. export function apiHref(locale: Locale, href: string): string { diff --git a/website/src/lib/i18n.ts b/website/src/lib/i18n.ts index 722945e04..db433dbd8 100644 --- a/website/src/lib/i18n.ts +++ b/website/src/lib/i18n.ts @@ -168,6 +168,29 @@ const chineseComponentNames: Record = { 'chart-downsample': '图表降采样', 'split-button': '分离按钮', list: '列表', + descriptions: '描述列表', + tag: '标签', + timeline: '时间轴', + 'expandable-text': '可展开文本', + 'progress-ring': '环形进度', + result: '结果页', + 'date-picker': '日期选择器', + 'input-number': '数字输入框', + rate: '评分', + 'select-groups': '分组选择', + 'slider-marks': '滑块刻度', + 'time-picker': '时间选择器', + transfer: '穿梭框', + upload: '文件上传', + anchor: '锚点', + comment: '评论', + 'image-preview': '图片预览', + mentions: '提及', + tour: '引导', + 'labeled-divider': '带文字分隔线', + 'editable-tabs': '可编辑标签页', + steps: '步骤条', + popconfirm: '气泡确认框', }; export function componentName(locale: Locale, id: string, fallback: string): string { @@ -229,6 +252,114 @@ const englishComponents: Record>> = { diff --git a/website/src/lib/site.ts b/website/src/lib/site.ts index 3dac48323..711e34bba 100644 --- a/website/src/lib/site.ts +++ b/website/src/lib/site.ts @@ -30,6 +30,9 @@ const english = { apiTitle: 'API reference', apiSummary: 'Every exported type, function and constant of the Viva packages, generated from the Go source and its doc comments.', apiPackages: 'Packages', apiType: 'Type', apiPackage: 'Package', apiTypes: 'Types', apiFunctions: 'Functions', apiConstants: 'Constants', apiVariables: 'Variables', apiConstructors: 'Constructors', apiMethods: 'Methods', apiOverview: 'Overview', apiImport: 'Import path', + apiTable: 'API', apiField: 'Field', apiDescription: 'Description', apiSignature: 'Signature', + apiPageGroup: 'Page API', apiCanvasGroup: 'Canvas recipe', + apiCanvasNote: 'Use inside ui.Control/Draw, or copy the recipe with viva add. Prefer the ui.* page control where one exists.', apiEnglishOnly: 'API documentation is generated from the Go source and is in English.', notFoundGuide: 'This guide has no translation yet.', }; @@ -61,6 +64,9 @@ const chinese: typeof english = { apiTitle: 'API 参考', apiSummary: 'Viva 各个包导出的全部类型、函数与常量,由 Go 源码及其文档注释生成。', apiPackages: '包', apiType: '类型', apiPackage: '包', apiTypes: '类型', apiFunctions: '函数', apiConstants: '常量', apiVariables: '变量', apiConstructors: '构造函数', apiMethods: '方法', apiOverview: '概览', apiImport: '导入路径', + apiTable: 'API', apiField: '字段', apiDescription: '说明', apiSignature: '签名', + apiPageGroup: '页面 API', apiCanvasGroup: '画布配方', + apiCanvasNote: '在 ui.Control/Draw 内使用,或用 viva add 复制源码;有页面控件时优先用 ui.*。', apiEnglishOnly: 'API 文档由 Go 源码生成,内容为英文。', notFoundGuide: '这篇指南暂无翻译。', }; diff --git a/website/src/lib/types.ts b/website/src/lib/types.ts index 9de8c6368..66ea958c2 100644 --- a/website/src/lib/types.ts +++ b/website/src/lib/types.ts @@ -32,6 +32,8 @@ export interface Page extends Nav { Revision: string; /** The Go file the examples call: components/.go, or ui/list.go for a page-layer control. */ Source: string; + /** The API symbols this page summarizes, as "package.Name". */ + api?: string[]; All: Nav[]; Examples: Demo[]; InstallCommand: string; diff --git a/website/src/pages/[lang]/ui/[component].astro b/website/src/pages/[lang]/ui/[component].astro index dd4b7a922..ec471e93d 100644 --- a/website/src/pages/[lang]/ui/[component].astro +++ b/website/src/pages/[lang]/ui/[component].astro @@ -5,8 +5,10 @@ import DocsLayout from '../../../layouts/DocsLayout.astro'; import Preview from '../../../components/Preview.svelte'; import CopyButton from '../../../components/CopyButton.svelte'; import Icon from '../../../components/Icon.svelte'; +import ComponentAPI from '../../../components/ComponentAPI.astro'; import { navigationFor, readCatalog } from '../../../lib/catalog'; import { locales, messages, isLocale, localizePage, componentPath, categoryLabel, componentName } from '../../../lib/i18n'; +import { siteText } from '../../../lib/site'; export const getStaticPaths = (() => locales.flatMap(lang => readCatalog().pages.map(page => ({ params: { lang, component: page.ID } })))) satisfies GetStaticPaths; const locale = Astro.params.lang; @@ -16,10 +18,12 @@ const original = catalog.pages.find(entry => entry.ID === Astro.params.component const page = localizePage(original, locale); const zhName = locale === 'zh' ? componentName(locale, page.ID, page.Title) : ''; const text = messages[locale]; +const apiText = siteText(locale); const themes = { light: 'github-light', dark: 'github-dark' } as const; const sourceFile = `${page.ID.replaceAll('-', '_')}.go`; const sourcePath = page.PageUsage && page.PageSource ? page.PageSource : (page.Source || `components/${sourceFile}`); const sections = page.Sections.filter(section => section.ID !== 'source-ownership'); +const apiSymbols = page.api ?? []; const optionalImports = { text: 'github.com/vivaui/viva/text', gfx: 'github.com/vivaui/viva/gfx', @@ -93,6 +97,7 @@ const optionalImports = { {sections.map(section =>

{section.Title}#

{section.Text}

{section.Items && section.Items.length > 0 &&
    {section.Items.map(item =>
  • {item}
  • )}
}
)} + {apiSymbols.length > 0 && }

{text.keyboard}

{text.keyboardIntro}

- + diff --git a/website/src/styles/site.css b/website/src/styles/site.css index 64c3c71d1..0f95a0460 100644 --- a/website/src/styles/site.css +++ b/website/src/styles/site.css @@ -25,6 +25,7 @@ --viva-accent-border: #e4e4e7; --viva-error: #b91c1c; --viva-success: #15803d; + --viva-type: #3b62c9; --viva-mono: "JetBrains Mono", "SFMono-Regular", Consolas, "Liberation Mono", monospace; --viva-radius: 8px; --viva-header-height: 56px; @@ -45,6 +46,7 @@ --viva-accent-border: #27272a; --viva-error: #f87171; --viva-success: #4ade80; + --viva-type: #93b8ff; color-scheme: dark; } html { overscroll-behavior-y: none; } @@ -188,6 +190,39 @@ .section-intro { margin: 10px 0 18px; font-size: 15px; } .example-section { margin-top: 36px; } .example-summary { margin: 8px 0 16px; font-size: 15px; } + .component-api-group { margin-top: 34px; } + .component-api-group > h3 { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; } + .component-api-package { display: inline-flex; align-items: center; padding: 4px 9px; border: 1px solid var(--viva-border); border-radius: 999px; background: var(--viva-surface); color: var(--viva-doc-secondary); font-size: 12px; font-weight: 500; } + .component-api-group-label { color: var(--viva-muted); font-size: 12px; font-weight: 400; } + .component-api-canvas { margin-top: 34px; padding: 0 18px 18px; border: 1px solid var(--viva-border); border-radius: 8px; } + .component-api-canvas > summary { display: flex; align-items: center; gap: 8px; margin: 0 -18px; padding: 14px 18px; cursor: pointer; list-style: none; } + .component-api-canvas > summary::-webkit-details-marker { display: none; } + .component-api-canvas > summary::before { content: '▸'; color: var(--viva-muted); font-size: 11px; } + .component-api-canvas[open] > summary { margin-bottom: 14px; border-bottom: 1px solid var(--viva-border); } + .component-api-canvas[open] > summary::before { content: '▾'; } + .component-api-note { margin: 0 0 6px; color: var(--viva-muted); font-size: 13px; } + .component-api-canvas .component-api-group { margin-top: 18px; } + .component-api-type { margin-top: 24px; } + .component-api-type h4 { margin-bottom: 4px; font-size: 17px; } + .component-api-type h4 code { font-size: inherit; } + .component-api-synopsis { margin-top: 0; color: var(--viva-doc-secondary); font-size: 14px; } + .component-api-caption { margin: 22px 0 0; color: var(--viva-muted); font-size: 12px; font-weight: 500; } + .component-api-table { width: 100%; margin-top: 10px; border: 1px solid var(--viva-border); border-radius: 8px; border-collapse: separate; border-spacing: 0; table-layout: fixed; overflow: hidden; font-size: 14px; } + .component-api-table th, .component-api-table td { padding: 10px 14px; vertical-align: top; } + .component-api-table thead { background: var(--viva-surface); } + .component-api-table th { color: var(--viva-muted); font-size: 12px; font-weight: 500; } + .component-api-table tbody td { border-top: 1px solid var(--viva-border); } + .component-api-table tbody td:first-child { color: var(--viva-text); font-weight: 500; } + .component-api-table.fields td:nth-child(2) { color: var(--viva-muted); } + .component-api-type-link { color: var(--viva-type); } + .component-api-type-link:hover { text-decoration: underline; text-underline-offset: 2px; } + .component-api-table.fields th:nth-child(1), .component-api-table.fields td:nth-child(1) { width: 22%; } + .component-api-table.fields th:nth-child(2), .component-api-table.fields td:nth-child(2) { width: 22%; } + .component-api-table.calls th:nth-child(1), .component-api-table.calls td:nth-child(1) { width: 18%; } + .component-api-table.calls th:nth-child(2), .component-api-table.calls td:nth-child(2) { width: 42%; } + .component-api-table td code { overflow-wrap: normal; word-break: normal; } + .component-api-table.fields td:nth-child(2) code { white-space: nowrap; } + .component-api-table.calls td:nth-child(2) code { font-size: 12px; line-height: 1.55; } .example-demo { border: 1px solid var(--viva-border); border-radius: 12px; overflow: hidden; background: var(--viva-background); } .example-toolbar { position: relative; display: flex; align-items: center; height: 38px; padding: 0 12px; border-bottom: 1px solid var(--viva-border); background: var(--viva-surface); } .window-dots { display: flex; align-items: center; gap: 7px; }