From d795dc6e328bdc3d89b3512c4c840b0793d6b27a Mon Sep 17 00:00:00 2001 From: Ren Amamiya Date: Tue, 17 Nov 2026 09:36:20 +0700 Subject: [PATCH] Vendor the native UI kit as crates/ui - crates/ui holds the theme, icons, components, data widgets, editor surfaces, layout, and utilities; cargo feature gates are gone. - One merged icon set of 154 SVGs where the app file wins every duplicate name, served by a single rust-embed Assets source. - IconRole grows the 25 app glyphs, so assets::CustomIconName and crates/assets are deleted. - ui::init owns the theme and key bindings that desktop used to bind in three calls. - docs/gpui-native-kit-gaps.md becomes docs/ui-gaps.md; the icon gap is closed. --- Cargo.lock | 564 +++- Cargo.toml | 2 - crates/assets/Cargo.toml | 13 - crates/assets/assets/.keep | 0 crates/assets/src/lib.rs | 98 - crates/signed_app/Cargo.toml | 3 +- crates/signed_app/src/app/helpers.rs | 2 +- crates/signed_app/src/app/mod.rs | 12 +- crates/signed_app/src/app/placeholder.rs | 4 +- crates/signed_app/src/app/sign_in.rs | 6 +- crates/signed_app/src/explore/helpers.rs | 11 +- crates/signed_app/src/explore/mod.rs | 19 +- crates/signed_app/src/identity/exit.rs | 8 +- crates/signed_app/src/identity/import.rs | 12 +- crates/signed_app/src/identity/onboarding.rs | 12 +- crates/signed_app/src/identity/passphrase.rs | 12 +- crates/signed_app/src/inbox/helpers.rs | 15 +- crates/signed_app/src/inbox/mod.rs | 12 +- crates/signed_app/src/issues/detail.rs | 14 +- crates/signed_app/src/issues/helpers.rs | 19 +- crates/signed_app/src/issues/mod.rs | 27 +- crates/signed_app/src/issues/new_issue.rs | 12 +- crates/signed_app/src/pull_requests/detail.rs | 27 +- .../src/pull_requests/dialogs/update.rs | 12 +- .../signed_app/src/pull_requests/helpers.rs | 2 +- crates/signed_app/src/pull_requests/mod.rs | 33 +- crates/signed_app/src/pull_requests/new.rs | 29 +- .../src/pull_requests/send_patch.rs | 15 +- crates/signed_app/src/repo/commit_diff.rs | 20 +- crates/signed_app/src/repo/dialogs/about.rs | 10 +- crates/signed_app/src/repo/dialogs/create.rs | 16 +- .../src/repo/dialogs/grasp_servers.rs | 14 +- crates/signed_app/src/repo/dialogs/init.rs | 16 +- crates/signed_app/src/repo/dialogs/reset.rs | 8 +- crates/signed_app/src/repo/files.rs | 12 +- crates/signed_app/src/repo/header.rs | 36 +- crates/signed_app/src/repo/helpers.rs | 23 +- crates/signed_app/src/repo/history.rs | 8 +- crates/signed_app/src/repo/mod.rs | 21 +- crates/signed_app/src/repo/refs.rs | 2 +- crates/signed_app/src/settings/helpers.rs | 22 +- crates/signed_app/src/settings/mod.rs | 8 +- crates/signed_app/src/shared/panels.rs | 2 +- crates/signed_app/src/shared/progress.rs | 8 +- crates/signed_app/src/shared/widgets.rs | 33 +- crates/signed_app/src/titlebar/helpers.rs | 4 +- crates/signed_app/src/titlebar/mod.rs | 18 +- crates/signed_app/src/workspace.rs | 6 +- crates/ui/Cargo.toml | 71 + crates/ui/src/components/alert.rs | 407 +++ crates/ui/src/components/avatar.rs | 331 +++ crates/ui/src/components/badge.rs | 161 + crates/ui/src/components/button.rs | 342 +++ crates/ui/src/components/checkbox.rs | 177 ++ crates/ui/src/components/clipboard.rs | 177 ++ crates/ui/src/components/combobox.rs | 752 +++++ crates/ui/src/components/command_palette.rs | 529 ++++ crates/ui/src/components/common.rs | 50 + crates/ui/src/components/context_menu.rs | 127 + crates/ui/src/components/dialog.rs | 331 +++ crates/ui/src/components/dropdown_menu.rs | 491 ++++ crates/ui/src/components/empty_state.rs | 111 + crates/ui/src/components/field.rs | 181 ++ crates/ui/src/components/grain.rs | 90 + crates/ui/src/components/input.rs | 2580 +++++++++++++++++ crates/ui/src/components/link.rs | 139 + crates/ui/src/components/menu.rs | 1111 +++++++ crates/ui/src/components/mod.rs | 36 + crates/ui/src/components/popover.rs | 244 ++ crates/ui/src/components/progress.rs | 124 + crates/ui/src/components/radio.rs | 242 ++ crates/ui/src/components/scroll_area.rs | 143 + crates/ui/src/components/scrollbar.rs | 520 ++++ crates/ui/src/components/segmented.rs | 358 +++ crates/ui/src/components/select.rs | 348 +++ crates/ui/src/components/separator.rs | 91 + crates/ui/src/components/slider.rs | 312 ++ crates/ui/src/components/speech.rs | 1074 +++++++ crates/ui/src/components/spinner.rs | 299 ++ crates/ui/src/components/status_dot.rs | 108 + crates/ui/src/components/switch.rs | 180 ++ crates/ui/src/components/toast.rs | 354 +++ crates/ui/src/components/toggle.rs | 166 ++ crates/ui/src/components/tooltip.rs | 141 + crates/ui/src/data/list.rs | 270 ++ crates/ui/src/data/mod.rs | 6 + crates/ui/src/data/sidebar.rs | 524 ++++ crates/ui/src/data/tabs.rs | 1224 ++++++++ crates/ui/src/data/tree.rs | 476 +++ crates/ui/src/editor/code.rs | 576 ++++ crates/ui/src/editor/diff.rs | 691 +++++ crates/ui/src/editor/highlight.rs | 267 ++ crates/ui/src/editor/markdown.rs | 2072 +++++++++++++ crates/ui/src/editor/mod.rs | 8 + crates/ui/src/editor/utils.rs | 123 + crates/ui/src/icons/NOTICE.md | 9 + .../src/icons/assets}/a-large-small.svg | 0 .../src/icons/assets}/arrow-down.svg | 0 .../src/icons/assets}/arrow-left.svg | 0 .../src/icons/assets}/arrow-right.svg | 0 crates/ui/src/icons/assets/arrow-up-down.svg | 16 + .../src/icons/assets}/arrow-up.svg | 0 .../src/icons/assets}/asterisk.svg | 0 .../src/icons/assets}/battery-charging.svg | 0 .../src/icons/assets}/battery-full.svg | 0 .../src/icons/assets}/battery-low.svg | 0 .../src/icons/assets}/battery-medium.svg | 0 .../src/icons/assets}/battery-warning.svg | 0 .../icons => ui/src/icons/assets}/battery.svg | 0 .../icons => ui/src/icons/assets}/bell.svg | 0 .../src/icons/assets}/book-open.svg | 0 .../icons => ui/src/icons/assets}/bot.svg | 0 .../src/icons/assets}/building-2.svg | 0 .../src/icons/assets}/calendar.svg | 0 .../src/icons/assets}/case-sensitive.svg | 0 .../src/icons/assets}/chart-pie.svg | 0 .../icons => ui/src/icons/assets}/check.svg | 0 .../src/icons/assets}/chevron-down.svg | 0 .../src/icons/assets}/chevron-left.svg | 0 .../src/icons/assets}/chevron-right.svg | 0 .../src/icons/assets}/chevron-up.svg | 0 .../src/icons/assets}/chevrons-up-down.svg | 0 .../src/icons/assets}/circle-check.svg | 0 .../src/icons/assets}/circle-plus.svg | 0 .../src/icons/assets/circle-question-mark.svg | 15 + .../src/icons/assets}/circle-user.svg | 0 .../src/icons/assets}/circle-x.svg | 0 .../ui/src/icons/assets/clipboard-paste.svg | 17 + crates/ui/src/icons/assets/clock.svg | 14 + .../icons => ui/src/icons/assets}/close.svg | 0 .../icons => ui/src/icons/assets}/copy.svg | 0 .../icons => ui/src/icons/assets}/cpu.svg | 0 .../icons => ui/src/icons/assets}/dash.svg | 0 .../icons => ui/src/icons/assets}/delete.svg | 0 crates/ui/src/icons/assets/download.svg | 15 + .../src/icons/assets}/ellipsis-vertical.svg | 0 .../src/icons/assets}/ellipsis.svg | 0 .../src/icons/assets}/external-link.svg | 0 .../icons => ui/src/icons/assets}/eye-off.svg | 0 .../icons => ui/src/icons/assets}/eye.svg | 0 .../icons => ui/src/icons/assets}/file.svg | 0 .../icons => ui/src/icons/assets}/filter.svg | 0 .../src/icons/assets}/folder-closed.svg | 0 .../src/icons/assets}/folder-open.svg | 0 .../icons => ui/src/icons/assets}/folder.svg | 0 .../icons => ui/src/icons/assets}/frame.svg | 0 .../icons/assets}/gallery-vertical-end.svg | 0 .../src/icons/assets}/git-branch.svg | 0 .../src/icons/assets}/git-clone.svg | 0 .../src/icons/assets}/git-commit.svg | 0 .../src/icons/assets}/git-file.svg | 0 .../src/icons/assets}/git-issue-close.svg | 0 .../src/icons/assets}/git-issue-done.svg | 0 .../src/icons/assets}/git-issue-ongoing.svg | 0 .../src/icons/assets}/git-issue-open.svg | 0 .../icons/assets}/git-pull-request-closed.svg | 0 .../icons/assets}/git-pull-request-draft.svg | 0 .../icons/assets}/git-pull-request-merged.svg | 0 .../src/icons/assets}/git-pull-request.svg | 0 .../icons => ui/src/icons/assets}/github.svg | 0 .../src/icons/assets}/global-on.svg | 0 .../icons => ui/src/icons/assets}/globe.svg | 0 .../icons => ui/src/icons/assets}/grid.svg | 0 .../src/icons/assets}/hard-drive.svg | 0 .../src/icons/assets}/heart-off.svg | 0 .../icons => ui/src/icons/assets}/heart.svg | 0 crates/ui/src/icons/assets/house.svg | 14 + crates/ui/src/icons/assets/image.svg | 15 + .../icons => ui/src/icons/assets}/inbox.svg | 0 .../icons => ui/src/icons/assets}/info.svg | 0 .../icons => ui/src/icons/assets}/init.svg | 0 .../src/icons/assets}/inspector.svg | 0 .../src/icons/assets}/layout-dashboard.svg | 0 crates/ui/src/icons/assets/layout-grid.svg | 16 + crates/ui/src/icons/assets/link.svg | 14 + crates/ui/src/icons/assets/list.svg | 18 + .../src/icons/assets}/loader-circle.svg | 0 .../icons => ui/src/icons/assets}/loader.svg | 0 crates/ui/src/icons/assets/lock-open.svg | 14 + crates/ui/src/icons/assets/lock.svg | 14 + crates/ui/src/icons/assets/mail.svg | 14 + .../icons => ui/src/icons/assets}/map.svg | 0 .../src/icons/assets}/markdown.svg | 0 .../src/icons/assets}/maximize.svg | 0 .../src/icons/assets}/memory-stick.svg | 0 .../icons => ui/src/icons/assets}/menu.svg | 0 crates/ui/src/icons/assets/mic.svg | 15 + .../src/icons/assets}/minimize.svg | 0 .../icons => ui/src/icons/assets}/minus.svg | 0 .../icons => ui/src/icons/assets}/moon.svg | 0 .../icons => ui/src/icons/assets}/network.svg | 0 .../icons => ui/src/icons/assets}/palette.svg | 0 .../src/icons/assets}/panel-bottom-open.svg | 0 .../src/icons/assets}/panel-bottom.svg | 0 .../src/icons/assets}/panel-left-close.svg | 0 .../src/icons/assets}/panel-left-open.svg | 0 .../src/icons/assets}/panel-left.svg | 0 .../src/icons/assets}/panel-right-close.svg | 0 .../src/icons/assets}/panel-right-open.svg | 0 .../src/icons/assets}/panel-right.svg | 0 .../icons => ui/src/icons/assets}/pause.svg | 0 crates/ui/src/icons/assets/pencil.svg | 14 + crates/ui/src/icons/assets/pin.svg | 14 + .../icons => ui/src/icons/assets}/play.svg | 0 .../icons => ui/src/icons/assets}/plus.svg | 0 crates/ui/src/icons/assets/printer.svg | 15 + .../icons => ui/src/icons/assets}/recent.svg | 0 .../icons => ui/src/icons/assets}/redo-2.svg | 0 .../icons => ui/src/icons/assets}/redo.svg | 0 crates/ui/src/icons/assets/refresh-cw.svg | 16 + .../icons => ui/src/icons/assets}/refresh.svg | 0 .../icons => ui/src/icons/assets}/replace.svg | 0 .../src/icons/assets}/resize-corner.svg | 0 crates/ui/src/icons/assets/save.svg | 15 + crates/ui/src/icons/assets/scissors.svg | 17 + .../icons => ui/src/icons/assets}/search.svg | 0 crates/ui/src/icons/assets/send.svg | 14 + .../src/icons/assets}/settings-2.svg | 0 .../src/icons/assets}/settings.svg | 0 .../icons => ui/src/icons/assets}/share.svg | 0 .../src/icons/assets}/sort-ascending.svg | 0 .../src/icons/assets}/sort-descending.svg | 0 .../src/icons/assets}/square-terminal.svg | 0 crates/ui/src/icons/assets/square.svg | 13 + .../src/icons/assets}/star-fill.svg | 0 .../src/icons/assets}/star-off.svg | 0 .../icons => ui/src/icons/assets}/star.svg | 0 .../icons => ui/src/icons/assets}/sun.svg | 0 .../icons => ui/src/icons/assets}/tag.svg | 0 .../ui/src/icons/assets/text-align-center.svg | 15 + crates/ui/src/icons/assets/text-align-end.svg | 15 + .../ui/src/icons/assets/text-align-start.svg | 15 + .../src/icons/assets}/thumbs-down.svg | 0 .../src/icons/assets}/thumbs-up.svg | 0 .../icons => ui/src/icons/assets}/trash.svg | 0 .../src/icons/assets}/trending.svg | 0 .../src/icons/assets}/triangle-alert.svg | 0 .../icons => ui/src/icons/assets}/undo-2.svg | 0 .../icons => ui/src/icons/assets}/undo.svg | 0 .../icons => ui/src/icons/assets}/unlock.svg | 0 .../icons => ui/src/icons/assets}/user.svg | 0 crates/ui/src/icons/assets/volume-2.svg | 15 + crates/ui/src/icons/assets/volume-x.svg | 15 + .../src/icons/assets}/window-close.svg | 0 .../src/icons/assets}/window-maximize.svg | 0 .../src/icons/assets}/window-minimize.svg | 0 .../src/icons/assets}/window-restore.svg | 0 crates/ui/src/icons/assets/x.svg | 14 + crates/ui/src/icons/assets/zoom-in.svg | 16 + crates/ui/src/icons/assets/zoom-out.svg | 15 + crates/ui/src/icons/freedesktop.rs | 429 +++ crates/ui/src/icons/mod.rs | 895 ++++++ crates/ui/src/icons/segoe.rs | 124 + crates/ui/src/layout/mod.rs | 10 + crates/ui/src/layout/panel.rs | 173 ++ crates/ui/src/layout/resizable.rs | 312 ++ crates/ui/src/layout/resize_handle.rs | 319 ++ crates/ui/src/layout/shell.rs | 134 + crates/ui/src/layout/titlebar.rs | 142 + crates/ui/src/layout/window_controls.rs | 316 ++ crates/ui/src/layout/window_frame.rs | 175 ++ crates/ui/src/lib.rs | 24 + crates/ui/src/theme/colors.rs | 170 ++ crates/ui/src/theme/definition.rs | 274 ++ crates/ui/src/theme/mod.rs | 789 +++++ crates/ui/src/theme/presets.rs | 40 + crates/ui/src/theme/presets/tokyo-night.toml | 21 + crates/ui/src/theme/ramps.rs | 274 ++ crates/ui/src/theme/resolve.rs | 804 +++++ crates/ui/src/theme/source.rs | 64 + crates/ui/src/theme/source/fallback.rs | 20 + crates/ui/src/theme/source/kde.rs | 255 ++ crates/ui/src/theme/source/linux.rs | 330 +++ crates/ui/src/theme/source/macos.rs | 158 + crates/ui/src/theme/source/omarchy.rs | 170 ++ crates/ui/src/theme/source/portal.rs | 230 ++ crates/ui/src/theme/source/signal.rs | 41 + crates/ui/src/theme/source/windows.rs | 208 ++ crates/ui/src/theme/system.rs | 69 + crates/ui/src/theme/typography.rs | 209 ++ crates/ui/src/utils.rs | 171 ++ crates/ui/tests/panel.rs | 152 + crates/ui/tests/sizing.rs | 59 + crates/ui/tests/tabs.rs | 259 ++ desktop/Cargo.toml | 3 +- desktop/src/main.rs | 8 +- docs/{gpui-native-kit-gaps.md => ui-gaps.md} | 26 +- 287 files changed, 28142 insertions(+), 590 deletions(-) delete mode 100644 crates/assets/Cargo.toml delete mode 100644 crates/assets/assets/.keep delete mode 100644 crates/assets/src/lib.rs create mode 100644 crates/ui/Cargo.toml create mode 100644 crates/ui/src/components/alert.rs create mode 100644 crates/ui/src/components/avatar.rs create mode 100644 crates/ui/src/components/badge.rs create mode 100644 crates/ui/src/components/button.rs create mode 100644 crates/ui/src/components/checkbox.rs create mode 100644 crates/ui/src/components/clipboard.rs create mode 100644 crates/ui/src/components/combobox.rs create mode 100644 crates/ui/src/components/command_palette.rs create mode 100644 crates/ui/src/components/common.rs create mode 100644 crates/ui/src/components/context_menu.rs create mode 100644 crates/ui/src/components/dialog.rs create mode 100644 crates/ui/src/components/dropdown_menu.rs create mode 100644 crates/ui/src/components/empty_state.rs create mode 100644 crates/ui/src/components/field.rs create mode 100644 crates/ui/src/components/grain.rs create mode 100644 crates/ui/src/components/input.rs create mode 100644 crates/ui/src/components/link.rs create mode 100644 crates/ui/src/components/menu.rs create mode 100644 crates/ui/src/components/mod.rs create mode 100644 crates/ui/src/components/popover.rs create mode 100644 crates/ui/src/components/progress.rs create mode 100644 crates/ui/src/components/radio.rs create mode 100644 crates/ui/src/components/scroll_area.rs create mode 100644 crates/ui/src/components/scrollbar.rs create mode 100644 crates/ui/src/components/segmented.rs create mode 100644 crates/ui/src/components/select.rs create mode 100644 crates/ui/src/components/separator.rs create mode 100644 crates/ui/src/components/slider.rs create mode 100644 crates/ui/src/components/speech.rs create mode 100644 crates/ui/src/components/spinner.rs create mode 100644 crates/ui/src/components/status_dot.rs create mode 100644 crates/ui/src/components/switch.rs create mode 100644 crates/ui/src/components/toast.rs create mode 100644 crates/ui/src/components/toggle.rs create mode 100644 crates/ui/src/components/tooltip.rs create mode 100644 crates/ui/src/data/list.rs create mode 100644 crates/ui/src/data/mod.rs create mode 100644 crates/ui/src/data/sidebar.rs create mode 100644 crates/ui/src/data/tabs.rs create mode 100644 crates/ui/src/data/tree.rs create mode 100644 crates/ui/src/editor/code.rs create mode 100644 crates/ui/src/editor/diff.rs create mode 100644 crates/ui/src/editor/highlight.rs create mode 100644 crates/ui/src/editor/markdown.rs create mode 100644 crates/ui/src/editor/mod.rs create mode 100644 crates/ui/src/editor/utils.rs create mode 100644 crates/ui/src/icons/NOTICE.md rename crates/{assets/assets/icons => ui/src/icons/assets}/a-large-small.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/arrow-down.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/arrow-left.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/arrow-right.svg (100%) create mode 100644 crates/ui/src/icons/assets/arrow-up-down.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/arrow-up.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/asterisk.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/battery-charging.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/battery-full.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/battery-low.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/battery-medium.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/battery-warning.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/battery.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/bell.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/book-open.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/bot.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/building-2.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/calendar.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/case-sensitive.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/chart-pie.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/check.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/chevron-down.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/chevron-left.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/chevron-right.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/chevron-up.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/chevrons-up-down.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/circle-check.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/circle-plus.svg (100%) create mode 100644 crates/ui/src/icons/assets/circle-question-mark.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/circle-user.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/circle-x.svg (100%) create mode 100644 crates/ui/src/icons/assets/clipboard-paste.svg create mode 100644 crates/ui/src/icons/assets/clock.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/close.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/copy.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/cpu.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/dash.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/delete.svg (100%) create mode 100644 crates/ui/src/icons/assets/download.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/ellipsis-vertical.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/ellipsis.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/external-link.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/eye-off.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/eye.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/file.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/filter.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/folder-closed.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/folder-open.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/folder.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/frame.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/gallery-vertical-end.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/git-branch.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/git-clone.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/git-commit.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/git-file.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/git-issue-close.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/git-issue-done.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/git-issue-ongoing.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/git-issue-open.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/git-pull-request-closed.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/git-pull-request-draft.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/git-pull-request-merged.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/git-pull-request.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/github.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/global-on.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/globe.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/grid.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/hard-drive.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/heart-off.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/heart.svg (100%) create mode 100644 crates/ui/src/icons/assets/house.svg create mode 100644 crates/ui/src/icons/assets/image.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/inbox.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/info.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/init.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/inspector.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/layout-dashboard.svg (100%) create mode 100644 crates/ui/src/icons/assets/layout-grid.svg create mode 100644 crates/ui/src/icons/assets/link.svg create mode 100644 crates/ui/src/icons/assets/list.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/loader-circle.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/loader.svg (100%) create mode 100644 crates/ui/src/icons/assets/lock-open.svg create mode 100644 crates/ui/src/icons/assets/lock.svg create mode 100644 crates/ui/src/icons/assets/mail.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/map.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/markdown.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/maximize.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/memory-stick.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/menu.svg (100%) create mode 100644 crates/ui/src/icons/assets/mic.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/minimize.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/minus.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/moon.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/network.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/palette.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/panel-bottom-open.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/panel-bottom.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/panel-left-close.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/panel-left-open.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/panel-left.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/panel-right-close.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/panel-right-open.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/panel-right.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/pause.svg (100%) create mode 100644 crates/ui/src/icons/assets/pencil.svg create mode 100644 crates/ui/src/icons/assets/pin.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/play.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/plus.svg (100%) create mode 100644 crates/ui/src/icons/assets/printer.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/recent.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/redo-2.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/redo.svg (100%) create mode 100644 crates/ui/src/icons/assets/refresh-cw.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/refresh.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/replace.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/resize-corner.svg (100%) create mode 100644 crates/ui/src/icons/assets/save.svg create mode 100644 crates/ui/src/icons/assets/scissors.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/search.svg (100%) create mode 100644 crates/ui/src/icons/assets/send.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/settings-2.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/settings.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/share.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/sort-ascending.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/sort-descending.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/square-terminal.svg (100%) create mode 100644 crates/ui/src/icons/assets/square.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/star-fill.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/star-off.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/star.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/sun.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/tag.svg (100%) create mode 100644 crates/ui/src/icons/assets/text-align-center.svg create mode 100644 crates/ui/src/icons/assets/text-align-end.svg create mode 100644 crates/ui/src/icons/assets/text-align-start.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/thumbs-down.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/thumbs-up.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/trash.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/trending.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/triangle-alert.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/undo-2.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/undo.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/unlock.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/user.svg (100%) create mode 100644 crates/ui/src/icons/assets/volume-2.svg create mode 100644 crates/ui/src/icons/assets/volume-x.svg rename crates/{assets/assets/icons => ui/src/icons/assets}/window-close.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/window-maximize.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/window-minimize.svg (100%) rename crates/{assets/assets/icons => ui/src/icons/assets}/window-restore.svg (100%) create mode 100644 crates/ui/src/icons/assets/x.svg create mode 100644 crates/ui/src/icons/assets/zoom-in.svg create mode 100644 crates/ui/src/icons/assets/zoom-out.svg create mode 100644 crates/ui/src/icons/freedesktop.rs create mode 100644 crates/ui/src/icons/mod.rs create mode 100644 crates/ui/src/icons/segoe.rs create mode 100644 crates/ui/src/layout/mod.rs create mode 100644 crates/ui/src/layout/panel.rs create mode 100644 crates/ui/src/layout/resizable.rs create mode 100644 crates/ui/src/layout/resize_handle.rs create mode 100644 crates/ui/src/layout/shell.rs create mode 100644 crates/ui/src/layout/titlebar.rs create mode 100644 crates/ui/src/layout/window_controls.rs create mode 100644 crates/ui/src/layout/window_frame.rs create mode 100644 crates/ui/src/lib.rs create mode 100644 crates/ui/src/theme/colors.rs create mode 100644 crates/ui/src/theme/definition.rs create mode 100644 crates/ui/src/theme/mod.rs create mode 100644 crates/ui/src/theme/presets.rs create mode 100644 crates/ui/src/theme/presets/tokyo-night.toml create mode 100644 crates/ui/src/theme/ramps.rs create mode 100644 crates/ui/src/theme/resolve.rs create mode 100644 crates/ui/src/theme/source.rs create mode 100644 crates/ui/src/theme/source/fallback.rs create mode 100644 crates/ui/src/theme/source/kde.rs create mode 100644 crates/ui/src/theme/source/linux.rs create mode 100644 crates/ui/src/theme/source/macos.rs create mode 100644 crates/ui/src/theme/source/omarchy.rs create mode 100644 crates/ui/src/theme/source/portal.rs create mode 100644 crates/ui/src/theme/source/signal.rs create mode 100644 crates/ui/src/theme/source/windows.rs create mode 100644 crates/ui/src/theme/system.rs create mode 100644 crates/ui/src/theme/typography.rs create mode 100644 crates/ui/src/utils.rs create mode 100644 crates/ui/tests/panel.rs create mode 100644 crates/ui/tests/sizing.rs create mode 100644 crates/ui/tests/tabs.rs rename docs/{gpui-native-kit-gaps.md => ui-gaps.md} (57%) diff --git a/Cargo.lock b/Cargo.lock index a86eda1..a636fbc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -114,6 +114,15 @@ dependencies = [ "equator", ] +[[package]] +name = "alloca" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5a7d05ea6aea7e9e64d25b9156ba2fee3fdd659e34e41063cd2fc7cd020d7f4" +dependencies = [ + "cc", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -151,6 +160,18 @@ dependencies = [ "libc", ] +[[package]] +name = "anes" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + [[package]] name = "anyhow" version = "1.0.104" @@ -226,16 +247,6 @@ dependencies = [ "zbus 5.19.0", ] -[[package]] -name = "assets" -version = "0.2.0" -dependencies = [ - "gpui", - "gpui-native-kit", - "rust-embed", - "serde_json", -] - [[package]] name = "async-broadcast" version = "0.7.2" @@ -420,6 +431,12 @@ dependencies = [ "web-sys", ] +[[package]] +name = "atomic" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba" + [[package]] name = "atomic-waker" version = "1.1.2" @@ -531,6 +548,17 @@ version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "efbd3e1070bbdf4cd88a75264e18e8a26f7cb5c6949eadf0ceb85fb159cf08f8" +[[package]] +name = "bench_metrics" +version = "0.1.0" +source = "git+https://github.com/zed-industries/zed#d39178f6c9e6adeb68e7a0df0b2a5b7d7bd35877" +dependencies = [ + "anyhow", + "criterion", + "libc", + "perf-event2", +] + [[package]] name = "bip39" version = "2.2.2" @@ -556,6 +584,10 @@ name = "bit-vec" version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" +dependencies = [ + "borsh", + "serde", +] [[package]] name = "bit_field" @@ -699,6 +731,30 @@ dependencies = [ "piper", ] +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "bstr" version = "1.13.1" @@ -760,6 +816,12 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "c-enum" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd17eb909a8c6a894926bfcc3400a4bb0e732f5a57d37b1f14e8b29e329bace8" + [[package]] name = "calloop" version = "0.14.5" @@ -772,6 +834,12 @@ dependencies = [ "tracing", ] +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + [[package]] name = "cbc" version = "0.1.2" @@ -872,6 +940,33 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] + [[package]] name = "cipher" version = "0.4.4" @@ -894,6 +989,31 @@ dependencies = [ "inout 0.2.6", ] +[[package]] +name = "clap" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstyle", + "clap_lex", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + [[package]] name = "clru" version = "0.6.3" @@ -989,6 +1109,15 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "convert_case" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "affbf0190ed2caf063e3def54ff444b449371d55c58e513a95ab98eca50adb49" +dependencies = [ + "unicode-segmentation", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -1151,6 +1280,41 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "criterion" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "950046b2aa2492f9a536f5f4f9a3de7b9e2476e575e05bd6c333371add4d98f3" +dependencies = [ + "alloca", + "anes", + "cast", + "ciborium", + "clap", + "criterion-plot", + "itertools 0.13.0", + "num-traits", + "oorandom", + "page_size", + "plotters", + "rayon", + "regex", + "serde", + "serde_json", + "tinytemplate", + "walkdir", +] + +[[package]] +name = "criterion-plot" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8d80a2f4f5b554395e47b5d8305bc3d27813bacb73493eb1001e8f76dae29ea" +dependencies = [ + "cast", + "itertools 0.13.0", +] + [[package]] name = "crossbeam-channel" version = "0.5.17" @@ -1331,7 +1495,7 @@ version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" dependencies = [ - "convert_case", + "convert_case 0.10.0", "proc-macro2", "quote", "rustc_version", @@ -1689,6 +1853,12 @@ version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "fixedbitset" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" + [[package]] name = "flatbuffers" version = "25.12.19" @@ -1876,6 +2046,19 @@ dependencies = [ "futures-sink", ] +[[package]] +name = "futures-concurrency" +version = "7.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175cd8cca9e1d45b87f18ffa75088f2099e3c4fe5e2f83e42de112560bea8ea6" +dependencies = [ + "fixedbitset", + "futures-core", + "futures-lite", + "pin-project", + "smallvec", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -2995,6 +3178,7 @@ dependencies = [ "async-channel", "async-task", "backtrace", + "bench_metrics", "bitflags 2.13.2", "chrono", "collections", @@ -3002,6 +3186,7 @@ dependencies = [ "embed-resource", "etagere", "futures", + "futures-concurrency", "getrandom 0.3.4", "gpui_macros", "gpui_shared_string", @@ -3011,7 +3196,7 @@ dependencies = [ "icu_segmenter", "image", "inventory", - "itertools", + "itertools 0.14.0", "libc", "log", "lyon_path", @@ -3021,8 +3206,10 @@ dependencies = [ "parking", "parking_lot", "pin-project", - "pollster", + "pollster 0.4.0", + "postage", "profiling", + "proptest", "rand 0.9.5", "raw-window-handle", "refineable", @@ -3047,123 +3234,11 @@ dependencies = [ "usvg", "uuid", "waker-fn", + "web-time", "windows 0.62.2", "zed-scap", ] -[[package]] -name = "gpui-native-core" -version = "0.1.0" -source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169" -dependencies = [ - "cpal", - "flume 0.12.0", - "gpui", - "gpui-native-icons", - "gpui-native-theme", - "gpui-native-utils", - "image", - "log", - "unicode-segmentation", -] - -[[package]] -name = "gpui-native-data" -version = "0.1.0" -source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169" -dependencies = [ - "gpui", - "gpui-native-core", - "gpui-native-icons", - "gpui-native-theme", - "gpui-native-utils", -] - -[[package]] -name = "gpui-native-editor" -version = "0.1.0" -source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169" -dependencies = [ - "gpui", - "gpui-native-core", - "gpui-native-theme", - "gpui-native-utils", - "log", - "pulldown-cmark", - "similar", - "tree-sitter", - "tree-sitter-javascript", - "tree-sitter-python", - "tree-sitter-rust", - "tree-sitter-typescript", -] - -[[package]] -name = "gpui-native-icons" -version = "0.1.0" -source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169" -dependencies = [ - "anyhow", - "gpui", -] - -[[package]] -name = "gpui-native-kit" -version = "0.1.0" -source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169" -dependencies = [ - "gpui", - "gpui-native-core", - "gpui-native-data", - "gpui-native-editor", - "gpui-native-icons", - "gpui-native-layout", - "gpui-native-theme", -] - -[[package]] -name = "gpui-native-layout" -version = "0.1.0" -source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169" -dependencies = [ - "gpui", - "gpui-native-core", - "gpui-native-icons", - "gpui-native-theme", - "gpui-native-utils", -] - -[[package]] -name = "gpui-native-theme" -version = "0.1.0" -source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169" -dependencies = [ - "anyhow", - "async-channel", - "block2 0.6.2", - "gpui", - "log", - "notify", - "objc2 0.6.5", - "objc2-app-kit 0.3.2", - "objc2-foundation 0.3.2", - "serde", - "toml 0.8.23", - "windows 0.62.2", - "windows-registry 0.6.1", - "zbus 5.19.0", -] - -[[package]] -name = "gpui-native-utils" -version = "0.1.0" -source = "git+https://git.reya.info/reya/gpui-native-kit#aed3601c890e49a8aba354df06416ce95ecbe169" -dependencies = [ - "gpui", - "gpui-native-theme", - "log", -] - [[package]] name = "gpui_apple" version = "0.1.0" @@ -3272,7 +3347,7 @@ dependencies = [ "gpui_apple", "gpui_util", "image", - "itertools", + "itertools 0.14.0", "log", "objc2 0.6.5", "objc2-app-kit 0.3.2", @@ -3379,7 +3454,7 @@ dependencies = [ "etagere", "gpui", "gpui_util", - "itertools", + "itertools 0.14.0", "js-sys", "log", "parking_lot", @@ -3408,7 +3483,7 @@ dependencies = [ "gpui", "gpui_util", "image", - "itertools", + "itertools 0.14.0", "log", "parking_lot", "rand 0.9.5", @@ -3669,6 +3744,7 @@ dependencies = [ "futures", "http", "http-body", + "log", "parking_lot", "serde", "serde_json", @@ -3983,7 +4059,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" dependencies = [ "byteorder-lite", - "quick-error", + "quick-error 2.0.1", ] [[package]] @@ -4085,6 +4161,15 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.14.0" @@ -5408,6 +5493,12 @@ dependencies = [ "zvariant", ] +[[package]] +name = "oorandom" +version = "11.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" + [[package]] name = "opaque-debug" version = "0.3.1" @@ -5560,6 +5651,41 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "perf-event-data" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "575828d9d7d205188048eb1508560607a03d21eafdbba47b8cade1736c1c28e1" +dependencies = [ + "bitflags 2.13.2", + "c-enum", + "perf-event-open-sys2", +] + +[[package]] +name = "perf-event-open-sys2" +version = "5.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c25955321465255e437600b54296983fab1feac2cd0c38958adeb26dbae49e" +dependencies = [ + "libc", + "memoffset", +] + +[[package]] +name = "perf-event2" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0939b8fad77dfaeb29ebbd35faaeaadbf833167f30975f1b8993bbba09ea0a0f" +dependencies = [ + "bitflags 2.13.2", + "c-enum", + "libc", + "memmap2", + "perf-event-data", + "perf-event-open-sys2", +] + [[package]] name = "phf" version = "0.11.3" @@ -5651,6 +5777,34 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "plotters" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" +dependencies = [ + "num-traits", + "plotters-backend", + "plotters-svg", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "plotters-backend" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" + +[[package]] +name = "plotters-svg" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" +dependencies = [ + "plotters-backend", +] + [[package]] name = "png" version = "0.17.16" @@ -5691,6 +5845,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "pollster" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7" + [[package]] name = "pollster" version = "0.4.0" @@ -5732,6 +5892,21 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "postage" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3fb618632874fb76937c2361a7f22afd393c982a2165595407edc75b06d3c1" +dependencies = [ + "atomic", + "crossbeam-queue", + "parking_lot", + "pin-project", + "pollster 0.2.5", + "static_assertions", + "thiserror 1.0.69", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -5810,6 +5985,39 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bit-set", + "bit-vec", + "bitflags 2.13.2", + "chacha20 0.10.2", + "core_detect", + "num-traits", + "proptest-macro", + "rand 0.10.4", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "proptest-macro" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e99782ea31698c2206c6887c1220d2f594b291c26cb9ec5b6d7cf175320bc212" +dependencies = [ + "convert_case 0.11.0", + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "pulldown-cmark" version = "0.13.6" @@ -5836,6 +6044,12 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + [[package]] name = "quick-error" version = "2.0.1" @@ -6014,6 +6228,15 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "range-alloc" version = "0.1.5" @@ -6042,7 +6265,7 @@ dependencies = [ "built", "cfg-if", "interpolate_name", - "itertools", + "itertools 0.14.0", "libc", "libfuzzer-sys", "log", @@ -6070,7 +6293,7 @@ dependencies = [ "avif-serialize", "imgref", "loop9", - "quick-error", + "quick-error 2.0.1", "rav1e", "rayon", "rgb", @@ -6498,6 +6721,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error 1.2.3", + "tempfile", + "wait-timeout", +] + [[package]] name = "rustybuzz" version = "0.20.1" @@ -6868,9 +7103,7 @@ dependencies = [ name = "signed" version = "0.2.0" dependencies = [ - "assets", "gpui", - "gpui-native-kit", "gpui_platform", "metadata", "paths", @@ -6880,6 +7113,7 @@ dependencies = [ "signed_state", "tracing", "tracing-subscriber", + "ui", ] [[package]] @@ -6887,10 +7121,8 @@ name = "signed_app" version = "0.2.0" dependencies = [ "anyhow", - "assets", "futures", "gpui", - "gpui-native-kit", "log", "metadata", "nostr", @@ -6900,6 +7132,7 @@ dependencies = [ "signed_git", "signed_nostr", "signed_state", + "ui", "utils", ] @@ -7417,7 +7650,7 @@ dependencies = [ "fax", "flate2", "half", - "quick-error", + "quick-error 2.0.1", "weezl", "zune-jpeg", ] @@ -7478,6 +7711,16 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinytemplate" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "tinyvec" version = "1.13.3" @@ -7889,6 +8132,44 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "ui" +version = "0.2.0" +dependencies = [ + "anyhow", + "async-channel", + "block2 0.6.2", + "cpal", + "flume 0.11.1", + "gpui", + "image", + "log", + "notify", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "pulldown-cmark", + "rust-embed", + "serde", + "similar", + "toml 0.8.23", + "tree-sitter", + "tree-sitter-javascript", + "tree-sitter-python", + "tree-sitter-rust", + "tree-sitter-typescript", + "unicode-segmentation", + "windows 0.62.2", + "windows-registry 0.6.1", + "zbus 5.19.0", +] + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "unicase" version = "2.10.0" @@ -8116,6 +8397,15 @@ dependencies = [ "libc", ] +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + [[package]] name = "waker-fn" version = "1.2.0" diff --git a/Cargo.toml b/Cargo.toml index 73f1524..d181039 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,8 +13,6 @@ gpui = { git = "https://github.com/zed-industries/zed" } gpui_platform = { git = "https://github.com/zed-industries/zed", features = ["font-kit"] } reqwest_client = { git = "https://github.com/zed-industries/zed" } -gpui-native-kit = { git = "https://git.reya.info/reya/gpui-native-kit", features = ["layout", "editor"] } - settings = { path = "crates/settings" } signed_app = { path = "crates/signed_app" } diff --git a/crates/assets/Cargo.toml b/crates/assets/Cargo.toml deleted file mode 100644 index 1562b94..0000000 --- a/crates/assets/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "assets" -version.workspace = true -edition.workspace = true -publish.workspace = true - -[dependencies] -gpui.workspace = true -gpui-native-kit.workspace = true -rust-embed.workspace = true - -[dev-dependencies] -serde_json.workspace = true diff --git a/crates/assets/assets/.keep b/crates/assets/assets/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/crates/assets/src/lib.rs b/crates/assets/src/lib.rs deleted file mode 100644 index 667cb5d..0000000 --- a/crates/assets/src/lib.rs +++ /dev/null @@ -1,98 +0,0 @@ -use gpui::{AssetSource, Result, SharedString}; -use gpui_native_kit::icons::IconNamed; -use rust_embed::RustEmbed; - -#[derive(RustEmbed)] -#[folder = "assets"] -#[include = "icons/**/*.svg"] -#[exclude = "*.DS_Store"] -pub struct Assets; - -impl AssetSource for Assets { - fn load(&self, path: &str) -> Result>> { - if let Some(file) = Self::get(path) { - return Ok(Some(file.data)); - } - gpui_native_kit::icons::IconAssets.load(path) - } - - fn list(&self, path: &str) -> Result> { - let mut paths: Vec = Self::iter() - .filter(|p| p.starts_with(path)) - .map(Into::into) - .collect(); - paths.extend(gpui_native_kit::icons::IconAssets.list(path)?); - Ok(paths) - } -} - -pub enum CustomIconName { - CirclePlus, - Unlock, - Filter, - GlobalOn, - GlobalOff, - GitFile, - GitCommit, - GitIssueDone, - GitIssueOpen, - GitIssueClosed, - GitIssueOngoing, - GitPullRequest, - GitPullRequestClosed, - GitPullRequestDraft, - GitPullRequestMerged, - GitClone, - GitBranch, - Tag, - Markdown, - Share, - Trending, - Recent, - Refresh, - Grid, - Init, - EllipsisVertical, - ArrowUp, - Trash, - Globe, - Inbox, -} - -impl IconNamed for CustomIconName { - fn path(self) -> gpui::SharedString { - match self { - CustomIconName::CirclePlus => "icons/circle-plus.svg", - CustomIconName::Unlock => "icons/unlock.svg", - CustomIconName::Filter => "icons/filter.svg", - CustomIconName::GlobalOn => "icons/global-on.svg", - CustomIconName::GlobalOff => "icons/global-off.svg", - CustomIconName::GitCommit => "icons/git-commit.svg", - CustomIconName::GitFile => "icons/git-file.svg", - CustomIconName::GitIssueDone => "icons/git-issue-done.svg", - CustomIconName::GitIssueOpen => "icons/git-issue-open.svg", - CustomIconName::GitIssueClosed => "icons/git-issue-close.svg", - CustomIconName::GitIssueOngoing => "icons/git-issue-ongoing.svg", - CustomIconName::GitPullRequest => "icons/git-pull-request.svg", - CustomIconName::GitPullRequestClosed => "icons/git-pull-request-closed.svg", - CustomIconName::GitPullRequestDraft => "icons/git-pull-request-draft.svg", - CustomIconName::GitPullRequestMerged => "icons/git-pull-request-merged.svg", - CustomIconName::GitClone => "icons/git-clone.svg", - CustomIconName::GitBranch => "icons/git-branch.svg", - CustomIconName::Tag => "icons/tag.svg", - CustomIconName::Markdown => "icons/markdown.svg", - CustomIconName::Share => "icons/share.svg", - CustomIconName::Trending => "icons/trending.svg", - CustomIconName::Refresh => "icons/refresh.svg", - CustomIconName::Recent => "icons/recent.svg", - CustomIconName::Grid => "icons/grid.svg", - CustomIconName::Init => "icons/init.svg", - CustomIconName::EllipsisVertical => "icons/ellipsis-vertical.svg", - CustomIconName::ArrowUp => "icons/arrow-up.svg", - CustomIconName::Trash => "icons/trash.svg", - CustomIconName::Globe => "icons/globe.svg", - CustomIconName::Inbox => "icons/inbox.svg", - } - .into() - } -} diff --git a/crates/signed_app/Cargo.toml b/crates/signed_app/Cargo.toml index dbb638f..645a5aa 100644 --- a/crates/signed_app/Cargo.toml +++ b/crates/signed_app/Cargo.toml @@ -5,7 +5,6 @@ edition.workspace = true publish.workspace = true [dependencies] -assets = { path = "../assets" } metadata = { path = "../metadata" } paths = { path = "../paths" } settings = { path = "../settings" } @@ -16,7 +15,7 @@ signed_state = { path = "../signed_state" } utils = { path = "../utils" } gpui.workspace = true -gpui-native-kit.workspace = true +ui = { path = "../ui" } nostr.workspace = true anyhow.workspace = true futures.workspace = true diff --git a/crates/signed_app/src/app/helpers.rs b/crates/signed_app/src/app/helpers.rs index ee2d1e4..98ff04b 100644 --- a/crates/signed_app/src/app/helpers.rs +++ b/crates/signed_app/src/app/helpers.rs @@ -1,6 +1,6 @@ use gpui::App; -use gpui_native_kit::theme::{ThemeVariant, follow_system, set_mode_override}; use settings::{AppearanceMode, Settings}; +use ui::theme::{ThemeVariant, follow_system, set_mode_override}; /// Applies the persisted light/dark/system preference to the kit theme. pub fn apply_appearance(settings: &Settings, cx: &mut App) { diff --git a/crates/signed_app/src/app/mod.rs b/crates/signed_app/src/app/mod.rs index 2ad9a25..9cd35e2 100644 --- a/crates/signed_app/src/app/mod.rs +++ b/crates/signed_app/src/app/mod.rs @@ -6,15 +6,15 @@ use gpui::{ AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Subscription, Window, div, }; -use gpui_native_kit::icons::IconRole; -use gpui_native_kit::layout::panel::PanelRow; -use gpui_native_kit::layout::shell::Shell; -use gpui_native_kit::layout::titlebar::Titlebar; -use gpui_native_kit::theme::ActiveTheme as _; -use gpui_native_kit::toast::{Toast, Toasts}; use helpers::apply_appearance; use settings::SettingsStore; use signed_state::{Backend, BackendEvent}; +use ui::icons::IconRole; +use ui::layout::panel::PanelRow; +use ui::layout::shell::Shell; +use ui::layout::titlebar::Titlebar; +use ui::theme::ActiveTheme as _; +use ui::toast::{Toast, Toasts}; use crate::app::placeholder::PlaceholderView; use crate::app::sign_in::SignedOutView; diff --git a/crates/signed_app/src/app/placeholder.rs b/crates/signed_app/src/app/placeholder.rs index 11fd817..62633b0 100644 --- a/crates/signed_app/src/app/placeholder.rs +++ b/crates/signed_app/src/app/placeholder.rs @@ -1,8 +1,8 @@ use gpui::{ Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div, }; -use gpui_native_kit::empty_state::EmptyState; -use gpui_native_kit::layout::panel::Panel; +use ui::empty_state::EmptyState; +use ui::layout::panel::Panel; /// A tab that stands in for a screen that is not ported yet. pub struct PlaceholderView { diff --git a/crates/signed_app/src/app/sign_in.rs b/crates/signed_app/src/app/sign_in.rs index 0f5dcf8..5eccd24 100644 --- a/crates/signed_app/src/app/sign_in.rs +++ b/crates/signed_app/src/app/sign_in.rs @@ -1,9 +1,9 @@ use gpui::{ Context, FontWeight, IntoElement, ParentElement as _, Render, Styled as _, Window, div, }; -use gpui_native_kit::button::{Button, ButtonVariant}; -use gpui_native_kit::common::v_flex; -use gpui_native_kit::layout::panel::Panel; +use ui::button::{Button, ButtonVariant}; +use ui::common::v_flex; +use ui::layout::panel::Panel; use crate::identity; diff --git a/crates/signed_app/src/explore/helpers.rs b/crates/signed_app/src/explore/helpers.rs index 8044d13..a2d1ab6 100644 --- a/crates/signed_app/src/explore/helpers.rs +++ b/crates/signed_app/src/explore/helpers.rs @@ -1,16 +1,15 @@ -use assets::CustomIconName; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, Entity, InteractiveElement as _, IntoElement, ParentElement as _, SharedString, StatefulInteractiveElement as _, Styled as _, WeakEntity, div, px, }; -use gpui_native_kit::avatar::Avatar; -use gpui_native_kit::common::{Sizable as _, h_flex, v_flex}; -use gpui_native_kit::icons::Icon; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use metadata::ProfileDirectory; use signed_core::Announcement; use signed_state::{RepoListStore, Timestamp}; +use ui::avatar::Avatar; +use ui::common::{Sizable as _, h_flex, v_flex}; +use ui::icons::{Icon, IconRole}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use utils::relative_time; use crate::repo::actions::open_repo_panel; @@ -134,7 +133,7 @@ pub(super) fn render_card( .text_color(cx.theme().colors.muted_foreground) .whitespace_nowrap() .child( - Icon::named(CustomIconName::GitBranch) + Icon::named(IconRole::GitBranch) .size(px(12.)) .color(cx.theme().colors.muted_foreground), ) diff --git a/crates/signed_app/src/explore/mod.rs b/crates/signed_app/src/explore/mod.rs index da568e7..71f6c5f 100644 --- a/crates/signed_app/src/explore/mod.rs +++ b/crates/signed_app/src/explore/mod.rs @@ -1,24 +1,23 @@ mod helpers; -use assets::CustomIconName; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Subscription, UniformListScrollHandle, WeakEntity, Window, div, px, uniform_list, }; -use gpui_native_kit::common::{h_flex, v_flex}; -use gpui_native_kit::empty_state::EmptyState; -use gpui_native_kit::icons::{Icon, IconRole}; -use gpui_native_kit::input::{Input, InputState, InputStateEvent}; -use gpui_native_kit::layout::panel::Panel; -use gpui_native_kit::scrollbar::Scrollbar; -use gpui_native_kit::segmented::{Segmented, SegmentedOption}; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use helpers::{RepoFilter, render_card}; use metadata::ProfileDirectory; use nostr::prelude::PublicKey; use signed_state::RepoListStore; +use ui::common::{h_flex, v_flex}; +use ui::empty_state::EmptyState; +use ui::icons::{Icon, IconRole}; +use ui::input::{Input, InputState, InputStateEvent}; +use ui::layout::panel::Panel; +use ui::scrollbar::Scrollbar; +use ui::segmented::{Segmented, SegmentedOption}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use crate::workspace::Workspace; @@ -131,7 +130,7 @@ impl ExploreView { SegmentedOption::new(RepoFilter::All, "All") .icon(Icon::named(IconRole::Grid).small().color(muted)), SegmentedOption::new(RepoFilter::Popular, "Popular") - .icon(Icon::named(CustomIconName::Trending).small().color(muted)), + .icon(Icon::named(IconRole::Trending).small().color(muted)), SegmentedOption::new(RepoFilter::Recent, "Recent") .icon(Icon::named(IconRole::Clock).small().color(muted)), ]) diff --git a/crates/signed_app/src/identity/exit.rs b/crates/signed_app/src/identity/exit.rs index 15fc8be..6c56a71 100644 --- a/crates/signed_app/src/identity/exit.rs +++ b/crates/signed_app/src/identity/exit.rs @@ -1,11 +1,11 @@ use gpui::{ AnyElement, Context, IntoElement, ParentElement as _, Render, Styled as _, Window, div, }; -use gpui_native_kit::button::{Button, ButtonVariant}; -use gpui_native_kit::common::v_flex; -use gpui_native_kit::dialog::Dialog; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use signed_state::Backend; +use ui::button::{Button, ButtonVariant}; +use ui::common::v_flex; +use ui::dialog::Dialog; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use crate::shared::dialogs::close_global; diff --git a/crates/signed_app/src/identity/import.rs b/crates/signed_app/src/identity/import.rs index f4141cc..bae4dc0 100644 --- a/crates/signed_app/src/identity/import.rs +++ b/crates/signed_app/src/identity/import.rs @@ -3,13 +3,13 @@ use gpui::{ AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Subscription, Task, Window, div, px, }; -use gpui_native_kit::button::Button; -use gpui_native_kit::common::v_flex; -use gpui_native_kit::dialog::Dialog; -use gpui_native_kit::field::Field; -use gpui_native_kit::input::{Input, InputState, InputStateEvent}; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use signed_state::Backend; +use ui::button::Button; +use ui::common::v_flex; +use ui::dialog::Dialog; +use ui::field::Field; +use ui::input::{Input, InputState, InputStateEvent}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use crate::shared::dialogs::close_global; use crate::shared::progress::{DialogProgress, error_row}; diff --git a/crates/signed_app/src/identity/onboarding.rs b/crates/signed_app/src/identity/onboarding.rs index d7b1965..94d62ec 100644 --- a/crates/signed_app/src/identity/onboarding.rs +++ b/crates/signed_app/src/identity/onboarding.rs @@ -3,13 +3,13 @@ use gpui::{ AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Window, div, px, }; -use gpui_native_kit::button::Button; -use gpui_native_kit::common::v_flex; -use gpui_native_kit::dialog::Dialog; -use gpui_native_kit::field::Field; -use gpui_native_kit::input::{Input, InputState}; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use signed_state::Backend; +use ui::button::Button; +use ui::common::v_flex; +use ui::dialog::Dialog; +use ui::field::Field; +use ui::input::{Input, InputState}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use crate::shared::dialogs::close_global; use crate::shared::progress::{DialogProgress, error_row}; diff --git a/crates/signed_app/src/identity/passphrase.rs b/crates/signed_app/src/identity/passphrase.rs index 5060e27..4711f87 100644 --- a/crates/signed_app/src/identity/passphrase.rs +++ b/crates/signed_app/src/identity/passphrase.rs @@ -3,13 +3,13 @@ use gpui::{ AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Subscription, Window, px, }; -use gpui_native_kit::button::Button; -use gpui_native_kit::common::v_flex; -use gpui_native_kit::dialog::Dialog; -use gpui_native_kit::field::Field; -use gpui_native_kit::icons::{Icon, IconRole}; -use gpui_native_kit::input::{Input, InputState, InputStateEvent}; use signed_state::Backend; +use ui::button::Button; +use ui::common::v_flex; +use ui::dialog::Dialog; +use ui::field::Field; +use ui::icons::{Icon, IconRole}; +use ui::input::{Input, InputState, InputStateEvent}; use crate::shared::dialogs::close_global; use crate::shared::progress::{DialogProgress, error_row, push_steps_row}; diff --git a/crates/signed_app/src/inbox/helpers.rs b/crates/signed_app/src/inbox/helpers.rs index de32399..232145b 100644 --- a/crates/signed_app/src/inbox/helpers.rs +++ b/crates/signed_app/src/inbox/helpers.rs @@ -1,16 +1,15 @@ -use assets::CustomIconName; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, Div, Entity, InteractiveElement as _, IntoElement, ParentElement as _, SharedString, Stateful, Styled as _, div, px, }; -use gpui_native_kit::avatar::Avatar; -use gpui_native_kit::badge::Badge; -use gpui_native_kit::common::{Sizable as _, h_flex, v_flex}; -use gpui_native_kit::icons::Icon; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use metadata::ProfileDirectory; use nostr::prelude::{Event, Kind, PublicKey}; +use ui::avatar::Avatar; +use ui::badge::Badge; +use ui::common::{Sizable as _, h_flex, v_flex}; +use ui::icons::{Icon, IconRole}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use utils::relative_time; pub fn repo_header(id: SharedString, name: SharedString, unread: usize, cx: &App) -> AnyElement { @@ -87,7 +86,7 @@ pub fn thread( .items_center() .justify_center() .child( - Icon::named(CustomIconName::Inbox) + Icon::named(IconRole::Inbox) .small() .color(cx.theme().colors.muted_foreground), ), @@ -179,7 +178,7 @@ pub fn empty_state(message: &'static str, cx: &App) -> AnyElement { .gap_2() .py_8() .child( - Icon::named(CustomIconName::Inbox) + Icon::named(IconRole::Inbox) .size(px(24.)) .color(cx.theme().colors.muted_foreground), ) diff --git a/crates/signed_app/src/inbox/mod.rs b/crates/signed_app/src/inbox/mod.rs index 7231739..c7cc6ed 100644 --- a/crates/signed_app/src/inbox/mod.rs +++ b/crates/signed_app/src/inbox/mod.rs @@ -7,16 +7,16 @@ use gpui::{ SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, Task, WeakEntity, Window, div, }; -use gpui_native_kit::button::Button; -use gpui_native_kit::common::{h_flex, v_flex}; -use gpui_native_kit::icons::{Icon, IconRole}; -use gpui_native_kit::layout::panel::Panel; -use gpui_native_kit::scroll_area::ScrollArea; -use gpui_native_kit::theme::{TextRole, Typeset as _}; use metadata::ProfileDirectory; use nostr::prelude::{Event, EventId, Kind, PublicKey, Timestamp}; use signed_core::{InboxItem, InboxReadState, RepoAddr}; use signed_state::{Backend, BackendEvent, Inbox, RefreshGate, RefreshRequest, RepoListStore}; +use ui::button::Button; +use ui::common::{h_flex, v_flex}; +use ui::icons::{Icon, IconRole}; +use ui::layout::panel::Panel; +use ui::scroll_area::ScrollArea; +use ui::theme::{TextRole, Typeset as _}; mod helpers; diff --git a/crates/signed_app/src/issues/detail.rs b/crates/signed_app/src/issues/detail.rs index 383a526..c3850b4 100644 --- a/crates/signed_app/src/issues/detail.rs +++ b/crates/signed_app/src/issues/detail.rs @@ -2,17 +2,17 @@ use gpui::{ Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, ScrollHandle, SharedString, Styled as _, Subscription, Window, div, }; -use gpui_native_kit::avatar::Avatar; -use gpui_native_kit::common::{Sizable as _, h_flex, v_flex}; -use gpui_native_kit::empty_state::EmptyState; -use gpui_native_kit::input::InputState; -use gpui_native_kit::layout::panel::Panel; -use gpui_native_kit::scroll_area::ScrollArea; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use metadata::ProfileDirectory; use nostr::prelude::{EventId, PublicKey}; use signed_core::GitEvent; use signed_state::RepoStore; +use ui::avatar::Avatar; +use ui::common::{Sizable as _, h_flex, v_flex}; +use ui::empty_state::EmptyState; +use ui::input::InputState; +use ui::layout::panel::Panel; +use ui::scroll_area::ScrollArea; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use utils::relative_time; use crate::issues::helpers::{comment_form, comments_section, issue_roots, sidebar_section}; diff --git a/crates/signed_app/src/issues/helpers.rs b/crates/signed_app/src/issues/helpers.rs index c187c91..cb1e95a 100644 --- a/crates/signed_app/src/issues/helpers.rs +++ b/crates/signed_app/src/issues/helpers.rs @@ -1,20 +1,19 @@ -use assets::CustomIconName; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, Entity, IntoElement, ParentElement as _, SharedString, Styled as _, div, px, }; -use gpui_native_kit::avatar::Avatar; -use gpui_native_kit::badge::{Badge, BadgeVariant}; -use gpui_native_kit::button::Button; -use gpui_native_kit::common::{Sizable as _, h_flex, v_flex}; -use gpui_native_kit::icons::Icon; -use gpui_native_kit::input::{Input, InputState}; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; -use gpui_native_kit::tooltip::Tooltip; use metadata::ProfileDirectory; use nostr::prelude::{Event, EventId, PublicKey}; use signed_core::RepoStatus; use signed_state::RepoStore; +use ui::avatar::Avatar; +use ui::badge::{Badge, BadgeVariant}; +use ui::button::Button; +use ui::common::{Sizable as _, h_flex, v_flex}; +use ui::icons::{Icon, IconRole}; +use ui::input::{Input, InputState}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; +use ui::tooltip::Tooltip; use utils::relative_time; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -245,7 +244,7 @@ pub(crate) fn comment_form( .typeset(TextRole::Caption, cx) .text_color(cx.theme().colors.muted_foreground) .child( - Icon::named(CustomIconName::Markdown) + Icon::named(IconRole::Markdown) .size(px(12.)) .color(cx.theme().colors.muted_foreground), ) diff --git a/crates/signed_app/src/issues/mod.rs b/crates/signed_app/src/issues/mod.rs index 0f6b8bd..fe4c92f 100644 --- a/crates/signed_app/src/issues/mod.rs +++ b/crates/signed_app/src/issues/mod.rs @@ -1,24 +1,23 @@ -use assets::CustomIconName; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, UniformListScrollHandle, WeakEntity, Window, div, px, uniform_list, }; -use gpui_native_kit::avatar::Avatar; -use gpui_native_kit::button::Button; -use gpui_native_kit::common::{Sizable as _, h_flex, v_flex}; -use gpui_native_kit::empty_state::EmptyState; -use gpui_native_kit::icons::Icon; -use gpui_native_kit::layout::panel::Panel; -use gpui_native_kit::scrollbar::Scrollbar; -use gpui_native_kit::segmented::{Segmented, SegmentedOption}; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use helpers::{IssueFilter, StatusCounts, filter_by_status}; use metadata::ProfileDirectory; use nostr::prelude::PublicKey; use signed_core::GitEvent; use signed_state::RepoStore; +use ui::avatar::Avatar; +use ui::button::Button; +use ui::common::{Sizable as _, h_flex, v_flex}; +use ui::empty_state::EmptyState; +use ui::icons::{Icon, IconRole}; +use ui::layout::panel::Panel; +use ui::scrollbar::Scrollbar; +use ui::segmented::{Segmented, SegmentedOption}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use utils::relative_time; use self::detail::IssueDetailView; @@ -136,14 +135,14 @@ impl IssuesView { Segmented::new("issue-filter", self.filter) .options(vec![ SegmentedOption::new(IssueFilter::All, format!("All ({})", counts.total)) - .icon(Icon::named(CustomIconName::GitIssueDone).color(muted)), + .icon(Icon::named(IconRole::GitIssueDone).color(muted)), SegmentedOption::new(IssueFilter::Open, format!("Open ({})", counts.open)) - .icon(Icon::named(CustomIconName::GitIssueOpen).color(muted)), + .icon(Icon::named(IconRole::GitIssueOpen).color(muted)), SegmentedOption::new( IssueFilter::Closed, format!("Closed ({})", counts.closed), ) - .icon(Icon::named(CustomIconName::GitIssueClosed).color(muted)), + .icon(Icon::named(IconRole::GitIssueClosed).color(muted)), ]) .on_change(move |filter, _, cx| { if let Err(error) = weak.update(cx, |this, cx| { @@ -158,7 +157,7 @@ impl IssuesView { .child( Button::new("new-issue") .label("New issue") - .icon(Icon::named(CustomIconName::CirclePlus)) + .icon(Icon::named(IconRole::CirclePlus)) .on_click(cx.listener(|this, _, _, cx| { new_issue::open(this.store.clone(), cx); })), diff --git a/crates/signed_app/src/issues/new_issue.rs b/crates/signed_app/src/issues/new_issue.rs index d54b62d..70320e4 100644 --- a/crates/signed_app/src/issues/new_issue.rs +++ b/crates/signed_app/src/issues/new_issue.rs @@ -2,13 +2,13 @@ use gpui::{ AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Window, div, }; -use gpui_native_kit::button::Button; -use gpui_native_kit::common::v_flex; -use gpui_native_kit::dialog::Dialog; -use gpui_native_kit::field::Field; -use gpui_native_kit::input::{Input, InputState}; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use signed_state::RepoStore; +use ui::button::Button; +use ui::common::v_flex; +use ui::dialog::Dialog; +use ui::field::Field; +use ui::input::{Input, InputState}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use crate::shared::dialogs::{close_global, open_global}; diff --git a/crates/signed_app/src/pull_requests/detail.rs b/crates/signed_app/src/pull_requests/detail.rs index ef77027..a5c8ed9 100644 --- a/crates/signed_app/src/pull_requests/detail.rs +++ b/crates/signed_app/src/pull_requests/detail.rs @@ -1,29 +1,28 @@ use std::path::PathBuf; -use assets::CustomIconName; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Subscription, UniformListScrollHandle, WeakEntity, Window, div, uniform_list, }; -use gpui_native_kit::avatar::Avatar; -use gpui_native_kit::button::Button; -use gpui_native_kit::clipboard::ClipboardButton; -use gpui_native_kit::common::{Sizable as _, h_flex, v_flex}; -use gpui_native_kit::data::tabs::{Tab, Tabs}; -use gpui_native_kit::icons::Icon; -use gpui_native_kit::input::InputState; -use gpui_native_kit::layout::panel::Panel; -use gpui_native_kit::scroll_area::ScrollArea; -use gpui_native_kit::scrollbar::Scrollbar; -use gpui_native_kit::spinner::Spinner; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use metadata::ProfileDirectory; use nostr::prelude::{EventId, Kind, PublicKey, Url}; use signed_core::{GitEvent, PullRequest, RepoAddr}; use signed_git::{FileCommit, PatchParser}; use signed_state::{Backend, Mirrors, RepoStore}; +use ui::avatar::Avatar; +use ui::button::Button; +use ui::clipboard::ClipboardButton; +use ui::common::{Sizable as _, h_flex, v_flex}; +use ui::data::tabs::{Tab, Tabs}; +use ui::icons::{Icon, IconRole}; +use ui::input::InputState; +use ui::layout::panel::Panel; +use ui::scroll_area::ScrollArea; +use ui::scrollbar::Scrollbar; +use ui::spinner::Spinner; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use utils::relative_time; use super::dialogs; @@ -540,7 +539,7 @@ impl PullRequestDetailView { this.child( Button::new("branch") .label(branch) - .icon(Icon::named(CustomIconName::GitBranch)) + .icon(Icon::named(IconRole::GitBranch)) .small(), ) }) diff --git a/crates/signed_app/src/pull_requests/dialogs/update.rs b/crates/signed_app/src/pull_requests/dialogs/update.rs index 7a4e0fd..98bc023 100644 --- a/crates/signed_app/src/pull_requests/dialogs/update.rs +++ b/crates/signed_app/src/pull_requests/dialogs/update.rs @@ -2,14 +2,14 @@ use gpui::{ AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Window, div, }; -use gpui_native_kit::button::Button; -use gpui_native_kit::common::v_flex; -use gpui_native_kit::dialog::Dialog; -use gpui_native_kit::field::Field; -use gpui_native_kit::input::{Input, InputState}; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use nostr::prelude::Event; use signed_state::RepoStore; +use ui::button::Button; +use ui::common::v_flex; +use ui::dialog::Dialog; +use ui::field::Field; +use ui::input::{Input, InputState}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use crate::shared::dialogs::{close_global, open_global}; diff --git a/crates/signed_app/src/pull_requests/helpers.rs b/crates/signed_app/src/pull_requests/helpers.rs index 1e52efb..b39b227 100644 --- a/crates/signed_app/src/pull_requests/helpers.rs +++ b/crates/signed_app/src/pull_requests/helpers.rs @@ -1,9 +1,9 @@ use std::path::PathBuf; use gpui::{SharedString, WeakEntity}; -use gpui_native_kit::menu::MenuItem; use nostr::prelude::PublicKey; use signed_core::{Announcement, RepoAddr, RepoStatus}; +use ui::menu::MenuItem; use utils::middle_truncate; use super::NewPullRequestView; diff --git a/crates/signed_app/src/pull_requests/mod.rs b/crates/signed_app/src/pull_requests/mod.rs index c063d44..a47a96a 100644 --- a/crates/signed_app/src/pull_requests/mod.rs +++ b/crates/signed_app/src/pull_requests/mod.rs @@ -1,24 +1,23 @@ -use assets::CustomIconName; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, UniformListScrollHandle, WeakEntity, Window, div, px, uniform_list, }; -use gpui_native_kit::alert::{Alert, AlertSeverity}; -use gpui_native_kit::avatar::Avatar; -use gpui_native_kit::common::{Sizable as _, h_flex, v_flex}; -use gpui_native_kit::dropdown_menu::DropdownMenu; -use gpui_native_kit::icons::Icon; -use gpui_native_kit::layout::panel::Panel; -use gpui_native_kit::menu::MenuItem; -use gpui_native_kit::scrollbar::Scrollbar; -use gpui_native_kit::segmented::{Segmented, SegmentedOption}; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use metadata::ProfileDirectory; use nostr::prelude::{Kind, PublicKey}; use signed_core::GitEvent; use signed_state::RepoStore; +use ui::alert::{Alert, AlertSeverity}; +use ui::avatar::Avatar; +use ui::common::{Sizable as _, h_flex, v_flex}; +use ui::dropdown_menu::DropdownMenu; +use ui::icons::{Icon, IconRole}; +use ui::layout::panel::Panel; +use ui::menu::MenuItem; +use ui::scrollbar::Scrollbar; +use ui::segmented::{Segmented, SegmentedOption}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use utils::relative_time; mod detail; @@ -215,27 +214,27 @@ impl PullRequestsView { PullRequestFilter::All, format!("All ({})", counts.total), ) - .icon(Icon::named(CustomIconName::GitPullRequest).color(muted)), + .icon(Icon::named(IconRole::GitPullRequest).color(muted)), SegmentedOption::new( PullRequestFilter::Open, format!("Open ({})", counts.open), ) - .icon(Icon::named(CustomIconName::GitPullRequest).color(muted)), + .icon(Icon::named(IconRole::GitPullRequest).color(muted)), SegmentedOption::new( PullRequestFilter::Closed, format!("Closed ({})", counts.closed), ) - .icon(Icon::named(CustomIconName::GitPullRequestClosed).color(muted)), + .icon(Icon::named(IconRole::GitPullRequestClosed).color(muted)), SegmentedOption::new( PullRequestFilter::Draft, format!("Draft ({})", counts.draft), ) - .icon(Icon::named(CustomIconName::GitPullRequestDraft).color(muted)), + .icon(Icon::named(IconRole::GitPullRequestDraft).color(muted)), SegmentedOption::new( PullRequestFilter::Merged, format!("Merged ({})", counts.applied), ) - .icon(Icon::named(CustomIconName::GitPullRequestMerged).color(muted)), + .icon(Icon::named(IconRole::GitPullRequestMerged).color(muted)), ]) .on_change(move |filter, _, cx| { if let Err(error) = weak.update(cx, |this, cx| { @@ -250,7 +249,7 @@ impl PullRequestsView { .child( DropdownMenu::new("new-pr-actions") .label("New") - .icon(Icon::named(CustomIconName::GitPullRequest)) + .icon(Icon::named(IconRole::GitPullRequest)) .open(self.new_pr_menu_open) .on_click(move |_, window, cx| { if let Err(error) = diff --git a/crates/signed_app/src/pull_requests/new.rs b/crates/signed_app/src/pull_requests/new.rs index 699877b..5c12f5c 100644 --- a/crates/signed_app/src/pull_requests/new.rs +++ b/crates/signed_app/src/pull_requests/new.rs @@ -1,24 +1,23 @@ use std::path::PathBuf; -use assets::CustomIconName; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Subscription, UniformListScrollHandle, WeakEntity, Window, div, px, uniform_list, }; -use gpui_native_kit::button::Button; -use gpui_native_kit::combobox::{Combobox, ComboboxState}; -use gpui_native_kit::common::{h_flex, v_flex}; -use gpui_native_kit::data::tabs::{Tab, Tabs}; -use gpui_native_kit::icons::{Icon, IconRole}; -use gpui_native_kit::input::{Input, InputState}; -use gpui_native_kit::layout::panel::Panel; -use gpui_native_kit::menu::Menu; -use gpui_native_kit::scrollbar::Scrollbar; -use gpui_native_kit::spinner::Spinner; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use signed_state::{CheckoutsStore, RepoStore}; +use ui::button::Button; +use ui::combobox::{Combobox, ComboboxState}; +use ui::common::{h_flex, v_flex}; +use ui::data::tabs::{Tab, Tabs}; +use ui::icons::{Icon, IconRole}; +use ui::input::{Input, InputState}; +use ui::layout::panel::Panel; +use ui::menu::Menu; +use ui::scrollbar::Scrollbar; +use ui::spinner::Spinner; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use super::helpers::{ForkCompare, fork_display_name, truncate_label}; use crate::repo::commit_diff::{CommitDiffView, DiffPane}; @@ -307,7 +306,7 @@ impl NewPullRequestView { .trigger(move |_, _| { Button::new("compare-source") .label(source_label.clone()) - .variant(gpui_native_kit::button::ButtonVariant::Secondary) + .variant(ui::button::ButtonVariant::Secondary) .into_any_element() }) .items(move |_, _| { @@ -357,9 +356,9 @@ impl NewPullRequestView { .tabs(move |_, _| { vec![ Tab::new("files", format!("Files ({files})")) - .lead(Icon::named(CustomIconName::GitFile)), + .lead(Icon::named(IconRole::GitFile)), Tab::new("commits", format!("Commits ({commits})")) - .lead(Icon::named(CustomIconName::GitCommit)), + .lead(Icon::named(IconRole::GitCommit)), ] }) .on_change(move |index, _, cx| { diff --git a/crates/signed_app/src/pull_requests/send_patch.rs b/crates/signed_app/src/pull_requests/send_patch.rs index cd3318c..a2b937f 100644 --- a/crates/signed_app/src/pull_requests/send_patch.rs +++ b/crates/signed_app/src/pull_requests/send_patch.rs @@ -1,16 +1,15 @@ -use assets::CustomIconName; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, SharedString, Styled as _, WeakEntity, Window, div, }; -use gpui_native_kit::button::Button; -use gpui_native_kit::common::{h_flex, v_flex}; -use gpui_native_kit::icons::Icon; -use gpui_native_kit::input::{Input, InputState}; -use gpui_native_kit::layout::panel::Panel; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use signed_state::RepoStore; +use ui::button::Button; +use ui::common::{h_flex, v_flex}; +use ui::icons::{Icon, IconRole}; +use ui::input::{Input, InputState}; +use ui::layout::panel::Panel; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use crate::workspace::Workspace; @@ -110,7 +109,7 @@ impl SendPatchView { .child( Button::new("send-patch") .label("Send patch") - .icon(Icon::named(CustomIconName::ArrowUp)) + .icon(Icon::named(IconRole::ArrowUp)) .loading(self.submitting) .disabled(!can_submit) .on_click(move |_, _, cx| { diff --git a/crates/signed_app/src/repo/commit_diff.rs b/crates/signed_app/src/repo/commit_diff.rs index 1e64ea9..36b8544 100644 --- a/crates/signed_app/src/repo/commit_diff.rs +++ b/crates/signed_app/src/repo/commit_diff.rs @@ -7,17 +7,17 @@ use gpui::{ Render, ScrollStrategy, SharedString, Styled as _, Task, UniformListScrollHandle, Window, div, px, uniform_list, }; -use gpui_native_kit::badge::{Badge, BadgeVariant}; -use gpui_native_kit::clipboard::ClipboardButton; -use gpui_native_kit::common::{h_flex, v_flex}; -use gpui_native_kit::data::tree::{Tree, TreeItem}; -use gpui_native_kit::icons::{Icon, IconRole}; -use gpui_native_kit::layout::panel::Panel; -use gpui_native_kit::layout::resizable::{Resizable, ResizableState}; -use gpui_native_kit::scrollbar::Scrollbar; -use gpui_native_kit::spinner::Spinner; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use signed_git::{CommitDiff, DiffStatus, FileCommit, FileDiff, Repo}; +use ui::badge::{Badge, BadgeVariant}; +use ui::clipboard::ClipboardButton; +use ui::common::{h_flex, v_flex}; +use ui::data::tree::{Tree, TreeItem}; +use ui::icons::{Icon, IconRole}; +use ui::layout::panel::Panel; +use ui::layout::resizable::{Resizable, ResizableState}; +use ui::scrollbar::Scrollbar; +use ui::spinner::Spinner; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use utils::relative_time_secs; use super::helpers::{DiffRow, diff_rows, render_diff_row}; diff --git a/crates/signed_app/src/repo/dialogs/about.rs b/crates/signed_app/src/repo/dialogs/about.rs index 6bf63ce..e2b728e 100644 --- a/crates/signed_app/src/repo/dialogs/about.rs +++ b/crates/signed_app/src/repo/dialogs/about.rs @@ -2,14 +2,14 @@ use gpui::{ AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div, px, }; -use gpui_native_kit::avatar::Avatar; -use gpui_native_kit::clipboard::ClipboardButton; -use gpui_native_kit::common::{Sizable as _, h_flex, v_flex}; -use gpui_native_kit::dialog::Dialog; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use metadata::ProfileDirectory; use nostr::prelude::PublicKey; use signed_core::Announcement; +use ui::avatar::Avatar; +use ui::clipboard::ClipboardButton; +use ui::common::{Sizable as _, h_flex, v_flex}; +use ui::dialog::Dialog; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use utils::middle_truncate; use crate::shared::dialogs::{close_global, open_global}; diff --git a/crates/signed_app/src/repo/dialogs/create.rs b/crates/signed_app/src/repo/dialogs/create.rs index b6bf6de..478f3d8 100644 --- a/crates/signed_app/src/repo/dialogs/create.rs +++ b/crates/signed_app/src/repo/dialogs/create.rs @@ -5,16 +5,16 @@ use gpui::{ AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, PathPromptOptions, Render, Styled as _, WeakEntity, Window, div, px, }; -use gpui_native_kit::button::{Button, ButtonVariant}; -use gpui_native_kit::common::{h_flex, v_flex}; -use gpui_native_kit::dialog::Dialog; -use gpui_native_kit::field::Field; -use gpui_native_kit::icons::{Icon, IconRole}; -use gpui_native_kit::input::{Input, InputState}; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; -use gpui_native_kit::tooltip::Tooltip; use settings::SettingsStore; use signed_state::{Backend, CheckoutsStore}; +use ui::button::{Button, ButtonVariant}; +use ui::common::{h_flex, v_flex}; +use ui::dialog::Dialog; +use ui::field::Field; +use ui::icons::{Icon, IconRole}; +use ui::input::{Input, InputState}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; +use ui::tooltip::Tooltip; use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers}; use crate::repo::actions::open_repo_panel; diff --git a/crates/signed_app/src/repo/dialogs/grasp_servers.rs b/crates/signed_app/src/repo/dialogs/grasp_servers.rs index f9c9449..9994f14 100644 --- a/crates/signed_app/src/repo/dialogs/grasp_servers.rs +++ b/crates/signed_app/src/repo/dialogs/grasp_servers.rs @@ -3,16 +3,16 @@ use gpui::{ AnyElement, App, AppContext as _, Entity, IntoElement, ParentElement as _, SharedString, Styled as _, Window, div, }; -use gpui_native_kit::button::{Button, ButtonVariant}; -use gpui_native_kit::common::{h_flex, v_flex}; -use gpui_native_kit::icons::{Icon, IconRole}; -use gpui_native_kit::input::{Input, InputState}; -use gpui_native_kit::switch::Switch; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; -use gpui_native_kit::tooltip::Tooltip; use nostr::prelude::RelayUrl; use settings::{DEFAULT_GRASP_SERVERS, GraspServersSettings}; use signed_state::Backend; +use ui::button::{Button, ButtonVariant}; +use ui::common::{h_flex, v_flex}; +use ui::icons::{Icon, IconRole}; +use ui::input::{Input, InputState}; +use ui::switch::Switch; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; +use ui::tooltip::Tooltip; /// State of the grasp-server section of a publish dialog, so async results can be rendered. #[derive(Default)] diff --git a/crates/signed_app/src/repo/dialogs/init.rs b/crates/signed_app/src/repo/dialogs/init.rs index 037c731..2f3a2c6 100644 --- a/crates/signed_app/src/repo/dialogs/init.rs +++ b/crates/signed_app/src/repo/dialogs/init.rs @@ -5,18 +5,18 @@ use gpui::{ AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString, Styled as _, WeakEntity, Window, div, px, }; -use gpui_native_kit::button::Button; -use gpui_native_kit::common::v_flex; -use gpui_native_kit::dialog::Dialog; -use gpui_native_kit::field::Field; -use gpui_native_kit::icons::{Icon, IconRole}; -use gpui_native_kit::input::{Input, InputState}; -use gpui_native_kit::select::{Select, SelectOption}; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use settings::SettingsStore; use signed_core::RepoAddr; use signed_git::Repo; use signed_state::Backend; +use ui::button::Button; +use ui::common::v_flex; +use ui::dialog::Dialog; +use ui::field::Field; +use ui::icons::{Icon, IconRole}; +use ui::input::{Input, InputState}; +use ui::select::{Select, SelectOption}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use super::grasp_servers::{GraspServersState, grasp_servers_field, load_user_grasp_servers}; use crate::repo::RepoDetailView; diff --git a/crates/signed_app/src/repo/dialogs/reset.rs b/crates/signed_app/src/repo/dialogs/reset.rs index 1386144..63224dd 100644 --- a/crates/signed_app/src/repo/dialogs/reset.rs +++ b/crates/signed_app/src/repo/dialogs/reset.rs @@ -2,11 +2,11 @@ use gpui::{ AnyElement, App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Window, div, px, }; -use gpui_native_kit::button::{Button, ButtonVariant}; -use gpui_native_kit::common::v_flex; -use gpui_native_kit::dialog::Dialog; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use signed_state::RepoStore; +use ui::button::{Button, ButtonVariant}; +use ui::common::v_flex; +use ui::dialog::Dialog; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use crate::shared::dialogs::{close_global, open_global}; diff --git a/crates/signed_app/src/repo/files.rs b/crates/signed_app/src/repo/files.rs index be62b1b..eaa1573 100644 --- a/crates/signed_app/src/repo/files.rs +++ b/crates/signed_app/src/repo/files.rs @@ -7,13 +7,13 @@ use gpui::{ AnyElement, App, AppContext as _, Context, Entity, EventEmitter, IntoElement, ParentElement as _, SharedString, Styled as _, Task, WeakEntity, Window, div, px, }; -use gpui_native_kit::common::{h_flex, v_flex}; -use gpui_native_kit::data::tree::{Tree, TreeItem}; -use gpui_native_kit::editor::code::CodeViewState; -use gpui_native_kit::editor::markdown::MarkdownViewState; -use gpui_native_kit::icons::{Icon, IconRole}; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use signed_git::{FileCommit, Repo, WorktreeSnapshot}; +use ui::common::{h_flex, v_flex}; +use ui::data::tree::{Tree, TreeItem}; +use ui::editor::code::CodeViewState; +use ui::editor::markdown::MarkdownViewState; +use ui::icons::{Icon, IconRole}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use super::helpers::{code_language, is_markdown_path, preview_spinner, source_hash}; use crate::shared::tree::{TreeItemSeed, TreeRow, collect_expanded, flatten}; diff --git a/crates/signed_app/src/repo/header.rs b/crates/signed_app/src/repo/header.rs index 8fca25f..ceb99d8 100644 --- a/crates/signed_app/src/repo/header.rs +++ b/crates/signed_app/src/repo/header.rs @@ -1,23 +1,22 @@ use std::collections::HashSet; -use assets::CustomIconName; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Context, InteractiveElement as _, IntoElement, ParentElement as _, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, px, }; -use gpui_native_kit::avatar::Avatar; -use gpui_native_kit::button::{Button, ButtonVariant}; -use gpui_native_kit::clipboard::ClipboardButton; -use gpui_native_kit::common::{Sizable, h_flex, v_flex}; -use gpui_native_kit::dropdown_menu::DropdownMenu; -use gpui_native_kit::icons::{Icon, IconRole}; -use gpui_native_kit::menu::MenuItem; -use gpui_native_kit::popover::Popover; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; -use gpui_native_kit::tooltip::Tooltip; use signed_state::{Backend, CheckoutStatus, CheckoutSyncStatus, CheckoutsStore, Nip34Kind}; +use ui::avatar::Avatar; +use ui::button::{Button, ButtonVariant}; +use ui::clipboard::ClipboardButton; +use ui::common::{Sizable, h_flex, v_flex}; +use ui::dropdown_menu::DropdownMenu; +use ui::icons::{Icon, IconRole}; +use ui::menu::MenuItem; +use ui::popover::Popover; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; +use ui::tooltip::Tooltip; use utils::relative_time_secs; use super::helpers::{bound_repo_label, clone_group, fork_row, nostr_clone_url, repo_display_name}; @@ -197,7 +196,7 @@ impl RepoDetailView { .trigger(move |_, _| { Button::new("code") .label("Code") - .icon(Icon::named(CustomIconName::GitClone)) + .icon(Icon::named(IconRole::GitClone)) .tooltip(Tooltip::text("Clone repository")) .loading(cloning) .disabled(cloning) @@ -250,7 +249,7 @@ impl RepoDetailView { .child( h_flex().justify_end().child( Button::new("download") - .icon(Icon::named(CustomIconName::GitClone)) + .icon(Icon::named(IconRole::GitClone)) .label("Download") .on_click({ let weak = weak_download.clone(); @@ -271,7 +270,7 @@ impl RepoDetailView { ) .child( DropdownMenu::new("repo-menu") - .icon(CustomIconName::EllipsisVertical) + .icon(IconRole::EllipsisVertical) .variant(ButtonVariant::Ghost) .disabled(pushing) .open(self.repo_menu_open) @@ -374,7 +373,7 @@ impl RepoDetailView { Some(binding) => this.child(bound_repo_label(binding, &self.directory, cx)), None => this.child( Button::new("init") - .icon(Icon::named(CustomIconName::ArrowUp)) + .icon(Icon::named(IconRole::ArrowUp)) .label("Initialize on Nostr") .tooltip(Tooltip::text("Publish this repository to Nostr")) .on_click(cx.listener(|this, _, window, cx| { @@ -438,7 +437,7 @@ impl RepoDetailView { }; let path = status.path.clone(); ( - Icon::named(CustomIconName::ArrowUp), + Icon::named(IconRole::ArrowUp), SharedString::from(format!("{commits} ready to push")), format!("Push {}", status.branch), path, @@ -533,10 +532,7 @@ impl RepoDetailView { history.open_commit_diff(&commit_id, window, cx); }); }) - .child( - Icon::named(CustomIconName::GitCommit) - .color(cx.theme().colors.muted_foreground), - ) + .child(Icon::named(IconRole::GitCommit).color(cx.theme().colors.muted_foreground)) .child( div() .font_family(cx.theme().mono_font) diff --git a/crates/signed_app/src/repo/helpers.rs b/crates/signed_app/src/repo/helpers.rs index e0d0ea4..c8fac6c 100644 --- a/crates/signed_app/src/repo/helpers.rs +++ b/crates/signed_app/src/repo/helpers.rs @@ -1,23 +1,22 @@ use std::path::{Path, PathBuf}; use anyhow::Error; -use assets::CustomIconName; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, SharedString, StatefulInteractiveElement as _, Styled as _, Window, div, px, }; -use gpui_native_kit::avatar::Avatar; -use gpui_native_kit::clipboard::ClipboardButton; -use gpui_native_kit::combobox::ComboboxState; -use gpui_native_kit::common::{Sizable as _, h_flex, v_flex}; -use gpui_native_kit::icons::Icon; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use metadata::ProfileDirectory; use nostr::prelude::{RelayUrl, ToBech32}; use signed_core::Announcement; use signed_git::{DiffHunk, DiffLine, DiffLineKind, FileCommit, FileDiff, Repo}; use signed_state::{Nip34Binding, RepoListStore, RepoStore}; +use ui::avatar::Avatar; +use ui::clipboard::ClipboardButton; +use ui::combobox::ComboboxState; +use ui::common::{Sizable as _, h_flex, v_flex}; +use ui::icons::{Icon, IconRole}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use utils::relative_time_secs; use super::RepoDetailView; @@ -117,7 +116,7 @@ pub(super) fn fork_row( .min_w_0() .typeset(TextRole::Body, cx) .text_color(cx.theme().colors.muted_foreground) - .child(Icon::named(CustomIconName::GitBranch).small()) + .child(Icon::named(IconRole::GitBranch).small()) .child(div().whitespace_nowrap().text_ellipsis().child(label)); Some(if clickable { @@ -230,15 +229,13 @@ pub(super) fn preview_spinner() -> AnyElement { .size_full() .items_center() .justify_center() - .child(gpui_native_kit::spinner::Spinner::new( - "repo-preview-spinner", - )) + .child(ui::spinner::Spinner::new("repo-preview-spinner")) .into_any_element() } /// The kit grammar for a path; only four languages are supported. -pub(super) fn code_language(path: &str) -> gpui_native_kit::editor::highlight::Language { - use gpui_native_kit::editor::highlight::Language; +pub(super) fn code_language(path: &str) -> ui::editor::highlight::Language { + use ui::editor::highlight::Language; match Path::new(path) .extension() .and_then(|ext| ext.to_str()) diff --git a/crates/signed_app/src/repo/history.rs b/crates/signed_app/src/repo/history.rs index d0c0db0..8984457 100644 --- a/crates/signed_app/src/repo/history.rs +++ b/crates/signed_app/src/repo/history.rs @@ -6,12 +6,12 @@ use gpui::{ AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Task, UniformListScrollHandle, WeakEntity, Window, div, uniform_list, }; -use gpui_native_kit::common::v_flex; -use gpui_native_kit::scrollbar::Scrollbar; -use gpui_native_kit::spinner::Spinner; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use signed_git::{CommitList, Repo}; use signed_state::RepoStore; +use ui::common::v_flex; +use ui::scrollbar::Scrollbar; +use ui::spinner::Spinner; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; use super::commit_diff::CommitDiffView; use super::helpers::commit_row; diff --git a/crates/signed_app/src/repo/mod.rs b/crates/signed_app/src/repo/mod.rs index 0de592e..ffd90b2 100644 --- a/crates/signed_app/src/repo/mod.rs +++ b/crates/signed_app/src/repo/mod.rs @@ -2,20 +2,12 @@ use std::collections::HashSet; use std::path::PathBuf; use anyhow::Error; -use assets::CustomIconName; use gpui::prelude::FluentBuilder as _; use gpui::{ AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, PathPromptOptions, Render, SharedString, Styled as _, Subscription, Task, WeakEntity, Window, div, }; -use gpui_native_kit::alert::{Alert, AlertSeverity}; -use gpui_native_kit::common::{h_flex, v_flex}; -use gpui_native_kit::data::sidebar::{Sidebar, SidebarEntry}; -use gpui_native_kit::icons::Icon; -use gpui_native_kit::layout::panel::Panel; -use gpui_native_kit::spinner::Spinner; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use metadata::ProfileDirectory; use nostr::prelude::{PublicKey, Url}; use signed_core::{Announcement, RepoAddr}; @@ -23,6 +15,13 @@ use signed_git::{FileCommit, GitCache, Repo}; use signed_state::{ Backend, CheckoutsStore, LocalReposStore, Mirrors, Nip34Binding, RepoStore, SyncStatusDirectory, }; +use ui::alert::{Alert, AlertSeverity}; +use ui::common::{h_flex, v_flex}; +use ui::data::sidebar::{Sidebar, SidebarEntry}; +use ui::icons::{Icon, IconRole}; +use ui::layout::panel::Panel; +use ui::spinner::Spinner; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; pub mod actions; pub mod commit_diff; @@ -885,19 +884,19 @@ impl RepoDetailView { .entries(move |_, cx| { let mut entries = vec![ SidebarEntry::row("repo-nav-commits", "Commits") - .prefix(Icon::named(CustomIconName::GitCommit)) + .prefix(Icon::named(IconRole::GitCommit)) .when_some(commit_count, |entry, count| entry.suffix(count.to_string())), ]; if include_issues { entries.push( SidebarEntry::row("repo-nav-issues", "Issues") - .prefix(Icon::named(CustomIconName::GitIssueDone)) + .prefix(Icon::named(IconRole::GitIssueDone)) .when_some(issue_count, |entry, count| entry.suffix(count.to_string())), ); entries.push( SidebarEntry::row("repo-nav-pulls", "Pull requests") - .prefix(Icon::named(CustomIconName::GitPullRequest)) + .prefix(Icon::named(IconRole::GitPullRequest)) .when_some(pull_count, |entry, count| entry.suffix(count.to_string())), ); } diff --git a/crates/signed_app/src/repo/refs.rs b/crates/signed_app/src/repo/refs.rs index 8fd70f2..20f0439 100644 --- a/crates/signed_app/src/repo/refs.rs +++ b/crates/signed_app/src/repo/refs.rs @@ -1,5 +1,5 @@ use gpui::{App, AppContext as _, Entity, SharedString, WeakEntity, Window}; -use gpui_native_kit::combobox::{Combobox, ComboboxState}; +use ui::combobox::{Combobox, ComboboxState}; use super::RepoDetailView; use super::helpers::sync_selector; diff --git a/crates/signed_app/src/settings/helpers.rs b/crates/signed_app/src/settings/helpers.rs index a94e210..d7293bf 100644 --- a/crates/signed_app/src/settings/helpers.rs +++ b/crates/signed_app/src/settings/helpers.rs @@ -4,14 +4,14 @@ use gpui::{ AnyElement, App, AppContext as _, Entity, IntoElement, ParentElement as _, PathPromptOptions, SharedString, Styled as _, Window, div, px, }; -use gpui_native_kit::button::Button; -use gpui_native_kit::common::{h_flex, v_flex}; -use gpui_native_kit::icons::{Icon, IconRole}; -use gpui_native_kit::input::{Input, InputState}; -use gpui_native_kit::select::{Select, SelectOption}; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; -use gpui_native_kit::tooltip::Tooltip; use settings::{AppearanceMode, EventFetchingStrategy, SettingsStore}; +use ui::button::Button; +use ui::common::{h_flex, v_flex}; +use ui::icons::{Icon, IconRole}; +use ui::input::{Input, InputState}; +use ui::select::{Select, SelectOption}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; +use ui::tooltip::Tooltip; use crate::repo::dialogs::grasp_servers::{normalize_server, server_host}; @@ -134,7 +134,7 @@ pub fn grasp_servers_editor(input: &Entity, cx: &App) -> AnyElement .child( Button::new(format!("settings-remove-server:{ix}")) .icon(Icon::named(IconRole::Close)) - .variant(gpui_native_kit::button::ButtonVariant::Ghost) + .variant(ui::button::ButtonVariant::Ghost) .tooltip(Tooltip::text("Remove")) .on_click({ let store = store.clone(); @@ -163,7 +163,7 @@ pub fn grasp_servers_editor(input: &Entity, cx: &App) -> AnyElement .child( Button::new("settings-add-server") .icon(Icon::named(IconRole::Plus)) - .variant(gpui_native_kit::button::ButtonVariant::Ghost) + .variant(ui::button::ButtonVariant::Ghost) .tooltip(Tooltip::text("Add grasp server")) .on_click({ let input = input.clone(); @@ -234,7 +234,7 @@ pub fn scan_paths_editor(cx: &App) -> AnyElement { .child( Button::new(format!("settings-remove-path:{ix}")) .icon(Icon::named(IconRole::Close)) - .variant(gpui_native_kit::button::ButtonVariant::Ghost) + .variant(ui::button::ButtonVariant::Ghost) .tooltip(Tooltip::text("Remove")) .on_click(move |_, _, cx| { store.update(cx, |store, cx| { @@ -307,7 +307,7 @@ pub fn default_folder_selector(default_folder: &Entity) -> AnyElemen .child( Button::new("settings-choose-folder") .icon(Icon::named(IconRole::Folder)) - .variant(gpui_native_kit::button::ButtonVariant::Ghost) + .variant(ui::button::ButtonVariant::Ghost) .tooltip(Tooltip::text("Choose folder")) .on_click(move |_, window, cx| { choose_default_folder(&folder, window, cx); diff --git a/crates/signed_app/src/settings/mod.rs b/crates/signed_app/src/settings/mod.rs index c16d058..c898ac7 100644 --- a/crates/signed_app/src/settings/mod.rs +++ b/crates/signed_app/src/settings/mod.rs @@ -4,15 +4,15 @@ use gpui::{ App, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Window, px, }; -use gpui_native_kit::common::v_flex; -use gpui_native_kit::dialog::Dialog; -use gpui_native_kit::input::InputState; -use gpui_native_kit::separator::Separator; use helpers::{ appearance_select, default_folder_selector, event_fetching_select, grasp_servers_editor, scan_paths_editor, setting_block, setting_row, }; use settings::SettingsStore; +use ui::common::v_flex; +use ui::dialog::Dialog; +use ui::input::InputState; +use ui::separator::Separator; use crate::shared::dialogs::open_global; diff --git a/crates/signed_app/src/shared/panels.rs b/crates/signed_app/src/shared/panels.rs index af8f4af..e084146 100644 --- a/crates/signed_app/src/shared/panels.rs +++ b/crates/signed_app/src/shared/panels.rs @@ -1,7 +1,7 @@ use std::sync::Arc; use gpui::{App, Entity, SharedString, WeakEntity, Window}; -use gpui_native_kit::layout::panel::{Panel, PanelView}; +use ui::layout::panel::{Panel, PanelView}; use crate::workspace::Workspace; diff --git a/crates/signed_app/src/shared/progress.rs b/crates/signed_app/src/shared/progress.rs index 80252ba..cf8687f 100644 --- a/crates/signed_app/src/shared/progress.rs +++ b/crates/signed_app/src/shared/progress.rs @@ -2,12 +2,12 @@ use gpui::{ AnyElement, App, Context, IntoElement as _, ParentElement as _, SharedString, Styled as _, Subscription, div, }; -use gpui_native_kit::common::{h_flex, v_flex}; -use gpui_native_kit::icons::{Icon, IconRole}; -use gpui_native_kit::spinner::Spinner; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; use signed_core::RepoAddr; use signed_state::{Backend, BackendEvent, PushStepStatus}; +use ui::common::{h_flex, v_flex}; +use ui::icons::{Icon, IconRole}; +use ui::spinner::Spinner; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; /// Progress of an async dialog action: a busy flag that disables the form and an error shown below it. #[derive(Debug, Default)] diff --git a/crates/signed_app/src/shared/widgets.rs b/crates/signed_app/src/shared/widgets.rs index fb943da..23618d4 100644 --- a/crates/signed_app/src/shared/widgets.rs +++ b/crates/signed_app/src/shared/widgets.rs @@ -1,31 +1,18 @@ -use assets::CustomIconName; use gpui::{AnyElement, App, IntoElement, ParentElement as _, SharedString, Styled as _, div}; -use gpui_native_kit::badge::{Badge, BadgeVariant}; -use gpui_native_kit::empty_state::EmptyState; -use gpui_native_kit::icons::Icon; -use gpui_native_kit::theme::{ActiveTheme as _, TextRole, Typeset as _}; -use gpui_native_kit::tooltip::Tooltip; use signed_core::RepoStatus; +use ui::badge::{Badge, BadgeVariant}; +use ui::empty_state::EmptyState; +use ui::icons::{Icon, IconRole}; +use ui::theme::{ActiveTheme as _, TextRole, Typeset as _}; +use ui::tooltip::Tooltip; /// The status pill shown on issue and pull-request rows. pub fn status_badge(status: RepoStatus) -> Badge { let (label, variant, icon) = match status { - RepoStatus::Open => ("Open", BadgeVariant::Neutral, CustomIconName::GitIssueOpen), - RepoStatus::Closed => ( - "Closed", - BadgeVariant::Danger, - CustomIconName::GitIssueClosed, - ), - RepoStatus::Draft => ( - "Draft", - BadgeVariant::Warning, - CustomIconName::GitIssueOngoing, - ), - RepoStatus::Applied => ( - "Applied", - BadgeVariant::Success, - CustomIconName::GitIssueDone, - ), + RepoStatus::Open => ("Open", BadgeVariant::Neutral, IconRole::GitIssueOpen), + RepoStatus::Closed => ("Closed", BadgeVariant::Danger, IconRole::GitIssueClosed), + RepoStatus::Draft => ("Draft", BadgeVariant::Warning, IconRole::GitIssueOngoing), + RepoStatus::Applied => ("Applied", BadgeVariant::Success, IconRole::GitIssueDone), }; Badge::new(format!("status-{label}"), label) @@ -37,7 +24,7 @@ pub fn status_badge(status: RepoStatus) -> Badge { /// A centered empty-state message filling the available space. pub fn empty_state(message: impl Into) -> AnyElement { let message = message.into(); - gpui_native_kit::common::v_flex() + ui::common::v_flex() .size_full() .items_center() .justify_center() diff --git a/crates/signed_app/src/titlebar/helpers.rs b/crates/signed_app/src/titlebar/helpers.rs index 78adcec..987014a 100644 --- a/crates/signed_app/src/titlebar/helpers.rs +++ b/crates/signed_app/src/titlebar/helpers.rs @@ -1,7 +1,7 @@ use gpui::{AnyElement, App, IntoElement}; -use gpui_native_kit::avatar::Avatar; -use gpui_native_kit::common::Sizable as _; use signed_state::ResolvedLocalRepo; +use ui::avatar::Avatar; +use ui::common::Sizable as _; /// The bound owner's avatar, falling back to the path's pixel avatar when unowned. pub(super) fn local_avatar( diff --git a/crates/signed_app/src/titlebar/mod.rs b/crates/signed_app/src/titlebar/mod.rs index 18ea5d0..98c3906 100644 --- a/crates/signed_app/src/titlebar/mod.rs +++ b/crates/signed_app/src/titlebar/mod.rs @@ -4,20 +4,20 @@ use gpui::{ AnyElement, App, AppContext as _, Context, IntoElement, ParentElement as _, SharedString, Styled as _, Subscription, WeakEntity, Window, px, }; -use gpui_native_kit::avatar::Avatar; -use gpui_native_kit::button::{Button, ButtonVariant}; -use gpui_native_kit::command_palette::{Command, CommandPalette, CommandPaletteState}; -use gpui_native_kit::common::{Sizable as _, h_flex}; -use gpui_native_kit::data::tabs::{Tab, Tabs, TabsVariant}; -use gpui_native_kit::icons::{Icon, IconRole}; -use gpui_native_kit::menu::{Menu, MenuItem}; -use gpui_native_kit::theme::ActiveTheme as _; -use gpui_native_kit::tooltip::Tooltip; use helpers::local_avatar; use metadata::{Profile, ProfileDirectory}; use nostr::prelude::PublicKey; use signed_core::Announcement; use signed_state::{Backend, BackendEvent, LocalReposStore, RepoListStore, ResolvedLocalRepo}; +use ui::avatar::Avatar; +use ui::button::{Button, ButtonVariant}; +use ui::command_palette::{Command, CommandPalette, CommandPaletteState}; +use ui::common::{Sizable as _, h_flex}; +use ui::data::tabs::{Tab, Tabs, TabsVariant}; +use ui::icons::{Icon, IconRole}; +use ui::menu::{Menu, MenuItem}; +use ui::theme::ActiveTheme as _; +use ui::tooltip::Tooltip; use crate::repo::{RepoDetailView, actions, dialogs}; use crate::shared::{log_dropped, panels}; diff --git a/crates/signed_app/src/workspace.rs b/crates/signed_app/src/workspace.rs index 5143ba2..155d84a 100644 --- a/crates/signed_app/src/workspace.rs +++ b/crates/signed_app/src/workspace.rs @@ -4,9 +4,9 @@ use std::sync::Arc; use gpui::{ Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div, }; -use gpui_native_kit::common::v_flex; -use gpui_native_kit::data::tabs::{Tab, Tabs, TabsVariant}; -use gpui_native_kit::layout::panel::{Panel, PanelView}; +use ui::common::v_flex; +use ui::data::tabs::{Tab, Tabs, TabsVariant}; +use ui::layout::panel::{Panel, PanelView}; use crate::shared::log_dropped; diff --git a/crates/ui/Cargo.toml b/crates/ui/Cargo.toml new file mode 100644 index 0000000..2fbb772 --- /dev/null +++ b/crates/ui/Cargo.toml @@ -0,0 +1,71 @@ +[package] +name = "ui" +description = "Signed's native GPUI theme, icons, and components." +version.workspace = true +edition.workspace = true +publish.workspace = true + +[dependencies] +gpui.workspace = true +anyhow.workspace = true +log.workspace = true +serde.workspace = true +rust-embed.workspace = true +flume.workspace = true +unicode-segmentation = "1.12" +image = { version = "0.25.1", default-features = false } +similar = "2" +pulldown-cmark = { version = "0.13", default-features = false } +tree-sitter-rust = "0.24" +tree-sitter-typescript = "0.23" +tree-sitter-javascript = "0.23" +tree-sitter-python = "0.23" +toml = "0.8" + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +cpal = "0.18" +tree-sitter = "0.25" + +[target.'cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))'.dependencies] +async-channel = "2" + +[target.'cfg(target_os = "linux")'.dependencies] +notify = "8" +zbus = "5" + +[target.'cfg(target_os = "windows")'.dependencies] +windows = { version = "0.62", features = [ + "Foundation", + "UI", + "UI_ViewManagement", + "Win32_Foundation", + "Win32_System_Com", +] } +windows-registry = "0.6" + +[target.'cfg(target_os = "macos")'.dependencies] +block2 = "0.6" +objc2 = "0.6" +objc2-app-kit = { version = "0.3.2", default-features = false, features = [ + "NSAccessibility", + "NSAppearance", + "NSColor", + "NSColorSpace", + "NSWorkspace", + "block2", + "objc2-core-foundation", +] } +objc2-foundation = { version = "=0.3.2", default-features = false, features = [ + "NSDictionary", + "NSDistributedNotificationCenter", + "NSNotification", + "NSKeyValueObserving", + "NSOperation", + "NSUserDefaults", + "NSString", + "block2", + "std", +] } + +[dev-dependencies] +gpui = { workspace = true, features = ["test-support"] } diff --git a/crates/ui/src/components/alert.rs b/crates/ui/src/components/alert.rs new file mode 100644 index 0000000..c6e5ae7 --- /dev/null +++ b/crates/ui/src/components/alert.rs @@ -0,0 +1,407 @@ +use std::rc::Rc; + +use crate::icons::{Icon, IconRole}; +use crate::theme::{ + ALERT_EDGE_WIDTH, ALERT_STACK_WIDTH, ActiveTheme as _, ENTER_SLIDE_DISTANCE, Size, TextRole, + Typeset as _, +}; +use crate::utils::ResultLogErr as _; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + Animation, AnimationExt as _, App, Context, ElementId, Entity, InteractiveElement as _, + IntoElement, ParentElement as _, RenderOnce, Role, SharedString, + StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, deferred, div, + ease_out_quint, +}; + +use crate::components::button::{Button, ButtonVariant}; +use crate::components::common::DismissHandler; +use crate::components::common::Sizable as _; +use crate::components::common::StyledExt as _; +use crate::components::common::TOAST_LAYER; +use crate::components::common::v_flex; + +/// How alarming an [`Alert`] is; picks the accent color. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum AlertSeverity { + /// The default; uses the info role. + #[default] + Info, + /// Uses the success role. + Success, + /// Uses the warning role. + Warning, + /// Uses the destructive role. + Danger, +} + +/// How an [`Alert`] presents. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum AlertStyle { + /// A floating banner styled like a popover; the default. + #[default] + Overlay, + /// A tinted callout embedded in the page. + Inline, +} + +/// A static callout banner. +#[derive(Clone, IntoElement)] +#[must_use] +pub struct Alert { + id: ElementId, + title: Option, + message: Option, + severity: AlertSeverity, + presentation: AlertStyle, + icon: Option, + on_dismiss: Option, + style: StyleRefinement, +} + +impl Alert { + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + title: None, + message: None, + severity: AlertSeverity::Info, + presentation: AlertStyle::default(), + icon: None, + on_dismiss: None, + style: StyleRefinement::default(), + } + } + + /// Sets the primary line. + pub fn title(mut self, title: L) -> Self + where + L: Into, + { + self.title = Some(title.into()); + self + } + + /// Sets a secondary line under the title. + pub fn message(mut self, message: L) -> Self + where + L: Into, + { + self.message = Some(message.into()); + self + } + + /// Sets how alarming the alert is. + pub fn severity(mut self, severity: AlertSeverity) -> Self { + self.severity = severity; + self + } + + /// Sets how the alert presents. + pub fn style(mut self, style: AlertStyle) -> Self { + self.presentation = style; + self + } + + /// Shows an icon before the text. + pub fn icon(mut self, icon: I) -> Self + where + I: Into, + { + self.icon = Some(icon.into()); + self + } + + /// Runs when the user dismisses the alert. + pub fn on_dismiss(mut self, handler: F) -> Self + where + F: Fn(&mut App) + 'static, + { + self.on_dismiss = Some(Rc::new(handler)); + self + } + + fn rekey(mut self, id: usize) -> Self { + self.id = ElementId::from(id); + self + } +} + +impl gpui::Styled for Alert { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Alert { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + + let ramp = match self.severity { + AlertSeverity::Info => theme.ramps.info, + AlertSeverity::Success => theme.ramps.success, + AlertSeverity::Warning => theme.ramps.warning, + AlertSeverity::Danger => theme.ramps.destructive, + }; + + let foreground = theme.colors.foreground; + let muted_foreground = theme.colors.muted_foreground; + + let metrics = theme.sizes.resolve(Size::Medium); + let icon_size = metrics.icon_size; + let dense_icon_size = metrics.dense_icon_size; + + let content = v_flex() + .flex_1() + .gap_0p5() + .when_some(self.title.clone(), |alert, title| { + alert.child( + div() + .typeset(TextRole::Headline, cx) + .text_color(foreground) + .child(title), + ) + }) + .when_some(self.message.clone(), |alert, message| { + let color = if self.title.is_some() { + muted_foreground + } else { + foreground + }; + alert.child( + div() + .text_size(metrics.text_size) + .text_color(color) + .child(message), + ) + }); + + let dismiss = self.on_dismiss.clone().map(|on_dismiss| { + Button::new((self.id.clone(), "alert-close")) + .icon(IconRole::Close) + .variant(ButtonVariant::Ghost) + .xsmall() + .accessibility_label("Dismiss") + .on_click(move |_, _window, cx| on_dismiss(cx)) + }); + + match self.presentation { + AlertStyle::Overlay => { + let surface = theme.colors.surface; + let border = theme.colors.border; + + div() + .id(self.id.clone()) + .role(Role::Alert) + .w_full() + .flex() + .items_start() + .gap_2() + .px_3() + .py_2() + .rounded(theme.radius.overlay) + .bg(surface) + .border_1() + .border_color(border) + .shadow(theme.elevations.popover.shadows()) + .refine_style(&self.style) + .when_some(self.icon.clone(), |alert, icon_glyph| { + alert.child( + div() + .flex_none() + .flex() + .items_center() + .h(window.line_height()) + .child(icon_glyph.size(icon_size).color(ramp.base)), + ) + }) + .child(content) + .when_some(dismiss, |alert, dismiss| alert.child(dismiss)) + } + AlertStyle::Inline => div() + .id(self.id.clone()) + .role(Role::Alert) + .w_full() + .flex() + .overflow_hidden() + .bg(ramp.subtle) + .refine_style(&self.style) + .child( + div() + .flex_none() + .w(ALERT_EDGE_WIDTH) + .self_stretch() + .bg(ramp.base), + ) + .child( + div() + .flex_1() + .flex() + .items_start() + .gap_3() + .px_3() + .py_2() + .when_some(self.icon.clone(), |alert, icon_glyph| { + alert.child( + div() + .flex_none() + .flex() + .items_center() + .justify_center() + .size(theme.sizes.small.avatar_size) + .rounded(theme.radius.full) + .bg(ramp.base) + .child(icon_glyph.size(dense_icon_size).color(ramp.foreground)), + ) + }) + .child(content), + ) + .when_some(dismiss, |alert, dismiss| { + alert.child(div().flex_none().self_center().pr_3().child(dismiss)) + }), + } + } +} + +/// One pushed alert, with its identity in the stack. +#[derive(Clone)] +pub struct AlertEntry { + pub id: usize, + pub alert: Alert, + on_dismiss: Option, +} + +/// The stack of pushed alerts. +#[derive(Default)] +pub struct Alerts { + entries: Vec, + next_id: usize, +} + +impl Alerts { + /// Pushes an alert onto the stack. + pub fn push(&mut self, mut alert: Alert, cx: &mut Context) -> usize { + let id = self.next_id; + self.next_id += 1; + + let on_dismiss = alert.on_dismiss.take(); + let stack = cx.entity().downgrade(); + + alert.on_dismiss = Some(Rc::new(move |cx: &mut App| { + stack + .update(cx, |alerts, cx| alerts.dismiss(id, cx)) + .log_err(); + })); + + self.entries.push(AlertEntry { + id, + alert: alert.rekey(id), + on_dismiss, + }); + + cx.notify(); + + id + } + + /// Dismisses one alert by id, running its dismiss handler. + pub fn dismiss(&mut self, id: usize, cx: &mut Context) { + if let Some(position) = self.entries.iter().position(|entry| entry.id == id) { + let entry = self.entries.remove(position); + cx.notify(); + if let Some(on_dismiss) = &entry.on_dismiss { + (on_dismiss.clone())(cx); + } + } + } + + /// Dismisses every alert, running each entry's `on_dismiss` handler. + pub fn clear(&mut self, cx: &mut Context) { + if self.entries.is_empty() { + return; + } + + let entries = std::mem::take(&mut self.entries); + cx.notify(); + + for entry in entries { + if let Some(on_dismiss) = entry.on_dismiss { + on_dismiss(cx); + } + } + } + + /// The stacked alerts, oldest first. + pub fn entries(&self) -> &[AlertEntry] { + &self.entries + } + + /// How many alerts are stacked. + pub fn count(&self) -> usize { + self.entries.len() + } +} + +/// The floating stack of pushed alerts, topmost right. +#[derive(IntoElement)] +#[must_use] +pub struct AlertsView { + alerts: Entity, + id: ElementId, +} + +impl AlertsView { + /// Binds the view to an alert stack. + pub fn new(id: I, alerts: Entity) -> Self + where + I: Into, + { + Self { + id: id.into(), + alerts, + } + } +} + +impl RenderOnce for AlertsView { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let enter_duration = theme.motion.overlay; + + let entries = self.alerts.read(cx).entries(); + + deferred( + div() + .id(self.id) + .absolute() + .top_4() + .right_4() + .w(ALERT_STACK_WIDTH) + .flex() + .flex_col() + .items_end() + .gap_2() + .children(entries.iter().rev().map(|entry| { + let id = entry.id; + let ease_slide = ease_out_quint(); + + div() + .relative() + .w_full() + .debug_selector(|| "alert-entry".to_string()) + .child(entry.alert.clone()) + .with_animation( + ("alert-enter", id), + Animation::new(enter_duration), + move |layer, delta| { + layer.left(ENTER_SLIDE_DISTANCE * (1. - ease_slide(delta))) + }, + ) + })), + ) + .with_priority(TOAST_LAYER) + } +} diff --git a/crates/ui/src/components/avatar.rs b/crates/ui/src/components/avatar.rs new file mode 100644 index 0000000..ffe75ec --- /dev/null +++ b/crates/ui/src/components/avatar.rs @@ -0,0 +1,331 @@ +use std::fmt::Display; + +use crate::theme::{ + ActiveTheme as _, Oklch, PIXEL_AVATAR_DARK_FACTOR, PIXEL_AVATAR_DARK_FLOOR, + PIXEL_AVATAR_LIGHT_CAP, PIXEL_AVATAR_LIGHT_LIFT, PIXEL_AVATAR_TINT_ALPHA, Size, ThemeVariant, +}; +use gpui::{ + App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, + SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, div, +}; + +use crate::components::common::{Sizable, StyledExt, h_flex}; + +/// Number of rows and columns in the pixel grid. +const GRID_SIZE: usize = 8; +/// Empty cells kept between the pattern and the avatar edge. +const MARGIN: usize = 1; +/// Probability that a cell in the left half of the pattern area is filled. +const FILL_PROBABILITY: f32 = 0.42; +/// Probability that a filled cell uses the shade instead of the main color. +const SHADE_PROBABILITY: f32 = 0.25; +/// Minimum number of filled left-half cells. +const MIN_FILLED: usize = 5; + +/// An avatar for a user or other entity. +#[derive(IntoElement)] +#[must_use] +pub struct Avatar { + id: SharedString, + name: Option, + picture: Option, + size: Size, + fully_rounded: bool, + style: StyleRefinement, +} + +impl Avatar { + /// Create an avatar for `id`, a public key or any other stable string. + /// + /// The id seeds the pixel fallback shown when no picture is set. + pub fn new(id: T) -> Self + where + T: Display, + { + Self { + id: id.to_string().into(), + name: None, + picture: None, + size: Size::default(), + fully_rounded: false, + style: StyleRefinement::default(), + } + } + + /// The display name of the avatar's subject, if known. + pub fn name(mut self, name: N) -> Self + where + N: Into, + { + self.name = Some(name.into()); + self + } + + /// The user's picture URL. + pub fn picture

(mut self, picture: Option

) -> Self + where + P: Into, + { + self.picture = picture.map(Into::into); + self + } + + /// Renders the avatar circular instead of the control radius. + pub fn fully_rounded(mut self, fully_rounded: bool) -> Self { + self.fully_rounded = fully_rounded; + self + } +} + +impl Sizable for Avatar { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl gpui::Styled for Avatar { + fn style(&mut self) -> &mut gpui::StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Avatar { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + // Avatars sit one class below the shared control scale. + let size = match self.size { + Size::XSmall | Size::Small => Size::XSmall, + Size::Medium => Size::Small, + Size::Large => Size::Medium, + }; + let side = theme.sizes.resolve(size).avatar_size; + + let radius = if self.fully_rounded { + theme.radius.full + } else { + theme.radius.sm + }; + + let base = h_flex() + .id(ElementId::from(self.id.clone())) + .flex_none() + .justify_center() + .overflow_hidden() + .size(side) + .bg(theme.colors.secondary) + .rounded(radius) + .role(Role::Image) + .aria_label(self.name.clone().unwrap_or_else(|| self.id.clone())) + .refine_style(&self.style); + + match self.picture { + Some(url) => base.child(gpui::img(url).size_full().rounded(radius)), + None => base.child(PixelAvatar { + seed: fnv1a(self.id.as_bytes()), + side, + radius, + fully_rounded: self.fully_rounded, + }), + } + .into_any_element() + } +} + +/// A deterministic, offline pixel-art avatar. +#[derive(IntoElement)] +struct PixelAvatar { + seed: u64, + side: gpui::Pixels, + radius: gpui::Pixels, + fully_rounded: bool, +} + +impl RenderOnce for PixelAvatar { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let pattern = pattern(self.seed); + let mut cells = Vec::new(); + + let hue = (self.seed as f32 / u64::MAX as f32) * 360.0; + let accent = Oklch::from_hsla(theme.colors.accent); + let main = Oklch { h: hue, ..accent }.to_hsla(); + + let shade = if theme.variant == ThemeVariant::Dark { + Oklch { + l: (accent.l * PIXEL_AVATAR_LIGHT_LIFT).min(PIXEL_AVATAR_LIGHT_CAP), + ..Oklch::from_hsla(main) + } + .to_hsla() + } else { + Oklch { + l: (accent.l * PIXEL_AVATAR_DARK_FACTOR).max(PIXEL_AVATAR_DARK_FLOOR), + ..Oklch::from_hsla(main) + } + .to_hsla() + }; + + let inset = if self.fully_rounded { + self.side / GRID_SIZE as f32 + } else { + gpui::Pixels::ZERO + }; + + for row in 0..GRID_SIZE { + for col in 0..GRID_SIZE { + let value = pattern[row * GRID_SIZE + col]; + if value != 0 { + let color = if value == 2 { shade } else { main }; + cells.push( + div() + .row_start(row as i16 + 1) + .row_end(row as i16 + 2) + .col_start(col as i16 + 1) + .col_end(col as i16 + 2) + .bg(color), + ); + } + } + } + + div() + .grid() + .grid_cols(GRID_SIZE as u16) + .grid_rows(GRID_SIZE as u16) + .size(self.side) + .flex_none() + .p(inset) + .rounded(self.radius) + .bg(gpui::Hsla { + a: PIXEL_AVATAR_TINT_ALPHA, + ..main + }) + .children(cells) + } +} + +fn pattern(seed: u64) -> [u8; GRID_SIZE * GRID_SIZE] { + let mut rng = PixelRng::new(seed); + let mut pattern = [0u8; GRID_SIZE * GRID_SIZE]; + let mut filled = 0usize; + + let art_rows = GRID_SIZE - 2 * MARGIN; + let art_columns = GRID_SIZE / 2 - MARGIN; + + for row in MARGIN..GRID_SIZE - MARGIN { + for col in MARGIN..GRID_SIZE / 2 { + if rng.chance(FILL_PROBABILITY) { + let shade = rng.chance(SHADE_PROBABILITY); + set_cell(&mut pattern, row, col, if shade { 2 } else { 1 }); + filled += 1; + } + } + } + + if filled < MIN_FILLED { + let total = art_rows * art_columns; + let start = (rng.next() % total as u64) as usize; + + for offset in 0..total { + if filled >= MIN_FILLED { + break; + } + + let flat_index = (start + offset) % total; + let row = MARGIN + flat_index / art_columns; + let col = MARGIN + flat_index % art_columns; + + if pattern[row * GRID_SIZE + col] == 0 { + set_cell(&mut pattern, row, col, 1); + filled += 1; + } + } + } + + pattern +} + +/// Fill `cell (row, col)` and its horizontal mirror. +fn set_cell(pattern: &mut [u8; GRID_SIZE * GRID_SIZE], row: usize, col: usize, value: u8) { + pattern[row * GRID_SIZE + col] = value; + pattern[row * GRID_SIZE + (GRID_SIZE - 1 - col)] = value; +} + +/// FNV-1a 64-bit hash, stable across platforms and runs. +fn fnv1a(bytes: &[u8]) -> u64 { + let mut hash = 0xcbf2_9ce4_8422_2325u64; + for &byte in bytes { + hash ^= byte as u64; + hash = hash.wrapping_mul(0x0000_0100_0000_01b3); + } + hash +} + +/// Tiny xorshift64* PRNG for deriving the pattern from the seed. +struct PixelRng(u64); + +impl PixelRng { + fn new(seed: u64) -> Self { + Self(seed.max(1)) + } + + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + self.0 = x; + x.wrapping_mul(0x2545_f491_4f6c_dd1d) + } + + fn chance(&mut self, probability: f32) -> bool { + self.next() as f32 / (u64::MAX as f32) < probability + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pattern_is_mirror_symmetric() { + for seed in [0u64, 1, 42, u64::MAX] { + let pattern = pattern(seed); + for row in 0..GRID_SIZE { + for col in 0..GRID_SIZE / 2 { + assert_eq!( + pattern[row * GRID_SIZE + col], + pattern[row * GRID_SIZE + (GRID_SIZE - 1 - col)], + "seed {seed} row {row} col {col}" + ); + } + } + } + } + + #[test] + fn the_pattern_keeps_the_outer_ring_empty() { + for seed in [0u64, 1, 42, u64::MAX] { + let pattern = pattern(seed); + for col in 0..GRID_SIZE { + assert_eq!(pattern[col], 0, "top row, seed {seed}"); + assert_eq!(pattern[(GRID_SIZE - 1) * GRID_SIZE + col], 0, "bottom row"); + } + for row in 0..GRID_SIZE { + assert_eq!(pattern[row * GRID_SIZE], 0, "left column, seed {seed}"); + assert_eq!(pattern[row * GRID_SIZE + GRID_SIZE - 1], 0, "right column"); + } + } + } + + #[test] + fn the_pattern_is_deterministic_and_fills_the_minimum() { + for seed in [0u64, 7, 42, u64::MAX] { + let first = pattern(seed); + assert_eq!(first, pattern(seed), "seed {seed} must be stable"); + + // Mirrored cells count twice, so both halves carry the minimum. + let filled = first.iter().filter(|cell| **cell != 0).count(); + assert!(filled >= MIN_FILLED * 2, "seed {seed} filled {filled}"); + } + } +} diff --git a/crates/ui/src/components/badge.rs b/crates/ui/src/components/badge.rs new file mode 100644 index 0000000..4d9a798 --- /dev/null +++ b/crates/ui/src/components/badge.rs @@ -0,0 +1,161 @@ +use std::rc::Rc; + +use crate::icons::Icon; +use crate::theme::{ActiveTheme as _, Size, Theme}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + AnyView, App, ElementId, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, + RenderOnce, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, + Window, transparent_black, +}; + +use crate::components::common::{StyledExt, h_flex}; + +/// The tooltip view builder gpui's `.tooltip(...)` expects. +type TooltipBuilder = Rc AnyView>; + +/// How loud a badge is. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum BadgeVariant { + /// The default; quiet muted fill for counts. + #[default] + Neutral, + /// The accent ramp; something active or newly added. + Accent, + /// The success ramp. + Success, + /// The warning ramp. + Warning, + /// The destructive ramp. + Danger, + /// No fill, just a border; the quietest badge. + Outline, +} + +impl BadgeVariant { + fn tokens(self, theme: &Theme) -> (Hsla, Hsla, Hsla) { + match self { + Self::Neutral => ( + theme.colors.muted, + theme.colors.muted_foreground, + transparent_black(), + ), + Self::Accent => ( + theme.ramps.primary.base, + theme.colors.primary_foreground, + transparent_black(), + ), + Self::Success => ( + theme.ramps.success.base, + theme.colors.success_foreground, + transparent_black(), + ), + Self::Warning => ( + theme.ramps.warning.base, + theme.colors.warning_foreground, + transparent_black(), + ), + Self::Danger => ( + theme.ramps.destructive.base, + theme.colors.destructive_foreground, + transparent_black(), + ), + Self::Outline => ( + transparent_black(), + theme.colors.foreground, + theme.colors.border, + ), + } + } +} + +/// A small pill for a count or a state. +#[derive(IntoElement)] +#[must_use] +pub struct Badge { + id: ElementId, + label: SharedString, + icon: Option, + variant: BadgeVariant, + tooltip: Option, + style: StyleRefinement, +} + +impl Badge { + /// Creates a badge showing `label` — a count or state word the caller formats. + pub fn new(id: I, label: L) -> Self + where + I: Into, + L: Into, + { + Self { + id: id.into(), + label: label.into(), + icon: None, + variant: BadgeVariant::default(), + tooltip: None, + style: StyleRefinement::default(), + } + } + + /// Sets how loud the badge is. + pub fn variant(mut self, variant: BadgeVariant) -> Self { + self.variant = variant; + self + } + + /// Shows an icon before the label. + pub fn icon(mut self, icon: I) -> Self + where + I: Into, + { + self.icon = Some(icon.into()); + self + } + + /// Shows a tooltip view next to the badge after it is hovered. + pub fn tooltip(mut self, tooltip: F) -> Self + where + F: Fn(&mut Window, &mut App) -> AnyView + 'static, + { + self.tooltip = Some(Rc::new(tooltip)); + self + } +} + +impl gpui::Styled for Badge { + fn style(&mut self) -> &mut gpui::StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Badge { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let metrics = theme.sizes.resolve(Size::Small); + let label_size = metrics.caption_size; + let (background, foreground, border) = self.variant.tokens(theme); + + h_flex() + .id(self.id.clone()) + .flex_none() + .justify_center() + .gap_1() + .rounded(theme.radius.full) + .border_1() + .border_color(border) + .bg(background) + .text_color(foreground) + .text_size(label_size) + .px(metrics.dense_padding_x) + .py_0p5() + .when_some(self.icon, |badge, icon| { + badge.child(icon.size(metrics.dense_icon_size).color(foreground)) + }) + .child(self.label) + .refine_style(&self.style) + .when_some(self.tooltip, |badge, tooltip| { + badge.tooltip(move |window, cx| tooltip(window, cx)) + }) + } +} diff --git a/crates/ui/src/components/button.rs b/crates/ui/src/components/button.rs new file mode 100644 index 0000000..a8f3b5a --- /dev/null +++ b/crates/ui/src/components/button.rs @@ -0,0 +1,342 @@ +//! The push button: the API template for every control that follows. + +use crate::icons::Icon; +use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; +use crate::utils::{focus_ring, record_anchor_bounds}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + AnyElement, AnyView, App, ClickEvent, ElementId, InteractiveElement as _, IntoElement, + ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, + StyleRefinement, Styled as _, Window, canvas, relative, transparent_black, +}; +use std::rc::Rc; + +use crate::components::common::{Sizable, StyledExt as _, h_flex}; +use crate::components::spinner::Spinner; + +/// The single activation handler, shared by pointer, Enter, and Space. +type ClickHandler = Box; +/// The tooltip view builder gpui's `.tooltip(...)` expects. +type TooltipBuilder = Rc AnyView>; + +/// Which visual treatment a button uses. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ButtonVariant { + /// The platform's default action. + #[default] + Primary, + /// The everyday companion to `Primary`. + Secondary, + /// Unpainted until hovered, for toolbars and dense UI. + Ghost, + /// The destructive action. + Destructive, +} + +/// Which edge the button's content aligns to. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ButtonSide { + /// Centered content. + #[default] + Center, + /// Content on the left edge, icon leading the label. + Left, + /// Content on the right edge, icon trailing the label. + Right, +} + +/// A push button: pointer, Enter, and Space all fire the single `on_click`. +#[derive(IntoElement)] +#[must_use] +pub struct Button { + id: ElementId, + label: Option, + icon: Option, + children: Vec, + variant: ButtonVariant, + size: Size, + disabled: bool, + loading: bool, + padded: bool, + side: ButtonSide, + tab_stop: bool, + debug_selector: Option String>>, + a11y_label: Option, + tooltip: Option, + on_click: Option, + style: StyleRefinement, +} + +impl Button { + /// Creates a primary button. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + label: None, + icon: None, + children: Vec::new(), + variant: ButtonVariant::default(), + size: Size::default(), + disabled: false, + loading: false, + padded: true, + side: ButtonSide::default(), + tab_stop: true, + debug_selector: None, + a11y_label: None, + tooltip: None, + on_click: None, + style: StyleRefinement::default(), + } + } + + /// Sets the visible label. + pub fn label(mut self, label: L) -> Self + where + L: Into, + { + self.label = Some(label.into()); + self + } + + /// Shows an icon beside the label; without a label the button renders square. + pub fn icon(mut self, icon: I) -> Self + where + I: Into, + { + self.icon = Some(icon.into()); + self + } + + /// Shows a tooltip view next to the button after it is hovered. + pub fn tooltip(mut self, tooltip: F) -> Self + where + F: Fn(&mut Window, &mut App) -> AnyView + 'static, + { + self.tooltip = Some(Rc::new(tooltip)); + self + } + + /// Sets the button's visual language. + pub fn variant(mut self, variant: ButtonVariant) -> Self { + self.variant = variant; + self + } + + /// Whether the button is a keyboard tab stop, dense toolbars turn it off. + pub fn tab_stop(mut self, tab_stop: bool) -> Self { + self.tab_stop = tab_stop; + self + } + + /// Sets the debug-bounds selector, for headless tests. + pub fn debug_selector(mut self, selector: F) -> Self + where + F: Fn() -> String + 'static, + { + self.debug_selector = Some(Rc::new(selector)); + self + } + + /// Renders the button inert, unfocusable, and dimmed. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + + /// Shows the spinner in place of the content and suppresses activation. + pub fn loading(mut self, loading: bool) -> Self { + self.loading = loading; + self + } + + /// Whether the button pads its content. false removes all padding. + pub fn padded(mut self, padded: bool) -> Self { + self.padded = padded; + self + } + + /// Sets the edge the content aligns to, `Right` renders the icon after the label. + pub fn side(mut self, side: ButtonSide) -> Self { + self.side = side; + self + } + + /// Overrides the accessibility label, which defaults to the visible label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// The single activation handler, fired by pointer, Enter, and Space. + pub fn on_click(mut self, handler: F) -> Self + where + F: Fn(&ClickEvent, &mut Window, &mut App) + 'static, + { + self.on_click = Some(Box::new(handler)); + self + } +} + +impl ParentElement for Button { + fn extend(&mut self, elements: impl IntoIterator) { + self.children.extend(elements); + } +} + +impl gpui::Styled for Button { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl Sizable for Button { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl RenderOnce for Button { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let colors = theme.colors; + let ramps = theme.ramps; + let metrics = theme.sizes.resolve(self.size); + + let on_click = self.on_click; + let a11y_label = self.a11y_label.or_else(|| self.label.clone()); + let is_icon_only = self.icon.is_some() && self.label.is_none() && self.children.is_empty(); + let icon_trailing = self.side == ButtonSide::Right; + + let (background, foreground, hover, pressed) = match self.variant { + ButtonVariant::Primary => ( + Some(ramps.primary.base), + colors.primary_foreground, + ramps.primary.hover, + ramps.primary.pressed, + ), + ButtonVariant::Secondary => ( + Some(colors.surface), + colors.foreground, + colors.muted, + colors.muted_hover, + ), + ButtonVariant::Ghost => ( + None, + colors.foreground, + colors.muted_hover, + ramps.secondary.pressed, + ), + ButtonVariant::Destructive => ( + Some(ramps.destructive.base), + colors.destructive_foreground, + ramps.destructive.hover, + ramps.destructive.pressed, + ), + }; + + let (border, hover_border, pressed_border) = match self.variant { + ButtonVariant::Primary => ( + ramps.primary.base, + ramps.primary.hover, + ramps.primary.pressed, + ), + ButtonVariant::Secondary => (colors.border, colors.border, colors.border), + ButtonVariant::Ghost => ( + transparent_black(), + transparent_black(), + transparent_black(), + ), + ButtonVariant::Destructive => ( + ramps.destructive.base, + ramps.destructive.hover, + ramps.destructive.pressed, + ), + }; + + h_flex() + .id(self.id.clone()) + .when_some(self.debug_selector, |button, selector| { + button.debug_selector(move || selector()) + }) + .role(Role::Button) + .map(|button| match self.side { + ButtonSide::Center => button.justify_center(), + ButtonSide::Left => button.justify_start(), + ButtonSide::Right => button.justify_end(), + }) + .h(metrics.control_height) + .when(is_icon_only, |button| button.w(metrics.control_height)) + .when(!is_icon_only && self.padded, |button| { + button.px(metrics.padding_x) + }) + .line_height(relative(1.0)) + .rounded(theme.radius.control) + .text_size(metrics.text_size) + .border_1() + .border_color(border) + .when_some(background, |button, background| button.bg(background)) + .text_color(foreground) + .refine_style(&self.style) + .when_some(a11y_label, |button, label| button.aria_label(label)) + .child( + h_flex() + .gap_2() + .when(self.loading, |content| content.invisible()) + .map(|content| { + if icon_trailing { + content + .when_some(self.label, |content, label| content.child(label)) + .children(self.children) + .when_some(self.icon, |content, icon| { + content.child(icon.size(metrics.icon_size)) + }) + } else { + content + .when_some(self.icon, |content, icon| { + content.child(icon.size(metrics.icon_size)) + }) + .when_some(self.label, |content, label| content.child(label)) + .children(self.children) + } + }), + ) + .when(self.loading, |button| { + button.child( + h_flex().absolute().inset_0().justify_center().child( + Spinner::new((self.id.clone(), "spinner")) + .with_size(self.size) + .variant(crate::components::spinner::SpinnerVariant::Icon) + .color(foreground), + ), + ) + }) + .child( + canvas(record_anchor_bounds(self.id.clone()), |_, _, _, _| {}) + .absolute() + .inset_0(), + ) + .when(self.disabled, |button| button.opacity(DISABLED_OPACITY)) + .when_some(self.tooltip, |button, tooltip| { + button.tooltip(move |window, cx| tooltip(window, cx)) + }) + .when(!self.disabled && !self.loading, |button| { + button + .cursor_pointer() + .focusable() + .tab_stop(self.tab_stop) + .hover(move |style| style.bg(hover).border_color(hover_border)) + .active(move |style| style.bg(pressed).border_color(pressed_border)) + .focus_visible(|style| style.shadow(focus_ring(colors.ring))) + .when_some(on_click, |button, on_click| { + button.on_click(move |event, window, cx| on_click(event, window, cx)) + }) + }) + } +} diff --git a/crates/ui/src/components/checkbox.rs b/crates/ui/src/components/checkbox.rs new file mode 100644 index 0000000..a373216 --- /dev/null +++ b/crates/ui/src/components/checkbox.rs @@ -0,0 +1,177 @@ +//! The checkbox: a controlled on/off value with an optional label. + +use std::rc::Rc; + +use crate::icons::{IconRole, icon}; +use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; +use crate::utils::focus_ring; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, + SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window, +}; + +use crate::components::common::{Sizable, StyledExt as _, h_flex}; + +/// The change reporter, fired with the next value by pointer, Enter, and Space. +type ChangeHandler = Box; + +/// A controlled checkbox component. +#[derive(IntoElement)] +#[must_use] +pub struct Checkbox { + id: ElementId, + label: Option, + checked: bool, + size: Size, + disabled: bool, + debug_selector: Option String>>, + a11y_label: Option, + on_change: Option, + style: StyleRefinement, +} + +impl Checkbox { + /// Creates an unchecked checkbox. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + label: None, + checked: false, + size: Size::default(), + disabled: false, + debug_selector: None, + a11y_label: None, + on_change: None, + style: StyleRefinement::default(), + } + } + + /// Sets the visible label; clicking it toggles too. + pub fn label(mut self, label: L) -> Self + where + L: Into, + { + self.label = Some(label.into()); + self + } + + /// Sets the current value; the checkbox never owns it. + pub fn checked(mut self, checked: bool) -> Self { + self.checked = checked; + self + } + + /// Renders the checkbox inert, unfocusable, and dimmed; disabled always wins. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + + /// Sets the debug-bounds selector, for headless tests. + pub fn debug_selector(mut self, selector: F) -> Self + where + F: Fn() -> String + 'static, + { + self.debug_selector = Some(Rc::new(selector)); + self + } + + /// Overrides the accessibility label, which defaults to the visible label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// The change handler, fired with the next value by pointer, Enter, and Space. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(bool, &mut Window, &mut App) + 'static, + { + self.on_change = Some(Box::new(handler)); + self + } +} + +impl gpui::Styled for Checkbox { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl Sizable for Checkbox { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl RenderOnce for Checkbox { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let colors = theme.colors; + let ramps = theme.ramps; + let metrics = theme.sizes.resolve(self.size); + let on_change = self.on_change; + let next = !self.checked; + let a11y_label = self.a11y_label.or_else(|| self.label.clone()); + + h_flex() + .id(self.id) + .gap_2() + .text_size(metrics.text_size) + .refine_style(&self.style) + .when_some(self.debug_selector, |checkbox, selector| { + checkbox.debug_selector(move || selector()) + }) + .role(Role::CheckBox) + .when_some(a11y_label, |checkbox, label| checkbox.aria_label(label)) + .aria_toggled(Toggled::from(self.checked)) + .when(self.disabled, |checkbox| checkbox.opacity(DISABLED_OPACITY)) + .when(!self.disabled, |checkbox| { + checkbox + .cursor_pointer() + .focusable() + .tab_stop(true) + .focus_visible(|style| style.shadow(focus_ring(colors.ring))) + .when_some(on_change, |checkbox, on_change| { + checkbox.on_click(move |_, window, cx| on_change(next, window, cx)) + }) + }) + .child( + h_flex() + .justify_center() + .flex_none() + .size(metrics.indicator_size) + .rounded(theme.radius.sm) + .border_1() + .when(self.checked, |indicator| { + indicator + .bg(ramps.primary.base) + .border_color(ramps.primary.base) + .hover(|style| { + style + .bg(ramps.primary.hover) + .border_color(ramps.primary.hover) + }) + .child( + icon(IconRole::Check) + .size(metrics.dense_icon_size) + .color(colors.primary_foreground), + ) + }) + .when(!self.checked, |indicator| { + indicator + .bg(colors.input) + .border_color(colors.border) + .hover(|style| style.border_color(colors.muted_foreground)) + }), + ) + .when_some(self.label, |checkbox, label| checkbox.child(label)) + } +} diff --git a/crates/ui/src/components/clipboard.rs b/crates/ui/src/components/clipboard.rs new file mode 100644 index 0000000..622a091 --- /dev/null +++ b/crates/ui/src/components/clipboard.rs @@ -0,0 +1,177 @@ +//! The clipboard button: copies a value and confirms with a brief check mark. + +use std::rc::Rc; +use std::time::Duration; + +use crate::icons::IconRole; +use crate::theme::Size; +use crate::utils::ResultLogErr as _; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + AnyView, App, ClipboardItem, ElementId, Entity, IntoElement, RenderOnce, SharedString, + StyleRefinement, Task, Window, +}; + +use crate::components::button::{Button, ButtonVariant}; +use crate::components::common::{Sizable, StyledExt as _}; + +/// How long the check mark shows before reverting to the copy icon. +pub const COPIED_DURATION: Duration = Duration::from_secs(1); + +/// The tooltip view builder gpui's `.tooltip(...)` expects. +type TooltipBuilder = Rc AnyView>; + +/// Runs after the value lands on the clipboard. +type CopiedHandler = Box; + +/// A quiet icon button that copies a value to the system clipboard. +#[derive(IntoElement)] +#[must_use] +pub struct ClipboardButton { + id: ElementId, + value: SharedString, + size: Size, + disabled: bool, + a11y_label: Option, + tooltip: Option, + on_copied: Option, + style: StyleRefinement, +} + +impl ClipboardButton { + /// Creates a copy button for this value. + pub fn new(id: I, value: V) -> Self + where + I: Into, + V: Into, + { + Self { + id: id.into(), + value: value.into(), + size: Size::default(), + disabled: false, + a11y_label: None, + tooltip: None, + on_copied: None, + style: StyleRefinement::default(), + } + } + + /// Shows a tooltip view next to the button after it is hovered. + pub fn tooltip(mut self, tooltip: F) -> Self + where + F: Fn(&mut Window, &mut App) -> AnyView + 'static, + { + self.tooltip = Some(Rc::new(tooltip)); + self + } + + /// Renders the button inert and dimmed. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + + /// Overrides the accessibility label, which defaults to `Copy`. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// Runs after the value lands on the clipboard. + pub fn on_copied(mut self, handler: F) -> Self + where + F: Fn(&mut App) + 'static, + { + self.on_copied = Some(Box::new(handler)); + self + } +} + +impl Sizable for ClipboardButton { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +/// The transient copied marker keyed per button. +struct CopiedState { + generation: u64, + tasks: Vec>, +} + +impl RenderOnce for ClipboardButton { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let copied: Entity = + window.use_keyed_state((self.id.clone(), "clipboard-copied"), cx, |_, _| { + CopiedState { + generation: 0, + tasks: Vec::new(), + } + }); + let is_copied = copied.read(cx).generation != 0; + + let selector = if is_copied { + "clipboard-copied" + } else { + "clipboard" + }; + + Button::new((self.id.clone(), "clipboard-button")) + .icon(if is_copied { + IconRole::Check + } else { + IconRole::Copy + }) + .variant(ButtonVariant::Ghost) + .with_size(self.size) + .disabled(self.disabled) + .refine_style(&self.style) + .debug_selector(move || selector.to_string()) + .accessibility_label(self.a11y_label.unwrap_or_else(|| "Copy".into())) + .when_some(self.tooltip, |button, tooltip| { + button.tooltip(move |window, cx| tooltip(window, cx)) + }) + .on_click({ + let value = self.value; + let copied = copied.clone(); + let on_copied = self.on_copied; + move |_, window, cx| { + cx.write_to_clipboard(ClipboardItem::new_string(value.to_string())); + + let generation = copied.update(cx, |state, cx| { + state.generation += 1; + cx.notify(); + state.generation + }); + + let weak = copied.downgrade(); + let task = window.spawn(cx, async move |cx| { + cx.background_executor().timer(COPIED_DURATION).await; + cx.update(|_, cx| { + weak.update(cx, |state, cx| { + if state.generation == generation { + state.generation = 0; + cx.notify(); + } + }) + .log_err(); + }) + .log_err(); + }); + + copied.update(cx, |state, _| { + state.tasks.push(task); + }); + + // Invoke the callback after copying + if let Some(on_copied) = &on_copied { + on_copied(cx); + } + } + }) + } +} diff --git a/crates/ui/src/components/combobox.rs b/crates/ui/src/components/combobox.rs new file mode 100644 index 0000000..3ae67b7 --- /dev/null +++ b/crates/ui/src/components/combobox.rs @@ -0,0 +1,752 @@ +//! The combobox: an editable field that filters its options while typing. +//! +//! The state is the view: it owns the query field and the options, and the +//! owner renders the entity itself. Typing filters, the arrow keys move a +//! highlight, Enter commits, and what happens to unmatched text when the +//! field loses focus is [`UnmatchedText`] — revert by default. + +use std::cell::RefCell; +use std::rc::Rc; + +use crate::icons::{IconRole, icon}; +use crate::theme::ActiveTheme as _; +use crate::theme::{COMBOBOX_MIN_WIDTH, COMBOBOX_WIDTH, POPUP_MAX_HEIGHT, Size}; +use crate::utils::ResultLogErr as _; +use gpui::prelude::FluentBuilder; +use gpui::{ + App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding, + MouseButton, MouseDownEvent, ParentElement as _, Pixels, Render, Role, ScrollHandle, + SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, Task, + Window, actions, anchored, canvas, deferred, div, point, px, +}; + +use crate::components::common::{OVERLAY_LAYER, Sizable, StyledExt as _, h_flex, v_flex}; +use crate::components::input::{Input, InputState, InputStateEvent}; +use crate::components::scroll_area::ScrollArea; + +actions!( + combobox, + [HighlightNext, HighlightPrevious, Choose, Dismiss] +); + +/// The key context the combobox's wrapper declares. +pub const COMBOBOX_CONTEXT: &str = "Combobox"; + +/// Binds the combobox's four keys: down, up, enter, and escape. +pub fn bind_combobox_keys(cx: &mut App) { + let under_input = Some("Combobox > Input"); + cx.bind_keys([ + KeyBinding::new("down", HighlightNext, under_input), + KeyBinding::new("up", HighlightPrevious, under_input), + KeyBinding::new("enter", Choose, under_input), + KeyBinding::new("escape", Dismiss, under_input), + KeyBinding::new("down", HighlightNext, Some(COMBOBOX_CONTEXT)), + KeyBinding::new("up", HighlightPrevious, Some(COMBOBOX_CONTEXT)), + KeyBinding::new("enter", Choose, Some(COMBOBOX_CONTEXT)), + KeyBinding::new("escape", Dismiss, Some(COMBOBOX_CONTEXT)), + ]); +} + +/// What happens to text that matches no option when the field loses focus. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum UnmatchedText { + /// Restore the chosen option's label, or empty the field. + #[default] + Revert, + /// Leave the text and leave the value cleared. + Keep, + /// Hand the text to the `on_create` handler. + Create, +} + +/// An option for a [`Combobox`]: a value and the label the filter matches on. +pub type ComboboxOption = (T, SharedString); +/// Reports the value whenever it changes; +pub type ComboboxHandler = Rc, &mut Window, &mut App)>; +/// Receives unmatched text when the field loses focus in create mode. +pub type ComboboxCreateHandler = Rc; +/// Decides which options survive a query: the query, the value, the label. +pub type ComboboxFilter = Rc bool>; + +/// Builder for a combobox. Pass it to [`ComboboxState::new`]. +#[must_use] +pub struct Combobox +where + T: Clone + PartialEq + 'static, +{ + id: ElementId, + name: SharedString, + options: Vec>, + selected: Option, + placeholder: SharedString, + on_change: Option>, + on_create: Option, + filter: Option>, + unmatched: UnmatchedText, + size: Size, + style: StyleRefinement, +} + +impl Combobox +where + T: Clone + PartialEq + 'static, +{ + pub fn new(id: I, name: N, options: Vec>) -> Self + where + I: Into, + N: Into, + { + Self { + id: id.into(), + name: name.into(), + options, + selected: None, + placeholder: SharedString::from("Select..."), + on_change: None, + on_create: None, + filter: None, + unmatched: UnmatchedText::default(), + size: Size::default(), + style: StyleRefinement::default(), + } + } + + /// Sets the initially selected value; its label seeds the field. + pub fn selected(mut self, selected: S) -> Self + where + S: Into>, + { + self.selected = selected.into(); + self + } + + /// Sets the text shown while the field is empty. + pub fn placeholder(mut self, placeholder: L) -> Self + where + L: Into, + { + self.placeholder = placeholder.into(); + self + } + + /// Reports the value whenever it changes. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(Option, &mut Window, &mut App) + 'static, + { + self.on_change = Some(Rc::new(handler)); + self + } + + /// Hands unmatched text to `handler` when the field loses focus. + pub fn on_create(mut self, handler: F) -> Self + where + F: Fn(SharedString, &mut Window, &mut App) + 'static, + { + self.on_create = Some(Rc::new(handler)); + self.unmatched = UnmatchedText::Create; + self + } + + /// Sets the matcher that decides which options survive a query. + pub fn filter(mut self, filter: F) -> Self + where + F: Fn(&str, &T, &SharedString) -> bool + 'static, + { + self.filter = Some(Rc::new(filter)); + self + } + + /// Leaves unmatched text in the field on blur. + pub fn keep_unmatched_text(mut self) -> Self { + self.unmatched = UnmatchedText::Keep; + self + } + + /// Overrides the accessibility label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.name = label.into(); + self + } +} + +/// Style refinements set the combobox's width. +impl Styled for Combobox +where + T: Clone + PartialEq + 'static, +{ + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +// Combobox is a data builder, not an element, adopt the combinators explicitly. +impl FluentBuilder for Combobox where T: Clone + PartialEq + 'static {} + +/// The stateful combobox. +pub struct ComboboxState +where + T: Clone + PartialEq + 'static, +{ + id: ElementId, + name: SharedString, + placeholder: SharedString, + options: Vec>, + /// The chosen value. `None` while the text names nothing. + selected: Option, + query: Entity, + /// Indices into `options` that survived the filter, in popup row order. + visible: Vec, + /// The highlighted popup *row*, when the popup is open. + highlight: Option, + on_change: Option>, + on_create: Option, + filter: ComboboxFilter, + unmatched: UnmatchedText, + size: Size, + /// Width refinements from the builder, applied to the wrapper each render. + style: StyleRefinement, + /// Handler reports in flight; held so they die with the state. + tasks: Vec>, + /// Keeps the query-event subscription tied to the state's lifetime. + _subscription: Subscription, +} + +impl Sizable for ComboboxState +where + T: Clone + PartialEq + 'static, +{ + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl ComboboxState +where + T: Clone + PartialEq + 'static, +{ + /// Builds the state, its query field, and the subscription tying them. + pub fn new(combobox: Combobox, window: &mut Window, cx: &mut Context) -> Self { + let query = InputState::new(cx); + + // The field starts showing the label of whatever was chosen, + // so text and value agree from the first frame. + if let Some(selected) = &combobox.selected + && let Some((_, label)) = combobox.options.iter().find(|(value, _)| value == selected) + { + let label = label.to_string(); + query.update(cx, |query, cx| query.set_value_silent(label, window, cx)); + } + + let subscription = + cx.subscribe_in(&query, window, |state, _, event, window, cx| match event { + InputStateEvent::Focused => state.query_focused(window, cx), + InputStateEvent::TextChanged => state.text_changed(window, cx), + InputStateEvent::Blurred => state.blurred(window, cx), + _ => {} + }); + + let visible = (0..combobox.options.len()).collect(); + + Self { + id: combobox.id, + name: combobox.name, + placeholder: combobox.placeholder, + options: combobox.options, + selected: combobox.selected, + query, + visible, + highlight: None, + on_change: combobox.on_change, + on_create: combobox.on_create, + filter: combobox.filter.unwrap_or_else(|| { + Rc::new(|query, _value, label| label.to_lowercase().contains(&query.to_lowercase())) + }), + unmatched: combobox.unmatched, + size: combobox.size, + style: combobox.style, + tasks: Vec::new(), + _subscription: subscription, + } + } + + /// The text currently in the field. + pub fn text(&self, cx: &App) -> String { + self.query.read(cx).value().to_string() + } + + /// Focuses the query field. + pub fn focus(&self, window: &mut Window, cx: &mut App) { + window.focus(&self.query.read(cx).focus_handle(), cx); + } + + /// Whether the option list is showing. + pub fn is_open(&self) -> bool { + self.highlight.is_some() + } + + /// The chosen value. + pub fn selected(&self) -> Option<&T> { + self.selected.as_ref() + } + + /// Replaces the value; reports it when it actually changed. + pub fn set_selected(&mut self, value: Option, window: &mut Window, cx: &mut Context) { + self.set_value(value, window, cx); + } + + /// Replaces the choice list and re-runs the current filter. + pub fn set_options(&mut self, options: Vec>, cx: &mut Context) { + self.options = options; + let query = self.query.read(cx).value().to_string(); + self.refilter(&query); + cx.notify(); + } + + /// A copy of the current choice list. + pub fn options_snapshot(&self) -> Vec> { + self.options.clone() + } + + /// The label of the chosen option, if there is one. + fn selected_label(&self) -> Option { + let selected = self.selected.as_ref()?; + self.options + .iter() + .find(|(value, _)| value == selected) + .map(|(_, label)| label.clone()) + } + + /// Recomputes `visible` for `query` and clamps the highlight onto it. + fn refilter(&mut self, query: &str) { + let filter = self.filter.clone(); + self.visible = self + .options + .iter() + .enumerate() + .filter(|(_, (value, label))| filter(query, value, label)) + .map(|(index, _)| index) + .collect(); + self.highlight = self.highlight.filter(|row| *row < self.visible.len()); + } + + fn query_text(&self, cx: &Context) -> String { + self.query.read(cx).value().trim().to_string() + } + + /// Sets the value and reports it, including when it is `None`. + fn set_value(&mut self, value: Option, window: &mut Window, cx: &mut Context) { + if self.selected == value { + return; + } + self.selected = value.clone(); + if let Some(on_change) = self.on_change.clone() { + let value = value.clone(); + let task = window.spawn(cx, async move |cx| { + cx.update(|window, cx| on_change(value, window, cx)) + .log_err(); + }); + self.tasks.push(task); + } + cx.notify(); + } + + /// Commits the option at popup *row*. + fn choose_row(&mut self, row: usize, window: &mut Window, cx: &mut Context) { + let Some(option_index) = self.visible.get(row).copied() else { + return; + }; + + let Some((value, label)) = self.options.get(option_index).cloned() else { + return; + }; + + self.query.update(cx, |query, cx| { + query.set_value_silent(label.to_string(), window, cx) + }); + self.highlight = None; + self.refilter(""); + self.set_value(Some(value), window, cx); + } + + /// Typing: re-filter, open, reset the highlight, and clear the value. + fn text_changed(&mut self, window: &mut Window, cx: &mut Context) { + let query = self.query_text(cx); + self.refilter(&query); + self.highlight = Some(0); + self.set_value(None, window, cx); + cx.notify(); + } + + /// Gaining focus. + fn query_focused(&mut self, _window: &mut Window, cx: &mut Context) { + if self.selected.is_some() { + return; + } + self.refilter(""); + self.highlight = Some(0); + cx.notify(); + } + + /// Losing focus. [`UnmatchedText`] decides what the text becomes. + fn blurred(&mut self, window: &mut Window, cx: &mut Context) { + self.highlight = None; + let text = self.query_text(cx); + + if self.selected_label().as_deref() == Some(text.as_str()) { + cx.notify(); + return; + } + + match self.unmatched { + UnmatchedText::Revert => { + let restored = self.selected_label().unwrap_or_default().to_string(); + self.query + .update(cx, |query, cx| query.set_value_silent(restored, window, cx)); + } + UnmatchedText::Keep => {} + UnmatchedText::Create => { + if !text.is_empty() + && let Some(on_create) = self.on_create.clone() + { + let text = SharedString::from(text); + let task = window.spawn(cx, async move |cx| { + cx.update(|window, cx| on_create(text, window, cx)) + .log_err(); + }); + self.tasks.push(task); + } + } + } + cx.notify(); + } + + /// Down and Up over the visible rows. + fn move_highlight(&mut self, delta: i32, cx: &mut Context) { + if self.visible.is_empty() { + return; + } + + let count = self.visible.len(); + let current = self.highlight.filter(|row| *row < count); + let next = match current { + Some(row) => match row.checked_add_signed(isize::try_from(delta).unwrap_or(0)) { + Some(next) if next < count => next, + Some(_) => 0, + None => count - 1, + }, + None => { + if delta > 0 { + 0 + } else { + count - 1 + } + } + }; + self.highlight = Some(next); + cx.notify(); + } + + /// Enter. Commits the highlighted row. + fn choose(&mut self, window: &mut Window, cx: &mut Context) { + let Some(row) = self.highlight else { + cx.propagate(); + return; + }; + self.choose_row(row, window, cx); + } + + /// Escape. Closes the picker. + fn dismiss(&mut self, _window: &mut Window, cx: &mut Context) { + if self.highlight.is_none() { + cx.propagate(); + return; + } + self.highlight = None; + cx.notify(); + } +} + +impl Render for ComboboxState +where + T: Clone + PartialEq + 'static, +{ + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let (metrics, colors, radius, panel_border, spacing_unit, shadows) = { + let theme = cx.theme(); + let metrics = theme.sizes.resolve(self.size); + + ( + metrics, + theme.colors, + theme.radius, + theme.colors.border, + theme.spacing.unit, + theme.elevations.popover.shadows(), + ) + }; + + let icon_size = metrics.dense_icon_size; + let id = self.id.clone(); + let state = cx.entity(); + let open = self.highlight.is_some(); + + let chevron = h_flex() + .id((id.clone(), "chevron")) + .cursor_pointer() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_click({ + let state = state.clone(); + move |_, window, cx| { + let focus = state.read(cx).query.read(cx).focus_handle(); + window.focus(&focus, cx); + state.update(cx, |state, cx| { + if state.highlight.is_some() { + state.highlight = None; + } else { + if state.selected.is_some() { + state.refilter(""); + } else { + let query = state.query.read(cx).value().to_string(); + state.refilter(&query); + } + state.highlight = Some(0); + } + cx.notify(); + }); + } + }) + .child( + icon(IconRole::ChevronDown) + .size(icon_size) + .color(colors.muted_foreground), + ); + + let wrapper_bounds: Rc>>> = Rc::new(RefCell::new(None)); + + div() + .id(id.clone()) + .key_context(COMBOBOX_CONTEXT) + .relative() + .w(COMBOBOX_WIDTH) + .min_w(COMBOBOX_MIN_WIDTH) + .refine_style(&self.style) + .role(Role::ComboBox) + .aria_expanded(open) + .aria_label(self.name.clone()) + .on_action({ + let state = state.clone(); + move |_: &HighlightNext, _window, cx| { + state.update(cx, |state, cx| state.move_highlight(1, cx)); + } + }) + .on_action({ + let state = state.clone(); + move |_: &HighlightPrevious, _window, cx| { + state.update(cx, |state, cx| state.move_highlight(-1, cx)); + } + }) + .on_action({ + let state = state.clone(); + move |_: &Choose, window, cx| { + state.update(cx, |state, cx| state.choose(window, cx)); + } + }) + .on_action({ + let state = state.clone(); + move |_: &Dismiss, _window, cx| { + state.update(cx, |state, cx| state.dismiss(_window, cx)); + } + }) + .child( + canvas( + { + let cell = wrapper_bounds.clone(); + move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) + }, + |_, _, _window, _cx| {}, + ) + .absolute() + .inset_0(), + ) + .child( + Input::new((id.clone(), "query"), self.query.clone()) + .placeholder(self.placeholder.clone()) + .placeholder_when_focused(true) + .with_size(self.size), + ) + .child( + h_flex() + .absolute() + .right(metrics.dense_padding_x) + .top((metrics.input_height - icon_size) / 2.) + .child(chevron), + ) + .when(open, |wrapper| { + let rows: Vec = self + .visible + .iter() + .enumerate() + .map(|(row, option_index)| { + let Some((value, label)) = self.options.get(*option_index) else { + return div().into_any_element(); + }; + + let highlighted = self.highlight == Some(row); + let checked = self.selected.as_ref() == Some(value); + let state = state.clone(); + let row_index = row; + + div() + .id(("option", *option_index)) + .debug_selector({ + let id = id.clone(); + move || format!("{id}-option-{row}") + }) + .role(Role::ListBoxOption) + .aria_label(label.clone()) + .flex() + .items_center() + .gap_2() + .px_2() + .py_1() + .min_h(metrics.control_height) + .rounded(radius.sm) + .when(highlighted, |row| row.bg(colors.muted)) + .when(!highlighted, |row| row.hover(|row| row.bg(colors.muted))) + .on_mouse_move({ + let state = state.clone(); + move |_, _window, cx| { + if state.read(cx).highlight != Some(row_index) { + state.update(cx, |state, cx| { + state.highlight = Some(row_index); + cx.notify(); + }); + } + } + }) + .on_click({ + let state = state.clone(); + move |_, window, cx| { + state.update(cx, |state, cx| { + state.choose_row(row_index, window, cx) + }); + } + }) + .child( + div() + .flex_1() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .child(label.clone()), + ) + .when(checked, |row| { + row.child( + icon(IconRole::Check) + .size(icon_size) + .color(colors.foreground), + ) + }) + .into_any_element() + }) + .collect(); + + let rows: gpui::AnyElement = if rows.is_empty() { + div() + .px_2() + .py_1() + .text_size(metrics.caption_size) + .text_color(colors.muted_foreground) + .child("No matches") + .into_any_element() + } else { + let scroll = window.use_keyed_state((id.clone(), "rows-scroll"), cx, |_, _| { + ScrollHandle::new() + }); + + ScrollArea::new((id.clone(), "rows")) + .handle(scroll.read(cx).clone()) + .axes(crate::components::scroll_area::ScrollAxes::Vertical) + .max_h(POPUP_MAX_HEIGHT) + .children(rows) + .into_any_element() + }; + + let panel_bounds: Rc>>> = Rc::new(RefCell::new(None)); + + let popup_width = wrapper_bounds + .borrow() + .map(|bounds| bounds.size.width) + .unwrap_or(COMBOBOX_WIDTH); + + let panel = v_flex() + .id((id.clone(), "panel")) + .debug_selector({ + let id = id.clone(); + move || format!("{id}-panel") + }) + .w(popup_width) + .p_1() + .bg(colors.surface) + .text_color(colors.foreground) + .rounded(radius.overlay) + .border_1() + .border_color(panel_border) + .shadow(shadows) + .overflow_hidden() + .child(rows) + .child( + canvas( + { + let cell = panel_bounds.clone(); + move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) + }, + { + let state = state.clone(); + let panel_bounds = panel_bounds.clone(); + let wrapper_bounds = wrapper_bounds.clone(); + move |_, _, window, _cx| { + window.on_mouse_event({ + let state = state.clone(); + let panel_bounds = panel_bounds.clone(); + let wrapper_bounds = wrapper_bounds.clone(); + move |event: &MouseDownEvent, phase, _window, cx| { + if phase != gpui::DispatchPhase::Bubble { + return; + } + let on_panel = + panel_bounds.borrow().is_some_and(|bounds| { + bounds.contains(&event.position) + }); + let on_wrapper = + wrapper_bounds.borrow().is_some_and(|bounds| { + bounds.contains(&event.position) + }); + if on_panel || on_wrapper { + return; + } + state.update(cx, |state, cx| { + state.highlight = None; + cx.notify(); + }); + } + }); + } + }, + ) + .absolute() + .inset_0(), + ); + + wrapper.child( + deferred(anchored().offset(point(px(0.), spacing_unit)).child(panel)) + .with_priority(OVERLAY_LAYER), + ) + }) + } +} diff --git a/crates/ui/src/components/command_palette.rs b/crates/ui/src/components/command_palette.rs new file mode 100644 index 0000000..aa192ce --- /dev/null +++ b/crates/ui/src/components/command_palette.rs @@ -0,0 +1,529 @@ +//! The command palette: a modal query field over the application's actions. + +use std::rc::Rc; + +use crate::icons::Icon; +use crate::theme::{ActiveTheme as _, POPUP_MAX_HEIGHT, Size}; +use gpui::prelude::FluentBuilder; +use gpui::{ + AnyElement, App, Context, ElementId, Entity, InteractiveElement as _, IntoElement, KeyBinding, + MouseButton, ParentElement as _, Render, Role, ScrollHandle, SharedString, + StatefulInteractiveElement as _, StyleRefinement, Styled as _, Subscription, Window, actions, + canvas, deferred, div, relative, +}; + +use crate::components::common::{DIALOG_LAYER, StyledExt as _, h_flex, v_flex}; +use crate::components::input::{Input, InputState, InputStateEvent}; +use crate::components::scroll_area::{ScrollArea, ScrollAxes}; + +actions!( + command_palette, + [HighlightNext, HighlightPrevious, Choose, Dismiss] +); + +/// The key context the palette's panel declares. +pub const COMMAND_PALETTE_CONTEXT: &str = "CommandPalette"; + +/// Binds the palette's four keys: down, up, enter, and escape. +pub fn bind_command_palette_keys(cx: &mut App) { + let under_input = Some("CommandPalette > Input"); + cx.bind_keys([ + KeyBinding::new("down", HighlightNext, under_input), + KeyBinding::new("up", HighlightPrevious, under_input), + KeyBinding::new("enter", Choose, under_input), + KeyBinding::new("escape", Dismiss, under_input), + KeyBinding::new("down", HighlightNext, Some(COMMAND_PALETTE_CONTEXT)), + KeyBinding::new("up", HighlightPrevious, Some(COMMAND_PALETTE_CONTEXT)), + KeyBinding::new("enter", Choose, Some(COMMAND_PALETTE_CONTEXT)), + KeyBinding::new("escape", Dismiss, Some(COMMAND_PALETTE_CONTEXT)), + ]); +} + +/// A command the palette can run: a stable id and the label the matcher sees. +#[derive(Clone)] +#[must_use] +pub struct Command { + /// The stable domain id handed to `on_execute`. + pub id: SharedString, + /// What the matcher matches and the row shows. + pub label: SharedString, + /// Gray text on the row's right edge, e.g. the keybinding. + pub hint: Option, + /// Leading glyph shown before the label. + pub icon: Option, +} + +impl Command { + /// Creates a command without a hint or icon. + pub fn new(id: I, label: L) -> Self + where + I: Into, + L: Into, + { + Self { + id: id.into(), + label: label.into(), + hint: None, + icon: None, + } + } + + /// Shows an icon before the label. + pub fn icon(mut self, icon: I) -> Self + where + I: Into, + { + self.icon = Some(icon.into()); + self + } + + /// Sets the row's right-edge hint. + pub fn hint(mut self, hint: H) -> Self + where + H: Into, + { + self.hint = Some(hint.into()); + self + } +} + +// Command is a data builder, not an element, adopt the combinators explicitly. +impl FluentBuilder for Command {} + +/// Filters and ranks the commands for a query. +pub type CommandMatcher = Rc Vec>; +/// Runs the chosen command. +pub type CommandHandler = Rc; + +/// Builder for a command palette. Pass it to [`CommandPaletteState::new`]. +#[must_use] +pub struct CommandPalette { + id: ElementId, + name: SharedString, + placeholder: SharedString, + commands: Vec, + matcher: CommandMatcher, + on_execute: Option, + style: StyleRefinement, +} + +impl CommandPalette { + /// Creates the builder, the caller-owned matcher decides what matches. + pub fn new(id: I, commands: Vec, matcher: M) -> Self + where + I: Into, + M: Fn(&str, &[Command]) -> Vec + 'static, + { + Self { + id: id.into(), + name: SharedString::from("Command palette"), + placeholder: SharedString::from("Type a command..."), + commands, + matcher: Rc::new(matcher), + on_execute: None, + style: StyleRefinement::default(), + } + } + + /// Sets the text shown while the query is empty. + pub fn placeholder(mut self, placeholder: L) -> Self + where + L: Into, + { + self.placeholder = placeholder.into(); + self + } + + /// Runs `handler` with the chosen command, then closes the palette. + pub fn on_execute(mut self, handler: F) -> Self + where + F: Fn(&Command, &mut Window, &mut App) + 'static, + { + self.on_execute = Some(Rc::new(handler)); + self + } + + /// Overrides the accessibility label of the panel. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.name = label.into(); + self + } +} + +// CommandPalette is a data builder, not an element, adopt the combinators explicitly. +impl FluentBuilder for CommandPalette {} + +/// The stateful palette. +pub struct CommandPaletteState { + id: ElementId, + name: SharedString, + placeholder: SharedString, + commands: Vec, + matcher: CommandMatcher, + on_execute: Option, + style: StyleRefinement, + query: Entity, + /// The commands the matcher returned for the query, in display order. + matches: Vec, + /// The highlighted row, when the palette is open. + highlight: Option, + open: bool, + /// Keeps the query-event subscription tied to the state's lifetime. + _subscription: Subscription, +} + +impl CommandPaletteState { + /// Builds the state, its query field, and the subscription tying them. + pub fn new(palette: CommandPalette, window: &mut Window, cx: &mut Context) -> Self { + let query = InputState::new(cx); + let subscription = cx.subscribe_in(&query, window, |state, _, event, window, cx| { + if event == &InputStateEvent::TextChanged { + state.text_changed(window, cx); + } + }); + + let matches = (palette.matcher)("", &palette.commands); + + Self { + id: palette.id, + name: palette.name, + placeholder: palette.placeholder, + commands: palette.commands, + matcher: palette.matcher, + on_execute: palette.on_execute, + style: palette.style, + query, + matches, + highlight: None, + open: false, + _subscription: subscription, + } + } + + /// Opens the palette: fresh query, fresh matches, focus in the field. + pub fn open(&mut self, window: &mut Window, cx: &mut Context) { + if self.open { + self.focus(window, cx); + return; + } + self.open = true; + + self.query.update(cx, |query, cx| { + query.set_value_silent("", window, cx); + }); + + self.refilter(""); + self.highlight = (!self.matches.is_empty()).then_some(0); + self.focus(window, cx); + + cx.notify(); + } + + /// Closes the palette. + pub fn close(&mut self, cx: &mut Context) { + if !self.open { + return; + } + self.open = false; + self.highlight = None; + cx.notify(); + } + + /// Opens the palette when closed, closes it when open. + pub fn toggle(&mut self, window: &mut Window, cx: &mut Context) { + if self.open { + self.close(cx); + } else { + self.open(window, cx); + } + } + + /// Whether the palette is showing. + pub fn is_open(&self) -> bool { + self.open + } + + /// Replaces the command list and re-runs the current query's matches. + pub fn set_commands(&mut self, commands: Vec, cx: &mut Context) { + self.commands = commands; + let query = self.query.read(cx).value().to_string(); + self.refilter(&query); + cx.notify(); + } + + /// Focuses the query field. + pub fn focus(&self, window: &mut Window, cx: &mut App) { + window.focus(&self.query.read(cx).focus_handle(), cx); + } + + /// Asks the caller's matcher who matches, and clamps the highlight. + fn refilter(&mut self, query: &str) { + self.matches = (self.matcher)(query, &self.commands); + if let Some(highlight) = self.highlight { + self.highlight = (highlight < self.matches.len()).then_some(highlight); + } + } + + /// Typing: fresh matches, highlight the first row. + fn text_changed(&mut self, _window: &mut Window, cx: &mut Context) { + let query = self.query.read(cx).value().to_string(); + self.refilter(&query); + self.highlight = (!self.matches.is_empty()).then_some(0); + cx.notify(); + } + + /// Down and Up over the matched rows, wrapping at the ends. + fn move_highlight(&mut self, delta: i32, cx: &mut Context) { + if self.matches.is_empty() { + return; + } + let count = self.matches.len(); + let next = match self.highlight { + Some(row) => match row.checked_add_signed(isize::try_from(delta).unwrap_or(0)) { + Some(next) if next < count => next, + Some(_) => 0, + None => count - 1, + }, + None if delta > 0 => 0, + None => count - 1, + }; + self.highlight = Some(next); + cx.notify(); + } + + /// Enter. Runs the highlighted command and closes. + fn choose(&mut self, window: &mut Window, cx: &mut Context) { + let Some(row) = self.highlight else { + cx.propagate(); + return; + }; + self.choose_row(row, window, cx); + } + + /// Runs the command at a row and closes. + fn choose_row(&mut self, row: usize, window: &mut Window, cx: &mut Context) { + let Some(command) = self.matches.get(row) else { + return; + }; + let command = command.clone(); + if let Some(on_execute) = self.on_execute.clone() { + on_execute(&command, window, cx); + } + self.close(cx); + } + + /// Escape. Closes the palette. + fn dismiss(&mut self, _window: &mut Window, cx: &mut Context) { + if !self.open { + cx.propagate(); + return; + } + self.close(cx); + } +} + +impl Render for CommandPaletteState { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + if !self.open { + return div().into_any_element(); + } + + let (colors, radius, metrics, panel_border, shadows, titlebar_height) = { + let theme = cx.theme(); + ( + theme.colors, + theme.radius, + theme.sizes.resolve(Size::default()), + theme.colors.border, + theme.elevations.dialog.shadows(), + theme.titlebar_height, + ) + }; + + let id = self.id.clone(); + let state = cx.entity(); + let query_focus = self.query.read(cx).focus_handle(); + + let rows: Vec = self + .matches + .iter() + .enumerate() + .map(|(row, command)| { + let highlighted = self.highlight == Some(row); + let state = state.clone(); + let row_index = row; + + h_flex() + .id((ElementId::from(command.id.clone()), "command")) + .debug_selector({ + let id = id.clone(); + move || format!("{id}-command-{row}") + }) + .role(Role::ListBoxOption) + .aria_label(command.label.clone()) + .gap_2() + .px_2() + .py_1() + .min_h(metrics.control_height) + .text_size(metrics.text_size) + .line_height(relative(1.0)) + .rounded(radius.sm) + .when(highlighted, |row| row.bg(colors.muted)) + .when(!highlighted, |row| row.hover(|row| row.bg(colors.muted))) + .on_mouse_move({ + let state = state.clone(); + move |_, _window, cx| { + if state.read(cx).highlight != Some(row_index) { + state.update(cx, |state, cx| { + state.highlight = Some(row_index); + cx.notify(); + }); + } + } + }) + .on_click({ + let state = state.clone(); + move |_, window, cx| { + state.update(cx, |state, cx| state.choose_row(row_index, window, cx)); + } + }) + .when_some(command.icon.clone(), |row, icon| { + row.child(icon.size(metrics.icon_size).color(colors.foreground)) + }) + .child( + div() + .flex_1() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .child(command.label.clone()), + ) + .when_some(command.hint.clone(), |row, hint| { + row.child( + div() + .flex_shrink_0() + .text_size(metrics.caption_size) + .text_color(colors.muted_foreground) + .child(hint), + ) + }) + .into_any_element() + }) + .collect(); + + let rows: AnyElement = if rows.is_empty() { + div() + .px_2() + .py_1() + .text_size(metrics.caption_size) + .text_color(colors.muted_foreground) + .child("No matches") + .into_any_element() + } else { + let scroll = + window.use_keyed_state((id.clone(), "rows-scroll"), cx, |_, _| ScrollHandle::new()); + + ScrollArea::new((id.clone(), "rows")) + .handle(scroll.read(cx).clone()) + .axes(ScrollAxes::Vertical) + .max_h(POPUP_MAX_HEIGHT) + .children(rows) + .into_any_element() + }; + + let panel = v_flex() + .id((id.clone(), "panel")) + .debug_selector({ + let id = id.clone(); + move || format!("{id}-panel") + }) + .key_context(COMMAND_PALETTE_CONTEXT) + .role(Role::Dialog) + .aria_label(self.name.clone()) + .w_full() + .max_w(relative(0.6)) + .p_2() + .gap_2() + .bg(colors.surface) + .text_color(colors.foreground) + .rounded(radius.overlay) + .border_1() + .border_color(panel_border) + .shadow(shadows) + .overflow_hidden() + .refine_style(&self.style) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_action({ + let state = state.clone(); + move |_: &HighlightNext, _window, cx| { + state.update(cx, |state, cx| state.move_highlight(1, cx)); + } + }) + .on_action({ + let state = state.clone(); + move |_: &HighlightPrevious, _window, cx| { + state.update(cx, |state, cx| state.move_highlight(-1, cx)); + } + }) + .on_action({ + let state = state.clone(); + move |_: &Choose, window, cx| { + state.update(cx, |state, cx| state.choose(window, cx)); + } + }) + .on_action({ + let state = state.clone(); + move |_: &Dismiss, window, cx| { + state.update(cx, |state, cx| state.dismiss(window, cx)); + } + }) + .child( + Input::new((id.clone(), "query"), self.query.clone()) + .placeholder(self.placeholder.clone()), + ) + .child(rows) + .child( + canvas(|_, _, _| {}, { + let focus = query_focus.clone(); + move |_, _, window, cx| { + if !focus.contains_focused(window, cx) { + window.focus(&focus, cx); + } + } + }) + .absolute() + .inset_0(), + ); + + let scrim = div() + .absolute() + .inset_0() + .bg(colors.overlay) + .occlude() + .on_mouse_down(MouseButton::Left, { + let state = state.clone(); + move |_, _window, cx| { + state.update(cx, |state, cx| state.close(cx)); + cx.stop_propagation(); + } + }); + + deferred( + div() + .absolute() + .inset_0() + .flex() + .justify_center() + .items_start() + .pt(titlebar_height) + .child(scrim) + .child(panel), + ) + .with_priority(DIALOG_LAYER) + .into_any_element() + } +} diff --git a/crates/ui/src/components/common.rs b/crates/ui/src/components/common.rs new file mode 100644 index 0000000..43d8263 --- /dev/null +++ b/crates/ui/src/components/common.rs @@ -0,0 +1,50 @@ +//! Shared element constructors and small style helpers. + +pub use crate::theme::Size; +pub use crate::utils::{StyledExt, h_flex, v_flex}; + +/// A handler told to clean up after a dismissed surface. +pub type DismissHandler = std::rc::Rc; + +/// Deferred draw priority of window-modal surfaces; default layer 0 stays for in-flow chrome like resize handles. +pub const DIALOG_LAYER: usize = 1; +/// Deferred draw priority of floating panels, so controls inside a dialog open above it. +pub const OVERLAY_LAYER: usize = 2; +/// Deferred draw priority of passive notifications, so they stay visible over dialogs. +pub const TOAST_LAYER: usize = 3; + +/// A component that can be told which size to render at. +pub trait Sizable: Sized { + /// Sets the size. + fn with_size(mut self, size: Size) -> Self { + self.apply_size(size); + self + } + + /// Applies the size to the component's fields. + fn apply_size(&mut self, size: Size); + + /// Sets `Size::XSmall`. + fn xsmall(self) -> Self + where + Self: Sized, + { + self.with_size(Size::XSmall) + } + + /// Sets `Size::Small`. + fn small(self) -> Self + where + Self: Sized, + { + self.with_size(Size::Small) + } + + /// Sets `Size::Large`. + fn large(self) -> Self + where + Self: Sized, + { + self.with_size(Size::Large) + } +} diff --git a/crates/ui/src/components/context_menu.rs b/crates/ui/src/components/context_menu.rs new file mode 100644 index 0000000..0723676 --- /dev/null +++ b/crates/ui/src/components/context_menu.rs @@ -0,0 +1,127 @@ +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, ElementId, InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent, + ParentElement as _, RenderOnce, SharedString, StyleRefinement, Window, div, +}; + +use crate::components::common::StyledExt as _; +use crate::components::menu::{Menu, MenuItem}; + +/// Builds the element that opens the menu on right-click. +type TargetFn = Box gpui::AnyElement>; +/// Builds the menu's items fresh each render. +type ItemsFn = Box Vec>; + +/// A menu that opens at the pointer when its target is right-clicked. +/// +/// Open state is owned internally by design, unlike the controlled [`Menu`]. +#[derive(IntoElement)] +#[must_use] +pub struct ContextMenu { + id: ElementId, + target: Option, + items: Option, + a11y_label: Option, + style: StyleRefinement, +} + +impl ContextMenu { + /// Creates a context menu over a target set with [`ContextMenu::target`]. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + target: None, + items: None, + a11y_label: None, + style: StyleRefinement::default(), + } + } + + /// Sets the element that opens the menu on right-click. + pub fn target(mut self, target: F) -> Self + where + F: Fn(&mut Window, &mut App) -> gpui::AnyElement + 'static, + { + self.target = Some(Box::new(target)); + self + } + + /// Sets the menu's items, built fresh each render. + pub fn items(mut self, items: F) -> Self + where + F: Fn(&mut Window, &mut App) -> Vec + 'static, + { + self.items = Some(Box::new(items)); + self + } + + /// Overrides the menu's accessibility label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } +} + +impl RenderOnce for ContextMenu { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let open = window.with_element_namespace(self.id.clone(), |window| { + window + .use_keyed_state("context-open", cx, |_, _| false) + .clone() + }); + + let at = window.with_element_namespace(self.id.clone(), |window| { + window + .use_keyed_state("context-position", cx, |_, _| None) + .clone() + }); + + let is_open = *open.read(cx); + let position = *at.read(cx); + + let target = self.target; + let at_for_target = at.clone(); + + let trigger = move |window: &mut Window, cx: &mut App| { + let base = target + .as_ref() + .map(|build| build(window, cx)) + .unwrap_or_else(|| div().into_any_element()); + + div() + .on_mouse_down(MouseButton::Right, { + let at = at_for_target.clone(); + move |event: &MouseDownEvent, _window, cx| { + at.update(cx, |at, _| *at = Some(event.position)); + } + }) + .child(base) + .into_any_element() + }; + + let items = move |window: &mut Window, cx: &mut App| { + self.items + .as_ref() + .map(|build| build(window, cx)) + .unwrap_or_default() + }; + + Menu::new(self.id) + .open(is_open) + .on_change(move |next, _window, cx| open.update(cx, |open, _| *open = next)) + .open_at(position) + .trigger_button(MouseButton::Right) + .trigger(trigger) + .items(items) + .refine_style(&self.style) + .when_some(self.a11y_label.clone(), |menu, label| { + menu.accessibility_label(label) + }) + } +} diff --git a/crates/ui/src/components/dialog.rs b/crates/ui/src/components/dialog.rs new file mode 100644 index 0000000..7cd7f67 --- /dev/null +++ b/crates/ui/src/components/dialog.rs @@ -0,0 +1,331 @@ +use gpui::prelude::FluentBuilder as _; +use std::rc::Rc; + +use crate::icons::IconRole; +use crate::theme::{ActiveTheme as _, DIALOG_MIN_WIDTH, TextRole, Typeset as _}; +use gpui::{ + Animation, AnimationExt as _, AnyElement, App, DefiniteLength, ElementId, + InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, ParentElement as _, + RenderOnce, Role, ScrollHandle, SharedString, StatefulInteractiveElement as _, StyleRefinement, + Styled as _, Window, canvas, deferred, div, ease_out_quint, relative, +}; + +use crate::components::button::{Button, ButtonVariant}; +use crate::components::common::{DIALOG_LAYER, Sizable, StyledExt as _, v_flex}; +use crate::components::grain::grain; +use crate::components::scroll_area::ScrollArea; + +/// Requests the dialog's close: `false` closes. +pub type ChangeHandler = Rc; +type ContentFn = Box AnyElement>; +type ActionsFn = Box Vec>; + +/// A centred panel over a dim scrim: the platform's modal. +#[derive(IntoElement)] +#[must_use] +pub struct Dialog { + id: ElementId, + open: bool, + alert: bool, + grain: bool, + title: Option, + a11y_label: Option, + on_change: Option, + content: Option, + actions: Option, + min_width: Option, + height: Option, + style: StyleRefinement, +} + +impl Dialog { + /// Creates a closed dialog. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + open: false, + alert: false, + grain: false, + title: None, + a11y_label: None, + on_change: None, + content: None, + actions: None, + min_width: None, + height: None, + style: StyleRefinement::default(), + } + } + + /// Sets the current open state. + pub fn open(mut self, open: bool) -> Self { + self.open = open; + self + } + + /// Sets the alert mode. + pub fn alert(mut self, alert: bool) -> Self { + self.alert = alert; + self + } + + /// Textures the scrim with a film-grain overlay. + pub fn grain(mut self, grain: bool) -> Self { + self.grain = grain; + self + } + + /// Requests close through `on_change` on escape, scrim clicks, and the close button. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(bool, &mut Window, &mut App) + 'static, + { + self.on_change = Some(Rc::new(handler)); + self + } + + /// Sets the dialog's title. + pub fn title(mut self, title: L) -> Self + where + L: Into, + { + self.title = Some(title.into()); + self + } + + /// Sets the body content between the title and the actions. + pub fn content(mut self, content: F) -> Self + where + F: Fn(&mut Window, &mut App) -> AnyElement + 'static, + { + self.content = Some(Box::new(content)); + self + } + + /// Sets the footer actions, laid out right-aligned in the given order. + pub fn actions(mut self, actions: F) -> Self + where + F: Fn(&mut Window, &mut App) -> Vec + 'static, + { + self.actions = Some(Box::new(actions)); + self + } + + /// Overrides the accessibility label of the panel. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// Sets the panel's minimum width, defaults to the standard dialog width. + pub fn min_width(mut self, width: W) -> Self + where + W: Into, + { + self.min_width = Some(width.into()); + self + } + + /// Sets the panel's height, body content taller than the panel scrolls. + pub fn height(mut self, height: H) -> Self + where + H: Into, + { + self.height = Some(height.into()); + self + } +} + +impl gpui::Styled for Dialog { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Dialog { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let root = div().absolute().inset_0(); + + if !self.open { + return root.into_any_element(); + } + + let (scrim_color, border, foreground, surface, radius, shadows, enter_duration) = { + let theme = cx.theme(); + ( + theme.colors.overlay, + theme.colors.border, + theme.colors.foreground, + theme.colors.surface, + theme.radius.overlay, + theme.elevations.dialog.shadows(), + theme.motion.overlay, + ) + }; + + let role = if self.alert { + Role::AlertDialog + } else { + Role::Dialog + }; + + let label = self + .a11y_label + .clone() + .or_else(|| self.title.clone()) + .unwrap_or_else(|| SharedString::from(self.id.to_string())); + + let on_change = self.on_change.clone(); + let alert = self.alert; + let show_close = !alert && on_change.is_some(); + + // Keyboard focus rides the panel across frames. + let focus = crate::utils::focus_handle(&self.id, window, cx); + + let content = self.content.map(|build| build(window, cx)); + let actions = self.actions.map(|build| build(window, cx)); + let height = self.height; + + let scroll = window + .use_keyed_state("dialog-content-scroll", cx, |_, _| ScrollHandle::new()) + .read(cx) + .clone(); + + let panel = v_flex() + .id("dialog-panel") + .track_focus(&focus) + .role(role) + .aria_label(label) + .when_some(self.min_width, |panel, width| panel.min_w(width)) + .when(self.min_width.is_none(), |panel| { + panel.min_w(DIALOG_MIN_WIDTH) + }) + .max_w(relative(0.9)) + .when_some(height, |panel, height| panel.h(height)) + .p_4() + .gap_4() + .bg(surface) + .text_color(foreground) + .rounded(radius) + .border_1() + .border_color(border) + .shadow(shadows) + .overflow_hidden() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .on_key_down({ + let on_change = on_change.clone(); + move |event: &KeyDownEvent, window, cx| { + if event.keystroke.key == "escape" + && !alert + && let Some(on_change) = &on_change + { + on_change(false, window, cx); + } + cx.stop_propagation(); + } + }) + .when(self.title.is_some() || show_close, |panel| { + panel.child( + div() + .flex() + .items_center() + .justify_end() + .gap_2() + .when_some(self.title.clone(), |row, title| { + row.child(div().flex_1().typeset(TextRole::Title3, cx).child(title)) + }) + .when(show_close, |row| { + row.child( + Button::new("dialog-close") + .icon(IconRole::Close) + .variant(ButtonVariant::Ghost) + .xsmall() + .debug_selector(|| "dialog-close".to_string()) + .accessibility_label("Close") + .on_click({ + let on_change = on_change.clone(); + move |_, window, cx| { + if let Some(on_change) = &on_change { + on_change(false, window, cx); + } + } + }), + ) + }), + ) + }) + .when_some(content, |panel, content| { + panel.map(|this| { + if height.is_some() { + this.child( + ScrollArea::new("dialog-content") + .handle(scroll) + .flex_1() + .min_h_0() + .child(content), + ) + } else { + this.child(content) + } + }) + }) + .when_some(actions, |panel, actions| { + panel.child(div().flex().justify_end().gap_3().children(actions)) + }) + .child( + canvas(|_, _, _| {}, { + move |_, _, window, cx| { + if !focus.contains_focused(window, cx) { + window.focus(&focus, cx); + } + } + }) + .absolute() + .inset_0(), + ); + + let scrim = div() + .absolute() + .inset_0() + .bg(scrim_color) + .occlude() + .when(self.grain, |scrim| scrim.child(grain())) + .when(!alert, |scrim| { + scrim.on_mouse_down(MouseButton::Left, { + let on_change = on_change.clone(); + move |_, _window, cx| { + if let Some(on_change) = &on_change { + on_change(false, _window, cx); + } + cx.stop_propagation(); + } + }) + }); + + deferred( + root.flex() + .items_center() + .justify_center() + .p_4() + .refine_style(&self.style) + .child(scrim.with_animation( + "dialog-scrim-enter", + Animation::new(enter_duration).with_easing(ease_out_quint()), + |scrim, delta| scrim.opacity(delta), + )) + .child(panel.with_animation( + "dialog-enter", + Animation::new(enter_duration).with_easing(ease_out_quint()), + |panel, delta| panel.opacity(delta), + )), + ) + .with_priority(DIALOG_LAYER) + .into_any_element() + } +} diff --git a/crates/ui/src/components/dropdown_menu.rs b/crates/ui/src/components/dropdown_menu.rs new file mode 100644 index 0000000..15fd92e --- /dev/null +++ b/crates/ui/src/components/dropdown_menu.rs @@ -0,0 +1,491 @@ +//! The dropdown menu: a push button with an attached menu of actions. + +use std::cell::RefCell; +use std::rc::Rc; + +use crate::icons::{Icon, IconRole, icon}; +use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; +use crate::utils::{focus_handle, focus_ring}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, ClickEvent, DefiniteLength, DispatchPhase, ElementId, InteractiveElement as _, + IntoElement, KeyDownEvent, MouseButton, MouseDownEvent, ParentElement as _, RenderOnce, Role, + SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas, + div, relative, +}; + +use crate::components::button::ButtonVariant; +use crate::components::common::{Sizable, StyledExt as _, h_flex}; +use crate::components::menu::{ + ChangeHandler, MenuChrome, MenuItem, MenuPanelSpec, TriggerBoundsCell, anchored_menu_panel, +}; +use crate::components::spinner::Spinner; + +/// The main zone's activation handler, shared by pointer, Enter, and Space. +type ClickHandler = Box; +type ItemsFn = Box Vec>; + +/// A push button with an attached dropdown menu. +#[derive(IntoElement)] +#[must_use] +pub struct DropdownMenu { + id: ElementId, + label: Option, + icon: Option, + variant: ButtonVariant, + size: Size, + disabled: bool, + loading: bool, + tab_stop: bool, + open: bool, + a11y_label: Option, + on_click: Option, + on_open_change: Option, + items: Option, + min_width: Option, + style: StyleRefinement, +} + +impl DropdownMenu { + /// Creates a closed dropdown menu rendered as a primary button. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + label: None, + icon: None, + variant: ButtonVariant::default(), + size: Size::default(), + disabled: false, + loading: false, + tab_stop: true, + open: false, + a11y_label: None, + on_click: None, + on_open_change: None, + items: None, + min_width: None, + style: StyleRefinement::default(), + } + } + + /// Sets the visible label. + pub fn label(mut self, label: L) -> Self + where + L: Into, + { + self.label = Some(label.into()); + self + } + + /// Shows an icon. Omitting the label renders an icon-only trigger. + pub fn icon(mut self, icon: I) -> Self + where + I: Into, + { + self.icon = Some(icon.into()); + self + } + + /// Sets the button's visual language. + pub fn variant(mut self, variant: ButtonVariant) -> Self { + self.variant = variant; + self + } + + /// Whether the trigger is a keyboard tab stop, dense toolbars turn it off. + pub fn tab_stop(mut self, tab_stop: bool) -> Self { + self.tab_stop = tab_stop; + self + } + + /// Renders the trigger inert, unfocusable, and dimmed. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + + /// Shows the spinner in place of the content and suppresses activation. + pub fn loading(mut self, loading: bool) -> Self { + self.loading = loading; + self + } + + /// Sets the current open state. + pub fn open(mut self, open: bool) -> Self { + self.open = open; + self + } + + /// Overrides the accessibility label, which defaults to the visible label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// The main zone's action. Without one, activating the button opens the menu. + pub fn on_click(mut self, handler: F) -> Self + where + F: Fn(&ClickEvent, &mut Window, &mut App) + 'static, + { + self.on_click = Some(Box::new(handler)); + self + } + + /// Reports the menu's next open state. + pub fn on_open_change(mut self, handler: F) -> Self + where + F: Fn(bool, &mut Window, &mut App) + 'static, + { + self.on_open_change = Some(Rc::new(handler)); + self + } + + /// Sets the menu's items, built fresh each render. + pub fn items(mut self, items: F) -> Self + where + F: Fn(&mut Window, &mut App) -> Vec + 'static, + { + self.items = Some(Box::new(items)); + self + } + + /// Sets the panel's minimum width, defaults to the standard menu width. + pub fn min_width(mut self, width: W) -> Self + where + W: Into, + { + self.min_width = Some(width.into()); + self + } +} + +impl Sizable for DropdownMenu { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl gpui::Styled for DropdownMenu { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for DropdownMenu { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let colors = theme.colors; + let ramps = theme.ramps; + let metrics = theme.sizes.resolve(self.size); + let radius = theme.radius.control; + + let ring = colors.ring; + + let (panel_chrome, enter_duration) = MenuChrome::read(cx); + let (background, foreground, hover, pressed) = match self.variant { + ButtonVariant::Primary => ( + Some(ramps.primary.base), + colors.primary_foreground, + ramps.primary.hover, + ramps.primary.pressed, + ), + ButtonVariant::Secondary => ( + Some(colors.surface), + colors.foreground, + colors.muted, + colors.muted_hover, + ), + ButtonVariant::Ghost => ( + None, + colors.foreground, + colors.muted_hover, + ramps.secondary.pressed, + ), + ButtonVariant::Destructive => ( + Some(ramps.destructive.base), + colors.destructive_foreground, + ramps.destructive.hover, + ramps.destructive.pressed, + ), + }; + + let border = match self.variant { + ButtonVariant::Primary => ramps.primary.base, + ButtonVariant::Secondary => colors.border, + ButtonVariant::Ghost => gpui::transparent_black(), + ButtonVariant::Destructive => ramps.destructive.base, + }; + + let split = self.on_click.is_some(); + let icon_only = self.icon.is_some() && self.label.is_none() && !split; + let inert = self.disabled || self.loading; + + let label = self + .a11y_label + .clone() + .unwrap_or_else(|| SharedString::from(self.id.to_string())); + + let a11y_label = self.a11y_label.or_else(|| self.label.clone()); + let focus = focus_handle(&self.id, window, cx).tab_stop(self.tab_stop); + // How the menu was last opened, read by the frame that mounts the panel. + let keyboard_open = + window.use_keyed_state((self.id.clone(), "dropdown-open-origin"), cx, |_, _| false); + + let on_open: ChangeHandler = { + let focus = focus.clone(); + let on_open_change = self.on_open_change.clone(); + let keyboard_open = keyboard_open.clone(); + Rc::new(move |next, window, cx| { + if !next { + window.focus(&focus, cx); + keyboard_open.update(cx, |keyboard_open, _| *keyboard_open = false); + } + if let Some(on_open_change) = &on_open_change { + on_open_change(next, window, cx); + } + }) + }; + + let trigger_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); + let chevron_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); + + let main = h_flex() + .id(self.id.clone()) + .debug_selector({ + let id = self.id.clone(); + move || id.to_string() + }) + .justify_center() + .h_full() + .when(icon_only, |zone| zone.w_full()) + .gap_2() + .line_height(relative(1.0)) + .text_size(metrics.text_size) + .text_color(foreground) + .role(Role::Button) + .when_some(a11y_label, |zone, label| zone.aria_label(label)) + .aria_expanded(self.open) + .px(if icon_only { + gpui::Pixels::ZERO + } else { + metrics.padding_x + }) + .when(split, |zone| zone.rounded_l(radius)) + .when(!split, |zone| { + zone.rounded(radius) + .when(self.open, |zone| zone.bg(pressed)) + }) + .when(!icon_only && !split, |zone| { + zone.child( + icon(IconRole::ChevronDown) + .size(metrics.dense_icon_size) + .color(foreground), + ) + }) + .child( + h_flex() + .gap_2() + .when(self.loading, |content| content.invisible()) + .when_some(self.icon, |content, icon| { + content.child(icon.size(metrics.icon_size).color(foreground)) + }) + .when_some(self.label, |content, label| content.child(label)), + ) + .when(self.loading, |zone| { + zone.child( + h_flex().absolute().inset_0().justify_center().child( + Spinner::new((self.id.clone(), "spinner")) + .with_size(self.size) + .variant(crate::components::spinner::SpinnerVariant::Icon) + .color(foreground), + ), + ) + }); + + let main = if inert { + main + } else { + main.track_focus(&focus) + .cursor_pointer() + .hover(move |style| style.bg(hover)) + .active(move |style| style.bg(pressed)) + .on_click({ + let on_click = self.on_click; + let on_open = on_open.clone(); + let keyboard_open = keyboard_open.clone(); + let open = self.open; + move |event, window, cx| match (on_click.as_ref(), event) { + (Some(on_click), _) => on_click(event, window, cx), + (None, ClickEvent::Keyboard(_)) => { + keyboard_open.update(cx, |keyboard_open, _| *keyboard_open = true); + on_open(!open, window, cx); + } + (None, _) => {} + } + }) + .on_key_down({ + let on_open = on_open.clone(); + let keyboard_open = keyboard_open.clone(); + move |event: &KeyDownEvent, window, cx| { + if event.keystroke.key == "down" { + keyboard_open.update(cx, |keyboard_open, _| *keyboard_open = true); + on_open(true, window, cx); + cx.stop_propagation(); + } + } + }) + }; + + let chevron_zone = h_flex() + .id((self.id.clone(), "chevron")) + .debug_selector({ + let id = self.id.clone(); + move || format!("{id}-chevron") + }) + .relative() + .h_full() + .px(metrics.dense_padding_x) + .rounded_r(radius) + .rounded_l_none() + .border_l_1() + .border_color(border) + .when(self.open, |zone| zone.bg(pressed)) + .when(!inert, |zone| { + zone.cursor_pointer() + .hover(move |style| style.bg(hover)) + .active(move |style| style.bg(pressed)) + }) + .child( + icon(IconRole::ChevronDown) + .size(metrics.dense_icon_size) + .color(foreground), + ) + .child( + canvas( + { + let cell = chevron_bounds.clone(); + move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ); + + let trigger = h_flex() + .debug_selector({ + let id = self.id.clone(); + move || format!("{id}-trigger") + }) + .h(metrics.control_height) + .when(icon_only, |trigger| trigger.w(metrics.control_height)) + .rounded(radius) + .border_1() + .border_color(border) + .when_some(background, |trigger, background| trigger.bg(background)) + .when(self.disabled, |trigger| trigger.opacity(DISABLED_OPACITY)) + .when(!inert, |trigger| { + trigger + .track_focus(&focus) + .focus_visible(move |style| style.shadow(focus_ring(ring))) + }) + .child(main); + + let trigger = if split { + trigger.child(chevron_zone) + } else { + trigger + }; + + let items = if self.open { + self.items + .map(|build| Rc::from(build(window, cx))) + .unwrap_or_else(|| Rc::from([])) + } else { + Rc::from([]) + }; + + let on_close = Some(on_open.clone()); + + let spec = MenuPanelSpec { + open: self.open, + items, + initial_selection: None, + preselect: *keyboard_open.read(cx), + min_width: self.min_width, + label, + position: None, + trigger_bounds: trigger_bounds.clone(), + on_dismiss: on_close.clone(), + on_activate: on_close, + }; + + div() + .relative() + .refine_style(&self.style) + .child( + canvas( + { + let cell = trigger_bounds.clone(); + move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) + }, + { + let on_open = on_open.clone(); + let trigger_bounds = trigger_bounds.clone(); + let chevron_bounds = chevron_bounds.clone(); + let keyboard_open = keyboard_open.clone(); + let open = self.open; + + move |_, _, window, _cx| { + window.on_mouse_event({ + let on_open = on_open.clone(); + let keyboard_open = keyboard_open.clone(); + move |event: &MouseDownEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble + || event.button != MouseButton::Left + || inert + { + return; + } + + let in_trigger = trigger_bounds + .borrow() + .is_some_and(|bounds| bounds.contains(&event.position)); + + if !in_trigger { + return; + } + + let in_chevron = chevron_bounds + .borrow() + .is_some_and(|bounds| bounds.contains(&event.position)); + + if !open && split && !in_chevron { + return; + } + + keyboard_open + .update(cx, |keyboard_open, _| *keyboard_open = false); + on_open(!open, window, cx); + cx.stop_propagation(); + } + }); + } + }, + ) + .absolute() + .inset_0(), + ) + .child(trigger) + .when_some( + anchored_menu_panel(window, cx, &self.id, spec, &panel_chrome, enter_duration), + |wrapper, panel| wrapper.child(panel), + ) + } +} diff --git a/crates/ui/src/components/empty_state.rs b/crates/ui/src/components/empty_state.rs new file mode 100644 index 0000000..f3b8df2 --- /dev/null +++ b/crates/ui/src/components/empty_state.rs @@ -0,0 +1,111 @@ +use crate::icons::Icon; +use crate::theme::{ActiveTheme as _, Size, TextRole, Typeset as _}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, IntoElement, ParentElement as _, RenderOnce, SharedString, StyleRefinement, Styled as _, + Window, div, +}; + +use crate::components::common::{StyledExt, v_flex}; + +/// The centered "nothing here yet" panel for lists, tables, and searches. +#[derive(IntoElement)] +#[must_use] +pub struct EmptyState { + icon: Option, + headline: SharedString, + hint: Option, + action: Option, + style: StyleRefinement, +} + +impl EmptyState { + /// Creates an empty state whose headline is the primary statement. + pub fn new(headline: L) -> Self + where + L: Into, + { + Self { + icon: None, + headline: headline.into(), + hint: None, + action: None, + style: StyleRefinement::default(), + } + } + + /// Sets a large muted icon above the headline. + pub fn icon(mut self, icon: I) -> Self + where + I: Into, + { + self.icon = Some(icon.into()); + self + } + + /// Sets a secondary line under the headline. + pub fn hint(mut self, hint: L) -> Self + where + L: Into, + { + self.hint = Some(hint.into()); + self + } + + /// Sets an action element — usually a button — under the hint. + pub fn action(mut self, action: E) -> Self + where + E: IntoElement, + { + self.action = Some(action.into_any_element()); + self + } +} + +impl gpui::Styled for EmptyState { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for EmptyState { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let metrics = theme.sizes.resolve(Size::Medium); + let muted_foreground = theme.colors.muted_foreground; + let foreground = theme.colors.foreground; + let illustration = metrics.icon_size * 2.0; + + v_flex() + .w_full() + .items_center() + .justify_center() + .text_center() + .p_4() + .when_some(self.icon, |state, icon| { + state.child( + div() + .mb_2() + .child(icon.size(illustration).color(muted_foreground)), + ) + }) + .child( + div() + .typeset(TextRole::Title3, cx) + .text_color(foreground) + .child(self.headline), + ) + .when_some(self.hint, |state, hint| { + state.child( + div() + .typeset(TextRole::Subheadline, cx) + .text_color(muted_foreground) + .child(hint), + ) + }) + .when_some(self.action, |state, action| { + state.child(div().mt_3().child(action)) + }) + .refine_style(&self.style) + } +} diff --git a/crates/ui/src/components/field.rs b/crates/ui/src/components/field.rs new file mode 100644 index 0000000..b94dd50 --- /dev/null +++ b/crates/ui/src/components/field.rs @@ -0,0 +1,181 @@ +//! The field: a label, description, and error wrapped around a control. + +use crate::theme::{ActiveTheme as _, TextRole, Typeset as _}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce, + Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div, +}; + +use crate::components::common::{StyledExt, h_flex, v_flex}; + +/// The arrangement of a [`Field`]'s label and control. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum FieldVariant { + /// The label block sits above the control, full width. + #[default] + Block, + /// The label block leads and the control trails — the settings row. + Row, +} + +/// A labeled control: the label, description, and error around any element. +#[derive(IntoElement)] +#[must_use] +pub struct Field { + id: ElementId, + label: SharedString, + description: Option, + error: Option, + variant: FieldVariant, + control: Vec, + style: StyleRefinement, +} + +impl Field { + /// Creates a field naming its control. + pub fn new(id: I, label: L) -> Self + where + I: Into, + L: Into, + { + Self { + id: id.into(), + label: label.into(), + description: None, + error: None, + variant: FieldVariant::default(), + control: Vec::new(), + style: StyleRefinement::default(), + } + } + + /// The helper text under the label. + pub fn description(mut self, description: D) -> Self + where + D: Into, + { + self.description = Some(description.into()); + self + } + + /// The error under the control; `None` clears it. + pub fn error(mut self, error: Option) -> Self + where + E: Into, + { + self.error = error.map(Into::into); + self + } + + /// Sets the field's arrangement. + pub fn variant(mut self, variant: FieldVariant) -> Self { + self.variant = variant; + self + } +} + +impl ParentElement for Field { + fn extend(&mut self, children: impl IntoIterator) { + self.control.extend(children); + } +} + +impl Styled for Field { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Field { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let metrics = theme.sizes.medium; + let error_color = theme.ramps.destructive.base; + let id = self.id.clone(); + + let title = div() + .debug_selector({ + let id = id.clone(); + move || format!("{id}-label") + }) + .when(self.description.is_some(), |title| { + title.typeset(TextRole::Headline, cx) + }) + .when(self.description.is_none(), |title| { + title.typeset(TextRole::Callout, cx) + }) + .child(self.label.clone()); + + let control = h_flex() + .items_center() + .gap_2() + .debug_selector({ + let id = id.clone(); + move || format!("{id}-control") + }) + .children(self.control); + + let error = self.error.map(|error| { + div() + .debug_selector({ + let id = id.clone(); + move || format!("{id}-error") + }) + .text_size(metrics.caption_size) + .text_color(error_color) + .child(error) + }); + + let description_text = |cx: &App| { + div() + .text_size(metrics.caption_size) + .text_color(cx.theme().colors.muted_foreground) + }; + + let content = if self.variant == FieldVariant::Row { + div() + .flex() + .flex_col() + .gap_1() + .child( + h_flex() + .items_center() + .justify_between() + .gap_4() + .child(title.flex_1().min_w_0()) + .child(control.flex_none()), + ) + .when_some(self.description.clone(), |field, description| { + field.child(description_text(cx).child(description)) + }) + .when_some(error, |field, error| field.child(error)) + } else { + div() + .flex() + .flex_col() + .gap_2() + .child( + v_flex() + .gap_0p5() + .child(title) + .when_some(self.description.clone(), |slot, description| { + slot.child(description_text(cx).child(description)) + }), + ) + .child(control) + .when_some(error, |field, error| field.child(error)) + }; + + div() + .id(self.id) + .w_full() + .role(Role::Group) + .aria_label(self.label.clone()) + .when_some(self.description, |field, description| { + field.aria_description(description) + }) + .refine_style(&self.style) + .child(content) + } +} diff --git a/crates/ui/src/components/grain.rs b/crates/ui/src/components/grain.rs new file mode 100644 index 0000000..9537050 --- /dev/null +++ b/crates/ui/src/components/grain.rs @@ -0,0 +1,90 @@ +//! The grain: a film-noise overlay for material surfaces. + +use std::sync::{Arc, OnceLock}; + +use crate::theme::GRAIN_ALPHA; +use crate::utils::ResultLogErr as _; +use gpui::{ + App, Bounds, Corners, IntoElement, RenderImage, RenderOnce, Styled as _, Window, canvas, point, + px, size, +}; +use image::{Frame, ImageBuffer, Rgba}; + +/// The side of one noise tile, in device pixels. +const TILE_PX: u32 = 256; + +/// A film-grain overlay: tiled monochrome noise at [`GRAIN_ALPHA`] strength. +#[derive(IntoElement)] +#[must_use] +pub struct Grain; + +/// Creates a grain overlay. +pub fn grain() -> Grain { + Grain +} + +impl RenderOnce for Grain { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + let texture = texture(); + canvas( + |_, _, _| (), + move |bounds, (), window, _| { + let tile = px(TILE_PX as f32); + let columns = (bounds.size.width / tile).ceil() as u32; + let rows = (bounds.size.height / tile).ceil() as u32; + + for row in 0..rows { + for column in 0..columns { + let x = bounds.origin.x + column as f32 * tile; + let y = bounds.origin.y + row as f32 * tile; + let tile_bounds = Bounds { + origin: point(x, y), + size: size( + tile.min(bounds.origin.x + bounds.size.width - x), + tile.min(bounds.origin.y + bounds.size.height - y), + ), + }; + window + .paint_image( + tile_bounds, + tile_bounds, + Corners::default(), + texture.clone(), + 0, + false, + ) + .log_err(); + } + } + }, + ) + .absolute() + .inset_0() + } +} + +/// The shared noise tile, every tile reuses its one atlas entry. +fn texture() -> Arc { + static TEXTURE: OnceLock> = OnceLock::new(); + + TEXTURE + .get_or_init(|| { + // An LCG keeps the grain deterministic across launches. + let mut state = 0x9E37_79B9_u32; + let mut noise = move || { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (state >> 24) as u8 + }; + // The grays are noise samples, not palette colors. + let alpha = (GRAIN_ALPHA * 255.0) as u8; + Arc::new(RenderImage::new([Frame::new(ImageBuffer::from_fn( + TILE_PX, + TILE_PX, + |_, _| { + let gray = noise(); + Rgba([gray, gray, gray, alpha]) + }, + ))])) + }) + .clone() +} diff --git a/crates/ui/src/components/input.rs b/crates/ui/src/components/input.rs new file mode 100644 index 0000000..6ec892f --- /dev/null +++ b/crates/ui/src/components/input.rs @@ -0,0 +1,2580 @@ +use std::ops::Range; +use std::rc::Rc; +use std::time::{Duration, Instant}; + +use unicode_segmentation::UnicodeSegmentation; + +use crate::icons::IconRole; +use crate::theme::{ + ActiveTheme as _, CARET_WIDTH, ColorTokens, DISABLED_OPACITY, Size, UNDERLINE_WIDTH, + WHEEL_LINE_HEIGHT, +}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + Animation, AnimationExt as _, AnyElement, App, AppContext as _, Bounds, ClipboardItem, + ContentMask, Context, CursorStyle, DefiniteLength, DispatchPhase, ElementId, Entity, + EntityInputHandler, EventEmitter, Font, HitboxBehavior, InteractiveElement as _, IntoElement, + KeyBinding, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, + ParentElement as _, Pixels, RenderOnce, Role, ScrollDelta, ScrollEvent, SharedString, + StatefulInteractiveElement as _, StyleRefinement, Styled as _, TextAlign, TextRun, + UTF16Selection, Window, WrappedLine, actions, canvas, div, fill, point, px, +}; + +use crate::components::button::{Button, ButtonVariant}; +use crate::components::common::{Sizable, StyledExt as _, h_flex}; + +/// The key context input bindings match against. +pub const INPUT_CONTEXT: &str = "Input"; +/// Consecutive edits within this interval merge into one undo entry. +const DEFAULT_GROUP_INTERVAL: Duration = Duration::from_millis(300); +/// How often the focused caret blinks. +const CARET_BLINK_INTERVAL: Duration = Duration::from_millis(500); +/// Pixel height of one scroll "line" for wheel scrolling. +const SCROLL_LINES_HEIGHT: f32 = WHEEL_LINE_HEIGHT; +/// The row count a multiline field shows until the app sets one. +const DEFAULT_ROWS: usize = 4; +/// Maximum undo entries kept; the oldest drops off the front. +const MAX_HISTORY: usize = 100; +/// The character a password field paints instead of each grapheme. +const MASK: &str = "\u{2022}"; +/// The byte length of [`MASK`]; the masked display is `graphemes × MASK_LEN`. +const MASK_LEN: usize = 3; + +/// Handler for key down events. +type KeyDownHandler = std::rc::Rc; +/// Handler for mouse down events. +type MouseDownHandler = std::rc::Rc; + +/// Significant changes in an [`InputState`], observable via `cx.subscribe`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum InputStateEvent { + /// The text content changed: typing, paste, IME commit, or `set_value`. + TextChanged, + /// The field gained focus. + Focused, + /// The field lost focus. + Blurred, + /// Enter was pressed + Submitted, +} + +/// Which keystroke submits a multiline field. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SubmitOn { + /// Enter inserts a newline; modifier + Enter submits. + #[default] + ModifiedEnter, + /// Enter submits; Shift + Enter inserts a newline. + Enter, +} + +actions!( + input, + [ + Escape, + Submit, + SecondarySubmit, + InsertNewline, + Up, + Down, + SelectUp, + SelectDown, + Backspace, + Delete, + DeleteWordLeft, + DeleteWordRight, + DeleteToBeginningOfLine, + Left, + Right, + SelectLeft, + SelectRight, + WordLeft, + WordRight, + SelectWordLeft, + SelectWordRight, + Home, + End, + SelectHome, + SelectEnd, + SelectAll, + Copy, + Cut, + Paste, + Undo, + Redo, + ] +); + +/// Keybindings for input actions. +#[derive(Clone, Debug)] +pub struct InputBindings { + pub escape: Option, + pub submit: Option, + pub secondary_submit: Option, + pub insert_newline: Option, + pub backspace: Option, + pub delete: Option, + pub delete_word_left: Option, + pub delete_word_right: Option, + pub delete_to_beginning_of_line: Option, + pub left: Option, + pub right: Option, + pub up: Option, + pub down: Option, + pub select_left: Option, + pub select_right: Option, + pub select_up: Option, + pub select_down: Option, + pub word_left: Option, + pub word_right: Option, + pub select_word_left: Option, + pub select_word_right: Option, + pub home: Option, + pub end: Option, + pub select_home: Option, + pub select_end: Option, + pub select_all: Option, + pub copy: Option, + pub cut: Option, + pub paste: Option, + pub undo: Option, + pub redo: Option, +} + +impl Default for InputBindings { + /// The platform-specific defaults: cmd on macOS, ctrl elsewhere. + fn default() -> Self { + let context = Some(INPUT_CONTEXT); + + #[cfg(target_os = "macos")] + let bindings = Self { + escape: Some(KeyBinding::new("escape", Escape, context)), + submit: Some(KeyBinding::new("enter", Submit, context)), + secondary_submit: Some(KeyBinding::new("cmd-enter", SecondarySubmit, context)), + insert_newline: Some(KeyBinding::new("shift-enter", InsertNewline, context)), + backspace: Some(KeyBinding::new("backspace", Backspace, context)), + delete: Some(KeyBinding::new("delete", Delete, context)), + delete_word_left: Some(KeyBinding::new("alt-backspace", DeleteWordLeft, context)), + delete_word_right: Some(KeyBinding::new("alt-delete", DeleteWordRight, context)), + delete_to_beginning_of_line: Some(KeyBinding::new( + "cmd-backspace", + DeleteToBeginningOfLine, + context, + )), + left: Some(KeyBinding::new("left", Left, context)), + right: Some(KeyBinding::new("right", Right, context)), + up: Some(KeyBinding::new("up", Up, context)), + down: Some(KeyBinding::new("down", Down, context)), + select_left: Some(KeyBinding::new("shift-left", SelectLeft, context)), + select_right: Some(KeyBinding::new("shift-right", SelectRight, context)), + select_up: Some(KeyBinding::new("shift-up", SelectUp, context)), + select_down: Some(KeyBinding::new("shift-down", SelectDown, context)), + word_left: Some(KeyBinding::new("alt-left", WordLeft, context)), + word_right: Some(KeyBinding::new("alt-right", WordRight, context)), + select_word_left: Some(KeyBinding::new("alt-shift-left", SelectWordLeft, context)), + select_word_right: Some(KeyBinding::new("alt-shift-right", SelectWordRight, context)), + home: Some(KeyBinding::new("home", Home, context)), + end: Some(KeyBinding::new("end", End, context)), + select_home: Some(KeyBinding::new("shift-home", SelectHome, context)), + select_end: Some(KeyBinding::new("shift-end", SelectEnd, context)), + select_all: Some(KeyBinding::new("cmd-a", SelectAll, context)), + copy: Some(KeyBinding::new("cmd-c", Copy, context)), + cut: Some(KeyBinding::new("cmd-x", Cut, context)), + paste: Some(KeyBinding::new("cmd-v", Paste, context)), + undo: Some(KeyBinding::new("cmd-z", Undo, context)), + redo: Some(KeyBinding::new("cmd-shift-z", Redo, context)), + }; + + #[cfg(not(target_os = "macos"))] + let bindings = Self { + escape: Some(KeyBinding::new("escape", Escape, context)), + submit: Some(KeyBinding::new("enter", Submit, context)), + secondary_submit: Some(KeyBinding::new("ctrl-enter", SecondarySubmit, context)), + insert_newline: Some(KeyBinding::new("shift-enter", InsertNewline, context)), + backspace: Some(KeyBinding::new("backspace", Backspace, context)), + delete: Some(KeyBinding::new("delete", Delete, context)), + delete_word_left: Some(KeyBinding::new("ctrl-backspace", DeleteWordLeft, context)), + delete_word_right: Some(KeyBinding::new("ctrl-delete", DeleteWordRight, context)), + delete_to_beginning_of_line: Some(KeyBinding::new( + "ctrl-shift-backspace", + DeleteToBeginningOfLine, + context, + )), + left: Some(KeyBinding::new("left", Left, context)), + right: Some(KeyBinding::new("right", Right, context)), + up: Some(KeyBinding::new("up", Up, context)), + down: Some(KeyBinding::new("down", Down, context)), + select_left: Some(KeyBinding::new("shift-left", SelectLeft, context)), + select_right: Some(KeyBinding::new("shift-right", SelectRight, context)), + select_up: Some(KeyBinding::new("shift-up", SelectUp, context)), + select_down: Some(KeyBinding::new("shift-down", SelectDown, context)), + word_left: Some(KeyBinding::new("ctrl-left", WordLeft, context)), + word_right: Some(KeyBinding::new("ctrl-right", WordRight, context)), + select_word_left: Some(KeyBinding::new("ctrl-shift-left", SelectWordLeft, context)), + select_word_right: Some(KeyBinding::new( + "ctrl-shift-right", + SelectWordRight, + context, + )), + home: Some(KeyBinding::new("home", Home, context)), + end: Some(KeyBinding::new("end", End, context)), + select_home: Some(KeyBinding::new("shift-home", SelectHome, context)), + select_end: Some(KeyBinding::new("shift-end", SelectEnd, context)), + select_all: Some(KeyBinding::new("ctrl-a", SelectAll, context)), + copy: Some(KeyBinding::new("ctrl-c", Copy, context)), + cut: Some(KeyBinding::new("ctrl-x", Cut, context)), + paste: Some(KeyBinding::new("ctrl-v", Paste, context)), + undo: Some(KeyBinding::new("ctrl-z", Undo, context)), + redo: Some(KeyBinding::new("ctrl-shift-z", Redo, context)), + }; + + bindings + } +} + +impl InputBindings { + /// A table with every key unbound, for building custom bindings. + pub fn empty() -> Self { + Self { + escape: None, + submit: None, + secondary_submit: None, + insert_newline: None, + backspace: None, + delete: None, + delete_word_left: None, + delete_word_right: None, + delete_to_beginning_of_line: None, + left: None, + right: None, + up: None, + down: None, + select_left: None, + select_right: None, + select_up: None, + select_down: None, + word_left: None, + word_right: None, + select_word_left: None, + select_word_right: None, + home: None, + end: None, + select_home: None, + select_end: None, + select_all: None, + copy: None, + cut: None, + paste: None, + undo: None, + redo: None, + } + } + + /// Collects the table into keybindings. + pub(crate) fn into_bindings(self) -> Vec { + let mut bindings: Vec = [ + self.escape, + self.submit, + self.secondary_submit, + self.insert_newline, + self.backspace, + self.delete, + self.delete_word_left, + self.delete_word_right, + self.delete_to_beginning_of_line, + self.left, + self.right, + self.up, + self.down, + self.select_left, + self.select_right, + self.select_up, + self.select_down, + self.word_left, + self.word_right, + self.select_word_left, + self.select_word_right, + self.home, + self.end, + self.select_home, + self.select_end, + self.select_all, + self.copy, + self.cut, + self.paste, + self.undo, + self.redo, + ] + .into_iter() + .flatten() + .collect(); + + #[cfg(target_os = "macos")] + { + let context = Some(INPUT_CONTEXT); + bindings.extend([ + KeyBinding::new("cmd-left", Home, context), + KeyBinding::new("cmd-right", End, context), + KeyBinding::new("cmd-up", Home, context), + KeyBinding::new("cmd-down", End, context), + KeyBinding::new("cmd-shift-left", SelectHome, context), + KeyBinding::new("cmd-shift-right", SelectEnd, context), + ]); + } + + bindings + } +} + +/// The shaped text: one wrapped line per buffer line, plus the mask map when masking. +struct ShapedText { + lines: Vec, + mask_map: Option>, +} + +/// One shaped source line and its first byte's offset in the display text. +struct ShapedLineEntry { + start: usize, + line: WrappedLine, +} + +/// The field's inner padding. +#[derive(Clone, Copy)] +struct FieldPadding { + left: Pixels, + right: Pixels, + /// Top inset; multiline fields balance it below the last row. + top: Pixels, +} + +/// One visual (wrapped) row: a display-byte range and its y offset from the text origin. +struct VisualRow { + range: Range, + y: Pixels, + /// Index of the source line this row belongs to. + line_ix: usize, +} + +/// Input layout information for hit testing and caret positioning. +struct InputLayout { + lines: Vec, + /// The visual rows in order, top to bottom. + rows: Vec, + bounds: Bounds, + /// Where the text origin (top-left of row 0) sits inside `bounds`. + origin: gpui::Point, + /// Maps display offsets to real buffer offsets for masked input. + mask_map: Option>, + /// The height of one visual row. + line_height: Pixels, + /// Inner width available to the text. + text_width: Pixels, + /// Height of all rows stacked. + content_height: Pixels, + /// Height of the region the rows scroll within. + visible_height: Pixels, +} + +impl InputLayout { + /// The x of a display index relative to its row's start. + fn row_x(&self, row_ix: usize, display: usize) -> Pixels { + let row = &self.rows[row_ix]; + let entry = &self.lines[row.line_ix]; + let layout = &entry.line.unwrapped_layout; + let row_start = row.range.start - entry.start; + layout.x_for_index(display - entry.start) - layout.x_for_index(row_start) + } + + /// The row containing `display` and the caret's x relative to the row start. + fn row_for_index(&self, display: usize) -> Option<(usize, Pixels)> { + if self.rows.is_empty() { + return None; + } + let row_ix = row_ix_for_display(&self.rows, display); + let display = display.min(self.rows[row_ix].range.end); + Some((row_ix, self.row_x(row_ix, display))) + } + + /// The display index within `row_ix` closest to `x`, which is relative to the row start. + fn index_at_row_x(&self, row_ix: usize, x: Pixels) -> usize { + let row = &self.rows[row_ix]; + let entry = &self.lines[row.line_ix]; + let layout = &entry.line.unwrapped_layout; + let row_start = row.range.start - entry.start; + layout + .closest_index_for_x(layout.x_for_index(row_start) + x) + .clamp(row_start, row.range.end - entry.start) + + entry.start + } + + /// The display index at a window point, using the last painted layout. + fn index_at(&self, position: gpui::Point) -> usize { + if self.rows.is_empty() { + return 0; + } + let rel_y = (position.y - self.origin.y) / self.line_height; + let row_ix = (rel_y.floor().max(0.0) as usize).min(self.rows.len() - 1); + self.index_at_row_x(row_ix, position.x - self.origin.x) + } + + /// The display range of the row containing `display`. + fn row_range_at(&self, display: usize) -> Option> { + self.rows + .iter() + .find(|row| display <= row.range.end) + .map(|row| row.range.clone()) + } + + /// The overlaps of a display range with each visual row: + /// `(row index, clipped range, the range continues past the row)`. + /// + /// A range that strictly passes an empty row paints that row full width. + fn row_overlaps(&self, range: Range) -> Vec<(usize, Range, bool)> { + let mut overlaps = Vec::new(); + for (row_ix, row) in self.rows.iter().enumerate() { + let touches = range.start < row.range.end + || (row.range.is_empty() && range.start <= row.range.start); + let beyond = touches && range.end > row.range.end; + let start = range.start.clamp(row.range.start, row.range.end); + let end = range.end.clamp(row.range.start, row.range.end); + if start < end || beyond { + overlaps.push((row_ix, start..end, beyond)); + } + } + overlaps + } +} + +/// History entry for undo/redo operations. +#[derive(Clone, Debug)] +struct HistoryEntry { + /// The range the replacement occupies after the edit. + range: Range, + /// The text the edit replaced, restored on undo. + old_text: String, + /// The length of the replacement. + new_len: usize, + /// The selection before the edit. + cursor: usize, + anchor: usize, + /// When the edit happened, for grouping. + timestamp: Instant, +} + +impl HistoryEntry { + /// Applies this entry in reverse, returning the entry that reverses it back. + fn reverse(&self, text: &mut String) -> HistoryEntry { + let end = (self.range.start + self.new_len).min(text.len()); + let removed = text[self.range.start..end].to_string(); + text.replace_range(self.range.start..end, &self.old_text); + + HistoryEntry { + range: self.range.start..self.range.start + self.old_text.len(), + old_text: removed, + new_len: self.old_text.len(), + cursor: self.cursor, + anchor: self.anchor, + timestamp: self.timestamp, + } + } +} + +/// The application-owned state of a text field. +pub struct InputState { + text: String, + /// The caret's byte offset. + cursor: usize, + /// The byte offset the selection extends from. + anchor: usize, + /// The byte range of in-progress IME composition, if any. + marked_range: Option>, + /// Whether the field had focus at the last paint, for focus transitions. + focused: bool, + focus_handle: gpui::FocusHandle, + /// The key-down handler, bound to this entity with `cx.listener`. + key_down_handler: KeyDownHandler, + /// The mouse-down handler, bound to this entity with `cx.listener`. + mouse_down_handler: MouseDownHandler, + /// Whether a drag-select is in progress. + dragging: bool, + /// Patch history. `redo_stack` holds undone entries awaiting redo. + undo_stack: Vec, + redo_stack: Vec, + /// Consecutive edits within this interval merge into one undo entry. + group_interval: Duration, + /// When set, user edits are refused, focus, movement, selection and copy stay. + read_only: bool, + /// When set, the field is a password field. + password: bool, + /// Whether a password field currently shows its content. + revealed: bool, + /// Whether the field holds multiple lines of text. + multiline: bool, + /// Which keystroke submits a multiline field. + submit_on: SubmitOn, + /// The x the caret keeps across vertical movement, reset on any other move. + goal_x: Option, + /// Content scroll inside the field: x for single-line, y for multiline, clamped at paint. + scroll_offset: gpui::Point, + /// Set by every caret-affecting change. + scroll_to_caret_pending: bool, + /// Bumped on every edit. + caret_epoch: usize, + /// When the current caret epoch started. + caret_epoch_started: Instant, + /// The shaped line and element bounds, recorded during each paint. + layout: Option, +} + +impl EventEmitter for InputState {} + +/// Builder for [`InputState`] settings that are fixed at creation. +#[derive(Default)] +pub struct InputStateBuilder { + text: String, + multiline: bool, + password: bool, + read_only: bool, +} + +impl InputStateBuilder { + /// Sets the initial text, caret at the end. + pub fn text(mut self, text: T) -> Self + where + T: Into, + { + self.text = text.into(); + self + } + + /// Makes the field hold multiple lines. + pub fn multiline(mut self) -> Self { + self.multiline = true; + self + } + + /// Makes the field a password field. + pub fn password(mut self) -> Self { + self.password = true; + self + } + + /// Refuses user edits, focus, movement, selection and copy stay. + pub fn read_only(mut self) -> Self { + self.read_only = true; + self + } + + /// Creates the state entity. + pub fn build(self, cx: &mut App) -> Entity { + let InputStateBuilder { + text, + multiline, + password, + read_only, + } = self; + + cx.new(|cx| { + let mut state = InputState::new_inner(cx); + state.text = sanitize(text, multiline); + state.cursor = state.text.len(); + state.anchor = state.cursor; + state.multiline = multiline; + state.password = password; + state.read_only = read_only; + state + }) + } +} + +impl InputState { + fn new_inner(cx: &mut Context) -> Self { + Self { + text: String::new(), + cursor: 0, + anchor: 0, + marked_range: None, + focused: false, + focus_handle: cx.focus_handle(), + key_down_handler: Rc::new(cx.listener(|state, event: &KeyDownEvent, window, cx| { + state.handle_key_down(event, window, cx); + })), + mouse_down_handler: Rc::new(cx.listener( + |state, event: &MouseDownEvent, window, cx| { + state.handle_mouse_down(event, window, cx); + }, + )), + dragging: false, + undo_stack: Vec::new(), + redo_stack: Vec::new(), + group_interval: DEFAULT_GROUP_INTERVAL, + read_only: false, + password: false, + revealed: false, + multiline: false, + submit_on: SubmitOn::default(), + goal_x: None, + scroll_offset: point(Pixels::ZERO, Pixels::ZERO), + scroll_to_caret_pending: true, + caret_epoch: 0, + caret_epoch_started: Instant::now(), + layout: None, + } + } + + /// Creates the state entity for an application-owned input. + pub fn new(cx: &mut App) -> Entity { + cx.new(Self::new_inner) + } + + /// Returns a builder for creation-time settings like text, multiline and password. + pub fn builder() -> InputStateBuilder { + InputStateBuilder::default() + } + + /// The current text. + pub fn value(&self) -> &str { + &self.text + } + + /// Replaces the whole value and collapses the selection to the end. + pub fn set_value(&mut self, value: V, window: &mut Window, cx: &mut Context) + where + V: Into, + { + self.set_value_inner(value, true, window, cx); + } + + /// Like [`set_value`], but does not emit `TextChanged`. + pub fn set_value_silent(&mut self, value: V, window: &mut Window, cx: &mut Context) + where + V: Into, + { + self.set_value_inner(value, false, window, cx); + } + + fn set_value_inner( + &mut self, + value: V, + emit: bool, + window: &mut Window, + cx: &mut Context, + ) where + V: Into, + { + let text = sanitize(value.into(), self.multiline); + if text == self.text { + return; + } + self.text = text; + self.cursor = self.text.len(); + self.anchor = self.cursor; + self.marked_range = None; + self.undo_stack.clear(); + self.redo_stack.clear(); + if emit { + cx.emit(InputStateEvent::TextChanged); + } + self.notify(window, cx); + } + + /// Sets how long consecutive edits keep merging into one undo entry. + pub fn set_group_interval(&mut self, interval: Duration) { + self.group_interval = interval; + } + + /// Sets whether user edits are refused. + pub fn set_read_only(&mut self, read_only: bool, cx: &mut Context) { + if self.read_only != read_only { + self.read_only = read_only; + cx.notify(); + } + } + + /// Whether user edits are refused. + pub fn is_read_only(&self) -> bool { + self.read_only + } + + /// Whether the field is a password field. + pub fn is_password(&self) -> bool { + self.password + } + + /// Sets whether a password field currently shows its content. + pub fn set_revealed(&mut self, revealed: bool, cx: &mut Context) { + if self.revealed != revealed { + self.revealed = revealed; + cx.notify(); + } + } + + /// Whether a password field currently shows its content. + pub fn is_revealed(&self) -> bool { + self.revealed + } + + /// Whether the field holds multiple lines. + pub fn is_multiline(&self) -> bool { + self.multiline + } + + /// Sets which keystroke submits a multiline field. + pub fn set_submit_on(&mut self, submit_on: SubmitOn, cx: &mut Context) { + if self.submit_on != submit_on { + self.submit_on = submit_on; + cx.notify(); + } + } + + // Whether the painted line masks the buffer. + fn masked(&self) -> bool { + self.password && !self.revealed + } + + /// Records `old_text` at `range` being replaced by `new_len` bytes. + fn push_history(&mut self, range: Range, old_text: String, new_len: usize) { + self.redo_stack.clear(); + + let now = Instant::now(); + if let Some(last) = self.undo_stack.last_mut() { + let last_end = last.range.start + last.new_len; + + if self.marked_range.is_some() { + // A pre-edit step overlapping the previous entry's region. + if range.start >= last.range.start { + last.new_len += new_len; + let replaced = range.len(); + last.new_len -= replaced; + last.timestamp = now; + return; + } + } + + if now.duration_since(last.timestamp) < self.group_interval { + // Typing that continues right after the previous edit. + if range.start == last_end { + last.new_len += new_len; + last.timestamp = now; + return; + } + + // A deletion of text that sat right before the previous edit. + if range.end == last.range.start && new_len == 0 { + last.range.start = range.start; + last.old_text = old_text + &last.old_text; + last.timestamp = now; + return; + } + + // An edit fully inside the previous edit's replacement. + if range.start >= last.range.start && range.end <= last_end { + last.new_len += new_len; + last.new_len -= range.len(); + last.timestamp = now; + return; + } + } + } + + self.undo_stack.push(HistoryEntry { + range: range.start..range.start + new_len, + old_text, + new_len, + cursor: self.cursor, + anchor: self.anchor, + timestamp: now, + }); + + if self.undo_stack.len() > MAX_HISTORY { + self.undo_stack.remove(0); + } + } + + /// The focus handle, for applications that focus the field programmatically. + pub fn focus_handle(&self) -> gpui::FocusHandle { + self.focus_handle.clone() + } + + /// The selected byte range of the buffer. + fn selection(&self) -> Range { + self.cursor.min(self.anchor)..self.cursor.max(self.anchor) + } + + fn notify(&mut self, window: &mut Window, cx: &mut Context) { + cx.notify(); + self.scroll_to_caret_pending = true; + self.goal_x = None; + self.caret_epoch += 1; + self.caret_epoch_started = Instant::now(); + window.notify_text_input_changed(&self.focus_handle); + } + + /// Scrolls the field by a wheel delta, clamped at paint. + fn scroll_by( + &mut self, + delta: gpui::Point, + window: &mut Window, + cx: &mut Context, + ) -> bool { + if self.multiline { + let next_y = (self.scroll_offset.y + delta.y).max(Pixels::ZERO); + if next_y == self.scroll_offset.y { + return self.multiline_scrollable(); + } + self.scroll_offset.y = next_y; + } else { + let next_x = (self.scroll_offset.x - delta.x).max(Pixels::ZERO); + if next_x == self.scroll_offset.x { + return false; + } + self.scroll_offset.x = next_x; + } + + let scrollable = self + .layout + .as_ref() + .is_some_and(|layout| layout.content_height > layout.visible_height); + + cx.notify(); + window.notify_text_input_changed(&self.focus_handle); + self.multiline && scrollable + } + + /// Whether a multiline field's content overflows vertically. + fn multiline_scrollable(&self) -> bool { + self.multiline + && self + .layout + .as_ref() + .is_some_and(|layout| layout.content_height > layout.visible_height) + } + + /// Emits `Focused`/`Blurred` when the field's focus state changed since the last paint. + fn sync_focus(&mut self, focused: bool, cx: &mut Context) { + if self.focused == focused { + return; + } + self.focused = focused; + + if focused { + self.caret_epoch += 1; + self.caret_epoch_started = Instant::now(); + } + + cx.emit(if focused { + InputStateEvent::Focused + } else { + InputStateEvent::Blurred + }); + } + + /// Whether the caret should paint. + pub fn caret_visible(&self, focused: bool) -> bool { + let elapsed = self.caret_epoch_started.elapsed(); + self.caret_blink_visible_at(focused, elapsed) + } + + /// The visibility math at a given time since the epoch started. + pub fn caret_blink_visible_at(&self, focused: bool, elapsed: Duration) -> bool { + if !focused || self.read_only { + return false; + } + let period = CARET_BLINK_INTERVAL * 2; + (elapsed.as_millis() as u64 % period.as_millis() as u64) + < CARET_BLINK_INTERVAL.as_millis() as u64 + } + + /// Replaces a byte range with `text` and collapses the caret to its end. + fn replace_range( + &mut self, + range: Range, + text: &str, + window: &mut Window, + cx: &mut Context, + ) { + if self.read_only { + return; + } + + if range.is_empty() && text.is_empty() { + return; + } + + let text = sanitize(text, self.multiline); + let old_text = self.text[range.clone()].to_string(); + self.push_history(range.clone(), old_text, text.len()); + self.text.replace_range(range.clone(), &text); + self.cursor = range.start + text.len(); + self.anchor = self.cursor; + self.marked_range = None; + + cx.emit(InputStateEvent::TextChanged); + self.notify(window, cx); + } + + /// Deletes the selection, or one character/word before the caret. + fn delete_backward(&mut self, word: bool, window: &mut Window, cx: &mut Context) { + if !self.selection().is_empty() { + let range = self.selection(); + self.replace_range(range, "", window, cx); + } else if self.cursor > 0 { + let start = if word { + previous_word_start(&self.text, self.cursor) + } else { + previous_grapheme_start(&self.text, self.cursor) + }; + self.replace_range(start..self.cursor, "", window, cx); + } + } + + /// Deletes the selection, or one character/word after the caret. + fn delete_forward(&mut self, word: bool, window: &mut Window, cx: &mut Context) { + if !self.selection().is_empty() { + let range = self.selection(); + self.replace_range(range, "", window, cx); + } else if self.cursor < self.text.len() { + let end = if word { + next_word_end(&self.text, self.cursor) + } else { + next_grapheme_start(&self.text, self.cursor) + }; + self.replace_range(self.cursor..end, "", window, cx); + } + } + + /// Moves the caret, extending the selection when `extend`. + fn move_cursor( + &mut self, + to: usize, + extend: bool, + window: &mut Window, + cx: &mut Context, + ) { + let cursor = to.clamp(0, self.text.len()); + let anchor = if extend { self.anchor } else { cursor }; + if cursor == self.cursor && anchor == self.anchor { + return; + } + self.cursor = cursor; + self.anchor = anchor; + self.notify(window, cx); + } + + /// Selects `range`. + fn select_range(&mut self, range: Range, window: &mut Window, cx: &mut Context) { + if range.start == self.anchor && range.end == self.cursor { + return; + } + self.anchor = range.start; + self.cursor = range.end; + self.notify(window, cx); + } + + /// Copies the selected text to the clipboard. + fn copy_selection(&mut self, _window: &mut Window, cx: &mut Context) -> bool { + if self.password { + return false; + } + let range = self.selection(); + if range.is_empty() { + return false; + } + cx.write_to_clipboard(ClipboardItem::new_string( + self.text[range.clone()].to_string(), + )); + true + } + + /// Deletes the selected range, if any. + fn delete_selection(&mut self, window: &mut Window, cx: &mut Context) { + let range = self.selection(); + if !range.is_empty() { + self.replace_range(range, "", window, cx); + } + } + + /// Shapes the masked or plain buffer, wrapping to `wrap_width` when set, + /// with the paint-time text style. + fn shape_current_text(&self, wrap_width: Option, window: &Window) -> ShapedText { + let (text, mask_map) = if self.masked() { + masked_display(&self.text) + } else { + (self.text.clone(), None) + }; + let text_style = window.text_style(); + + let font = Font { + family: text_style.font_family.clone(), + features: text_style.font_features.clone(), + weight: text_style.font_weight, + style: text_style.font_style, + fallbacks: text_style.font_fallbacks.clone(), + }; + + let font_size = text_style.font_size.to_pixels(window.rem_size()); + let runs = [TextRun { + len: text.len(), + font, + color: text_style.color, + background_color: None, + underline: None, + strikethrough: None, + }]; + + let shaped = + window + .text_system() + .shape_text(text.into(), font_size, &runs, wrap_width, None); + + let mut lines = Vec::new(); + match shaped { + Ok(shaped) => { + let mut start = 0; + for line in shaped { + let end = start + line.len(); + lines.push(ShapedLineEntry { start, line }); + start = end + '\n'.len_utf8(); + } + } + Err(err) => log::warn!("shaping input text failed: {err}"), + } + + ShapedText { lines, mask_map } + } + + /// Stores the paint geometry for hit-testing and the IME conversions. + fn store_layout( + &mut self, + text: ShapedText, + bounds: Bounds, + padding: FieldPadding, + line_height: Pixels, + ) -> gpui::Point { + // The visual row table: one entry per wrapped row, top to bottom. + let mut rows = Vec::new(); + let mut y = Pixels::ZERO; + + for (line_ix, entry) in text.lines.iter().enumerate() { + let mut row_start = 0; + let boundaries = + entry.line.wrap_boundaries().iter().map(|boundary| { + entry.line.runs()[boundary.run_ix].glyphs[boundary.glyph_ix].index + }); + for end in boundaries.chain([entry.line.len()]) { + rows.push(VisualRow { + range: entry.start + row_start..entry.start + end, + y, + line_ix, + }); + y += line_height; + row_start = end; + } + } + + let content_height = y; + + let visible_height = if self.multiline { + (bounds.size.height - padding.top * 2.0).max(Pixels::ZERO) + } else { + bounds.size.height + }; + + let caret = if rows.is_empty() { + (Pixels::ZERO, Pixels::ZERO) + } else { + let display = display_index(&text.mask_map, self.selection().end); + let row_ix = row_ix_for_display(&rows, display); + let row = &rows[row_ix]; + let entry = &text.lines[row.line_ix]; + let shaped = &entry.line.unwrapped_layout; + let row_start = row.range.start - entry.start; + let x = shaped.x_for_index(display.min(row.range.end) - entry.start) + - shaped.x_for_index(row_start); + (row.y, x) + }; + + if self.multiline { + let max_scroll = (content_height - visible_height).max(Pixels::ZERO); + if self.scroll_to_caret_pending { + self.scroll_to_caret_pending = false; + let (caret_y, _) = caret; + if caret_y + line_height > self.scroll_offset.y + visible_height { + self.scroll_offset.y = caret_y + line_height - visible_height; + } + if caret_y < self.scroll_offset.y { + self.scroll_offset.y = caret_y; + } + } + self.scroll_offset.y = self.scroll_offset.y.clamp(Pixels::ZERO, max_scroll); + self.scroll_offset.x = Pixels::ZERO; + } else { + let visible = (bounds.size.width - padding.left - padding.right).max(Pixels::ZERO); + let line_width = text + .lines + .first() + .map(|entry| entry.line.width()) + .unwrap_or(Pixels::ZERO); + let max_scroll = (line_width - visible).max(Pixels::ZERO); + if self.scroll_to_caret_pending { + self.scroll_to_caret_pending = false; + // Pull the scroll just far enough to reveal the caret on whichever edge it left. + let (_, caret_x) = caret; + if caret_x - self.scroll_offset.x > visible { + self.scroll_offset.x = caret_x - visible; + } + if caret_x < self.scroll_offset.x { + self.scroll_offset.x = caret_x; + } + } + self.scroll_offset.x = self.scroll_offset.x.clamp(Pixels::ZERO, max_scroll); + self.scroll_offset.y = Pixels::ZERO; + } + + let origin = point( + bounds.left() + padding.left - self.scroll_offset.x, + if self.multiline { + bounds.top() + padding.top - self.scroll_offset.y + } else { + bounds.top() + (bounds.size.height - line_height) / 2.0 + }, + ); + + let text_width = (bounds.size.width - padding.left - padding.right).max(Pixels::ZERO); + self.layout = Some(InputLayout { + lines: text.lines, + rows, + bounds, + origin, + mask_map: text.mask_map, + line_height, + text_width, + content_height, + visible_height, + }); + + origin + } + + /// Paints the selection highlight behind the text. + fn paint_selection(&self, origin: gpui::Point, color: gpui::Hsla, window: &mut Window) { + let selection = self.selection(); + if selection.is_empty() { + return; + } + + let Some(layout) = self.layout.as_ref() else { + return; + }; + + let start = display_index(&layout.mask_map, selection.start); + let end = display_index(&layout.mask_map, selection.end); + + for (row_ix, clipped, beyond) in layout.row_overlaps(start..end) { + let top = origin.y + layout.rows[row_ix].y; + let left = origin.x + layout.row_x(row_ix, clipped.start); + let right = origin.x + + if beyond { + layout.text_width + } else { + layout.row_x(row_ix, clipped.end) + }; + let rect = + Bounds::from_corners(point(left, top), point(right, top + layout.line_height)); + window.paint_quad(fill(rect, color)); + } + } + + /// Paints the text itself. + fn paint_text( + &self, + origin: gpui::Point, + right_padding: Pixels, + window: &mut Window, + cx: &mut App, + ) { + let Some(layout) = self.layout.as_ref() else { + return; + }; + + let mask = Bounds::from_corners( + point(layout.bounds.left(), layout.bounds.top()), + point( + layout.bounds.right() - right_padding, + layout.bounds.bottom(), + ), + ); + + window.with_content_mask(Some(ContentMask { bounds: mask }), |window| { + let mut line_top = Pixels::ZERO; + for entry in &layout.lines { + let line_origin = point(origin.x, origin.y + line_top); + if let Err(err) = entry.line.paint( + line_origin, + layout.line_height, + TextAlign::Left, + None, + window, + cx, + ) { + log::warn!("painting input text failed: {err}"); + } + line_top += layout.line_height * (entry.line.wrap_boundaries().len() + 1) as f32; + } + }); + } + + /// Paints the caret at the cursor position. + fn paint_caret( + &self, + origin: gpui::Point, + font_size: Pixels, + color: gpui::Hsla, + window: &mut Window, + ) { + let Some(layout) = self.layout.as_ref() else { + return; + }; + + let display = display_index(&layout.mask_map, self.cursor); + let Some((row_ix, caret_x)) = layout.row_for_index(display) else { + return; + }; + + let caret_top = origin.y + layout.rows[row_ix].y + (layout.line_height - font_size) / 2.0; + let caret = Bounds::from_corners( + point(origin.x + caret_x, caret_top), + point(origin.x + caret_x + CARET_WIDTH, caret_top + font_size), + ); + + window.paint_quad(fill(caret, color)); + } + + /// Paints the field contents; returns whether a drag-select is in progress. + fn paint( + &mut self, + text: ShapedText, + bounds: Bounds, + padding: FieldPadding, + colors: ColorTokens, + window: &mut Window, + cx: &mut Context, + ) -> bool { + let focused = self.focus_handle.is_focused(window); + self.sync_focus(focused, cx); + + let text_style = window.text_style(); + let font_size = text_style.font_size.to_pixels(window.rem_size()); + let line_height = text_style + .line_height + .to_pixels(text_style.font_size, window.rem_size()); + + let origin = self.store_layout(text, bounds, padding, line_height); + + if focused && !self.selection().is_empty() { + self.paint_selection(origin, colors.selection, window); + } + + self.paint_text(origin, padding.right, window, cx); + + // The composition underline shows the in-progress IME text. + if let Some(range) = self.marked_range.clone() + && !range.is_empty() + { + self.paint_marked_underline(origin, range, colors.foreground, window); + } + + // A caret promises that typing lands there; in read-only it does not. + if focused && self.caret_visible(focused) && self.selection().is_empty() { + self.paint_caret(origin, font_size, colors.foreground, window); + } + + self.dragging + } + + /// The text index at a window point, using the last painted layout. + fn index_at(&self, position: gpui::Point) -> usize { + let Some(layout) = self.layout.as_ref() else { + return 0; + }; + real_index(&layout.mask_map, layout.index_at(position)) + } + + /// Extends the selection to `position` while drag-selecting. + fn drag_select_to( + &mut self, + position: gpui::Point, + window: &mut Window, + cx: &mut Context, + ) { + let cursor = self.index_at(position); + if cursor == self.cursor { + return; + } + self.cursor = cursor; + self.notify(window, cx); + } + + /// Paints the composition underline under the marked range. + fn paint_marked_underline( + &self, + origin: gpui::Point, + range: Range, + color: gpui::Hsla, + window: &mut Window, + ) { + let Some(layout) = self.layout.as_ref() else { + return; + }; + + let start = display_index(&layout.mask_map, range.start); + let end = display_index(&layout.mask_map, range.end); + let thickness = UNDERLINE_WIDTH; + + for (row_ix, clipped, beyond) in layout.row_overlaps(start..end) { + let top = origin.y + layout.rows[row_ix].y + layout.line_height - thickness; + let left = origin.x + layout.row_x(row_ix, clipped.start); + let right = origin.x + + if beyond { + layout.text_width + } else { + layout.row_x(row_ix, clipped.end) + }; + let rect = Bounds::from_corners(point(left, top), point(right, top + thickness)); + window.paint_quad(fill(rect, color)); + } + } + + /// Register drag listeners. + fn register_drag_listeners(entity: &Entity, window: &mut Window) { + window.on_mouse_event({ + let state = entity.clone(); + move |event: &MouseMoveEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble || event.pressed_button != Some(MouseButton::Left) + { + return; + } + state.update(cx, |state, cx| { + state.drag_select_to(event.position, window, cx) + }); + } + }); + window.on_mouse_event({ + let state = entity.clone(); + move |event: &MouseUpEvent, phase, _window, cx| { + if phase != DispatchPhase::Bubble || event.button != MouseButton::Left { + return; + } + state.update(cx, |state, _| state.dragging = false); + } + }); + } + + /// The mouse-down handler: starts a drag and places or extends the selection. + fn handle_mouse_down( + &mut self, + event: &MouseDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + self.dragging = true; + + let index = self.index_at(event.position); + + if event.click_count >= 3 { + // Triple-click selects the clicked row, which is all of it when single-line. + let row_range = self.layout.as_ref().and_then(|layout| { + let display = display_index(&layout.mask_map, index); + layout.row_range_at(display).map(|range| { + real_index(&layout.mask_map, range.start) + ..real_index(&layout.mask_map, range.end) + }) + }); + + match row_range { + Some(range) => self.select_range(range, window, cx), + None => { + let len = self.text.len(); + self.select_range(0..len, window, cx); + } + } + } else if event.click_count == 2 { + let start = previous_word_start(&self.text, index); + let end = next_word_end(&self.text, index); + self.select_range(start..end, window, cx); + } else if event.modifiers.shift { + self.cursor = index; + self.notify(window, cx); + } else { + self.cursor = index; + self.anchor = index; + self.notify(window, cx); + } + } + + /// The key-down handler: inserts typed characters. + fn handle_key_down( + &mut self, + event: &KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + if !self.focus_handle.contains_focused(window, cx) { + return; + } + + let keystroke = &event.keystroke; + // Chars typed with a menu modifier are shortcuts, not text, + // and control characters (enter, tab) have their own semantics. + if let Some(text) = &keystroke.key_char + && !keystroke.modifiers.platform + && !keystroke.modifiers.control + && text.chars().all(|ch| !ch.is_control()) + { + let range = self.selection(); + self.replace_range(range, text, window, cx); + cx.stop_propagation(); + } + } + + fn left(&mut self, _: &Left, window: &mut Window, cx: &mut Context) { + let to = previous_grapheme_start(&self.text, self.cursor); + self.move_cursor(to, false, window, cx); + } + + fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context) { + let to = previous_grapheme_start(&self.text, self.cursor); + self.move_cursor(to, true, window, cx); + } + + fn right(&mut self, _: &Right, window: &mut Window, cx: &mut Context) { + let to = next_grapheme_start(&self.text, self.cursor); + self.move_cursor(to, false, window, cx); + } + + fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context) { + let to = next_grapheme_start(&self.text, self.cursor); + self.move_cursor(to, true, window, cx); + } + + fn word_left(&mut self, _: &WordLeft, window: &mut Window, cx: &mut Context) { + let to = previous_word_start(&self.text, self.cursor); + self.move_cursor(to, false, window, cx); + } + + fn select_word_left( + &mut self, + _: &SelectWordLeft, + window: &mut Window, + cx: &mut Context, + ) { + let to = previous_word_start(&self.text, self.cursor); + self.move_cursor(to, true, window, cx); + } + + fn word_right(&mut self, _: &WordRight, window: &mut Window, cx: &mut Context) { + let to = next_word_end(&self.text, self.cursor); + self.move_cursor(to, false, window, cx); + } + + fn select_word_right( + &mut self, + _: &SelectWordRight, + window: &mut Window, + cx: &mut Context, + ) { + let to = next_word_end(&self.text, self.cursor); + self.move_cursor(to, true, window, cx); + } + + fn up(&mut self, _: &Up, window: &mut Window, cx: &mut Context) { + self.move_vertical(-1, false, window, cx); + } + + fn down(&mut self, _: &Down, window: &mut Window, cx: &mut Context) { + self.move_vertical(1, false, window, cx); + } + + fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context) { + self.move_vertical(-1, true, window, cx); + } + + fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context) { + self.move_vertical(1, true, window, cx); + } + + /// Moves the caret one visual row up or down, keeping the goal column. + fn move_vertical( + &mut self, + delta: isize, + extend: bool, + window: &mut Window, + cx: &mut Context, + ) { + if !self.multiline { + return; + } + + let target = { + let Some(layout) = self.layout.as_ref() else { + return; + }; + let display = display_index(&layout.mask_map, self.cursor); + + let Some((row_ix, caret_x)) = layout.row_for_index(display) else { + return; + }; + let target = row_ix as isize + delta; + + let (display, goal_x) = if target < 0 { + (0, None) + } else if target as usize >= layout.rows.len() { + (display_index(&layout.mask_map, self.text.len()), None) + } else { + let goal_x = self.goal_x.unwrap_or(caret_x); + (layout.index_at_row_x(target as usize, goal_x), Some(goal_x)) + }; + + Some((real_index(&layout.mask_map, display), goal_x)) + }; + + let Some((to, goal_x)) = target else { + return; + }; + + self.move_cursor(to, extend, window, cx); + // Set after `move_cursor`, which resets the goal on every move. + self.goal_x = goal_x; + } + + fn home(&mut self, _: &Home, window: &mut Window, cx: &mut Context) { + self.move_cursor(0, false, window, cx); + } + + fn end(&mut self, _: &End, window: &mut Window, cx: &mut Context) { + self.move_cursor(self.text.len(), false, window, cx); + } + + fn select_home(&mut self, _: &SelectHome, window: &mut Window, cx: &mut Context) { + self.move_cursor(0, true, window, cx); + } + + fn select_end(&mut self, _: &SelectEnd, window: &mut Window, cx: &mut Context) { + self.move_cursor(self.text.len(), true, window, cx); + } + + fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context) { + self.delete_backward(false, window, cx); + } + + fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context) { + self.delete_forward(false, window, cx); + } + + fn delete_word_left( + &mut self, + _: &DeleteWordLeft, + window: &mut Window, + cx: &mut Context, + ) { + self.delete_backward(true, window, cx); + } + + fn delete_word_right( + &mut self, + _: &DeleteWordRight, + window: &mut Window, + cx: &mut Context, + ) { + self.delete_forward(true, window, cx); + } + + fn delete_to_beginning_of_line( + &mut self, + _: &DeleteToBeginningOfLine, + window: &mut Window, + cx: &mut Context, + ) { + let range = 0..self.cursor; + self.replace_range(range, "", window, cx); + } + + fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context) { + let len = self.text.len(); + self.select_range(0..len, window, cx); + } + + fn copy(&mut self, _: &Copy, window: &mut Window, cx: &mut Context) { + if self.selection().is_empty() { + // Let an outer handler copy its own selection instead. + cx.propagate(); + return; + } + self.copy_selection(window, cx); + } + + fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context) { + if self.read_only || self.password { + return; + } + + if self.copy_selection(window, cx) { + self.delete_selection(window, cx); + } + } + + fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context) { + if let Some(item) = cx.read_from_clipboard() + && let Some(text) = item.text() + { + let range = self.selection(); + self.replace_range(range, &text, window, cx); + } + } + + fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context) { + if self.read_only { + return; + } + + let Some(entry) = self.undo_stack.pop() else { + return; + }; + + let inverse = entry.reverse(&mut self.text); + self.redo_stack.push(inverse); + self.cursor = entry.cursor.min(self.text.len()); + self.anchor = entry.anchor.min(self.text.len()); + + cx.emit(InputStateEvent::TextChanged); + self.notify(window, cx); + } + + fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context) { + if self.read_only { + return; + } + + let Some(entry) = self.redo_stack.pop() else { + return; + }; + + let inverse = entry.reverse(&mut self.text); + self.undo_stack.push(inverse); + + // The caret lands at the end of the restored text, + // not where it was before the original edit. + let caret = entry.range.start + entry.old_text.len(); + self.cursor = caret.min(self.text.len()); + self.anchor = self.cursor; + + cx.emit(InputStateEvent::TextChanged); + self.notify(window, cx); + } + + fn submit(&mut self, _: &Submit, _window: &mut Window, cx: &mut Context) { + // A multiline field in the default mode turns Enter into a newline + if self.multiline && self.submit_on == SubmitOn::ModifiedEnter { + let range = self.selection(); + self.replace_range(range, "\n", _window, cx); + } else { + cx.emit(InputStateEvent::Submitted); + } + } + + fn secondary_submit( + &mut self, + _: &SecondarySubmit, + _window: &mut Window, + cx: &mut Context, + ) { + cx.emit(InputStateEvent::Submitted); + } + + fn insert_newline(&mut self, _: &InsertNewline, window: &mut Window, cx: &mut Context) { + if self.multiline { + let range = self.selection(); + self.replace_range(range, "\n", window, cx); + } + } + + fn escape(&mut self, _: &Escape, window: &mut Window, cx: &mut Context) { + window.blur(cx); + } +} + +impl EntityInputHandler for InputState { + fn text_for_range( + &mut self, + range_utf16: Range, + adjusted_range: &mut Option>, + _window: &mut Window, + _cx: &mut Context, + ) -> Option { + let range = utf16_range_to_utf8(&self.text, range_utf16); + adjusted_range.replace(utf8_range_to_utf16(&self.text, range.clone())); + Some(self.text[range].to_string()) + } + + fn selected_text_range( + &mut self, + _ignore_disabled_input: bool, + _window: &mut Window, + _cx: &mut Context, + ) -> Option { + Some(UTF16Selection { + range: utf8_range_to_utf16(&self.text, self.selection()), + reversed: self.cursor < self.anchor, + }) + } + + fn marked_text_range( + &self, + _window: &mut Window, + _cx: &mut Context, + ) -> Option> { + self.marked_range + .clone() + .map(|range| utf8_range_to_utf16(&self.text, range)) + } + + fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context) { + self.marked_range = None; + } + + fn replace_text_in_range( + &mut self, + range_utf16: Option>, + text: &str, + window: &mut Window, + cx: &mut Context, + ) { + // Simulated typing delivers named keys' control characters here + if text.chars().all(|ch| ch.is_control()) { + return; + } + let range = range_utf16.map_or_else( + || self.selection(), + |range| utf16_range_to_utf8(&self.text, range), + ); + self.replace_range(range, text, window, cx); + } + + fn replace_and_mark_text_in_range( + &mut self, + range_utf16: Option>, + new_text: &str, + new_selected_range_utf16: Option>, + window: &mut Window, + cx: &mut Context, + ) { + if self.read_only { + return; + } + + let range = range_utf16.map_or_else( + || self.selection(), + |range| utf16_range_to_utf8(&self.text, range), + ); + + let new_text = sanitize(new_text, self.multiline); + let old_text = self.text[range.clone()].to_string(); + self.push_history(range.clone(), old_text, new_text.len()); + self.text.replace_range(range.clone(), &new_text); + + let start = range.start; + let end = start + new_text.len(); + self.marked_range = Some(start..end); + + let selected_end = new_selected_range_utf16 + .map(|selected| utf16_range_to_utf8(&self.text, selected).end) + .unwrap_or(end); + + self.cursor = selected_end; + self.anchor = selected_end; + + cx.emit(InputStateEvent::TextChanged); + self.notify(window, cx); + } + + fn bounds_for_range( + &mut self, + range_utf16: Range, + _element_bounds: Bounds, + _window: &mut Window, + _cx: &mut Context, + ) -> Option> { + let layout = self.layout.as_ref()?; + + let start = display_index( + &layout.mask_map, + utf16_to_utf8_offset(&self.text, range_utf16.start), + ); + let end = display_index( + &layout.mask_map, + utf16_to_utf8_offset(&self.text, range_utf16.end), + ); + + // `origin` is already an absolute window point. + if start == end { + let (row_ix, x) = layout.row_for_index(start)?; + let top = layout.origin.y + layout.rows[row_ix].y; + return Some(Bounds::from_corners( + point(layout.origin.x + x, top), + point(layout.origin.x + x, top + layout.line_height), + )); + } + + let overlaps = layout.row_overlaps(start..end); + let (first_ix, first_range, _) = overlaps.first().cloned()?; + let (last_ix, last_range, last_beyond) = overlaps.last().cloned()?; + + let left = layout.origin.x + layout.row_x(first_ix, first_range.start); + let right = layout.origin.x + + if last_beyond { + layout.text_width + } else { + layout.row_x(last_ix, last_range.end) + }; + + Some(Bounds::from_corners( + point(left, layout.origin.y + layout.rows[first_ix].y), + point( + right, + layout.origin.y + layout.rows[last_ix].y + layout.line_height, + ), + )) + } + + fn character_index_for_point( + &mut self, + window_point: gpui::Point, + _window: &mut Window, + _cx: &mut Context, + ) -> Option { + let layout = self.layout.as_ref()?; + let index = + real_index(&layout.mask_map, layout.index_at(window_point)).min(self.text.len()); + Some(utf8_range_to_utf16(&self.text, index..index).start) + } + + fn text_length_utf16( + &mut self, + _window: &mut Window, + _cx: &mut Context, + ) -> Option { + Some(self.text.encode_utf16().count()) + } +} + +/// A text field bound to an application-owned [`InputState`]. +#[derive(IntoElement)] +#[must_use] +pub struct Input { + id: ElementId, + state: Entity, + placeholder: SharedString, + size: Size, + disabled: bool, + /// The placeholder stays visible while focused. + placeholder_when_focused: bool, + a11y_label: Option, + /// Multiline field height in row, ignored when the state is single-line. + rows: usize, + prefix: Option, + suffix: Option, + style: StyleRefinement, +} + +impl Input { + /// Creates a text field bound to `state`. + pub fn new(id: I, state: Entity) -> Self + where + I: Into, + { + Self { + id: id.into(), + state, + placeholder: SharedString::default(), + size: Size::default(), + disabled: false, + placeholder_when_focused: false, + a11y_label: None, + rows: DEFAULT_ROWS, + prefix: None, + suffix: None, + style: StyleRefinement::default(), + } + } + + /// Sets the placeholder shown when the field is empty and unfocused. + pub fn placeholder

(mut self, placeholder: P) -> Self + where + P: Into, + { + self.placeholder = placeholder.into(); + self + } + + /// Sets the height of a multiline field, in rows. + pub fn rows(mut self, rows: usize) -> Self { + self.rows = rows.max(1); + self + } + + /// Shows the placeholder while the field is focused. + pub fn placeholder_when_focused(mut self, when_focused: bool) -> Self { + self.placeholder_when_focused = when_focused; + self + } + + /// Renders the field inert, unfocusable, and dimmed; disabled always wins. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + + /// Overrides the accessibility label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// Docks an element inside the field's leading edge. + pub fn prefix(mut self, prefix: E) -> Self + where + E: IntoElement, + { + self.prefix = Some(prefix.into_any_element()); + self + } + + /// Docks an element inside the field's trailing edge. + pub fn suffix(mut self, suffix: E) -> Self + where + E: IntoElement, + { + self.suffix = Some(suffix.into_any_element()); + self + } +} + +impl gpui::Styled for Input { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl Sizable for Input { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl RenderOnce for Input { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let colors = theme.colors; + let radius = theme.radius; + let metrics = theme.sizes.resolve(self.size); + let focus_handle = self.state.read(cx).focus_handle.clone(); + let focused = focus_handle.is_focused(window); + + let is_empty = self.state.read(cx).text.is_empty(); + let is_password = self.state.read(cx).is_password(); + let revealed = self.state.read(cx).is_revealed(); + let multiline = self.state.read(cx).is_multiline(); + let recording = focused && !self.disabled && !self.state.read(cx).is_read_only(); + + let small = theme.sizes.resolve(Size::Small); + let docked_height = small.control_height; + let edge_inset = ((metrics.input_height - docked_height) / 2.0).max(Pixels::ZERO); + + let vertical_inset = metrics.dense_padding_x * 0.5; + let reveal_width = small.dense_padding_x * 2.0 + small.icon_size; + + let field_padding = FieldPadding { + left: Pixels::ZERO, + right: if is_password { + (edge_inset + reveal_width - metrics.dense_padding_x).max(Pixels::ZERO) + } else { + Pixels::ZERO + }, + top: vertical_inset, + }; + + let line_height = multiline.then(|| match window.text_style().line_height { + DefiniteLength::Fraction(ratio) => metrics.text_size * ratio, + DefiniteLength::Absolute(length) => length.to_pixels(window.rem_size()), + }); + + let field_height = line_height.map_or(metrics.input_height, |line_height| { + line_height * self.rows as f32 + vertical_inset * 2.0 + }); + + let fallback_label = self + .a11y_label + .clone() + .or_else(|| (!self.placeholder.is_empty()).then_some(self.placeholder.clone())) + .unwrap_or_else(|| SharedString::from(self.id.to_string())); + + let edge_zone = |name: &'static str, element: AnyElement| { + div() + .debug_selector(|| name.to_string()) + .flex_none() + .h_full() + .flex() + .items_center() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .child(element) + }; + + let canvas_element = { + let canvas = canvas( + { + let state = self.state.clone(); + move |bounds, window, cx| { + // The hitbox backs the I-beam hover cursor. + let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal); + let wrap_width = multiline.then(|| { + (bounds.size.width - field_padding.left - field_padding.right) + .max(Pixels::ZERO) + }); + let text = state.read(cx).shape_current_text(wrap_width, window); + (text, hitbox) + } + }, + { + let state = self.state.clone(); + let focus = focus_handle.clone(); + let disabled = self.disabled; + + move |bounds, (text, hitbox), window, cx| { + if !disabled { + window.set_cursor_style(CursorStyle::IBeam, &hitbox); + } + + let dragging = state.update(cx, |state, cx| { + state.paint(text, bounds, field_padding, colors, window, cx) + }); + + if disabled { + return; + } + + window.handle_input( + &focus, + gpui::ElementInputHandler::new(bounds, state.clone()), + cx, + ); + + window.on_mouse_event({ + let state = state.clone(); + move |event: &ScrollEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble + || !bounds.contains(&event.position) + { + return; + } + + let delta = match event.delta { + ScrollDelta::Pixels(delta) => delta, + ScrollDelta::Lines(lines) => point( + px(lines.x * SCROLL_LINES_HEIGHT), + px(lines.y * SCROLL_LINES_HEIGHT), + ), + }; + + let consumed = state + .update(cx, |state, cx| state.scroll_by(delta, window, cx)); + + if consumed { + cx.stop_propagation(); + } + } + }); + + if dragging { + InputState::register_drag_listeners(&state, window); + } + } + }, + ) + .absolute() + .inset_0(); + if recording { + let epoch = self.state.read(cx).caret_epoch; + let animation_id = ElementId::from(SharedString::from(format!( + "{self_id}-caret-blink-{epoch}", + self_id = self.id, + ))); + canvas + .with_animation( + animation_id, + // The blink needs four repaints per period, + // not the display's refresh rate. + Animation::new(CARET_BLINK_INTERVAL * 2) + .repeat() + .with_max_fps(4.0), + |canvas, _| canvas, + ) + .into_any_element() + } else { + canvas.into_any_element() + } + }; + + h_flex() + .id(self.id.clone()) + .debug_selector(|| "input-field".to_string()) + .key_context(INPUT_CONTEXT) + .role(Role::TextInput) + .aria_label(fallback_label) + .relative() + .overflow_hidden() + .w_full() + .h(field_height) + .pl(if self.prefix.is_some() { + edge_inset + } else { + metrics.dense_padding_x + }) + .pr(if self.suffix.is_some() { + edge_inset + } else { + metrics.dense_padding_x + }) + .gap_2() + .rounded(radius.control) + .bg(colors.input) + .text_size(metrics.text_size) + .text_color(colors.foreground) + .border_1() + .border_color(colors.border) + .refine_style(&self.style) + .when(self.disabled, |input| input.opacity(DISABLED_OPACITY)) + .when(!self.disabled, |input| { + input.track_focus(&focus_handle).tab_stop(true) + }) + .when(focused, |input| input.border_color(colors.ring)) + .when_some(self.prefix, |input, prefix| { + input.child(edge_zone("input-prefix", prefix)) + }) + .child( + div() + .relative() + .flex_1() + .min_w_0() + .h_full() + .overflow_hidden() + .flex() + .flex_row() + .items_center() + .when_some(line_height, |region, line_height| { + region.items_start().line_height(line_height) + }) + .when( + is_empty && (!focused || self.placeholder_when_focused), + |region| { + region.child( + div() + .text_color(colors.muted_foreground) + .when(multiline, |placeholder| placeholder.pt(vertical_inset)) + .child(self.placeholder.clone()), + ) + }, + ) + .child(canvas_element), + ) + .when_some(self.suffix, |input, suffix| { + input.child(edge_zone("input-suffix", suffix)) + }) + .when(is_password && !self.disabled, |input| { + input.child( + div() + .id((self.id.clone(), "input-reveal")) + .debug_selector(|| "input-reveal".to_string()) + .absolute() + .right(edge_inset) + .top_0() + .bottom_0() + .flex() + .items_center() + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .child( + Button::new((self.id.clone(), "input-reveal-button")) + .debug_selector(|| "input-reveal-button".to_string()) + .icon(if revealed { + IconRole::EyeOff + } else { + IconRole::Eye + }) + .variant(ButtonVariant::Ghost) + .small() + .accessibility_label(if revealed { + "Hide password" + } else { + "Show password" + }) + .on_click({ + let state = self.state.clone(); + move |_, _, cx| { + state.update(cx, |state, cx| { + state.set_revealed(!state.is_revealed(), cx) + }); + } + }), + ), + ) + }) + .when(!self.disabled, |input| { + input + .on_mouse_down(MouseButton::Left, { + let mouse_down_handler = self.state.read(cx).mouse_down_handler.clone(); + move |event: &MouseDownEvent, window, cx| { + mouse_down_handler(event, window, cx); + } + }) + .on_key_down({ + let key_down_handler = self.state.read(cx).key_down_handler.clone(); + move |event: &KeyDownEvent, window, cx| { + key_down_handler(event, window, cx); + } + }) + }) + .on_action({ + let state = self.state.clone(); + move |action: &Escape, window, cx| { + state.update(cx, |state, cx| state.escape(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &Submit, window, cx| { + state.update(cx, |state, cx| state.submit(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &SecondarySubmit, window, cx| { + state.update(cx, |state, cx| state.secondary_submit(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &InsertNewline, window, cx| { + state.update(cx, |state, cx| state.insert_newline(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &Backspace, window, cx| { + state.update(cx, |state, cx| state.backspace(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &Delete, window, cx| { + state.update(cx, |state, cx| state.delete(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &DeleteWordLeft, window, cx| { + state.update(cx, |state, cx| state.delete_word_left(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &DeleteWordRight, window, cx| { + state.update(cx, |state, cx| state.delete_word_right(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &DeleteToBeginningOfLine, window, cx| { + state.update(cx, |state, cx| { + state.delete_to_beginning_of_line(action, window, cx) + }) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &Left, window, cx| { + state.update(cx, |state, cx| state.left(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &Right, window, cx| { + state.update(cx, |state, cx| state.right(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &SelectLeft, window, cx| { + state.update(cx, |state, cx| state.select_left(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &SelectRight, window, cx| { + state.update(cx, |state, cx| state.select_right(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &Up, window, cx| { + state.update(cx, |state, cx| state.up(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &Down, window, cx| { + state.update(cx, |state, cx| state.down(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &SelectUp, window, cx| { + state.update(cx, |state, cx| state.select_up(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &SelectDown, window, cx| { + state.update(cx, |state, cx| state.select_down(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &WordLeft, window, cx| { + state.update(cx, |state, cx| state.word_left(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &WordRight, window, cx| { + state.update(cx, |state, cx| state.word_right(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &SelectWordLeft, window, cx| { + state.update(cx, |state, cx| state.select_word_left(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &SelectWordRight, window, cx| { + state.update(cx, |state, cx| state.select_word_right(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &Home, window, cx| { + state.update(cx, |state, cx| state.home(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &End, window, cx| { + state.update(cx, |state, cx| state.end(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &SelectHome, window, cx| { + state.update(cx, |state, cx| state.select_home(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &SelectEnd, window, cx| { + state.update(cx, |state, cx| state.select_end(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &SelectAll, window, cx| { + state.update(cx, |state, cx| state.select_all(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &Copy, window, cx| { + state.update(cx, |state, cx| state.copy(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &Cut, window, cx| { + state.update(cx, |state, cx| state.cut(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &Paste, window, cx| { + state.update(cx, |state, cx| state.paste(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &Undo, window, cx| { + state.update(cx, |state, cx| state.undo(action, window, cx)) + } + }) + .on_action({ + let state = self.state.clone(); + move |action: &Redo, window, cx| { + state.update(cx, |state, cx| state.redo(action, window, cx)) + } + }) + } +} + +/// Registers input keybindings on the application. +/// +/// Pass `None` for the platform defaults. +pub fn bind_input_keys(cx: &mut App, bindings: B) +where + B: Into>, +{ + cx.bind_keys(bindings.into().unwrap_or_default().into_bindings()); +} + +/// The row holding `display`. +fn row_ix_for_display(rows: &[VisualRow], display: usize) -> usize { + rows.iter() + .position(|row| display <= row.range.end) + .unwrap_or(rows.len() - 1) +} + +/// Builds the masked display: one bullet per grapheme, newlines kept as line breaks. +fn masked_display(text: &str) -> (String, Option>) { + let mut display = String::new(); + let mut map = Vec::with_capacity(text.len() + 1); + for (offset, grapheme) in text.grapheme_indices(true) { + if grapheme == "\n" { + display.push('\n'); + map.push((offset, 1)); + } else { + display.push_str(MASK); + map.push((offset, MASK_LEN)); + } + } + // The end sentinel maps a click past the last glyph to the buffer end. + map.push((text.len(), 0)); + (display, Some(map)) +} + +/// Maps a real buffer offset onto the masked display; identity when unmasked. +fn display_index(mask_map: &Option>, real: usize) -> usize { + match mask_map { + None => real, + Some(map) => map + .iter() + .take_while(|&&(offset, _)| offset < real) + .map(|&(_, len)| len) + .sum(), + } +} + +/// Maps a display offset from a click back onto the real buffer. +fn real_index(mask_map: &Option>, display: usize) -> usize { + match mask_map { + None => display, + Some(map) => { + let mut consumed = 0; + for &(offset, len) in map { + if consumed >= display { + return offset; + } + consumed += len; + } + map.last().map(|&(offset, _)| offset).unwrap_or(0) + } + } +} + +/// Newlines have no meaning in a single-line field. +fn sanitize(text: T, multiline: bool) -> String +where + T: Into, +{ + let text = text.into(); + if multiline { + text.replace('\r', "") + } else { + text.replace('\n', " ").replace('\r', "") + } +} + +/// Floors `index` to the nearest grapheme-cluster boundary at or below it. +fn previous_grapheme_start(text: &str, index: usize) -> usize { + text.grapheme_indices(true) + .rev() + .find(|(offset, _)| *offset < index) + .map(|(offset, _)| offset) + .unwrap_or(0) +} + +/// Advances `index` to the next grapheme-cluster boundary. +fn next_grapheme_start(text: &str, index: usize) -> usize { + text.grapheme_indices(true) + .find(|(offset, _)| *offset > index) + .map(|(offset, _)| offset) + .unwrap_or(text.len()) +} + +/// The start of the word before `from`. +fn previous_word_start(text: &str, from: usize) -> usize { + let mut best = 0; + for (offset, word) in text.split_word_bound_indices() { + if offset >= from { + break; + } + if !word.starts_with(char::is_whitespace) { + best = offset; + } + } + best +} + +/// The end of the word after `from`. +fn next_word_end(text: &str, from: usize) -> usize { + for (offset, word) in text.split_word_bound_indices() { + let end = offset + word.len(); + if end > from && !word.starts_with(char::is_whitespace) { + return end; + } + } + text.len() +} + +/// Converts a UTF-16 offset into a UTF-8 byte offset. +fn utf16_to_utf8_offset(text: &str, utf16_offset: usize) -> usize { + let mut utf16_count = 0; + for (byte_offset, char) in text.char_indices() { + if utf16_count >= utf16_offset { + return byte_offset; + } + utf16_count += char.len_utf16(); + } + text.len() +} + +/// Converts a UTF-8 byte range to a UTF-16 range. +fn utf8_range_to_utf16(text: &str, range: Range) -> Range { + let start = text[..range.start].encode_utf16().count(); + let end = start + text[range.start..range.end].encode_utf16().count(); + start..end +} + +/// Converts a UTF-16 range to a UTF-8 byte range. +fn utf16_range_to_utf8(text: &str, range: Range) -> Range { + utf16_to_utf8_offset(text, range.start)..utf16_to_utf8_offset(text, range.end) +} diff --git a/crates/ui/src/components/link.rs b/crates/ui/src/components/link.rs new file mode 100644 index 0000000..f90cbaf --- /dev/null +++ b/crates/ui/src/components/link.rs @@ -0,0 +1,139 @@ +use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; +use crate::utils::focus_ring; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, ClickEvent, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, + RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, + Window, +}; + +use crate::components::common::{Sizable, StyledExt as _, h_flex}; + +/// The click handler. When set it replaces the default `href` opening. +type ClickHandler = Box; + +/// Link component. +#[derive(IntoElement)] +#[must_use] +pub struct Link { + id: ElementId, + label: Option, + href: Option, + size: Size, + disabled: bool, + a11y_label: Option, + on_click: Option, + style: StyleRefinement, +} + +impl Link { + /// Creates a link without a label or target. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + label: None, + href: None, + size: Size::default(), + disabled: false, + a11y_label: None, + on_click: None, + style: StyleRefinement::default(), + } + } + + /// Sets the visible label. + pub fn label(mut self, label: L) -> Self + where + L: Into, + { + self.label = Some(label.into()); + self + } + + /// Sets the URL the link opens through the platform. + pub fn href(mut self, href: U) -> Self + where + U: Into, + { + self.href = Some(href.into()); + self + } + + /// Renders the link inert, unfocusable, and dimmed; disabled always wins. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + + /// Overrides the accessibility label, which defaults to the visible label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// Replaces the default `href` opening with this handler. + pub fn on_click(mut self, handler: F) -> Self + where + F: Fn(&ClickEvent, &mut Window, &mut App) + 'static, + { + self.on_click = Some(Box::new(handler)); + self + } +} + +impl gpui::Styled for Link { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl Sizable for Link { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl RenderOnce for Link { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let colors = theme.colors; + let ramps = theme.ramps; + let metrics = theme.sizes.resolve(self.size); + + let on_click = self.on_click; + let href = self.href; + let a11y_label = self.a11y_label.or_else(|| self.label.clone()); + + h_flex() + .id(self.id) + .text_size(metrics.text_size) + .text_color(ramps.primary.base) + .underline() + .refine_style(&self.style) + .role(Role::Link) + .when_some(a11y_label, |link, label| link.aria_label(label)) + .when(self.disabled, |link| link.opacity(DISABLED_OPACITY)) + .when(!self.disabled, |link| { + link.cursor_pointer() + .focusable() + .tab_stop(true) + .hover(move |style| style.text_color(ramps.primary.hover)) + .focus_visible(|style| style.shadow(focus_ring(colors.ring))) + .on_click(move |event, window, cx| match on_click.as_ref() { + Some(on_click) => on_click(event, window, cx), + None => { + if let Some(href) = href.as_ref() { + cx.open_url(href); + } + } + }) + }) + .when_some(self.label, |link, label| link.child(label)) + } +} diff --git a/crates/ui/src/components/menu.rs b/crates/ui/src/components/menu.rs new file mode 100644 index 0000000..2f195fd --- /dev/null +++ b/crates/ui/src/components/menu.rs @@ -0,0 +1,1111 @@ +//! The floating menu panel shared by menus, dropdowns, and context menus. + +use std::cell::RefCell; +use std::rc::Rc; + +use crate::icons::{Icon, IconRole, icon as icon_glyph}; +use crate::theme::{ActiveTheme as _, BORDER_WIDTH, MENU_MIN_WIDTH, POPUP_MAX_HEIGHT}; +use crate::utils::focus_handle; +use gpui::prelude::FluentBuilder; +use gpui::{ + Animation, AnimationExt as _, AnyElement, App, Bounds, BoxShadow, DefiniteLength, + DispatchPhase, ElementId, Entity, FocusHandle, InteractiveElement as _, IntoElement, + KeyDownEvent, MouseButton, MouseDownEvent, ParentElement as _, Pixels, Point, RenderOnce, Role, + ScrollHandle, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, + Window, anchored, canvas, deferred, div, ease_out_quint, point, px, relative, +}; + +use crate::components::common::{OVERLAY_LAYER, StyledExt as _, v_flex}; +use crate::components::scroll_area::{ScrollArea, ScrollAxes}; + +/// Runs the item's action. The menu closes itself before the handler runs. +pub type ItemHandler = Rc; + +/// Reports the next open state of a menu: `true` to open, `false` to close. +pub(crate) type ChangeHandler = Rc; +/// Flips a panel's flyout open state; `true` arms the first row for keyboard. +type FlyoutSetter = Rc, bool, &mut App)>; +/// Bounds captured during the last paint, shared with the dismissal listener. +pub(crate) type TriggerBoundsCell = Rc>>>; +type TriggerFn = Box AnyElement>; +type ItemsFn = Box Vec>; + +/// One row of a [`Menu`]: an action, a checkable action, a submenu, or a separator. +#[derive(Clone)] +#[must_use] +pub struct MenuItem { + id: Option, + kind: MenuItemKind, + label: SharedString, + icon: Option, + shortcut: Option, + handler: Option, + disabled: bool, + destructive: bool, + checked: bool, +} + +#[derive(Clone)] +enum MenuItemKind { + Action, + Separator, + Submenu(Rc<[MenuItem]>), +} + +impl MenuItem { + /// An action row with this label. + pub fn new(label: L) -> Self + where + L: Into, + { + Self { + id: None, + kind: MenuItemKind::Action, + label: label.into(), + icon: None, + shortcut: None, + handler: None, + disabled: false, + destructive: false, + checked: false, + } + } + + /// A divider between groups of actions. + pub fn separator() -> Self { + Self { + id: None, + kind: MenuItemKind::Separator, + label: SharedString::default(), + icon: None, + shortcut: None, + handler: None, + disabled: false, + destructive: false, + checked: false, + } + } + + /// Overrides the row's element id, for stable identity across reorderings. + pub fn id(mut self, id: I) -> Self + where + I: Into, + { + self.id = Some(id.into()); + self + } + + /// Runs this action when the item is activated. The menu closes first. + pub fn handler(mut self, handler: F) -> Self + where + F: Fn(&mut Window, &mut App) + 'static, + { + self.handler = Some(Rc::new(handler)); + self + } + + /// Shows an icon before the label. + pub fn icon(mut self, icon: I) -> Self + where + I: Into, + { + self.icon = Some(icon.into()); + self + } + + /// Shows a shortcut hint after the label. + pub fn shortcut(mut self, shortcut: S) -> Self + where + S: Into, + { + self.shortcut = Some(shortcut.into()); + self + } + + /// Marks the item non-selectable and non-activatable. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + + /// Paints the row in the danger role. + pub fn destructive(mut self, destructive: bool) -> Self { + self.destructive = destructive; + self + } + + /// Shows a check slot before the label. + pub fn checked(mut self, checked: bool) -> Self { + self.checked = checked; + self + } + + /// Opens a submenu with these rows instead of running an action. + pub fn submenu(mut self, items: I) -> Self + where + I: IntoIterator, + { + self.kind = MenuItemKind::Submenu(items.into_iter().collect::>().into()); + self + } + + /// The submenu's rows, when this item opens one. + fn submenu_items(&self) -> Option<&[MenuItem]> { + match &self.kind { + MenuItemKind::Submenu(items) => Some(items), + _ => None, + } + } + + /// Whether keyboard navigation and activation may land on this item. + fn selectable(&self) -> bool { + matches!(self.kind, MenuItemKind::Action | MenuItemKind::Submenu(_)) && !self.disabled + } +} + +// MenuItem is a data builder, not an element, adopt the combinators explicitly. +impl FluentBuilder for MenuItem {} + +/// Menu chrome styles. +#[derive(Clone)] +pub(crate) struct MenuChrome { + surface: gpui::Hsla, + border: gpui::Hsla, + foreground: gpui::Hsla, + muted_foreground: gpui::Hsla, + muted_hover: gpui::Hsla, + primary: gpui::Hsla, + primary_foreground: gpui::Hsla, + destructive: gpui::Hsla, + destructive_foreground: gpui::Hsla, + radius_overlay: Pixels, + radius_sm: Pixels, + icon_size: Pixels, + dense_icon_size: Pixels, + menu_item_height: Pixels, + spacing_unit: Pixels, + text_size: Pixels, + shadow: Vec, +} + +/// A floating menu of actions anchored below its trigger. +#[derive(IntoElement)] +#[must_use] +pub struct Menu { + id: ElementId, + open: bool, + initial_selection: Option, + trigger_button: MouseButton, + open_at: Option>, + a11y_label: Option, + on_change: Option, + trigger: Option, + items: Option, + min_width: Option, + style: StyleRefinement, +} + +impl MenuChrome { + /// Reads the menu's chrome and enter duration from the active theme. + pub(crate) fn read(cx: &App) -> (Self, std::time::Duration) { + let theme = cx.theme(); + ( + Self { + surface: theme.colors.surface, + border: theme.colors.border, + foreground: theme.colors.foreground, + muted_foreground: theme.colors.muted_foreground, + muted_hover: theme.colors.muted_hover, + primary: theme.ramps.primary.base, + primary_foreground: theme.colors.primary_foreground, + destructive: theme.ramps.destructive.base, + destructive_foreground: theme.colors.destructive_foreground, + radius_overlay: theme.radius.overlay, + radius_sm: theme.radius.sm, + icon_size: theme.sizes.medium.icon_size, + dense_icon_size: theme.sizes.medium.dense_icon_size, + menu_item_height: theme.sizes.medium.menu_item_height, + spacing_unit: theme.spacing.unit, + text_size: theme.sizes.medium.text_size, + shadow: theme.elevations.popover.shadows(), + }, + theme.motion.overlay, + ) + } +} + +impl Menu { + /// Creates a closed menu. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + open: false, + initial_selection: None, + trigger_button: MouseButton::Left, + open_at: None, + a11y_label: None, + on_change: None, + trigger: None, + items: None, + min_width: None, + style: StyleRefinement::default(), + } + } + + /// Sets the row keyboard-highlighted when the menu opens. + pub fn initial_selection(mut self, index: usize) -> Self { + self.initial_selection = Some(index); + self + } + + /// Sets the mouse button that toggles the menu; right for context menus. + pub fn trigger_button(mut self, button: MouseButton) -> Self { + self.trigger_button = button; + self + } + + /// Positions the panel at this window point when it opens. + pub fn open_at

(mut self, position: P) -> Self + where + P: Into>>, + { + self.open_at = position.into(); + self + } + + /// Sets the current open state. + pub fn open(mut self, open: bool) -> Self { + self.open = open; + self + } + + /// Reports the next open state, from dismissals, toggles, and activations alike. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(bool, &mut Window, &mut App) + 'static, + { + self.on_change = Some(Rc::new(handler)); + self + } + + /// Sets the element the panel anchors below. + pub fn trigger(mut self, trigger: F) -> Self + where + F: Fn(&mut Window, &mut App) -> AnyElement + 'static, + { + self.trigger = Some(Box::new(trigger)); + self + } + + /// Sets the menu's items, built fresh each render. + pub fn items(mut self, items: F) -> Self + where + F: Fn(&mut Window, &mut App) -> Vec + 'static, + { + self.items = Some(Box::new(items)); + self + } + + /// Overrides the accessibility label of the panel. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// Sets the panel's minimum width; defaults to the standard menu width. + pub fn min_width(mut self, width: W) -> Self + where + W: Into, + { + self.min_width = Some(width.into()); + self + } +} + +impl gpui::Styled for Menu { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Menu { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let (chrome, enter_duration) = MenuChrome::read(cx); + let trigger_bounds: Rc>>> = Rc::new(RefCell::new(None)); + let on_change = self.on_change.clone(); + + let fallback_label = self + .a11y_label + .clone() + .unwrap_or_else(|| SharedString::from(self.id.to_string())); + + let items = if self.open { + match self.items { + Some(build) => Rc::from(build(window, cx)), + None => Rc::from([]), + } + } else { + Rc::from([]) + }; + + let spec = MenuPanelSpec { + open: self.open, + items, + initial_selection: self.initial_selection, + preselect: false, + min_width: self.min_width, + label: fallback_label, + position: self.open_at, + trigger_bounds: trigger_bounds.clone(), + on_dismiss: on_change.clone(), + on_activate: self.on_change, + }; + + div() + .relative() + .refine_style(&self.style) + .child( + canvas( + { + let cell = trigger_bounds.clone(); + move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) + }, + { + let on_change = on_change; + let open = self.open; + let trigger_button = self.trigger_button; + let cell = trigger_bounds.clone(); + + move |_, _, window, _cx| { + let trigger_bounds = cell; + + window.on_mouse_event({ + let on_change = on_change.clone(); + move |event: &MouseDownEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble + || event.button != trigger_button + { + return; + } + + let on_trigger = trigger_bounds + .borrow() + .is_some_and(|bounds| bounds.contains(&event.position)); + if !on_trigger { + return; + } + + if let Some(on_change) = &on_change { + on_change(!open, window, cx); + } + cx.stop_propagation(); + } + }); + } + }, + ) + .absolute() + .inset_0(), + ) + .when_some(self.trigger, |wrapper, trigger| { + wrapper.child(trigger(window, cx)) + }) + .when_some( + anchored_menu_panel(window, cx, &self.id, spec, &chrome, enter_duration), + |wrapper, panel| wrapper.child(panel), + ) + } +} + +/// Everything the floating menu panel needs from its owner. +pub(crate) struct MenuPanelSpec { + pub open: bool, + pub items: Rc<[MenuItem]>, + pub initial_selection: Option, + pub preselect: bool, + pub min_width: Option, + pub label: SharedString, + pub position: Option>, + pub trigger_bounds: TriggerBoundsCell, + /// Closes this panel: outside clicks, `escape`, and `left` past a closed flyout. + pub on_dismiss: Option, + /// Closes the whole menu when a row inside activates. + pub on_activate: Option, +} + +/// Per-panel state that survives across frames while the panel stays mounted. +struct MenuPanelState { + focus: FocusHandle, + was_open: Entity, + scroll: Entity, + selection: Entity>, +} + +fn create_menu_panel_state(id: &ElementId, window: &mut Window, cx: &mut App) -> MenuPanelState { + MenuPanelState { + focus: focus_handle(&(id.clone(), "panel").into(), window, cx), + was_open: window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false), + scroll: window.use_keyed_state((id.clone(), "menu-scroll"), cx, |_, _| ScrollHandle::new()), + selection: window.use_keyed_state((id.clone(), "menu-selection"), cx, |_, _| None), + } +} + +struct MenuPanelParams<'a> { + id: &'a ElementId, + items: Rc<[MenuItem]>, + initial_selection: Option, + preselect: bool, + min_width: Option, + label: SharedString, + /// Clicks here do not dismiss the panel: the trigger or the owning row. + dismiss_bounds: &'a TriggerBoundsCell, + /// Receives the panel's painted bounds, for a parent's dismissal checks. + bounds_sink: Option<&'a TriggerBoundsCell>, + /// This panel's flyout bounds are pushed here. + outer_stack: Option<&'a Rc>>>, + on_dismiss: Option, + on_activate: Option, + /// Flyout panels dismiss themselves on `left`; top-level panels ignore it. + is_flyout: bool, + chrome: &'a MenuChrome, + enter_duration: std::time::Duration, + debug_prefix: &'static str, +} + +/// Wiring a panel's rows need to open their submenus. +struct FlyoutContext<'a> { + state: &'a MenuPanelState, + open: &'a Entity>, + preselect: &'a Entity, + /// Opens or closes this level's flyout, re-arming it on every switch. + set_flyout: FlyoutSetter, + /// The open flyout's painted bounds; a parent ignores clicks inside them. + bounds: &'a TriggerBoundsCell, + /// Bounds of every open flyout below this panel, this level's included. + stack: &'a Rc>>, + /// Closes this level's flyout and returns focus to this panel. + dismiss: ChangeHandler, + on_activate: Option, + id: ElementId, + enter_duration: std::time::Duration, + min_width: Option, +} + +struct RowEnv<'a> { + chrome: &'a MenuChrome, + selection: &'a Entity>, + on_activate: Option, + flyout: &'a FlyoutContext<'a>, + debug_prefix: &'static str, +} + +/// Assembles the floating menu panel anchored to its trigger. +pub(crate) fn anchored_menu_panel( + window: &mut Window, + cx: &mut App, + id: &ElementId, + spec: MenuPanelSpec, + chrome: &MenuChrome, + enter_duration: std::time::Duration, +) -> Option { + let was_open = window.use_keyed_state((id.clone(), "menu-was-open"), cx, |_, _| false); + + // Render-phase residue: trigger-toggle and owner-driven closes bypass every + // dismissal handler, so this closed frame is the only universal close hook. + if !spec.open { + was_open.update(cx, |was_open, _| *was_open = false); + // A closed menu drops any open flyout; fresh state on the next open. + window + .use_keyed_state::>((id.clone(), "submenu-open"), cx, |_, _| None) + .update(cx, |open, _| *open = None); + window + .use_keyed_state((id.clone(), "submenu-preselect"), cx, |_, _| false) + .update(cx, |preselect, _| *preselect = false); + return None; + } + + let state = create_menu_panel_state(id, window, cx); + let panel = menu_panel( + window, + cx, + &state, + MenuPanelParams { + id, + items: spec.items, + initial_selection: spec.initial_selection, + preselect: spec.preselect, + min_width: spec.min_width, + label: spec.label, + dismiss_bounds: &spec.trigger_bounds, + bounds_sink: None, + outer_stack: None, + on_dismiss: spec.on_dismiss, + on_activate: spec.on_activate, + is_flyout: false, + chrome, + enter_duration, + debug_prefix: "menu", + }, + ); + + let anchored = match spec.position { + Some(position) => anchored().position(position), + None => anchored(), + } + .offset(point(px(0.), chrome.spacing_unit)); + + Some( + deferred(anchored.child(panel)) + .with_priority(OVERLAY_LAYER) + .into_any_element(), + ) +} + +/// Builds one menu panel: chrome, rows, focus, navigation, and dismissals. +fn menu_panel( + window: &mut Window, + cx: &mut App, + state: &MenuPanelState, + params: MenuPanelParams, +) -> AnyElement { + let MenuPanelState { + focus, + was_open, + scroll, + selection, + } = state; + + // Render-phase residue: panels open from owner state alone, so this mount + // frame is the only place fresh-selection init can read its params. + let selected = if *was_open.read(cx) { + *selection.read(cx) + } else { + let requested = params + .initial_selection + .map(|index| index.min(params.items.len().saturating_sub(1))) + .or_else(|| { + params + .preselect + .then(|| params.items.iter().position(MenuItem::selectable)) + .flatten() + }); + selection.update(cx, |selection, _| *selection = requested); + requested + }; + was_open.update(cx, |was_open, _| *was_open = true); + + // Submenu plumbing for this level; a flyout panel recurses with its own. + let flyout_id: ElementId = (params.id.clone(), "submenu").into(); + let flyout_state = create_menu_panel_state(&flyout_id, window, cx); + let flyout_open = window.use_keyed_state((params.id.clone(), "submenu-open"), cx, |_, _| None); + let flyout_preselect = + window.use_keyed_state((params.id.clone(), "submenu-preselect"), cx, |_, _| false); + let flyout_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); + let flyout_stack: Rc>> = Rc::new(RefCell::new(Vec::new())); + flyout_stack.borrow_mut().push(flyout_bounds.clone()); + + if let Some(outer_stack) = params.outer_stack { + outer_stack.borrow_mut().push(flyout_bounds.clone()); + } + + // Every open flip re-arms a clean flyout, so render never reconciles one. + let set_flyout: FlyoutSetter = { + let flyout_open = flyout_open.clone(); + let flyout_preselect = flyout_preselect.clone(); + let flyout_was_open = flyout_state.was_open.clone(); + let flyout_selection = flyout_state.selection.clone(); + Rc::new(move |index, opens_preselected, cx| { + if index.is_some() && *flyout_open.read(cx) == index { + return; + } + + flyout_open.update(cx, |open, _| *open = index); + flyout_preselect.update(cx, |preselect, _| *preselect = opens_preselected); + flyout_was_open.update(cx, |was_open, _| *was_open = false); + flyout_selection.update(cx, |selection, _| *selection = None); + }) + }; + + let dismiss_flyout: ChangeHandler = { + let set_flyout = set_flyout.clone(); + let focus = focus.clone(); + Rc::new(move |_, window, cx| { + set_flyout(None, false, cx); + window.focus(&focus, cx); + }) + }; + + let flyout = FlyoutContext { + state: &flyout_state, + open: &flyout_open, + preselect: &flyout_preselect, + set_flyout: set_flyout.clone(), + bounds: &flyout_bounds, + stack: &flyout_stack, + dismiss: dismiss_flyout, + on_activate: params.on_activate.clone(), + id: flyout_id, + enter_duration: params.enter_duration, + min_width: params.min_width, + }; + + let rows: Vec = params + .items + .iter() + .enumerate() + .map(|(index, item)| { + render_item( + window, + cx, + item, + index, + selected == Some(index), + &RowEnv { + chrome: params.chrome, + selection, + on_activate: params.on_activate.clone(), + flyout: &flyout, + debug_prefix: params.debug_prefix, + }, + ) + }) + .collect(); + + v_flex() + .id("menu-panel") + .debug_selector(move || format!("{}-panel", params.debug_prefix)) + .occlude() + .track_focus(focus) + .role(Role::Menu) + .aria_label(params.label) + .when_some(params.min_width, |panel, width| panel.min_w(width)) + .when(params.min_width.is_none(), |panel| { + panel.min_w(MENU_MIN_WIDTH) + }) + .p(params.chrome.spacing_unit) + .bg(params.chrome.surface) + .text_color(params.chrome.foreground) + .rounded(params.chrome.radius_overlay) + .border_1() + .border_color(params.chrome.border) + .shadow(params.chrome.shadow.clone()) + .overflow_hidden() + .on_mouse_down_out({ + let on_dismiss = params.on_dismiss.clone(); + let dismiss_bounds = params.dismiss_bounds.clone(); + let flyout_stack = flyout_stack.clone(); + + move |event, window, cx| { + if dismiss_bounds + .borrow() + .is_some_and(|bounds| bounds.contains(&event.position)) + { + return; + } + + // Clicks inside any open flyout belong to that flyout. + if flyout_stack.borrow().iter().any(|cell| { + cell.borrow() + .is_some_and(|bounds| bounds.contains(&event.position)) + }) { + return; + } + + if let Some(on_dismiss) = &on_dismiss { + on_dismiss(false, window, cx); + } + } + }) + .on_key_down({ + let items = params.items.clone(); + let selection = selection.clone(); + let set_flyout = set_flyout.clone(); + let on_dismiss = params.on_dismiss.clone(); + let on_activate = params.on_activate.clone(); + let left_dismisses = params.is_flyout; + move |event: &KeyDownEvent, window, cx| { + handle_menu_key( + event, + MenuKeyEnv { + items: &items, + selection: &selection, + set_flyout: &set_flyout, + on_dismiss: &on_dismiss, + on_activate: &on_activate, + left_dismisses, + }, + window, + cx, + ); + } + }) + .child( + ScrollArea::new("menu-items") + .handle(scroll.read(cx).clone()) + .axes(ScrollAxes::Vertical) + .max_h(POPUP_MAX_HEIGHT) + .child(v_flex().gap_0p5().children(rows)), + ) + .child( + canvas( + { + let bounds_sink = params.bounds_sink.cloned(); + move |bounds, _window, _cx| { + if let Some(cell) = &bounds_sink { + *cell.borrow_mut() = Some(bounds); + } + } + }, + { + let focus = focus.clone(); + let flyout_open = flyout_open.clone(); + move |_, _, window, cx| { + if flyout_open.read(cx).is_none() && !focus.contains_focused(window, cx) { + window.focus(&focus, cx); + } + } + }, + ) + .absolute() + .inset_0(), + ) + .with_animation( + "menu-enter", + Animation::new(params.enter_duration).with_easing(ease_out_quint()), + |panel, delta| panel.opacity(delta), + ) + .into_any_element() +} + +/// Renders one menu row. +fn render_item( + window: &mut Window, + cx: &mut App, + item: &MenuItem, + index: usize, + selected: bool, + env: &RowEnv, +) -> AnyElement { + match &item.kind { + MenuItemKind::Separator => div() + .h(BORDER_WIDTH) + .debug_selector(move || format!("{}-separator-{index}", env.debug_prefix)) + .mx(env.chrome.spacing_unit * 2.0) + .my(env.chrome.spacing_unit) + .bg(env.chrome.border) + .into_any_element(), + MenuItemKind::Action => { + let label_color = row_color(item, selected, false, env.chrome); + let disabled = item.disabled; + let destructive = item.destructive; + let checked = item.checked; + let shortcut = item.shortcut.clone(); + let icon = item.icon.clone(); + + row_shell(cx, item, index, selected, env) + .on_click({ + let handler = item.handler.clone(); + let on_activate = env.on_activate.clone(); + move |_, window, cx| { + if disabled { + return; + } + + if let Some(on_activate) = &on_activate { + on_activate(false, window, cx); + } + + if let Some(handler) = &handler { + handler(window, cx); + } + } + }) + .when_some(icon, |row, icon| { + row.child(icon.size(env.chrome.icon_size).color(label_color)) + }) + .child( + div() + .flex_1() + .text_color(label_color) + .child(item.label.clone()), + ) + .when_some(shortcut, |row, shortcut| { + row.child( + div() + .text_color(if selected && !destructive && !disabled { + env.chrome.primary_foreground + } else { + env.chrome.muted_foreground + }) + .child(shortcut), + ) + }) + .when(checked, |row| { + row.child( + icon_glyph(IconRole::Check) + .size(env.chrome.dense_icon_size) + .color(label_color), + ) + }) + .into_any_element() + } + MenuItemKind::Submenu(items) => { + let chrome = env.chrome; + let flyout = env.flyout; + let disabled = item.disabled; + let open = *flyout.open.read(cx) == Some(index); + let label_color = row_color(item, selected, open, chrome); + let row_bounds: TriggerBoundsCell = Rc::new(RefCell::new(None)); + + row_shell(cx, item, index, selected, env) + .on_click({ + let set_flyout = flyout.set_flyout.clone(); + move |_, _window, cx| { + if disabled { + return; + } + // Hover already opens the flyout; a click never closes it. + set_flyout(Some(index), false, cx); + } + }) + .child( + div() + .flex_1() + .text_color(label_color) + .child(item.label.clone()), + ) + .child( + icon_glyph(IconRole::ChevronRight) + .size(chrome.dense_icon_size) + .color(label_color), + ) + .aria_expanded(open) + .when(open, |row| { + row.child( + canvas( + { + let cell = row_bounds.clone(); + move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ) + .child( + deferred(div().absolute().left_full().top_0().child(menu_panel( + window, + cx, + flyout.state, + MenuPanelParams { + id: &flyout.id, + items: items.clone(), + initial_selection: None, + preselect: *flyout.preselect.read(cx), + min_width: flyout.min_width, + label: item.label.clone(), + dismiss_bounds: &row_bounds, + bounds_sink: Some(flyout.bounds), + outer_stack: Some(flyout.stack), + on_dismiss: Some(flyout.dismiss.clone()), + on_activate: flyout.on_activate.clone(), + is_flyout: true, + chrome, + enter_duration: flyout.enter_duration, + debug_prefix: "submenu", + }, + ))) + .with_priority(OVERLAY_LAYER), + ) + }) + .into_any_element() + } + } +} + +/// The shared row shell: metrics, highlight, and hover-selection. +fn row_shell( + cx: &App, + item: &MenuItem, + index: usize, + selected: bool, + env: &RowEnv, +) -> gpui::Stateful { + let chrome = env.chrome; + let selectable = item.selectable(); + let opens_submenu = item.submenu_items().is_some(); + let flyout_open = *env.flyout.open.read(cx) == Some(index); + let row_id = item + .id + .clone() + .unwrap_or_else(|| ("menu-item", index).into()); + + div() + .id(row_id) + .role(Role::MenuItem) + .debug_selector(move || format!("{}-item-{index}", env.debug_prefix)) + .flex() + .items_center() + .gap_2() + .min_h(chrome.menu_item_height) + .px(chrome.spacing_unit * 4.0) + .text_size(chrome.text_size) + .line_height(relative(1.0)) + .rounded(chrome.radius_sm) + .map(|row| { + if item.disabled { + row + } else if selected && flyout_open { + row.bg(chrome.muted_hover) + } else if selected { + let highlight = if item.destructive { + chrome.destructive + } else { + chrome.primary + }; + row.bg(highlight) + } else { + row.hover(|row| row.bg(chrome.muted_hover)) + } + }) + .on_mouse_move({ + let selection = env.selection.clone(); + let flyout_open = env.flyout.open.clone(); + let set_flyout = env.flyout.set_flyout.clone(); + let dismiss = env.flyout.dismiss.clone(); + move |_, window, cx| { + if !selectable { + return; + } + + if *selection.read(cx) != Some(index) { + selection.update(cx, |selection, _| *selection = Some(index)); + } + + if opens_submenu { + set_flyout(Some(index), false, cx); + } else if flyout_open.read(cx).is_some() { + dismiss(false, window, cx); + } + } + }) +} + +/// The row's label/icon color. +fn row_color( + item: &MenuItem, + selected: bool, + flyout_open: bool, + chrome: &MenuChrome, +) -> gpui::Hsla { + if item.disabled { + return chrome.muted_foreground; + } + if item.destructive { + return if selected && !flyout_open { + chrome.destructive_foreground + } else { + chrome.destructive + }; + } + if selected && !flyout_open { + chrome.primary_foreground + } else { + chrome.foreground + } +} + +/// Everything key navigation needs from the panel. +struct MenuKeyEnv<'a> { + items: &'a [MenuItem], + selection: &'a Entity>, + set_flyout: &'a FlyoutSetter, + on_dismiss: &'a Option, + on_activate: &'a Option, + left_dismisses: bool, +} + +/// Handles the panel's navigation keys. +fn handle_menu_key(event: &KeyDownEvent, env: MenuKeyEnv, window: &mut Window, cx: &mut App) { + let selectable: Vec = env + .items + .iter() + .enumerate() + .filter(|(_, item)| item.selectable()) + .map(|(index, _)| index) + .collect(); + + let current = *env.selection.read(cx); + let position = + current.and_then(|current| selectable.iter().position(|index| *index == current)); + + match event.keystroke.key.as_str() { + "down" | "up" | "home" | "end" => { + if selectable.is_empty() { + return; + } + let next = match event.keystroke.key.as_str() { + "down" => match position { + Some(pos) => (pos + 1).min(selectable.len() - 1), + None => 0, + }, + "up" => match position { + Some(pos) => pos.saturating_sub(1), + None => selectable.len() - 1, + }, + "home" => 0, + _ => selectable.len() - 1, + }; + env.selection + .update(cx, |selection, _| *selection = Some(selectable[next])); + } + "right" => { + let opens = current + .and_then(|current| env.items.get(current)) + .is_some_and(|item| item.selectable() && item.submenu_items().is_some()); + if !opens { + return; + } + (env.set_flyout)(current, true, cx); + } + "enter" | "space" => { + if let Some(current) = current + && let Some(item) = env.items.get(current) + && item.selectable() + { + if item.submenu_items().is_some() { + (env.set_flyout)(Some(current), true, cx); + } else { + if let Some(on_activate) = env.on_activate { + on_activate(false, window, cx); + } + if let Some(handler) = &item.handler { + handler(window, cx); + } + } + } + } + "escape" => { + if let Some(on_dismiss) = env.on_dismiss { + on_dismiss(false, window, cx); + } + } + "left" => { + if !env.left_dismisses { + return; + } + if let Some(on_dismiss) = env.on_dismiss { + on_dismiss(false, window, cx); + } + } + _ => return, + } + + cx.stop_propagation(); +} diff --git a/crates/ui/src/components/mod.rs b/crates/ui/src/components/mod.rs new file mode 100644 index 0000000..ec74d3d --- /dev/null +++ b/crates/ui/src/components/mod.rs @@ -0,0 +1,36 @@ +//! The components every application needs. + +pub mod alert; +pub mod avatar; +pub mod badge; +pub mod button; +pub mod checkbox; +pub mod clipboard; +pub mod combobox; +pub mod command_palette; +pub mod common; +pub mod context_menu; +pub mod dialog; +pub mod dropdown_menu; +pub mod empty_state; +pub mod field; +pub mod grain; +pub mod input; +pub mod link; +pub mod menu; +pub mod popover; +pub mod progress; +pub mod radio; +pub mod scroll_area; +pub mod scrollbar; +pub mod segmented; +pub mod select; +pub mod separator; +pub mod slider; +pub mod speech; +pub mod spinner; +pub mod status_dot; +pub mod switch; +pub mod toast; +pub mod toggle; +pub mod tooltip; diff --git a/crates/ui/src/components/popover.rs b/crates/ui/src/components/popover.rs new file mode 100644 index 0000000..6e4e9cf --- /dev/null +++ b/crates/ui/src/components/popover.rs @@ -0,0 +1,244 @@ +use std::cell::RefCell; +use std::rc::Rc; + +use crate::theme::{ActiveTheme as _, POPOVER_MIN_WIDTH}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + Animation, AnimationExt as _, AnyElement, App, Bounds, DispatchPhase, ElementId, + InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent, + ParentElement as _, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, + StyleRefinement, Styled as _, Window, anchored, canvas, deferred, div, ease_out_quint, point, +}; + +use crate::components::common::{OVERLAY_LAYER, StyledExt as _, v_flex}; + +/// Reports the next open state of a [`Popover`]: `true` to open, `false` to close. +type ChangeHandler = Rc; +type TriggerFn = Box AnyElement>; +type ContentFn = Box AnyElement>; +/// Bounds captured during the last paint, shared with the dismissal listener. +type BoundsCell = Rc>>>; + +/// A floating panel anchored below its trigger. +#[derive(IntoElement)] +#[must_use] +pub struct Popover { + id: ElementId, + open: bool, + a11y_label: Option, + on_change: Option, + trigger: Option, + content: Option, + style: StyleRefinement, +} + +impl Popover { + /// Creates a closed popover. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + open: false, + a11y_label: None, + on_change: None, + trigger: None, + content: None, + style: StyleRefinement::default(), + } + } + + /// Sets the current open state. + pub fn open(mut self, open: bool) -> Self { + self.open = open; + self + } + + /// Reports the next open state, from dismissals and app changes alike. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(bool, &mut Window, &mut App) + 'static, + { + self.on_change = Some(Rc::new(handler)); + self + } + + /// Sets the element the panel anchors below, rendered in place. + pub fn trigger(mut self, trigger: F) -> Self + where + F: FnOnce(&mut Window, &mut App) -> AnyElement + 'static, + { + self.trigger = Some(Box::new(trigger)); + self + } + + /// Sets the panel's contents. + pub fn content(mut self, content: F) -> Self + where + F: FnOnce(&mut Window, &mut App) -> AnyElement + 'static, + { + self.content = Some(Box::new(content)); + self + } + + /// Overrides the accessibility label of the panel. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } +} + +impl gpui::Styled for Popover { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Popover { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let (colors, radius, shadows, enter_duration, panel_border, anchor_gap) = { + let theme = cx.theme(); + ( + theme.colors, + theme.radius, + theme.elevations.popover.shadows(), + theme.motion.overlay, + theme.colors.border, + theme.spacing.unit, + ) + }; + + let trigger_bounds: BoundsCell = Rc::new(RefCell::new(None)); + + let fallback_label = self + .a11y_label + .clone() + .unwrap_or_else(|| SharedString::from(self.id.to_string())); + + div() + .relative() + .refine_style(&self.style) + .child( + canvas( + { + let cell = trigger_bounds.clone(); + move |bounds, _window, _cx| *cell.borrow_mut() = Some(bounds) + }, + { + let on_change = self.on_change.clone(); + let open = self.open; + let cell = trigger_bounds.clone(); + + move |_, _, window, _cx| { + window.on_mouse_event({ + let on_change = on_change.clone(); + let trigger_bounds = cell; + move |event: &MouseDownEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble + || event.button != MouseButton::Left + { + return; + } + + let on_trigger = trigger_bounds + .borrow() + .is_some_and(|bounds| bounds.contains(&event.position)); + + if !on_trigger { + return; + } + + if let Some(on_change) = &on_change { + on_change(!open, window, cx); + } + + cx.stop_propagation(); + } + }); + } + }, + ) + .absolute() + .inset_0(), + ) + .when_some(self.trigger, |wrapper, trigger| { + wrapper.child(trigger(window, cx)) + }) + .when(self.open, |wrapper| { + let on_change = self.on_change; + let label = fallback_label.clone(); + let focus = crate::utils::focus_handle(&self.id, window, cx); + let content = self.content.map(|content| content(window, cx)); + + let panel = v_flex() + .id("popover-panel") + .debug_selector(|| "popover-panel".to_string()) + .occlude() + .track_focus(&focus) + .role(Role::Dialog) + .aria_label(label) + .min_w(POPOVER_MIN_WIDTH) + .bg(colors.surface) + .text_color(colors.surface_foreground) + .rounded(radius.overlay) + .border_1() + .border_color(panel_border) + .shadow(shadows) + .overflow_hidden() + .on_mouse_down_out({ + let on_change = on_change.clone(); + let trigger_bounds = trigger_bounds.clone(); + move |event, window, cx| { + if trigger_bounds + .borrow() + .is_some_and(|bounds| bounds.contains(&event.position)) + { + return; + } + if let Some(on_change) = &on_change { + on_change(false, window, cx); + } + } + }) + .on_key_down({ + let on_change = on_change.clone(); + move |event: &KeyDownEvent, window, cx| { + if event.keystroke.key == "escape" { + if let Some(on_change) = &on_change { + on_change(false, window, cx); + } + cx.stop_propagation(); + } + } + }) + .when_some(content, |panel, content| panel.child(content)) + .child( + canvas(|_, _, _| {}, { + let focus = focus; + move |_, _, window, cx| { + if !focus.contains_focused(window, cx) { + window.focus(&focus, cx); + } + } + }) + .absolute() + .inset_0(), + ); + + wrapper.child( + deferred(anchored().offset(point(Pixels::ZERO, anchor_gap)).child( + panel.with_animation( + "popover-enter", + Animation::new(enter_duration).with_easing(ease_out_quint()), + |panel, delta| panel.opacity(delta), + ), + )) + .with_priority(OVERLAY_LAYER), + ) + }) + } +} diff --git a/crates/ui/src/components/progress.rs b/crates/ui/src/components/progress.rs new file mode 100644 index 0000000..6b910c0 --- /dev/null +++ b/crates/ui/src/components/progress.rs @@ -0,0 +1,124 @@ +//! The progress bar: determinate fill or an indeterminate sweep. + +use crate::theme::{ActiveTheme as _, PROGRESS_ANIMATION_PERIOD, Size}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + Animation, AnimationExt as _, App, ElementId, InteractiveElement as _, IntoElement, + ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, + StyleRefinement, Styled as _, Window, div, relative, +}; + +use crate::components::common::{Sizable, StyledExt as _}; + +/// A progress bar. With a `value` in `0..=1` it paints a determinate fill. +#[derive(IntoElement)] +#[must_use] +pub struct Progress { + id: ElementId, + value: f32, + indeterminate: bool, + size: Size, + a11y_label: Option, + style: StyleRefinement, +} + +impl Progress { + /// Creates a determinate progress bar at `value` (`0..=1`). + pub fn new(id: I, value: f32) -> Self + where + I: Into, + { + Self { + id: id.into(), + value, + indeterminate: false, + size: Size::default(), + a11y_label: None, + style: StyleRefinement::default(), + } + } + + /// Sweeps instead of painting a fill, for work of unknown length. + pub fn indeterminate(mut self, indeterminate: bool) -> Self { + self.indeterminate = indeterminate; + self + } + + /// Sets the accessibility label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } +} + +impl gpui::Styled for Progress { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl Sizable for Progress { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl RenderOnce for Progress { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let colors = theme.colors; + let ramps = theme.ramps; + let radius = theme.radius; + let metrics = theme.sizes.resolve(self.size); + + let track_height = metrics.icon_size / 4.0; + let value = self.value.clamp(0.0, 1.0); + + div() + .id(self.id) + .w_full() + .refine_style(&self.style) + .role(Role::ProgressIndicator) + .when_some(self.a11y_label, |progress, label| { + progress.aria_label(label) + }) + .when(!self.indeterminate, |progress| { + progress + .aria_numeric_value(f64::from(value)) + .aria_min_numeric_value(0.0) + .aria_max_numeric_value(1.0) + }) + .child( + div() + .w_full() + .h(track_height) + .rounded(radius.full) + .bg(colors.border) + .child(if self.indeterminate { + div() + .h_full() + .w(relative(0.3)) + .rounded(radius.full) + .bg(ramps.primary.base) + .with_animation( + "indeterminate", + Animation::new(PROGRESS_ANIMATION_PERIOD) + .repeat() + .with_max_fps(30.), + |pill, delta| pill.ml(relative(delta * 0.7)), + ) + .into_any_element() + } else { + div() + .h_full() + .w(relative(value)) + .rounded(radius.full) + .bg(ramps.primary.base) + .into_any_element() + }), + ) + } +} diff --git a/crates/ui/src/components/radio.rs b/crates/ui/src/components/radio.rs new file mode 100644 index 0000000..2947fbb --- /dev/null +++ b/crates/ui/src/components/radio.rs @@ -0,0 +1,242 @@ +use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; +use crate::utils::focus_ring; +use gpui::prelude::FluentBuilder; +use gpui::{ + App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, + SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window, + div, +}; + +use crate::components::common::{Sizable, StyledExt as _, h_flex, v_flex}; + +/// The group's change reporter, fired with the clicked radio's value. +type ChangeHandler = std::rc::Rc; + +/// Radio button. +/// +/// Each radio is its own tab stop; the full ARIA radiogroup pattern (single +/// stop plus arrow-key roving focus) needs a group owner that does not exist yet. +#[must_use] +pub struct Radio { + id: ElementId, + value: V, + label: Option, + disabled: bool, + a11y_label: Option, +} + +impl Radio +where + V: Clone + PartialEq + 'static, +{ + /// Creates a radio representing `value`. + pub fn new(id: I, value: V) -> Self + where + I: Into, + { + Self { + id: id.into(), + value, + label: None, + disabled: false, + a11y_label: None, + } + } + + /// Sets the visible label; clicking it selects the radio too. + pub fn label(mut self, label: L) -> Self + where + L: Into, + { + self.label = Some(label.into()); + self + } + + /// Renders the radio inert, unfocusable, and dimmed. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + + /// Overrides the accessibility label, which defaults to the visible label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } +} + +// Radio is a data builder, not an element, adopt the combinators explicitly. +impl FluentBuilder for Radio {} + +/// Group of radio buttons. +#[derive(IntoElement)] +#[must_use] +pub struct RadioGroup +where + V: Clone + PartialEq + 'static, +{ + id: ElementId, + selected: Option, + children: Vec>, + size: Size, + a11y_label: Option, + on_change: Option>, + style: StyleRefinement, +} + +impl RadioGroup +where + V: Clone + PartialEq + 'static, +{ + /// Creates an empty group with nothing selected. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + selected: None, + children: Vec::new(), + size: Size::default(), + a11y_label: None, + on_change: None, + style: StyleRefinement::default(), + } + } + + /// Sets the currently selected value. + pub fn selected(mut self, selected: Option) -> Self { + self.selected = selected; + self + } + + /// Adds a radio to the group. + pub fn child(mut self, radio: Radio) -> Self { + self.children.push(radio); + self + } + + /// Sets the group's accessibility label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// Sets the change handler. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(V, &mut Window, &mut App) + 'static, + { + self.on_change = Some(std::rc::Rc::new(handler)); + self + } +} + +impl Sizable for RadioGroup +where + V: Clone + PartialEq + 'static, +{ + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl gpui::Styled for RadioGroup +where + V: Clone + PartialEq + 'static, +{ + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for RadioGroup +where + V: Clone + PartialEq + 'static, +{ + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let colors = theme.colors; + let ramps = theme.ramps; + let radius = theme.radius; + let metrics = theme.sizes.resolve(self.size); + let selected = self.selected; + let on_change = self.on_change; + let group_label = self.a11y_label; + + v_flex() + .id(self.id) + .gap_2() + .text_size(metrics.text_size) + .refine_style(&self.style) + .role(Role::RadioGroup) + .when_some(group_label.clone(), |group, label| group.aria_label(label)) + .children(self.children.into_iter().map(move |radio| { + let is_selected = selected.as_ref() == Some(&radio.value); + let disabled = radio.disabled; + let row_on_change = on_change.clone(); + + let a11y_label = radio + .a11y_label + .or(radio.label.clone()) + .or_else(|| group_label.clone()); + + h_flex() + .id(radio.id) + .gap_2() + .role(Role::RadioButton) + .when_some(a11y_label, |row, label| row.aria_label(label)) + .aria_toggled(Toggled::from(is_selected)) + .when(disabled, |row| row.opacity(DISABLED_OPACITY)) + .when(!disabled, move |row| { + let value = radio.value.clone(); + row.cursor_pointer() + .focusable() + .tab_stop(true) + .focus_visible(|style| style.shadow(focus_ring(colors.ring))) + .when_some(row_on_change, |row, on_change| { + row.on_click(move |_, window, cx| { + on_change(value.clone(), window, cx) + }) + }) + }) + .child( + h_flex() + .justify_center() + .flex_none() + .size(metrics.indicator_size) + .rounded(radius.full) + .border_1() + .when(is_selected, |indicator| { + indicator + .bg(ramps.primary.base) + .border_color(ramps.primary.base) + .hover(|style| { + style + .bg(ramps.primary.hover) + .border_color(ramps.primary.hover) + }) + .child( + div() + .size(metrics.indicator_size / 2.0) + .rounded(radius.full) + .bg(colors.primary_foreground), + ) + }) + .when(!is_selected, |indicator| { + indicator + .bg(colors.input) + .border_color(colors.border) + .hover(|style| style.border_color(colors.muted_foreground)) + }), + ) + .when_some(radio.label, |row, label| row.child(label)) + })) + } +} diff --git a/crates/ui/src/components/scroll_area.rs b/crates/ui/src/components/scroll_area.rs new file mode 100644 index 0000000..62c4105 --- /dev/null +++ b/crates/ui/src/components/scroll_area.rs @@ -0,0 +1,143 @@ +//! A scrollable container with an overlay scrollbar. + +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce, ScrollHandle, + SharedString, StatefulInteractiveElement as _, Styled, Window, div, +}; + +use crate::components::common::StyledExt; +use crate::components::scrollbar::{Scrollbar, ScrollbarVisibility}; + +/// Which directions the content scrolls in. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum ScrollAxes { + /// Vertical only; the default. + #[default] + Vertical, + /// Horizontal only. + Horizontal, + /// Both directions. + Both, +} + +/// A scrollable container with an overlay scrollbar. +#[derive(IntoElement)] +#[must_use] +pub struct ScrollArea { + id: ElementId, + handle: Option, + axes: ScrollAxes, + visibility: ScrollbarVisibility, + a11y_label: Option, + style: gpui::StyleRefinement, + children: Vec, +} + +impl ParentElement for ScrollArea { + fn extend(&mut self, children: impl IntoIterator) { + self.children.extend(children); + } +} + +impl Styled for ScrollArea { + fn style(&mut self) -> &mut gpui::StyleRefinement { + &mut self.style + } +} + +impl ScrollArea { + /// Creates a vertically scrolling area. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + handle: None, + axes: ScrollAxes::Vertical, + visibility: ScrollbarVisibility::default(), + a11y_label: None, + style: gpui::StyleRefinement::default(), + children: Vec::new(), + } + } + + /// Sets which directions the content scrolls in. + pub fn axes(mut self, axes: ScrollAxes) -> Self { + self.axes = axes; + self + } + + /// Overrides when the scrollbar shows, instead of the platform default. + pub fn visibility(mut self, visibility: ScrollbarVisibility) -> Self { + self.visibility = visibility; + self + } + + /// Scrolls with a handle held on the owning view. + pub fn handle(mut self, handle: ScrollHandle) -> Self { + self.handle = Some(handle); + self + } + + /// Overrides the accessibility label of the container. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } +} + +impl RenderOnce for ScrollArea { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + let mut pane_style = self.style.clone(); + pane_style.padding = Default::default(); + + let pane = div() + .id(self.id.clone()) + .overflow_hidden() + .when(self.axes != ScrollAxes::Horizontal, |area| { + area.overflow_y_scroll() + }) + .when(self.axes != ScrollAxes::Vertical, |area| { + area.overflow_x_scroll() + }) + .when_some(self.handle.clone(), |area, handle| { + area.track_scroll(&handle) + }) + .when_some(self.a11y_label, |area, label| area.aria_label(label)) + .on_scroll(|_, _, cx| { + // Keep wheel events from scrolling an outer scroll area too. + cx.stop_propagation(); + }) + .refine_style(&pane_style) + .children(self.children); + + div() + .relative() + .refine_style(&self.style) + .child(pane.into_any_element()) + .when_some(self.handle, |wrapper, handle| { + let id = self.id.clone(); + + wrapper + .when(self.axes != ScrollAxes::Horizontal, |wrapper| { + wrapper.child( + Scrollbar::vertical((id.clone(), "v-scrollbar"), handle.clone()) + .visibility(self.visibility) + .into_any_element(), + ) + }) + .when(self.axes != ScrollAxes::Vertical, |wrapper| { + wrapper.child( + Scrollbar::horizontal((id, "h-scrollbar"), handle) + .visibility(self.visibility) + .into_any_element(), + ) + }) + }) + } +} diff --git a/crates/ui/src/components/scrollbar.rs b/crates/ui/src/components/scrollbar.rs new file mode 100644 index 0000000..fa83722 --- /dev/null +++ b/crates/ui/src/components/scrollbar.rs @@ -0,0 +1,520 @@ +//! Overlay scrollbars for scroll surfaces. + +use std::rc::Rc; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use crate::theme::{ActiveTheme as _, SCROLLBAR_AUTOHIDE_DELAY, SCROLLBAR_FADE_DURATION}; +use crate::utils::ResultLogErr as _; +use gpui::{ + App, Bounds, DispatchPhase, ElementId, Entity, EntityId, IntoElement, ListState, MouseButton, + MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, RenderOnce, ScrollEvent, + ScrollHandle, SharedString, Styled as _, Task, UniformListScrollHandle, Window, canvas, fill, + point, +}; + +/// When an overlay scrollbar shows. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ScrollbarVisibility { + /// The running platform's behavior, from the theme. + #[default] + Platform, + Always, + Autohide, +} + +/// How often the autohide fade repaints while it runs. +const FADE_STEP: Duration = Duration::from_millis(50); + +/// The shared autohide timeline for an overlay scrollbar. +#[derive(Clone)] +struct Autohide { + view: EntityId, + state: Entity, +} + +struct AutohideState { + last_activity: Option, + hide_task: Option>, +} + +impl Autohide { + fn new(key: ElementId, window: &mut Window, cx: &mut App) -> Self { + let view = window.current_view(); + let state = window.use_keyed_state(key, cx, |_, _| AutohideState { + last_activity: None, + hide_task: None, + }); + Self { view, state } + } + + /// Marks interaction. + fn touch(&self, window: &mut Window, cx: &mut App) { + let view = self.view; + let reduce_motion = cx.theme().accessibility.reduce_motion; + + let task = window.spawn(cx, async move |cx| { + if reduce_motion { + cx.background_executor() + .timer(SCROLLBAR_AUTOHIDE_DELAY + SCROLLBAR_FADE_DURATION) + .await; + cx.update(|_, cx| cx.notify(view)).log_err(); + return; + } + + let steps = (SCROLLBAR_FADE_DURATION.as_millis() / FADE_STEP.as_millis()).max(1); + cx.background_executor() + .timer(SCROLLBAR_AUTOHIDE_DELAY) + .await; + + for _ in 0..steps { + cx.update(|_, cx| cx.notify(view)).log_err(); + cx.background_executor().timer(FADE_STEP).await; + } + + cx.update(|_, cx| cx.notify(view)).log_err(); + }); + + self.state.update(cx, |state, _| { + state.last_activity = Some(Instant::now()); + state.hide_task = Some(task); + }); + } + + /// The thumb's opacity. + fn alpha(&self, cx: &App, dragging: bool) -> f32 { + if dragging { + return 1.0; + } + + let Some(activity) = self.state.read(cx).last_activity else { + return 0.0; + }; + + let idle = activity.elapsed(); + if idle <= SCROLLBAR_AUTOHIDE_DELAY { + return 1.0; + } + + let fade = idle.saturating_sub(SCROLLBAR_AUTOHIDE_DELAY); + if fade >= SCROLLBAR_FADE_DURATION { + return 0.0; + } + + 1.0 - fade.as_secs_f32() / SCROLLBAR_FADE_DURATION.as_secs_f32() + } +} + +/// The scroll state a scrollbar drives, implemented for gpui's scroll handles. +pub trait ScrollbarHandle: 'static { + /// How far the content can scroll, positive along each axis. + fn max_offset(&self) -> Point; + /// The current offset, non-positive along each axis. + fn offset(&self) -> Point; + /// Applies the offset along one axis, keeping the other. + fn set_offset(&self, offset: Point); + /// The bounds of the scrolled surface. + fn viewport(&self) -> Bounds; + /// A thumb drag began. + fn drag_started(&self) {} + /// A thumb drag ended. + fn drag_ended(&self) {} +} + +impl ScrollbarHandle for ScrollHandle { + fn max_offset(&self) -> Point { + ScrollHandle::max_offset(self) + } + + fn offset(&self) -> Point { + ScrollHandle::offset(self) + } + + fn set_offset(&self, offset: Point) { + ScrollHandle::set_offset(self, offset); + } + + fn viewport(&self) -> Bounds { + self.bounds() + } +} + +impl ScrollbarHandle for UniformListScrollHandle { + fn max_offset(&self) -> Point { + self.0.borrow().base_handle.max_offset() + } + + fn offset(&self) -> Point { + self.0.borrow().base_handle.offset() + } + + fn set_offset(&self, offset: Point) { + self.0.borrow().base_handle.set_offset(offset); + } + + fn viewport(&self) -> Bounds { + self.0.borrow().base_handle.bounds() + } +} + +impl ScrollbarHandle for ListState { + fn max_offset(&self) -> Point { + ListState::max_offset_for_scrollbar(self) + } + + fn offset(&self) -> Point { + ListState::scroll_px_offset_for_scrollbar(self) + } + + fn set_offset(&self, offset: Point) { + ListState::set_offset_from_scrollbar(self, offset); + } + + fn viewport(&self) -> Bounds { + self.viewport_bounds() + } + + fn drag_started(&self) { + ListState::scrollbar_drag_started(self); + } + + fn drag_ended(&self) { + ListState::scrollbar_drag_ended(self); + } +} + +/// Which direction the scrollbar lies along. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Axis { + Vertical, + Horizontal, +} + +impl Axis { + fn along(self, position: Point) -> Pixels { + match self { + Axis::Vertical => position.y, + Axis::Horizontal => position.x, + } + } + + fn with_along(self, position: Point, along: Pixels) -> Point { + match self { + Axis::Vertical => point(position.x, along), + Axis::Horizontal => point(along, position.y), + } + } + + fn viewport_along(self, viewport: &Bounds) -> Pixels { + match self { + Axis::Vertical => viewport.size.height, + Axis::Horizontal => viewport.size.width, + } + } +} + +/// An overlay scrollbar, rendered over the scrolled surface. +#[derive(IntoElement)] +#[must_use] +pub struct Scrollbar { + axis: Axis, + handle: Rc, + visibility: ScrollbarVisibility, + id: ElementId, +} + +impl Scrollbar { + /// A vertical scrollbar named by `id`, driven by `handle`. + pub fn vertical(id: I, handle: H) -> Self + where + I: Into, + H: ScrollbarHandle, + { + Self { + axis: Axis::Vertical, + handle: Rc::new(handle), + visibility: ScrollbarVisibility::default(), + id: id.into(), + } + } + + /// A horizontal scrollbar named by `id`, driven by `handle`. + pub fn horizontal(id: I, handle: H) -> Self + where + I: Into, + H: ScrollbarHandle, + { + Self { + axis: Axis::Horizontal, + handle: Rc::new(handle), + visibility: ScrollbarVisibility::default(), + id: id.into(), + } + } + + /// Overrides when the scrollbar shows, instead of the platform default. + pub fn visibility(mut self, visibility: ScrollbarVisibility) -> Self { + self.visibility = visibility; + self + } + + fn state_key(name: &'static str, id: &ElementId) -> ElementId { + ElementId::NamedChild(Arc::new(id.clone()), SharedString::from(name)) + } + + /// Pure thumb geometry for an overlay scrollbar. + fn thumb_geometry( + viewport: Pixels, + content: Pixels, + offset: Pixels, + track: Pixels, + min_thumb: Pixels, + ) -> (Pixels, Pixels) { + if content <= viewport || content <= Pixels::ZERO { + return (track, Pixels::ZERO); + } + + let length = (viewport / content * track).max(min_thumb).min(track); + let overflow = content - viewport; + let progress = (-offset / overflow).clamp(0., 1.); + let travel = track - length; + (length, travel * progress) + } + + /// An overlay scrollbar thumb's style for one paint: `None` hides it. + fn thumb_style(color: gpui::Hsla, alpha: f32) -> Option { + (alpha > 0.0).then_some(gpui::Hsla { + a: color.a * alpha, + ..color + }) + } +} + +impl RenderOnce for Scrollbar { + fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { + canvas(|_, _, _| {}, { + let handle = self.handle; + let axis = self.axis; + let visibility = self.visibility; + let id = self.id; + move |_, _, window, cx| Self::paint(&handle, axis, visibility, &id, window, cx) + }) + .absolute() + .inset_0() + } +} + +/// The drag state shared between the scrollbar's mouse handlers. +type Drag = Option<(Pixels, Pixels)>; + +impl Scrollbar { + fn paint( + handle: &Rc, + axis: Axis, + visibility: ScrollbarVisibility, + id: &ElementId, + window: &mut Window, + cx: &mut App, + ) { + let view = window.current_view(); + let theme = cx.theme(); + + let color = theme.colors.scrollbar_thumb; + let width = theme.scrollbar.width; + let inset = theme.scrollbar.inset; + let min_thumb = theme.scrollbar.min_thumb; + + let viewport = handle.viewport(); + let viewport_along = axis.viewport_along(&viewport); + let max_offset = axis.along(handle.max_offset()); + + if max_offset <= Pixels::ZERO || viewport_along <= Pixels::ZERO { + return; + } + + let autohide = match visibility { + ScrollbarVisibility::Platform => theme.scrollbar.autohide, + ScrollbarVisibility::Always => false, + ScrollbarVisibility::Autohide => true, + }; + + let autohide_state = + autohide.then(|| Autohide::new(Self::state_key("autohide", id), window, cx)); + + let track_length = viewport_along - inset * 2.0; + let (thumb_length, thumb_travel) = Self::thumb_geometry( + viewport_along, + viewport_along + max_offset, + axis.along(handle.offset()), + track_length, + min_thumb, + ); + + // The track strip is the thumb's rail plus the padding the thumb rides inside. + let (thumb_bounds, track_bounds) = match axis { + Axis::Vertical => { + let thumb_x = viewport.right() - width - inset; + ( + Bounds::from_corners( + point(thumb_x, viewport.top() + inset + thumb_travel), + point( + thumb_x + width, + viewport.top() + inset + thumb_travel + thumb_length, + ), + ), + Bounds::from_corners( + point(viewport.right() - width, viewport.top() + inset), + point(viewport.right(), viewport.top() + inset + track_length), + ), + ) + } + Axis::Horizontal => { + let thumb_y = viewport.bottom() - width - inset; + ( + Bounds::from_corners( + point(viewport.left() + inset + thumb_travel, thumb_y), + point( + viewport.left() + inset + thumb_travel + thumb_length, + thumb_y + width, + ), + ), + Bounds::from_corners( + point(viewport.left() + inset, viewport.bottom() - width), + point(viewport.left() + inset + track_length, viewport.bottom()), + ), + ) + } + }; + + let drag = window.use_keyed_state(Self::state_key("thumb-drag", id), cx, |_, _| Drag::None); + let dragging = drag.read(cx).is_some(); + + let alpha = match &autohide_state { + Some(state) => state.alpha(cx, dragging), + None => 1.0, + }; + + if let Some(color) = Self::thumb_style(color, alpha) { + window.paint_quad(fill(thumb_bounds, color).corner_radii(width / 2.0)); + } + + if let Some(state) = &autohide_state { + window.on_mouse_event({ + let state = state.clone(); + move |event: &ScrollEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble || !viewport.contains(&event.position) { + return; + } + state.touch(window, cx); + } + }); + } + + window.on_mouse_event({ + let handle = handle.clone(); + let drag = drag.clone(); + let autohide_state = autohide_state.clone(); + move |event: &MouseDownEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble || event.button != MouseButton::Left { + return; + } + + let in_thumb = thumb_bounds.contains(&event.position); + let in_track = !in_thumb && track_bounds.contains(&event.position); + + if !in_thumb && !in_track { + return; + } + + let start_offset = if in_thumb { + axis.along(handle.offset()) + } else if track_length > thumb_length { + let thumb_start = ((axis.along(event.position) + - axis.along(track_bounds.origin)) + - thumb_length / 2.0) + .clamp(Pixels::ZERO, track_length - thumb_length); + let offset = -(thumb_start / (track_length - thumb_length)) * max_offset; + handle.set_offset(axis.with_along(handle.offset(), offset)); + cx.notify(view); + offset + } else { + return; + }; + + drag.update(cx, |drag, _| { + *drag = Some((axis.along(event.position), start_offset)); + }); + handle.drag_started(); + + if let Some(state) = &autohide_state { + state.touch(window, cx); + } + + cx.stop_propagation(); + } + }); + + window.on_mouse_event({ + let handle = handle.clone(); + let drag = drag.clone(); + let autohide_state = autohide_state.clone(); + move |event: &MouseMoveEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble { + return; + } + + if let Some(state) = &autohide_state + && track_bounds.contains(&event.position) + && drag.read(cx).is_none() + { + state.touch(window, cx); + } + + if event.pressed_button != Some(MouseButton::Left) { + return; + } + + let Some((start_position, start_offset)) = *drag.read(cx) else { + return; + }; + + if track_length <= thumb_length { + return; + } + + let scale = max_offset / (track_length - thumb_length); + let offset = (start_offset - (axis.along(event.position) - start_position) * scale) + .clamp(-max_offset, Pixels::ZERO); + handle.set_offset(axis.with_along(handle.offset(), offset)); + cx.notify(view); + } + }); + + window.on_mouse_event({ + let handle = handle.clone(); + let drag = drag.clone(); + let autohide_state = autohide_state.clone(); + move |event: &MouseUpEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble || event.button != MouseButton::Left { + return; + } + + if drag.read(cx).is_none() { + return; + } + + drag.update(cx, |drag, _| { + *drag = None; + }); + handle.drag_ended(); + + // Unfreezing a ListState's height can change the thumb's geometry. + cx.notify(view); + + if let Some(state) = &autohide_state { + state.touch(window, cx); + } + } + }); + } +} diff --git a/crates/ui/src/components/segmented.rs b/crates/ui/src/components/segmented.rs new file mode 100644 index 0000000..6631733 --- /dev/null +++ b/crates/ui/src/components/segmented.rs @@ -0,0 +1,358 @@ +use std::rc::Rc; + +use crate::icons::Icon; +use crate::theme::{ActiveTheme as _, CONTROL_SPRING, Size}; +use crate::utils::{focus_handle, focus_ring}; +use gpui::prelude::FluentBuilder; +use gpui::{ + AnimationExt as _, App, Bounds, ElementId, Entity, InteractiveElement as _, IntoElement, + KeyDownEvent, ParentElement as _, Point, RenderOnce, Role, SharedString, SpringAnimation, + StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window, canvas, div, +}; + +use crate::components::common::{Sizable, StyledExt, h_flex}; + +/// Reports the segment the user chose. +type ChangeHandler = Rc; + +/// Segment option for a segmented control. +#[derive(Clone)] +#[must_use] +pub struct SegmentedOption { + value: T, + label: SharedString, + icon: Option, +} + +impl SegmentedOption { + /// Creates a choice showing `label`; picking it reports `value`. + pub fn new(value: T, label: L) -> Self + where + L: Into, + { + Self { + value, + label: label.into(), + icon: None, + } + } + + /// Sets a leading icon for the segment. + pub fn icon(mut self, icon: I) -> Self + where + I: Into, + { + self.icon = Some(icon.into()); + self + } +} + +impl From<(T, L)> for SegmentedOption +where + L: Into, +{ + fn from((value, label): (T, L)) -> Self { + Self { + value, + label: label.into(), + icon: None, + } + } +} + +// SegmentedOption is a data builder, not an element, adopt the combinators explicitly. +impl FluentBuilder for SegmentedOption {} + +/// A pill strip of mutually exclusive choices. +#[derive(IntoElement)] +#[must_use] +pub struct Segmented +where + T: Clone + PartialEq + 'static, +{ + id: ElementId, + /// Shared with the per-segment and key handlers, so captures are bumps. + options: Rc<[SegmentedOption]>, + selected: T, + a11y_label: Option, + size: Size, + style: StyleRefinement, + on_change: Option>, +} + +impl Segmented +where + T: Clone + PartialEq + 'static, +{ + pub fn new(id: I, selected: T) -> Self + where + I: Into, + { + Self { + id: id.into(), + options: Rc::from([]), + selected, + a11y_label: None, + size: Size::Small, + style: StyleRefinement::default(), + on_change: None, + } + } + + /// Sets the choices. + pub fn options(mut self, options: I) -> Self + where + I: IntoIterator, + I::Item: Into>, + { + self.options = options.into_iter().map(Into::into).collect(); + self + } + + /// Reports the segment chosen, by pointer or by arrow. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(T, &mut Window, &mut App) + 'static, + { + self.on_change = Some(Rc::new(handler)); + self + } + + /// Overrides the strip's accessibility label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } +} + +impl Sizable for Segmented +where + T: Clone + PartialEq + 'static, +{ + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl gpui::Styled for Segmented +where + T: Clone + PartialEq + 'static, +{ + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Segmented +where + T: Clone + PartialEq + 'static, +{ + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let metrics = theme.sizes.resolve(self.size); + let muted = theme.colors.muted; + let surface = theme.colors.surface; + let foreground = theme.colors.foreground; + let muted_foreground = theme.colors.muted_foreground; + let ring = theme.colors.ring; + let radius = theme.radius.full; + let plate_shadow = theme.elevations.control.shadows(); + + let track_height = metrics.strip_height; + let track_inset = metrics.plate_inset; + let horizontal_padding = metrics.dense_padding_x; + let text_size = metrics.text_size; + let icon_size = metrics.icon_size; + + let selected_index = self + .options + .iter() + .position(|segment| segment.value == self.selected); + let option_count = self.options.len(); + + let on_change = self.on_change.clone(); + let key_on_change = on_change.clone(); + let key_options = self.options.clone(); + let options = self.options.clone(); + + let label = self + .a11y_label + .clone() + .unwrap_or_else(|| SharedString::from(self.id.to_string())); + + window.with_element_namespace(self.id.clone(), |window| { + let geometry: Entity>>> = + window.use_keyed_state("segmented-geometry", cx, |_, _| Vec::new()); + + let track_origin: Entity>> = + window.use_keyed_state("segmented-track-origin", cx, |_, _| None); + + let focus = focus_handle(&self.id, window, cx); + let track_point = *track_origin.read(cx); + + let plate_target = geometry + .read(cx) + .get(selected_index.unwrap_or(usize::MAX)) + .copied() + .flatten() + .zip(track_point) + .map(|(bounds, track)| (bounds.origin.x - track.x, bounds.size.width)); + + let segments = self + .options + .iter() + .enumerate() + .map(move |(index, segment)| { + let is_selected = Some(index) == selected_index; + let on_change = on_change.clone(); + let options = options.clone(); + + let content_color = if is_selected { + foreground + } else { + muted_foreground + }; + + h_flex() + .id((ElementId::from("segment"), segment.label.clone())) + .gap_2() + .justify_center() + .cursor_pointer() + .h_full() + .px(horizontal_padding) + .rounded(radius) + .text_size(text_size) + .text_color(content_color) + .when(!is_selected, |segment| { + segment.hover(|style| style.bg(surface)) + }) + .role(Role::RadioButton) + .aria_label(segment.label.clone()) + .aria_toggled(Toggled::from(is_selected)) + .when_some(segment.icon.clone(), |segment, icon| { + segment.child(icon.size(icon_size).color(content_color)) + }) + .child(segment.label.clone()) + .child( + canvas( + { + let geometry = geometry.clone(); + move |bounds, _, cx| { + geometry.update(cx, |geometry, _| { + if geometry.len() <= index { + geometry.resize(index + 1, None); + } + geometry[index] = Some(bounds); + }); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ) + .on_click({ + move |_, window, cx| { + if Some(index) != selected_index + && let Some(on_change) = &on_change + && let Some(option) = options.get(index) + { + on_change(option.value.clone(), window, cx); + } + } + }) + }); + + div().child( + div() + .id(self.id.clone()) + .track_focus(&focus) + .focusable() + .tab_stop(true) + .focus_visible(|style| style.shadow(focus_ring(ring))) + .role(Role::RadioGroup) + .aria_label(label) + .flex() + .items_center() + .gap_1() + .relative() + .flex_none() + .h(track_height) + .p(track_inset) + .rounded(radius) + .bg(muted) + .text_size(metrics.text_size) + .child( + canvas( + { + let track_origin = track_origin.clone(); + move |bounds, _, cx| { + track_origin + .update(cx, |origin, _| *origin = Some(bounds.origin)); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ) + .when_some(plate_target, |track, (x, width)| { + track.child( + div() + .id("segmented-plate") + .debug_selector(|| "segmented-plate".to_string()) + .absolute() + .top(track_inset) + .bottom(track_inset) + .rounded(radius) + .bg(surface) + .shadow(plate_shadow.clone()) + .with_spring( + "segmented-plate-x", + SpringAnimation::new(CONTROL_SPRING).to(x), + |plate, x| plate.left(x), + ) + .with_spring( + "segmented-plate-w", + SpringAnimation::new(CONTROL_SPRING).to(width), + |spring_plate, width| { + spring_plate.map_element(move |plate| plate.w(width)) + }, + ), + ) + }) + .on_key_down({ + move |event: &KeyDownEvent, window, cx| { + let target = match event.keystroke.key.as_str() { + "right" => match selected_index { + Some(index) => { + index.checked_add(1).filter(|next| *next < option_count) + } + None => (option_count > 0).then_some(0), + }, + "left" => selected_index.and_then(|index| index.checked_sub(1)), + "home" => (option_count > 0).then_some(0), + "end" => option_count.checked_sub(1), + _ => return, + }; + + if let Some(next) = target + && Some(next) != selected_index + && let Some(on_change) = &key_on_change + && let Some(option) = key_options.get(next) + { + on_change(option.value.clone(), window, cx); + } + + cx.stop_propagation(); + } + }) + .children(segments) + .refine_style(&self.style), + ) + }) + } +} diff --git a/crates/ui/src/components/select.rs b/crates/ui/src/components/select.rs new file mode 100644 index 0000000..d138c25 --- /dev/null +++ b/crates/ui/src/components/select.rs @@ -0,0 +1,348 @@ +use std::rc::Rc; + +use crate::icons::{Icon, IconRole, icon}; +use crate::theme::{ActiveTheme as _, Size}; +use crate::utils::focus_handle; +use gpui::prelude::FluentBuilder; +use gpui::{ + App, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, ParentElement as _, + RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, + Window, canvas, +}; + +use crate::components::common::{Sizable, StyledExt, h_flex}; +use crate::components::menu::{Menu, MenuItem}; + +/// Reports the value the user chose. `None` means the select holds no value. +pub type SelectHandler = Rc, &mut Window, &mut App)>; + +/// Select option for a [`Select`] control. +#[derive(Clone)] +#[must_use] +pub struct SelectOption { + value: T, + label: SharedString, + icon: Option, +} + +impl SelectOption { + /// Creates a choice showing `label`; picking it reports `value`. + pub fn new(value: T, label: L) -> Self + where + L: Into, + { + Self { + value, + label: label.into(), + icon: None, + } + } + + /// Sets a leading icon for the option's row. + pub fn icon(mut self, icon: I) -> Self + where + I: Into, + { + self.icon = Some(icon.into()); + self + } +} + +impl From<(T, L)> for SelectOption +where + L: Into, +{ + fn from((value, label): (T, L)) -> Self { + Self { + value, + label: label.into(), + icon: None, + } + } +} + +// SelectOption is a data builder, not an element, adopt the combinators explicitly. +impl FluentBuilder for SelectOption {} + +/// A control that shows the chosen value and opens a menu of the choices. +#[derive(IntoElement)] +#[must_use] +pub struct Select +where + T: Clone + PartialEq + 'static, +{ + id: ElementId, + options: Vec>, + selected: Option, + placeholder: SharedString, + a11y_label: Option, + size: Size, + style: StyleRefinement, + on_change: Option>, +} + +impl Select +where + T: Clone + PartialEq + 'static, +{ + /// Creates a closed select holding no value. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + options: Vec::new(), + selected: None, + placeholder: SharedString::from("Select..."), + a11y_label: None, + size: Size::default(), + style: StyleRefinement::default(), + on_change: None, + } + } + + /// Sets the choice. + pub fn options(mut self, options: I) -> Self + where + I: IntoIterator, + I::Item: Into>, + { + self.options = options.into_iter().map(Into::into).collect(); + self + } + + /// Sets the current value. `None` shows the placeholder. + pub fn selected(mut self, selected: S) -> Self + where + S: Into>, + { + self.selected = selected.into(); + self + } + + /// Sets the text shown while no value is chosen. + pub fn placeholder(mut self, placeholder: L) -> Self + where + L: Into, + { + self.placeholder = placeholder.into(); + self + } + + /// Reports the chosen value, when the user activates an option. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(Option, &mut Window, &mut App) + 'static, + { + self.on_change = Some(Rc::new(handler)); + self + } + + /// Overrides the trigger's accessibility label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } +} + +impl Sizable for Select +where + T: Clone + PartialEq + 'static, +{ + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl gpui::Styled for Select +where + T: Clone + PartialEq + 'static, +{ + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Select +where + T: Clone + PartialEq + 'static, +{ + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let metrics = theme.sizes.resolve(self.size); + let border = theme.colors.border; + let ring = theme.colors.ring; + let input = theme.colors.input; + let muted = theme.colors.muted; + let foreground = theme.colors.foreground; + let muted_foreground = theme.colors.muted_foreground; + let radius = theme.radius.control; + let icon_size = metrics.dense_icon_size; + + let label = self + .a11y_label + .clone() + .unwrap_or_else(|| self.placeholder.clone()); + + let open = window.with_element_namespace(self.id.clone(), |window| { + window + .use_keyed_state("select-open", cx, |_, _| false) + .clone() + }); + + let focus = focus_handle(&self.id, window, cx); + + // Set when the popup closes without an activation; the trigger claims + // focus at paint, leaving keyboard activations to drop focus in place. + let refocus_pending = window.with_element_namespace(self.id.clone(), |window| { + window + .use_keyed_state("select-refocus", cx, |_, _| false) + .clone() + }); + + let is_open = *open.read(cx); + let open_for_items = open.clone(); + + let rest_border = if is_open { ring } else { border }; + let hover_border = rest_border; + + let selected_index = self.selected.as_ref().and_then(|value| { + self.options + .iter() + .position(|option| &option.value == value) + }); + + // The trigger's text is fixed at render time; only it moves into the closure. + let trigger_text = selected_index + .and_then(|index| self.options.get(index)) + .map(|option| option.label.clone()) + .unwrap_or_else(|| self.placeholder.clone()); + + let trigger_has_value = self.selected.is_some(); + let trigger_id = self.id.clone(); + let trigger_label = label.clone(); + let trigger_style = self.style; + + let trigger = { + let open = open.clone(); + let focus = focus.clone(); + let refocus_for_trigger = refocus_pending.clone(); + move |_window: &mut Window, _cx: &mut App| { + h_flex() + .id((trigger_id.clone(), "select-trigger")) + .debug_selector(|| "select-trigger".to_string()) + .role(Role::ComboBox) + .aria_label(trigger_label.clone()) + .aria_expanded(is_open) + .track_focus(&focus) + .tab_stop(true) + .focus_visible(move |style| style.border_color(ring)) + .on_key_down({ + let open = open.clone(); + move |event: &KeyDownEvent, _window, cx| { + if !matches!(event.keystroke.key.as_str(), "enter" | "space") { + return; + } + + open.update(cx, |open, _| *open = !*open); + cx.stop_propagation(); + } + }) + .cursor_pointer() + .justify_between() + .gap_3() + .w_full() + .h(metrics.input_height) + .pl(metrics.dense_padding_x) + .pr(metrics.plate_inset * 2.0) + .rounded(radius) + .border_1() + .border_color(rest_border) + .bg(input) + .text_size(metrics.text_size) + .text_color(if trigger_has_value { + foreground + } else { + muted_foreground + }) + .hover(|style| style.bg(muted).border_color(hover_border)) + .child(trigger_text.clone()) + .child( + icon(IconRole::ChevronDown) + .size(icon_size) + .color(muted_foreground), + ) + .child( + canvas(|_, _, _| {}, { + let focus = focus.clone(); + let refocus_pending = refocus_for_trigger.clone(); + move |_, _, window, cx| { + if *refocus_pending.read(cx) { + refocus_pending.update(cx, |pending, _| *pending = false); + window.focus(&focus, cx); + } + } + }) + .absolute() + .inset_0(), + ) + .refine_style(&trigger_style) + .into_any_element() + } + }; + + let select_id = self.id.clone(); + let refocus_for_items = refocus_pending.clone(); + let items = move |_window: &mut Window, _cx: &mut App| { + self.options + .iter() + .enumerate() + .map(|(index, option)| { + let is_selected = self.selected.as_ref() == Some(&option.value); + + let handler = { + let open = open_for_items.clone(); + let refocus_pending = refocus_for_items.clone(); + let value = option.value.clone(); + let on_change = self.on_change.clone(); + move |window: &mut Window, cx: &mut App| { + open.update(cx, |open, _| *open = false); + // Activations own the close, so no focus returns to the trigger. + refocus_pending.update(cx, |pending, _| *pending = false); + if let Some(on_change) = &on_change { + on_change(Some(value.clone()), window, cx); + } + } + }; + + MenuItem::new(option.label.clone()) + .id((select_id.clone(), format!("option-{index}"))) + .when_some(option.icon.clone(), |row, icon| row.icon(icon)) + .checked(is_selected) + .handler(handler) + }) + .collect() + }; + + let menu = Menu::new(self.id) + .open(is_open) + .on_change({ + let open = open.clone(); + let refocus_pending = refocus_pending.clone(); + move |next, _window, cx| { + if !next { + refocus_pending.update(cx, |pending, _| *pending = true); + } + open.update(cx, |open, _| *open = next); + } + }) + .trigger(trigger) + .items(items); + + menu.when_some(selected_index, |menu, index| menu.initial_selection(index)) + } +} diff --git a/crates/ui/src/components/separator.rs b/crates/ui/src/components/separator.rs new file mode 100644 index 0000000..3098dbc --- /dev/null +++ b/crates/ui/src/components/separator.rs @@ -0,0 +1,91 @@ +//! The separator: a hairline rule between sibling content. + +use std::rc::Rc; + +use crate::theme::{ActiveTheme as _, BORDER_WIDTH}; +use crate::utils::StyledExt as _; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, InteractiveElement as _, IntoElement, RenderOnce, StyleRefinement, Styled as _, Window, + div, +}; + +/// Which axis the rule runs along. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SeparatorOrientation { + /// A horizontal rule between stacked content. + #[default] + Horizontal, + /// A vertical rule between side-by-side content. + Vertical, +} + +type DebugSelector = Rc String>; + +/// A hairline rule that divides sibling content. +#[derive(IntoElement)] +#[must_use] +pub struct Separator { + orientation: SeparatorOrientation, + debug_selector: Option, + style: StyleRefinement, +} + +impl Separator { + /// Creates a horizontal rule. + pub fn horizontal() -> Self { + Self { + orientation: SeparatorOrientation::Horizontal, + debug_selector: None, + style: StyleRefinement::default(), + } + } + + /// Creates a vertical rule. + pub fn vertical() -> Self { + Self { + orientation: SeparatorOrientation::Vertical, + debug_selector: None, + style: StyleRefinement::default(), + } + } + + /// Sets which axis the rule runs along. + pub fn orientation(mut self, orientation: SeparatorOrientation) -> Self { + self.orientation = orientation; + self + } + + /// Sets the debug-bounds selector, for headless tests. + pub fn debug_selector(mut self, selector: F) -> Self + where + F: Fn() -> String + 'static, + { + self.debug_selector = Some(Rc::new(selector)); + self + } +} + +impl gpui::Styled for Separator { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Separator { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let border = cx.theme().colors.border; + + div() + .flex_none() + .bg(border) + .when_some(self.debug_selector, |rule, selector| { + rule.debug_selector(move || selector()) + }) + .map(|rule| match self.orientation { + SeparatorOrientation::Horizontal => rule.w_full().h(BORDER_WIDTH), + SeparatorOrientation::Vertical => rule.self_stretch().w(BORDER_WIDTH), + }) + .refine_style(&self.style) + } +} diff --git a/crates/ui/src/components/slider.rs b/crates/ui/src/components/slider.rs new file mode 100644 index 0000000..90ae678 --- /dev/null +++ b/crates/ui/src/components/slider.rs @@ -0,0 +1,312 @@ +use std::cell::Cell; +use std::rc::Rc; + +use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; +use crate::utils::focus_ring; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, Bounds, DispatchPhase, ElementId, InteractiveElement as _, IntoElement, KeyDownEvent, + MouseButton, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, RenderOnce, Role, + SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas, + div, relative, +}; + +use crate::components::common::{Sizable, StyledExt as _, h_flex}; + +/// The change reporter, fired with the next value by click, drag, and arrows. +type ChangeHandler = Rc; + +/// The pointer→value setter shared by the click and drag listeners. +type ValueSetter = Rc; + +/// The arrow-key stride as a share of the range when the slider is continuous. +const FALLBACK_STEP_FRACTION: f32 = 0.05; + +impl Slider { + /// Clamps `value` into `[min, max]` and snaps it to `step` when stepped. + fn constrain(min: f32, max: f32, step: f32, value: f32) -> f32 { + let clamped = value.clamp(min, max); + if step > 0.0 { + (min + ((clamped - min) / step).round() * step).clamp(min, max) + } else { + clamped + } + } +} + +/// A controlled slider over `[min, max]`. +#[derive(IntoElement)] +#[must_use] +pub struct Slider { + id: ElementId, + min: f32, + max: f32, + step: f32, + value: f32, + size: Size, + disabled: bool, + a11y_label: Option, + on_change: Option, + style: StyleRefinement, +} + +impl Slider { + /// Creates a slider over `0..=1` with no stepping, at `value`. + pub fn new(id: I, value: f32) -> Self + where + I: Into, + { + Self { + id: id.into(), + min: 0.0, + max: 1.0, + step: 0.0, + value, + size: Size::default(), + disabled: false, + a11y_label: None, + on_change: None, + style: StyleRefinement::default(), + } + } + + /// Sets the range's lower bound. + pub fn min(mut self, min: f32) -> Self { + self.min = min; + self + } + + /// Sets the range's upper bound. + pub fn max(mut self, max: f32) -> Self { + self.max = max; + self + } + + /// Sets the step; values snap to `min + n * step`. `0` is continuous. + pub fn step(mut self, step: f32) -> Self { + self.step = step; + self + } + + /// Renders the slider inert, unfocusable, and dimmed; disabled always wins. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + + /// Sets the accessibility label, required for an unlabeled slider. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// The change handler, fired with the next value by click, drag, and arrows. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(f32, &mut Window, &mut App) + 'static, + { + self.on_change = Some(Rc::new(handler)); + self + } +} + +impl gpui::Styled for Slider { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl Sizable for Slider { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl RenderOnce for Slider { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let colors = theme.colors; + let ramps = theme.ramps; + let radius = theme.radius; + let metrics = theme.sizes.resolve(self.size); + + let row_height = metrics.icon_size * 2.5; + let track_height = metrics.icon_size / 4.0; + let knob = metrics.indicator_size; + + let value = self.value.clamp(self.min, self.max); + let fraction = if self.max > self.min { + (value - self.min) / (self.max - self.min) + } else { + 0.0 + }; + + let bounds_cell = Rc::new(Cell::new(None::>)); + let focus_handle = crate::utils::focus_handle(&self.id, window, cx); + + let dragging = + window.use_keyed_state((self.id.clone(), "slider-dragging"), cx, |_, _| false); + + let set_value: ValueSetter = { + let bounds_cell = bounds_cell.clone(); + let on_change = self.on_change.clone(); + let (min, max, step) = (self.min, self.max, self.step); + + Rc::new(move |x: Pixels, window: &mut Window, cx: &mut App| { + if let (Some(bounds), Some(on_change)) = (bounds_cell.get(), on_change.as_ref()) + && bounds.size.width > Pixels::ZERO + { + let fraction = ((x - bounds.origin.x) / bounds.size.width).clamp(0.0, 1.0); + on_change( + Self::constrain(min, max, step, min + fraction * (max - min)), + window, + cx, + ); + } + }) + }; + + let down_dragging = dragging.clone(); + let down_set_value = set_value.clone(); + let disabled = self.disabled; + + h_flex() + .id(self.id) + .relative() + .w_full() + .h(row_height) + .refine_style(&self.style) + .role(Role::Slider) + .when_some(self.a11y_label.clone(), |slider, label| { + slider.aria_label(label) + }) + .aria_numeric_value(f64::from(value)) + .aria_min_numeric_value(f64::from(self.min)) + .aria_max_numeric_value(f64::from(self.max)) + .when(self.disabled, |slider| slider.opacity(DISABLED_OPACITY)) + .when(!self.disabled, |slider| { + slider + .track_focus(&focus_handle) + .tab_stop(true) + .focus_visible(|style| style.shadow(focus_ring(colors.ring))) + .on_mouse_down(MouseButton::Left, move |event, window, cx| { + down_dragging.update(cx, |dragging, _| *dragging = true); + down_set_value(event.position.x, window, cx); + }) + .on_key_down(move |event: &KeyDownEvent, window, cx| { + if !focus_handle.contains_focused(window, cx) { + return; + } + + let single_step = if self.step > 0.0 { + self.step + } else { + (self.max - self.min) * FALLBACK_STEP_FRACTION + }; + + let next = match event.keystroke.key.as_str() { + "left" | "down" => Some(value - single_step), + "right" | "up" => Some(value + single_step), + "home" => Some(self.min), + "end" => Some(self.max), + _ => None, + }; + + if let Some(next) = next + && let Some(on_change) = self.on_change.as_ref() + { + on_change( + Self::constrain(self.min, self.max, self.step, next), + window, + cx, + ); + cx.stop_propagation(); + } + }) + }) + .child( + canvas( + { + let bounds_cell = bounds_cell.clone(); + move |bounds, _, _| bounds_cell.set(Some(bounds)) + }, + { + let dragging = dragging.clone(); + let set_value = set_value.clone(); + move |_, _, window, _cx| { + if disabled { + return; + } + window.on_mouse_event({ + let dragging = dragging.clone(); + let set_value = set_value.clone(); + move |event: &MouseMoveEvent, phase, window, cx| { + if phase == DispatchPhase::Bubble + && *dragging.read(cx) + && event.pressed_button == Some(MouseButton::Left) + { + set_value(event.position.x, window, cx); + } + } + }); + window.on_mouse_event({ + let dragging = dragging.clone(); + move |event: &MouseUpEvent, phase, _window, cx| { + if phase == DispatchPhase::Bubble + && event.button == MouseButton::Left + { + dragging.update(cx, |dragging, _| *dragging = false); + } + } + }); + } + }, + ) + .absolute() + .inset_0(), + ) + .child( + div() + .absolute() + .left_0() + .top((row_height - track_height) / 2.0) + .h(track_height) + .w_full() + .rounded(radius.full) + .bg(colors.border), + ) + .child( + div() + .absolute() + .left_0() + .top((row_height - track_height) / 2.0) + .h(track_height) + .w(relative(fraction)) + .rounded(radius.full) + .bg(ramps.primary.base), + ) + .child( + h_flex() + .absolute() + .left_0() + .top_0() + .h_full() + .w(relative(fraction)) + .justify_end() + .items_center() + .child( + div() + .size(knob) + .flex_none() + .rounded(radius.full) + .bg(colors.primary_foreground) + .border_1() + .border_color(colors.border) + .mr(-knob / 2.0), + ), + ) + } +} diff --git a/crates/ui/src/components/speech.rs b/crates/ui/src/components/speech.rs new file mode 100644 index 0000000..6c52e40 --- /dev/null +++ b/crates/ui/src/components/speech.rs @@ -0,0 +1,1074 @@ +//! Dictation: a state that turns speech into text, a button that drives the +//! session, and a waveform that shows what the microphone hears. +//! +//! The application owns where the text goes: subscribe to [`SpeechEvent`] and +//! insert the final transcript where it belongs. Recognition and capture are +//! both replaceable seams; without further setup the state uses [`Microphone`] +//! and has no recognizer, so [`SpeechButton`] renders nothing until the +//! application provides one. + +use std::time::Duration; + +#[cfg(not(target_arch = "wasm32"))] +use std::sync::{Arc, Mutex}; + +use crate::icons::{IconRole, icon}; +use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, SPEECH_WAVEFORM_WIDTH, Size}; +use crate::utils::focus_ring; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, Context, ElementId, Entity, EventEmitter, InteractiveElement as _, IntoElement, + ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, + StyleRefinement, Styled, Subscription, Task, WeakEntity, Window, div, relative, +}; + +use crate::components::common::{Sizable, StyledExt as _, h_flex}; +use crate::components::spinner::{Spinner, SpinnerVariant}; +use crate::components::tooltip::Tooltip; + +/// One input-level entry per this much of captured audio. +const LEVEL_BUCKET: Duration = Duration::from_millis(80); +/// The level history a waveform draws, one entry per [`LEVEL_BUCKET`]. +const MAX_LEVELS: usize = 128; +/// Amplitude below which background noise reads as silence. +const NOISE_GATE: f32 = 0.03; +/// How much of a full-scale peak maps to a full bar. +const LEVEL_SCALE: f32 = 0.5; +/// How fast a peak falls back before the next bucket's level. +const LEVEL_FALL: f32 = 0.72; +/// How long a session waits for the recognizer's final result once stopped. +const DEFAULT_STOP_TIMEOUT: Duration = Duration::from_secs(3); +/// The bars [`SpeechButton`] shows while capturing. +const BUTTON_BARS: usize = 4; +/// The share of the bar height a silent bar keeps, so silence reads as a dot. +const DOT_HEIGHT: f32 = 0.14; +/// The bar height reduced motion holds at. +const STILL_HEIGHT: f32 = 0.35; + +/// The PCM layout a recognizer consumes: interleaved 16-bit samples. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AudioFormat { + sample_rate: u32, + channels: u8, +} + +impl AudioFormat { + /// Creates a format at the given sample rate and channel count. + pub fn new(sample_rate: u32, channels: u8) -> Self { + Self { + sample_rate, + channels: channels.max(1), + } + } + + /// Samples per second per channel. + pub fn sample_rate(&self) -> u32 { + self.sample_rate + } + + /// The number of interleaved channels. + pub fn channels(&self) -> u8 { + self.channels + } +} + +impl Default for AudioFormat { + /// 16 kHz mono, what most recognizers consume. + fn default() -> Self { + Self::new(16_000, 1) + } +} + +/// Why a dictation session failed. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SpeechError { + message: SharedString, +} + +impl SpeechError { + /// A recognizer failed to start or to report a result. + pub fn recognizer(error: E) -> Self + where + E: std::fmt::Display, + { + Self::new(format!("Speech recognizer error: {error}")) + } + + /// Audio capture failed to start or to deliver samples. + pub fn input(error: E) -> Self + where + E: std::fmt::Display, + { + Self::new(format!("Audio input error: {error}")) + } + + fn new(message: String) -> Self { + Self { + message: message.into(), + } + } +} + +impl std::fmt::Display for SpeechError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for SpeechError {} + +/// Turns captured audio into text. +pub trait SpeechRecognizer { + /// The PCM layout [`RecognitionSession::push_audio`] delivers. + fn audio_format(&self) -> AudioFormat { + AudioFormat::default() + } + + /// Whether the recognizer can run right now. + fn is_available(&self, _cx: &App) -> bool { + true + } + + /// Opens a session. + fn start( + &self, + sink: SpeechSink, + cx: &mut App, + ) -> Result, SpeechError>; +} + +/// A recognition session opened by [`SpeechRecognizer::start`]. +pub trait RecognitionSession { + /// Delivers interleaved 16-bit PCM in the recognizer's [`SpeechRecognizer::audio_format`]. + fn push_audio(&mut self, samples: &[i16], cx: &mut App); + + /// The user stopped talking. + fn finish(&mut self, cx: &mut App); +} + +/// Reports recognition results for the active session. +#[derive(Clone)] +pub struct SpeechSink { + state: WeakEntity, + generation: u64, +} + +impl SpeechSink { + /// The recognizer accepts audio; the status moves to `Recording`. + pub fn ready(&self, cx: &mut App) { + self.defer(cx, |state, cx| state.mark_ready(cx)); + } + + /// Replaces the hypothesis of the phrase being spoken. + pub fn hypothesis(&self, text: T, cx: &mut App) + where + T: Into + 'static, + { + self.defer(cx, move |state, cx| { + state.report_hypothesis(text.into(), cx) + }); + } + + /// Commits a recognized phrase to the transcript. + pub fn phrase(&self, text: T, cx: &mut App) + where + T: Into + 'static, + { + self.defer(cx, move |state, cx| state.report_phrase(text.into(), cx)); + } + + /// Ends the session normally with what has been recognized so far. + pub fn finish(&self, cx: &mut App) { + self.defer(cx, |state, cx| state.report_finish(cx)); + } + + /// Ends the session with a failure. + pub fn error(&self, error: SpeechError, cx: &mut App) { + self.defer(cx, move |state, cx| state.report_error(error, cx)); + } + + fn defer(&self, cx: &mut App, apply: F) + where + F: FnOnce(&mut SpeechState, &mut Context) + 'static, + { + let state = self.state.clone(); + let generation = self.generation; + cx.defer(move |cx| { + // A report arriving after the state dropped is a normal lifecycle outcome. + if let Some(state) = state.upgrade() { + state.update(cx, |state, cx| state.apply(generation, cx, apply)); + } + }); + } +} + +/// Captures audio for a session. +pub trait AudioInput { + fn start( + &self, + format: AudioFormat, + sink: AudioSink, + cx: &mut App, + ) -> Result; +} + +/// Delivers captured audio to the active session. +#[derive(Clone)] +pub struct AudioSink { + state: WeakEntity, + generation: u64, +} + +impl AudioSink { + /// Pushes interleaved 16-bit PCM in the recognizer's format. + pub fn push(&self, samples: S, cx: &mut App) + where + S: Into> + 'static, + { + let state = self.state.clone(); + let generation = self.generation; + cx.defer(move |cx| { + // Audio arriving after the state dropped is a normal lifecycle outcome. + if let Some(state) = state.upgrade() { + state.update(cx, |state, cx| { + state.receive_audio(generation, samples.into(), cx) + }); + } + }); + } +} + +/// Where a dictation session is in its life. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SpeechStatus { + /// No session is running. + #[default] + Idle, + /// Audio is captured while the recognizer connects. + Connecting, + /// Audio is captured and recognized. + Recording, + /// Capture stopped; waiting for the final result. + Stopping, +} + +impl SpeechStatus { + /// True for every status but `Idle`. + pub fn is_active(self) -> bool { + self != Self::Idle + } + + /// True while audio is captured. + pub fn is_capturing(self) -> bool { + matches!(self, Self::Connecting | Self::Recording) + } +} + +/// What a session reports. +#[derive(Clone, Debug, PartialEq)] +pub enum SpeechEvent { + /// A session started and audio is being captured. + Started, + /// The transcript changed while the user speaks. + Partial(SharedString), + /// The session ended normally. The text may be empty. + Final(SharedString), + /// The session was cancelled and its transcript discarded. + Cancelled, + /// The session failed and ended. + Error(SpeechError), +} + +/// Owns a dictation session. +pub struct SpeechState { + recognizer: Option>, + input: Option>, + stop_timeout: Duration, + format: AudioFormat, + status: SpeechStatus, + phrases: Vec, + hypothesis: Option, + levels: Vec, + bucket: Vec, + session: Option>, + capture: Option, + generation: u64, + stop_task: Option>, +} + +impl EventEmitter for SpeechState {} + +impl SpeechState { + /// Creates an idle state without a recognizer or input. + pub fn new(_cx: &mut Context) -> Self { + Self { + recognizer: None, + input: None, + stop_timeout: DEFAULT_STOP_TIMEOUT, + format: AudioFormat::default(), + status: SpeechStatus::Idle, + phrases: Vec::new(), + hypothesis: None, + levels: Vec::new(), + bucket: Vec::new(), + session: None, + capture: None, + generation: 0, + stop_task: None, + } + } + + /// Sets the recognizer every session runs with. + pub fn recognizer(mut self, recognizer: R) -> Self + where + R: SpeechRecognizer + 'static, + { + self.recognizer = Some(Box::new(recognizer)); + self + } + + /// Sets the audio source every session captures with. + pub fn input(mut self, input: I) -> Self + where + I: AudioInput + 'static, + { + self.input = Some(Box::new(input)); + self + } + + /// How long `stop` waits for the recognizer's final result. + pub fn stop_timeout(mut self, timeout: Duration) -> Self { + self.stop_timeout = timeout; + self + } + + /// Where the session is. + pub fn status(&self) -> SpeechStatus { + self.status + } + + /// Whether a session can run on this platform. + pub fn has_recognizer(&self) -> bool { + self.recognizer.is_some() && (self.input.is_some() || Self::has_default_input()) + } + + /// Whether the recognizer reports itself ready to run. + pub fn is_available(&self, cx: &App) -> bool { + self.recognizer + .as_ref() + .is_some_and(|recognizer| recognizer.is_available(cx)) + } + + /// The whole transcript so far. + pub fn transcript(&self) -> SharedString { + let mut transcript = String::new(); + + for phrase in &self.phrases { + transcript.push_str(phrase); + } + + if let Some(hypothesis) = &self.hypothesis { + transcript.push_str(hypothesis); + } + + transcript.into() + } + + /// The recent input levels in `0.0..=1.0`, oldest first, one per 80 ms of audio. + pub fn levels(&self) -> &[f32] { + &self.levels + } + + /// Starts a session. Does nothing while one is running. + pub fn start(&mut self, cx: &mut Context) { + if self.status.is_active() { + return; + } + + self.generation = self.generation.wrapping_add(1); + let generation = self.generation; + + let Some(recognizer) = self.recognizer.as_ref() else { + self.fail("No speech recognizer is set up on this platform.", cx); + return; + }; + + if !recognizer.is_available(cx) { + self.fail("The speech recognizer is not available right now.", cx); + return; + } + + self.format = recognizer.audio_format(); + let sink = SpeechSink { + state: cx.entity().downgrade(), + generation, + }; + + let session = match recognizer.start(sink, cx) { + Ok(session) => session, + Err(error) => { + self.fail(error, cx); + return; + } + }; + + let audio_sink = AudioSink { + state: cx.entity().downgrade(), + generation, + }; + + let capture = match self.capture_input(self.format, audio_sink, cx) { + Ok(capture) => capture, + Err(error) => { + self.fail(error, cx); + return; + } + }; + + self.session = Some(session); + self.capture = Some(capture); + self.phrases.clear(); + self.hypothesis = None; + self.levels.clear(); + self.bucket.clear(); + self.status = SpeechStatus::Connecting; + cx.emit(SpeechEvent::Started); + cx.notify(); + } + + /// Ends the session and emits `Final` once the result is in, at the latest after the stop timeout. + pub fn stop(&mut self, cx: &mut Context) { + if !self.status.is_capturing() { + return; + } + self.capture = None; + self.status = SpeechStatus::Stopping; + cx.notify(); + + let generation = self.generation; + let stop_timeout = self.stop_timeout; + + if let Some(mut session) = self.session.take() { + session.finish(cx); + } + + self.stop_task = Some(cx.spawn(async move |this, cx| { + cx.background_executor().timer(stop_timeout).await; + // The state may drop while the timeout is still pending. + this.update(cx, |state, cx| state.apply_stop_timeout(generation, cx)) + .ok(); + })); + } + + /// Cancels the session at once and discards its transcript. + pub fn cancel(&mut self, cx: &mut Context) { + if !self.status.is_active() { + return; + } + self.capture = None; + self.session = None; + self.stop_task = None; + self.reset(); + cx.emit(SpeechEvent::Cancelled); + cx.notify(); + } + + /// `start` when idle, otherwise `stop`. + pub fn toggle(&mut self, cx: &mut Context) { + if self.status == SpeechStatus::Idle { + self.start(cx); + } else { + self.stop(cx); + } + } + + fn has_default_input() -> bool { + cfg!(not(target_arch = "wasm32")) + } + + #[cfg(not(target_arch = "wasm32"))] + fn default_input() -> Option> { + Some(Box::new(Microphone)) + } + + #[cfg(target_arch = "wasm32")] + fn default_input() -> Option> { + None + } + + fn capture_input( + &self, + format: AudioFormat, + sink: AudioSink, + cx: &mut App, + ) -> Result { + if let Some(input) = &self.input { + return input.start(format, sink, cx); + } + match Self::default_input() { + Some(input) => input.start(format, sink, cx), + None => Err(SpeechError::input( + "No audio input is available on this platform; provide one with `SpeechState::input`.", + )), + } + } + + fn reset(&mut self) { + self.generation = self.generation.wrapping_add(1); + self.status = SpeechStatus::Idle; + self.phrases.clear(); + self.hypothesis = None; + self.levels.clear(); + self.bucket.clear(); + } + + /// Ends a failed start without ever emitting `Started`. + fn fail(&mut self, message: M, cx: &mut Context) + where + M: std::fmt::Display, + { + self.capture = None; + self.session = None; + self.reset(); + cx.emit(SpeechEvent::Error(SpeechError::new(message.to_string()))); + cx.notify(); + } + + /// Ends the session normally, emitting `Final` with the transcript so far. + fn finalize(&mut self, cx: &mut Context) { + self.capture = None; + self.session = None; + self.stop_task = None; + let transcript = self.transcript(); + self.reset(); + cx.emit(SpeechEvent::Final(transcript)); + cx.notify(); + } + + fn apply(&mut self, generation: u64, cx: &mut Context, apply: F) + where + F: FnOnce(&mut Self, &mut Context), + { + if self.generation != generation { + return; + } + apply(self, cx); + } + + fn mark_ready(&mut self, cx: &mut Context) { + if self.status == SpeechStatus::Connecting { + self.status = SpeechStatus::Recording; + cx.notify(); + } + } + + fn report_hypothesis(&mut self, text: SharedString, cx: &mut Context) { + if !self.status.is_active() { + return; + } + self.hypothesis = Some(text); + cx.emit(SpeechEvent::Partial(self.transcript())); + cx.notify(); + } + + fn report_phrase(&mut self, text: SharedString, cx: &mut Context) { + if !self.status.is_active() { + return; + } + self.phrases.push(text); + self.hypothesis = None; + cx.emit(SpeechEvent::Partial(self.transcript())); + cx.notify(); + } + + fn report_finish(&mut self, cx: &mut Context) { + if self.status.is_active() { + self.finalize(cx); + } + } + + fn report_error(&mut self, error: SpeechError, cx: &mut Context) { + if !self.status.is_active() { + return; + } + self.capture = None; + self.session = None; + self.stop_task = None; + self.reset(); + cx.emit(SpeechEvent::Error(error)); + cx.notify(); + } + + fn apply_stop_timeout(&mut self, generation: u64, cx: &mut Context) { + if self.generation == generation && self.status == SpeechStatus::Stopping { + self.finalize(cx); + } + } + + fn receive_audio(&mut self, generation: u64, samples: Vec, cx: &mut Context) { + if self.generation != generation || !self.status.is_capturing() { + return; + } + if let Some(session) = self.session.as_mut() { + session.push_audio(&samples, cx); + } + if self.update_levels(&samples) { + cx.notify(); + } + } + + /// Fills one level per bucket; returns whether any level was recorded. + fn update_levels(&mut self, samples: &[i16]) -> bool { + let channels = self.format.channels() as usize; + let bucket_len = ((self.format.sample_rate() as f32 * LEVEL_BUCKET.as_secs_f32()) as usize + * channels) + .max(channels); + self.bucket.extend_from_slice(samples); + + let mut recorded = false; + while self.bucket.len() >= bucket_len { + let peak = self + .bucket + .drain(..bucket_len) + .map(|sample| sample.unsigned_abs() as f32 / i16::MAX as f32) + .fold(0.0f32, f32::max); + let previous = self.levels.last().copied().unwrap_or(0.0); + let level = ((peak - NOISE_GATE).max(0.0) / LEVEL_SCALE) + .min(1.0) + .max(previous * LEVEL_FALL); + self.levels.push(level); + if self.levels.len() > MAX_LEVELS { + self.levels.remove(0); + } + recorded = true; + } + recorded + } +} + +/// Starts and stops a dictation session. +#[derive(IntoElement)] +#[must_use] +pub struct SpeechButton { + speech: Entity, + size: Size, + disabled: bool, + show_when_unsupported: bool, + style: StyleRefinement, +} + +impl SpeechButton { + /// Creates the button driving the given state. + pub fn new(speech: &Entity) -> Self { + Self { + speech: speech.clone(), + size: Size::default(), + disabled: false, + show_when_unsupported: false, + style: StyleRefinement::default(), + } + } + + /// Renders the button disabled. + pub fn show_when_unsupported(mut self, show: bool) -> Self { + self.show_when_unsupported = show; + self + } + + /// Disables the button for application reasons, such as a readonly field. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } +} + +impl gpui::Styled for SpeechButton { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl Sizable for SpeechButton { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl RenderOnce for SpeechButton { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let unsupported = !self.speech.read(cx).has_recognizer(); + if unsupported && !self.show_when_unsupported { + return div().into_any_element(); + } + + let (status, unavailable, capturing, reduce_motion, bars) = { + let state = self.speech.read(cx); + let status = state.status(); + let levels = state.levels(); + let tail_start = levels.len().saturating_sub(BUTTON_BARS); + ( + status, + unsupported || !state.is_available(cx), + status.is_capturing(), + cx.theme().accessibility.reduce_motion, + levels[tail_start..].to_vec(), + ) + }; + + let stopping = status == SpeechStatus::Stopping; + let disabled = self.disabled || unavailable || stopping; + + let theme = cx.theme(); + let colors = theme.colors; + let metrics = theme.sizes.resolve(self.size); + let id: ElementId = ("speech-button", self.speech.entity_id()).into(); + + let group = SharedString::from(format!( + "speech-button-{}", + self.speech.entity_id().as_u64() + )); + + let label: SharedString = if unavailable { + "Dictation is unavailable".into() + } else if capturing { + "Stop dictation".into() + } else { + "Start dictation".into() + }; + + let foreground = colors.foreground; + + h_flex() + .id(id.clone()) + .group(group.clone()) + .role(Role::Button) + .justify_center() + .h(metrics.control_height) + .px(metrics.dense_padding_x) + .gap_0p5() + .rounded(theme.radius.control) + .text_color(foreground) + .when(capturing, |button| button.bg(colors.muted)) + .refine_style(&self.style) + .when(disabled, |button| button.opacity(DISABLED_OPACITY)) + .aria_label(label.clone()) + .tooltip(Tooltip::text(label)) + .child(if stopping { + Spinner::new(("speech-spinner", self.speech.entity_id())) + .with_size(self.size) + .variant(SpinnerVariant::Icon) + .color(foreground) + .into_any_element() + } else if capturing { + let bar_height = |level: f32| { + if reduce_motion { + STILL_HEIGHT + } else { + DOT_HEIGHT + (1.0 - DOT_HEIGHT) * level + } + }; + h_flex() + .id(("speech-bars", self.speech.entity_id())) + .h(metrics.icon_size) + .items_end() + .gap_0p5() + .children(bars.iter().map(|level| { + div() + .flex_none() + .w(metrics.dense_icon_size / 4.) + .h(relative(bar_height(*level))) + .rounded(theme.radius.full) + .bg(theme.ramps.primary.base) + })) + .group_hover(group.clone(), |style| style.invisible()) + .into_any_element() + } else { + icon(IconRole::Microphone) + .size(metrics.icon_size) + .color(foreground) + .into_any_element() + }) + .when(capturing, |button| { + button.child( + div() + .invisible() + .group_hover(group, |style| style.visible()) + .child( + icon(IconRole::Stop) + .size(metrics.icon_size) + .color(foreground), + ), + ) + }) + .when(!disabled, |button| { + let speech = self.speech.clone(); + button + .cursor_pointer() + .focusable() + .tab_stop(true) + .hover(move |style| style.bg(colors.muted_hover)) + .active(move |style| style.bg(theme.ramps.secondary.pressed)) + .focus_visible(move |style| style.shadow(focus_ring(colors.ring))) + .on_click(move |_, _, cx| speech.update(cx, |state, cx| state.toggle(cx))) + }) + .into_any_element() + } +} + +/// A live waveform of what a dictation session hears. +#[derive(IntoElement)] +#[must_use] +pub struct SpeechWaveform { + speech: Entity, + size: Size, + style: gpui::StyleRefinement, +} + +impl SpeechWaveform { + /// Creates the waveform drawn from the given state. + pub fn new(speech: &Entity) -> Self { + Self { + speech: speech.clone(), + size: Size::default(), + style: gpui::StyleRefinement::default(), + } + } +} + +impl Sizable for SpeechWaveform { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl Styled for SpeechWaveform { + fn style(&mut self) -> &mut gpui::StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for SpeechWaveform { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + if !self.speech.read(cx).status().is_capturing() { + return div().into_any_element(); + } + let (levels, reduce_motion) = { + let state = self.speech.read(cx); + ( + state.levels().to_vec(), + cx.theme().accessibility.reduce_motion, + ) + }; + + let theme = cx.theme(); + let colors = theme.colors; + let metrics = theme.sizes.resolve(self.size); + let bar_height = |level: f32| { + if reduce_motion { + STILL_HEIGHT + } else { + DOT_HEIGHT + (1.0 - DOT_HEIGHT) * level + } + }; + + h_flex() + .id(("speech-waveform", self.speech.entity_id())) + .items_end() + .justify_end() + .gap_0p5() + .h(metrics.icon_size) + .w(SPEECH_WAVEFORM_WIDTH) + .overflow_hidden() + .children(levels.iter().map(|level| { + div() + .flex_none() + .w(metrics.dense_icon_size / 4.) + .h(relative(bar_height(*level))) + .rounded(theme.radius.full) + .bg(if *level <= 0.0 { + colors.muted_foreground + } else { + theme.ramps.primary.base + }) + })) + .refine_style(&self.style) + .into_any_element() + } +} + +#[cfg(not(target_arch = "wasm32"))] +/// The built-in input. +pub struct Microphone; + +#[cfg(not(target_arch = "wasm32"))] +impl AudioInput for Microphone { + fn start( + &self, + format: AudioFormat, + sink: AudioSink, + cx: &mut App, + ) -> Result { + use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; + + let host = cpal::default_host(); + let device = host + .default_input_device() + .ok_or_else(|| SpeechError::input("No microphone is connected."))?; + + let config = device.default_input_config().map_err(SpeechError::input)?; + let stream_config = cpal::StreamConfig { + channels: config.channels(), + sample_rate: config.sample_rate(), + buffer_size: cpal::BufferSize::Default, + }; + let device_channels = stream_config.channels.max(1) as usize; + + let (sender, receiver) = flume::unbounded::>(); + let converter = Arc::new(Mutex::new(Resampler::new( + config.sample_rate() as f32 / format.sample_rate().max(1) as f32, + ))); + let error_handler = |error| log::warn!("microphone stream error: {error}"); + + let stream = match config.sample_format() { + cpal::SampleFormat::F32 => device.build_input_stream( + stream_config, + Microphone::callback( + |sample: f32| sample, + device_channels, + format, + converter.clone(), + sender.clone(), + ), + error_handler, + None, + ), + cpal::SampleFormat::I16 => device.build_input_stream( + stream_config, + Microphone::callback( + |sample: i16| sample as f32 / i16::MAX as f32, + device_channels, + format, + converter.clone(), + sender.clone(), + ), + error_handler, + None, + ), + cpal::SampleFormat::U16 => device.build_input_stream( + stream_config, + Microphone::callback( + |sample: u16| (sample as f32 - u16::MAX as f32 / 2.0) / (u16::MAX as f32 / 2.0), + device_channels, + format, + converter.clone(), + sender.clone(), + ), + error_handler, + None, + ), + sample_format => { + return Err(SpeechError::input(format!( + "Unsupported microphone sample format: {sample_format}" + ))); + } + } + .map_err(SpeechError::input)?; + + stream.play().map_err(SpeechError::input)?; + + let task = cx.spawn(async move |cx| { + while let Ok(samples) = receiver.recv_async().await { + cx.update(|cx| sink.push(samples, cx)); + } + }); + + Ok(Subscription::new(move || { + drop(stream); + drop(task); + })) + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Microphone { + fn callback( + to_sample: fn(T) -> f32, + device_channels: usize, + format: AudioFormat, + converter: Arc>, + sender: flume::Sender>, + ) -> impl FnMut(&[T], &cpal::InputCallbackInfo) + Send + 'static + where + T: Copy + 'static, + { + move |data: &[T], _: &cpal::InputCallbackInfo| { + let Ok(mut converter) = converter.lock() else { + return; + }; + + let mut mono = Vec::with_capacity(data.len() / device_channels + 1); + for frame in data.chunks(device_channels) { + let total: f32 = frame.iter().map(|sample| to_sample(*sample)).sum(); + mono.push(total / frame.len() as f32); + } + + let mut resampled = Vec::with_capacity(mono.len()); + converter.resample(&mono, &mut resampled); + + let channels = format.channels() as usize; + let mut samples = Vec::with_capacity(resampled.len() * channels); + + for value in resampled { + let sample = (value * i16::MAX as f32) + .round() + .clamp(i16::MIN as f32, i16::MAX as f32) as i16; + for _ in 0..channels { + samples.push(sample); + } + } + + if sender.send(samples).is_err() { + log::debug!("speech session closed before its audio arrived"); + } + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +/// A minimal linear resampler that carries its phase across callbacks. +struct Resampler { + step: f32, + phase: f32, + last: Option, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Resampler { + fn new(step: f32) -> Self { + Self { + step, + phase: 0.0, + last: None, + } + } + + fn resample(&mut self, input: &[f32], output: &mut Vec) { + if input.is_empty() { + return; + } + let mut phase = self.phase; + while phase < input.len() as f32 { + let index = (phase as usize).min(input.len() - 1); + let fraction = phase - index as f32; + let previous = if index == 0 { + self.last.unwrap_or(input[0]) + } else { + input[index - 1] + }; + output.push(previous + (input[index] - previous) * fraction); + phase += self.step; + } + self.phase = phase - input.len() as f32; + self.last = Some(input[input.len() - 1]); + } +} diff --git a/crates/ui/src/components/spinner.rs b/crates/ui/src/components/spinner.rs new file mode 100644 index 0000000..b57df4e --- /dev/null +++ b/crates/ui/src/components/spinner.rs @@ -0,0 +1,299 @@ +//! The loading ring: spins for unknown work, or holds a determinate arc. + +use std::cell::Cell; +use std::f32::consts::{PI, TAU}; +use std::rc::Rc; + +use crate::icons::{Icon, IconRole, icon}; +use crate::theme::{ActiveTheme as _, SPINNER_PERIOD, Size}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + Animation, AnimationElement, AnimationExt as _, App, Canvas, ElementId, Hsla, + InteractiveElement as _, IntoElement, ParentElement as _, Path, PathBuilder, Pixels, Point, + RenderOnce, Role, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, + Window, canvas, div, point, px, +}; + +use crate::components::common::{Sizable, StyledExt as _}; + +/// The share of the circle the spinning arc paints. +const SPIN_SWEEP: f32 = 0.75; +/// The ring stroke as a share of the side. +const RING_STROKE: f32 = 0.125; + +/// The visual language of a [`Spinner`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SpinnerVariant { + /// The painted arc ring. + #[default] + Ring, + /// The platform loader glyph, rotated. + Icon, +} + +/// A loading ring. +#[derive(IntoElement)] +#[must_use] +pub struct Spinner { + id: ElementId, + value: Option, + variant: SpinnerVariant, + size: Size, + color: Option, + a11y_label: Option, + style: StyleRefinement, +} + +impl Spinner { + /// Creates a spinning ring. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + value: None, + variant: SpinnerVariant::default(), + size: Size::default(), + color: None, + a11y_label: None, + style: StyleRefinement::default(), + } + } + + /// Overrides the arc color, for accent-filled surfaces. + pub fn color(mut self, color: Hsla) -> Self { + self.color = Some(color); + self + } + + /// Sets the spinner's visual language. + pub fn variant(mut self, variant: SpinnerVariant) -> Self { + self.variant = variant; + self + } + + /// Paints a determinate arc at `value` (`0..=1`) instead of spinning. + pub fn value(mut self, value: f32) -> Self { + self.value = Some(value); + self + } + + /// Sets the accessibility label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } +} + +impl gpui::Styled for Spinner { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl Sizable for Spinner { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl RenderOnce for Spinner { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let side = theme.sizes.resolve(self.size).icon_size; + let stroke = side * RING_STROKE; + let track = theme.colors.border; + let accent = self.color.unwrap_or(theme.ramps.primary.base); + let value = self.value.map(|value| value.clamp(0.0, 1.0)); + + div() + .id(self.id) + .flex_none() + .size(side) + .refine_style(&self.style) + .role(Role::ProgressIndicator) + .when_some(self.a11y_label, |spinner, label| spinner.aria_label(label)) + .when_some(value, |spinner, value| { + spinner + .aria_numeric_value(f64::from(value)) + .aria_min_numeric_value(0.0) + .aria_max_numeric_value(1.0) + }) + .child(match (self.variant, value) { + (SpinnerVariant::Ring, Some(value)) => { + determinate_ring(side, stroke, track, accent, value).into_any_element() + } + (SpinnerVariant::Ring, None) => { + spinning_ring(side, stroke, accent).into_any_element() + } + (SpinnerVariant::Icon, Some(_)) => icon(IconRole::Loader) + .size(side) + .color(accent) + .into_any_element(), + (SpinnerVariant::Icon, None) => spinning_icon(side, accent).into_any_element(), + }) + } +} + +fn determinate_ring( + side: Pixels, + stroke: Pixels, + track: Hsla, + accent: Hsla, + value: f32, +) -> Canvas<()> { + canvas( + |_, _, _| (), + move |bounds, (), window, _| { + let center = bounds.center(); + let radius = bounds.size.width / 2.0 - stroke / 2.0; + paint_circle(center, radius, stroke, track, window); + if value >= 1.0 { + paint_circle(center, radius, stroke, accent, window); + } else if value > 0.0 + && let Some(path) = arc_path(center, radius, stroke, 0.0, value * TAU) + { + window.paint_path(path, accent); + } + }, + ) + .size(side) +} + +fn spinning_ring(side: Pixels, stroke: Pixels, accent: Hsla) -> AnimationElement> { + let angle = Rc::new(Cell::new(0.0)); + let spun = angle.clone(); + canvas( + |_, _, _| (), + move |bounds, (), window, _| { + let radius = bounds.size.width / 2.0 - stroke / 2.0; + if let Some(path) = arc_path( + bounds.center(), + radius, + stroke, + spun.get(), + SPIN_SWEEP * TAU, + ) { + window.paint_path(path, accent); + } + }, + ) + .size(side) + .with_animation( + "spin", + Animation::new(SPINNER_PERIOD).repeat().with_max_fps(60.), + move |ring, delta| { + angle.set(delta * TAU); + ring + }, + ) +} + +fn spinning_icon(side: Pixels, accent: Hsla) -> Icon { + icon(IconRole::Loader) + .size(side) + .color(accent) + .with_rotation_animation(SPINNER_PERIOD) +} + +fn paint_circle( + center: Point, + radius: Pixels, + stroke: Pixels, + color: Hsla, + window: &mut Window, +) { + if let Some(path) = circle_path(center, radius, stroke) { + window.paint_path(path, color); + } +} + +/// A point on the ring at `angle`, clockwise from 12 o'clock. +fn ring_point(center: Point, radius: Pixels, angle: f32) -> Point { + point( + center.x + radius * angle.sin(), + center.y - radius * angle.cos(), + ) +} + +/// A stroked arc from `start`, sweeping clockwise by `sweep` radians. +fn arc_path( + center: Point, + radius: Pixels, + stroke: Pixels, + start: f32, + sweep: f32, +) -> Option { + let mut builder = PathBuilder::stroke(stroke); + builder.move_to(ring_point(center, radius, start)); + builder.arc_to( + point(radius, radius), + px(0.), + sweep > PI, + true, + ring_point(center, radius, start + sweep), + ); + builder.build().ok() +} + +/// A stroked full circle; `None` on degenerate geometry. +fn circle_path(center: Point, radius: Pixels, stroke: Pixels) -> Option { + let mut builder = PathBuilder::stroke(stroke); + builder.move_to(ring_point(center, radius, 0.0)); + builder.arc_to( + point(radius, radius), + px(0.), + false, + true, + ring_point(center, radius, PI), + ); + builder.arc_to( + point(radius, radius), + px(0.), + false, + true, + ring_point(center, radius, TAU), + ); + builder.build().ok() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::f32::consts::FRAC_PI_2; + + #[test] + fn ring_points_run_clockwise_from_twelve() { + let center = point(px(10.0), px(20.0)); + let radius = px(4.0); + assert_eq!(ring_point(center, radius, 0.0), point(px(10.0), px(16.0))); + assert_eq!( + ring_point(center, radius, FRAC_PI_2), + point(px(14.0), px(20.0)) + ); + assert_eq!(ring_point(center, radius, PI), point(px(10.0), px(24.0))); + assert_eq!( + ring_point(center, radius, -FRAC_PI_2), + point(px(6.0), px(20.0)) + ); + } + + #[test] + fn arcs_tessellate_across_the_range() { + let center = point(px(0.0), px(0.0)); + let radius = px(8.0); + let stroke = px(2.0); + // The large-arc flag flips past half a circle; both sides must build. + for fraction in [0.25, 0.5, 0.75] { + assert!( + arc_path(center, radius, stroke, 0.0, fraction * TAU).is_some(), + "fraction {fraction} failed to build" + ); + } + assert!(circle_path(center, radius, stroke).is_some()); + } +} diff --git a/crates/ui/src/components/status_dot.rs b/crates/ui/src/components/status_dot.rs new file mode 100644 index 0000000..0a03ae0 --- /dev/null +++ b/crates/ui/src/components/status_dot.rs @@ -0,0 +1,108 @@ +//! The status dot: a small colored bead for row state. + +use crate::theme::{ActiveTheme as _, Size, Theme}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, ElementId, Hsla, InteractiveElement as _, IntoElement, RenderOnce, Role, SharedString, + StatefulInteractiveElement as _, StyleRefinement, Styled, Window, div, +}; + +use crate::components::common::{Sizable, StyledExt}; + +/// How loud a dot is, the same vocabulary as [`crate::components::badge::BadgeVariant`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum StatusDotVariant { + #[default] + Neutral, + Accent, + Success, + Warning, + Danger, +} + +impl StatusDotVariant { + fn color(self, theme: &Theme) -> Hsla { + match self { + Self::Neutral => theme.colors.muted_foreground, + Self::Accent => theme.ramps.primary.base, + Self::Success => theme.ramps.success.base, + Self::Warning => theme.ramps.warning.base, + Self::Danger => theme.ramps.destructive.base, + } + } +} + +/// A small circular bead marking a row's state. +#[derive(IntoElement)] +#[must_use] +pub struct StatusDot { + id: ElementId, + variant: StatusDotVariant, + size: Size, + label: Option, + style: StyleRefinement, +} + +impl StatusDot { + /// Creates an idle dot. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + variant: StatusDotVariant::default(), + size: Size::default(), + label: None, + style: StyleRefinement::default(), + } + } + + /// Sets how loud the dot is. + pub fn variant(mut self, variant: StatusDotVariant) -> Self { + self.variant = variant; + self + } + + /// The state the dot announces to screen readers. + pub fn label(mut self, label: L) -> Self + where + L: Into, + { + self.label = Some(label.into()); + self + } +} + +impl Sizable for StatusDot { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl Styled for StatusDot { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for StatusDot { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let metrics = theme.sizes.resolve(self.size); + let side = metrics.icon_size / 2.; + let color = self.variant.color(theme); + + div() + .id(self.id.clone()) + .debug_selector(move || self.id.to_string()) + .flex_none() + .size(side) + .rounded(theme.radius.full) + .bg(color) + .when_some(self.label, |dot, label| { + dot.role(Role::Status).aria_label(label) + }) + .refine_style(&self.style) + } +} diff --git a/crates/ui/src/components/switch.rs b/crates/ui/src/components/switch.rs new file mode 100644 index 0000000..f2a89bc --- /dev/null +++ b/crates/ui/src/components/switch.rs @@ -0,0 +1,180 @@ +//! The switch: a controlled on/off pill with a thumb. + +use crate::theme::{ActiveTheme as _, BORDER_WIDTH, CONTROL_SPRING, DISABLED_OPACITY, Size}; +use crate::utils::focus_ring; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + AnimationExt as _, App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, + RenderOnce, Role, SharedString, SpringAnimation, StatefulInteractiveElement as _, + StyleRefinement, Styled as _, Toggled, Window, div, px, +}; + +use crate::components::common::{Sizable, StyledExt as _, h_flex}; + +/// The change reporter, fired with the next value by pointer, Enter, and Space. +type ChangeHandler = Box; + +/// Switch component. +#[derive(IntoElement)] +#[must_use] +pub struct Switch { + id: ElementId, + label: Option, + checked: bool, + size: Size, + disabled: bool, + a11y_label: Option, + on_change: Option, + style: StyleRefinement, +} + +impl Switch { + /// Creates an unchecked switch. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + label: None, + checked: false, + size: Size::default(), + disabled: false, + a11y_label: None, + on_change: None, + style: StyleRefinement::default(), + } + } + + /// Sets the visible label; clicking it toggles too. + pub fn label(mut self, label: L) -> Self + where + L: Into, + { + self.label = Some(label.into()); + self + } + + /// Sets the current value; the switch never owns it. + pub fn checked(mut self, checked: bool) -> Self { + self.checked = checked; + self + } + + /// Renders the switch inert, unfocusable, and dimmed; disabled always wins. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + + /// Overrides the accessibility label, which defaults to the visible label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// The change handler, fired with the next value by pointer, Enter, and Space. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(bool, &mut Window, &mut App) + 'static, + { + self.on_change = Some(Box::new(handler)); + self + } +} + +impl gpui::Styled for Switch { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl Sizable for Switch { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl RenderOnce for Switch { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let colors = theme.colors; + let ramps = theme.ramps; + let metrics = theme.sizes.resolve(self.size); + + let track_height = metrics.switch_height; + let track_width = metrics.switch_width; + + let knob = metrics.switch_knob; + // Absolute children sit inside the track's border, so remove it from the inset. + let inset = (track_height - knob) / 2. - BORDER_WIDTH; + let travel = track_width - BORDER_WIDTH * 2. - knob - inset * 2.; + + let next = !self.checked; + let on_change = self.on_change; + let a11y_label = self.a11y_label.or_else(|| self.label.clone()); + let id = self.id.clone(); + + let anim = + SpringAnimation::new(CONTROL_SPRING).to(if self.checked { travel } else { px(0.) }); + + h_flex() + .id(self.id) + .gap_2() + .text_size(metrics.text_size) + .refine_style(&self.style) + .role(Role::Switch) + .when_some(a11y_label, |switch, label| switch.aria_label(label)) + .aria_toggled(Toggled::from(self.checked)) + .when(self.disabled, |switch| switch.opacity(DISABLED_OPACITY)) + .when(!self.disabled, |switch| { + switch + .cursor_pointer() + .focusable() + .tab_stop(true) + .focus_visible(|style| style.shadow(focus_ring(colors.ring))) + .when_some(on_change, |switch, on_change| { + switch.on_click(move |_, window, cx| on_change(next, window, cx)) + }) + }) + .child( + div() + .flex_none() + .relative() + .debug_selector(move || format!("{id}-track")) + .w(track_width) + .h(track_height) + .rounded(theme.radius.full) + .border_1() + .when(self.checked, |track| { + track + .bg(ramps.primary.base) + .border_color(ramps.primary.base) + .hover(|style| { + style + .bg(ramps.primary.hover) + .border_color(ramps.primary.hover) + }) + }) + .when(!self.checked, |track| { + track.bg(colors.input).border_color(colors.border) + }) + .child( + div() + .absolute() + .top(inset) + .left(inset) + .size(knob) + .rounded(theme.radius.full) + .bg(colors.primary_foreground) + .with_spring("switch-thumb", anim, move |thumb, offset| { + thumb.left(inset + offset) + }), + ), + ) + .when_some(self.label, |switch, label| switch.child(label)) + } +} diff --git a/crates/ui/src/components/toast.rs b/crates/ui/src/components/toast.rs new file mode 100644 index 0000000..c7f9d1f --- /dev/null +++ b/crates/ui/src/components/toast.rs @@ -0,0 +1,354 @@ +//! Toasts: succinct, temporary messages at the bottom center of the window. + +use std::rc::Rc; +use std::time::Duration; + +use crate::icons::{Icon, IconRole}; +use crate::theme::{ActiveTheme as _, TOAST_MAX_WIDTH}; +use crate::utils::ResultLogErr as _; +use gpui::prelude::FluentBuilder; +use gpui::{ + Animation, AnimationExt as _, App, Context, ElementId, Entity, InteractiveElement as _, + IntoElement, ParentElement as _, RenderOnce, Role, SharedString, + StatefulInteractiveElement as _, StyleRefinement, Styled as _, Task, Window, deferred, div, + ease_out_quint, px, +}; + +use crate::components::button::{Button, ButtonVariant}; +use crate::components::common::{DismissHandler, Sizable as _, StyledExt as _, TOAST_LAYER}; + +/// The action handler of a [`Toast`]. +pub type ActionHandler = Rc; + +/// One user action offered by a toast. +#[derive(Clone)] +pub struct ToastAction { + label: SharedString, + handler: ActionHandler, +} + +impl ToastAction { + /// Creates an action with this label. + pub fn new(label: L, handler: F) -> Self + where + L: Into, + F: Fn(&mut App) + 'static, + { + Self { + label: label.into(), + handler: Rc::new(handler), + } + } +} + +/// A toast notification. +#[derive(Clone)] +#[must_use] +pub struct Toast { + message: SharedString, + icon: Option, + action: Option, + duration: Option, + on_dismiss: Option, + style: StyleRefinement, +} + +impl Toast { + /// How long a toast stays up by default. + pub const DURATION: Duration = Duration::from_secs(5); + + /// Creates a toast with this one-line content. + pub fn new(message: L) -> Self + where + L: Into, + { + Self { + message: message.into(), + icon: None, + action: None, + duration: Some(Self::DURATION), + on_dismiss: None, + style: StyleRefinement::default(), + } + } + + /// Shows this glyph before the content. + pub fn icon(mut self, icon: I) -> Self + where + I: Into, + { + self.icon = Some(icon.into()); + self + } + + /// Offers the user this action. + pub fn action(mut self, action: ToastAction) -> Self { + self.action = Some(action); + self + } + + /// Sets the time before the toast dismisses itself. + pub fn duration(mut self, duration: Duration) -> Self { + self.duration = Some(duration); + self + } + + /// Runs when the toast is dismissed by any means, once it is fully gone. + pub fn on_dismiss(mut self, handler: F) -> Self + where + F: Fn(&mut App) + 'static, + { + self.on_dismiss = Some(Rc::new(handler)); + self + } +} + +// Toast is a data builder, not an element, adopt the combinators explicitly. +impl FluentBuilder for Toast {} + +/// One raised toast, with its identity in the store. +#[derive(Clone)] +pub struct ToastEntry { + pub id: usize, + pub toast: Toast, +} + +/// The store of raised toasts. +#[derive(Default)] +pub struct Toasts { + current: Option, + exiting: Option, + next_id: usize, + /// Pending dismiss and fade timers; held so they die with the store. + tasks: Vec>, +} + +impl Toasts { + /// Raises a toast, replacing the one on screen. Returns its id. + pub fn push(&mut self, toast: Toast, cx: &mut Context) -> usize { + let id = self.next_id; + self.next_id += 1; + + let duration = toast.duration; + + if let Some(previous) = self.current.take() { + self.start_exit(previous, cx); + } + + self.current = Some(ToastEntry { id, toast }); + cx.notify(); + + if let Some(duration) = duration.filter(|duration| !duration.is_zero()) { + let task = cx.spawn(async move |this, cx| { + cx.background_executor().timer(duration).await; + this.update(cx, |toasts, cx| toasts.dismiss(id, cx)) + .log_err(); + }); + self.tasks.push(task); + } + + id + } + + /// Dismisses one toast by id. + pub fn dismiss(&mut self, id: usize, cx: &mut Context) { + if self.exiting.as_ref().is_some_and(|entry| entry.id == id) { + self.finish_exit(cx); + return; + } + if let Some(entry) = self.current.take_if(|entry| entry.id == id) { + self.start_exit(entry, cx); + } + } + + /// Dismisses the toast on screen. + pub fn clear(&mut self, cx: &mut Context) { + if let Some(entry) = self.current.take() { + self.start_exit(entry, cx); + } else { + self.finish_exit(cx); + } + } + + /// The toast now showing, if any. + pub fn current(&self) -> Option<&ToastEntry> { + self.current.as_ref() + } + + /// How many toasts are on screen, including one fading out. + pub fn count(&self) -> usize { + usize::from(self.current.is_some()) + usize::from(self.exiting.is_some()) + } + + /// Moves a toast into the fade-out phase. + fn start_exit(&mut self, entry: ToastEntry, cx: &mut Context) { + if let Some(previous) = self.exiting.take() + && let Some(on_dismiss) = &previous.toast.on_dismiss + { + on_dismiss(cx); + } + + self.exiting = Some(entry); + cx.notify(); + + let fade = cx.theme().motion.overlay; + let task = cx.spawn(async move |this, cx| { + cx.background_executor().timer(fade).await; + this.update(cx, |toasts, cx| toasts.finish_exit(cx)) + .log_err(); + }); + self.tasks.push(task); + } + + fn finish_exit(&mut self, cx: &mut Context) { + if let Some(entry) = self.exiting.take() { + cx.notify(); + if let Some(on_dismiss) = &entry.toast.on_dismiss { + on_dismiss(cx); + } + } + } +} + +/// The floating stack of toasts, bottom center. +#[derive(IntoElement)] +#[must_use] +pub struct ToastsView { + toasts: Entity, + id: ElementId, +} + +impl ToastsView { + /// Binds the view to a toast store. + pub fn new(id: I, toasts: Entity) -> Self + where + I: Into, + { + Self { + id: id.into(), + toasts, + } + } +} + +impl RenderOnce for ToastsView { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let fade = cx.theme().motion.overlay; + + let exiting = self.toasts.read(cx).exiting.clone(); + let current = self.toasts.read(cx).current.clone(); + + deferred( + div() + .id(self.id) + .absolute() + .left_0() + .bottom_4() + .w_full() + .flex() + .flex_col() + .items_center() + .when_some(exiting, |column, entry| { + let id = entry.id; + column.child(entry.pill(&self.toasts, cx).with_animation( + ("toast-exit", id), + Animation::new(fade), + |pill, delta| pill.opacity(1. - delta), + )) + }) + .when_some(current, |column, entry| { + let id = entry.id; + column.child(entry.pill(&self.toasts, cx).with_animation( + ("toast-enter", id), + Animation::new(fade).with_easing(ease_out_quint()), + |pill, delta| pill.opacity(delta), + )) + }), + ) + .with_priority(TOAST_LAYER) + } +} + +impl ToastEntry { + /// The rendered pill for this toast. + fn pill(&self, toasts: &Entity, cx: &App) -> gpui::Stateful { + let theme = cx.theme(); + let surface = theme.colors.surface; + let border = theme.colors.border; + let foreground = theme.colors.foreground; + let radius = theme.radius.full; + let shadows = theme.elevations.popover.shadows(); + let icon_size = theme.sizes.medium.icon_size; + let text_size = theme.sizes.medium.text_size; + let toast = &self.toast; + let toasts = toasts.clone(); + let id = self.id; + + div() + .id(("toast", id)) + .debug_selector(|| "toast-pill".to_string()) + .role(Role::Alert) + .aria_label(toast.message.clone()) + .max_w(TOAST_MAX_WIDTH) + .flex() + .items_center() + .gap_2() + .py_1p5() + .px_3() + .bg(surface) + .border_1() + .border_color(border) + .rounded(radius) + .shadow(shadows.clone()) + .refine_style(&toast.style) + .when_some(toast.icon.clone(), |pill, icon| { + pill.child( + div() + .flex_none() + .flex() + .items_center() + .child(icon.size(icon_size).color(foreground)), + ) + }) + .child( + div() + .flex_1() + .min_w(px(0.)) + .truncate() + .text_size(text_size) + .text_color(foreground) + .child(toast.message.clone()), + ) + .when_some(toast.action.clone(), |pill, action| { + let toasts = toasts.clone(); + pill.child( + div().flex_none().child( + Button::new(("toast-action", id)) + .label(action.label.clone()) + .variant(ButtonVariant::Primary) + .small() + .on_click(move |_, _window, cx| { + (action.handler)(cx); + toasts.update(cx, |toasts, cx| { + toasts.dismiss(id, cx); + }); + }), + ), + ) + }) + .child( + div().flex_none().child( + Button::new(("toast-close", id)) + .icon(IconRole::Close) + .variant(ButtonVariant::Ghost) + .small() + .accessibility_label("Dismiss") + .on_click(move |_, _window, cx| { + toasts.update(cx, |toasts, cx| { + toasts.dismiss(id, cx); + }); + }), + ), + ) + } +} diff --git a/crates/ui/src/components/toggle.rs b/crates/ui/src/components/toggle.rs new file mode 100644 index 0000000..166ae83 --- /dev/null +++ b/crates/ui/src/components/toggle.rs @@ -0,0 +1,166 @@ +use crate::icons::Icon; +use crate::theme::{ActiveTheme as _, DISABLED_OPACITY, Size}; +use crate::utils::focus_ring; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, ElementId, InteractiveElement as _, IntoElement, ParentElement as _, RenderOnce, Role, + SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Toggled, Window, +}; + +use crate::components::common::{Sizable, StyledExt as _, h_flex}; + +/// The change handler, fired with the next pressed state. +type ChangeHandler = Box; + +/// A toggle component. +#[derive(IntoElement)] +#[must_use] +pub struct Toggle { + id: ElementId, + label: Option, + icon: Option, + pressed: bool, + size: Size, + disabled: bool, + a11y_label: Option, + on_change: Option, + style: StyleRefinement, +} + +impl Toggle { + /// Creates an unpressed toggle. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + label: None, + icon: None, + pressed: false, + size: Size::default(), + disabled: false, + a11y_label: None, + on_change: None, + style: StyleRefinement::default(), + } + } + + /// Sets the visible label. + pub fn label(mut self, label: L) -> Self + where + L: Into, + { + self.label = Some(label.into()); + self + } + + /// Shows an icon. Omitting the label renders an icon-only toggle. + pub fn icon(mut self, icon: I) -> Self + where + I: Into, + { + self.icon = Some(icon.into()); + self + } + + /// Sets the current pressed state; the toggle never owns it. + pub fn pressed(mut self, pressed: bool) -> Self { + self.pressed = pressed; + self + } + + /// Renders the toggle inert, unfocusable, and dimmed; disabled always wins. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + + /// Overrides the accessibility label, which defaults to the visible label. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// Sets the change handler, fired with the next pressed state. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(bool, &mut Window, &mut App) + 'static, + { + self.on_change = Some(Box::new(handler)); + self + } +} + +impl gpui::Styled for Toggle { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl Sizable for Toggle { + fn apply_size(&mut self, size: Size) { + self.size = size; + } +} + +impl RenderOnce for Toggle { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let colors = theme.colors; + let ramps = theme.ramps; + let metrics = theme.sizes.resolve(self.size); + let on_change = self.on_change; + let next = !self.pressed; + let a11y_label = self.a11y_label.or_else(|| self.label.clone()); + let icon_only = self.icon.is_some() && self.label.is_none(); + + h_flex() + .id(self.id) + .justify_center() + .h(metrics.control_height) + .when(icon_only, |toggle| { + toggle.w(metrics.control_height).px(gpui::Pixels::ZERO) + }) + .when(!icon_only, |toggle| toggle.px(metrics.dense_padding_x)) + .rounded(theme.radius.control) + .text_size(metrics.text_size) + .text_color(colors.foreground) + .role(Role::Button) + .when_some(a11y_label, |toggle, label| toggle.aria_label(label)) + .aria_toggled(Toggled::from(self.pressed)) + .when(self.pressed, |toggle| { + toggle + .bg(ramps.secondary.hover) + .hover(|style| style.bg(ramps.secondary.pressed)) + }) + .when(!self.pressed, |toggle| { + toggle + .hover(|style| style.bg(colors.muted)) + .active(|style| style.bg(ramps.secondary.hover)) + }) + .refine_style(&self.style) + .when(self.disabled, |toggle| toggle.opacity(DISABLED_OPACITY)) + .when(!self.disabled, |toggle| { + toggle + .cursor_pointer() + .focusable() + .tab_stop(true) + .focus_visible(|style| style.shadow(focus_ring(colors.ring))) + .when_some(on_change, |toggle, on_change| { + toggle.on_click(move |_, window, cx| on_change(next, window, cx)) + }) + }) + .child( + h_flex() + .gap_2() + .when_some(self.icon, |content, icon| { + content.child(icon.size(metrics.icon_size)) + }) + .when_some(self.label, |content, label| content.child(label)), + ) + } +} diff --git a/crates/ui/src/components/tooltip.rs b/crates/ui/src/components/tooltip.rs new file mode 100644 index 0000000..ec658b7 --- /dev/null +++ b/crates/ui/src/components/tooltip.rs @@ -0,0 +1,141 @@ +use crate::theme::{ActiveTheme as _, BORDER_WIDTH, TOOLTIP_MAX_WIDTH, TOOLTIP_OFFSET}; +use crate::utils::{anchor_bounds, record_anchor_bounds}; +use gpui::AppContext as _; +use gpui::{ + AnyView, App, Bounds, Context, ElementId, Entity, InteractiveElement as _, IntoElement, + ParentElement as _, Pixels, Render, Role, SharedString, StatefulInteractiveElement as _, + Styled as _, Window, canvas, div, point, +}; + +const PANEL_BOUNDS_ID: &str = "tooltip-panel-bounds"; + +/// A small text panel gpui shows next to a hovered element. +pub struct Tooltip { + text: SharedString, + anchor: Option>, +} + +impl Tooltip { + /// Creates the tooltip view. + pub fn new(text: L, cx: &mut App) -> Entity + where + L: Into, + { + cx.new(|_| Self { + text: text.into(), + anchor: None, + }) + } + + /// Sets the anchor element ID for the tooltip. + /// + /// The `.tooltip(...)` closure pinning the panel next to `anchor_id`. + pub fn anchored( + text: L, + anchor_id: I, + ) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static + where + L: Into, + I: Into, + { + let text = text.into(); + let anchor_id = anchor_id.into(); + move |window, cx| { + let anchor = anchor_bounds(window.window_handle().window_id(), &anchor_id, cx); + cx.new(|_| Self { + text: text.clone(), + anchor, + }) + .into() + } + } + + /// The `.tooltip(...)` closure for a plain text tooltip. + pub fn text(text: L) -> impl Fn(&mut Window, &mut App) -> AnyView + 'static + where + L: Into, + { + let text = text.into(); + move |_, cx| Tooltip::new(text.clone(), cx).into() + } +} + +impl Render for Tooltip { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + // Copied out: the mutable reads below need `cx` free of this borrow. + let theme = cx.theme(); + let text_size = theme.sizes.medium.text_size; + let line_height = theme.typography.callout.line_height; + let spacing_unit = theme.spacing.unit; + let surface = theme.colors.surface; + let surface_foreground = theme.colors.surface_foreground; + let radius_sm = theme.radius.sm; + let shadows = theme.elevations.popover.shadows(); + + let border = theme.colors.border; + + let build_panel = || { + div() + .id("tooltip-panel") + .role(Role::Tooltip) + .debug_selector(|| "tooltip-panel".to_string()) + .px_2() + .py_1() + .max_w(TOOLTIP_MAX_WIDTH) + .bg(surface) + .border_1() + .border_color(border) + .rounded(radius_sm) + .shadow(shadows.clone()) + .text_size(text_size) + .line_height(line_height) + .text_color(surface_foreground) + .child(self.text.clone()) + }; + + let (wrapper, panel) = match self.anchor { + Some(parent) => { + let origin = window.mouse_position() + point(TOOLTIP_OFFSET, TOOLTIP_OFFSET); + let viewport_height = window.viewport_size().height; + + let height = anchor_bounds( + window.window_handle().window_id(), + &ElementId::from(PANEL_BOUNDS_ID), + cx, + ) + .map(|bounds| bounds.size.height) + .unwrap_or_else(|| line_height + spacing_unit * 2.0 + BORDER_WIDTH * 2.0); + + let below = viewport_height - spacing_unit - parent.bottom(); + let above = parent.top() - spacing_unit; + let hang_below = below >= height || below >= above; + + let panel = build_panel() + .ml(parent.left() - origin.x) + .mt(if hang_below { + parent.bottom() + spacing_unit - origin.y + } else { + parent.top() - spacing_unit - height - origin.y + }) + .child( + canvas( + record_anchor_bounds(ElementId::from(PANEL_BOUNDS_ID)), + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ); + (div().debug_selector(|| "tooltip-anchor".to_string()), panel) + } + None => { + let wrapper = div() + .debug_selector(|| "tooltip-anchor".to_string()) + .pl(spacing_unit * 2.0) + .pt(spacing_unit * 2.0); + (wrapper, build_panel()) + } + }; + + wrapper.child(panel) + } +} diff --git a/crates/ui/src/data/list.rs b/crates/ui/src/data/list.rs new file mode 100644 index 0000000..27a5d9f --- /dev/null +++ b/crates/ui/src/data/list.rs @@ -0,0 +1,270 @@ +use std::rc::Rc; + +use crate::icons::Icon; +use crate::theme::{ActiveTheme as _, TextRole, Typeset as _}; +use crate::utils::{StyledExt as _, nav_key, paint_selectable_row, selectable_label_color}; +use gpui::prelude::FluentBuilder; +use gpui::{ + AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent, + ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, + StyleRefinement, Styled as _, Window, div, +}; + +/// The change reporter, fired with the next selection by pointer and keys. +type ChangeHandler = Rc, &mut Window, &mut App)>; +type ItemsFn = Box Vec>; + +/// One row of a [`List`]. +#[must_use] +pub struct ListItem { + key: ElementId, + label: SharedString, + icon: Option, + detail: Option, + disabled: bool, +} + +impl ListItem { + /// Creates a row shown as `label`, identified by `key`. + pub fn new(key: K, label: L) -> Self + where + K: Into, + L: Into, + { + Self { + key: key.into(), + label: label.into(), + icon: None, + detail: None, + disabled: false, + } + } + + /// Shows an icon leading the label, a role or any custom [`crate::icons::IconNamed`]. + pub fn icon(mut self, icon: I) -> Self + where + I: Into, + { + self.icon = Some(icon.into()); + self + } + + /// Shows muted trailing text. + pub fn detail(mut self, detail: D) -> Self + where + D: Into, + { + self.detail = Some(detail.into()); + self + } + + /// Renders the row dimmed; clicks and keyboard skip it. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } +} + +// ListItem is a data builder, not an element, adopt the combinators explicitly. +impl FluentBuilder for ListItem {} + +/// A single-selection list. +#[derive(IntoElement)] +#[must_use] +pub struct List { + id: ElementId, + selected: Option, + a11y_label: Option, + on_change: Option, + items: Option, + style: StyleRefinement, +} + +impl List { + /// Creates a list with nothing selected. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + selected: None, + a11y_label: None, + on_change: None, + items: None, + style: StyleRefinement::default(), + } + } + + /// Sets the current selection. + pub fn selected(mut self, selected: Option) -> Self { + self.selected = selected; + self + } + + /// Reports the next selection, from clicks and keys alike. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(Option, &mut Window, &mut App) + 'static, + { + self.on_change = Some(Rc::new(handler)); + self + } + + /// Sets the rows, the closure runs during render and must not mutate entities or notify. + pub fn items(mut self, items: F) -> Self + where + F: Fn(&mut Window, &mut App) -> Vec + 'static, + { + self.items = Some(Box::new(items)); + self + } + + /// Overrides the accessibility label, which defaults to the id. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } +} + +impl gpui::Styled for List { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for List { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let items = match self.items { + Some(build) => build(window, cx), + None => Vec::new(), + }; + + let selectable: Vec = items + .iter() + .enumerate() + .filter(|(_, item)| !item.disabled) + .map(|(index, _)| index) + .collect(); + + let focus = crate::utils::focus_handle(&self.id, window, cx); + let theme = cx.theme(); + + let label = self + .a11y_label + .clone() + .unwrap_or_else(|| SharedString::from(self.id.to_string())); + + let rows: Vec = items + .iter() + .enumerate() + .map(|(index, item)| { + item.render_row( + cx, + index, + items.len(), + self.selected == Some(index), + &self.on_change, + &focus, + ) + }) + .collect(); + + div() + .id(self.id) + .flex() + .flex_col() + .gap_0p5() + .text_size(theme.sizes.medium.text_size) + .refine_style(&self.style) + .track_focus(&focus) + .focusable() + .tab_stop(true) + .role(Role::List) + .aria_label(label) + .on_key_down({ + let selected = self.selected; + let on_change = self.on_change.clone(); + + move |event: &KeyDownEvent, window, cx| { + if nav_key(&selectable, selected, &event.keystroke.key, |next| { + if let Some(on_change) = &on_change { + on_change(next, window, cx); + } + }) { + cx.stop_propagation(); + } + } + }) + .children(rows) + } +} + +impl ListItem { + fn render_row( + &self, + cx: &App, + index: usize, + count: usize, + selected: bool, + on_change: &Option, + focus: &FocusHandle, + ) -> AnyElement { + let theme = cx.theme(); + let label_color = selectable_label_color(cx, selected, self.disabled); + let disabled = self.disabled; + + div() + .id((self.key.clone(), "list-item")) + .flex() + .items_center() + .gap_2() + .px_2() + .py_1() + .min_h(theme.sizes.medium.control_height) + .rounded(theme.radius.sm) + .role(Role::ListItem) + .aria_selected(selected) + .aria_position_in_set(index + 1) + .aria_size_of_set(count) + .map(|row| paint_selectable_row(cx, row, selected, disabled)) + .when(!disabled, |row| { + row.cursor_pointer().on_click({ + let on_change = on_change.clone(); + let focus = focus.clone(); + move |_, window, cx| { + window.focus(&focus, cx); + if let Some(on_change) = &on_change { + on_change(Some(index), window, cx); + } + } + }) + }) + .when_some(self.icon.clone(), |row, icon| { + row.child(icon.size(theme.sizes.medium.icon_size).color(label_color)) + }) + .child( + div() + .flex_1() + .text_color(label_color) + .child(self.label.clone()), + ) + .when_some(self.detail.clone(), |row, detail| { + row.child( + div() + .flex_none() + .typeset(TextRole::Subheadline, cx) + .text_color(if selected { + theme.colors.primary_foreground + } else { + theme.colors.muted_foreground + }) + .child(detail), + ) + }) + .into_any_element() + } +} diff --git a/crates/ui/src/data/mod.rs b/crates/ui/src/data/mod.rs new file mode 100644 index 0000000..afea2d8 --- /dev/null +++ b/crates/ui/src/data/mod.rs @@ -0,0 +1,6 @@ +//! Data-heavy components: lists, trees, tabs, sidebars. + +pub mod list; +pub mod sidebar; +pub mod tabs; +pub mod tree; diff --git a/crates/ui/src/data/sidebar.rs b/crates/ui/src/data/sidebar.rs new file mode 100644 index 0000000..1f6ce98 --- /dev/null +++ b/crates/ui/src/data/sidebar.rs @@ -0,0 +1,524 @@ +//! The sidebar: a controlled list with section headers — the Finder +//! sidebar's model of rows grouped under non-selectable labels. Custom +//! entries slot user content between the rows. + +use std::rc::Rc; + +use crate::components::grain::grain as grain_overlay; +use crate::components::scroll_area::ScrollArea; +use crate::theme::{ActiveTheme as _, BORDER_WIDTH, SIDEBAR_DEFAULT_WIDTH, TextRole, Typeset as _}; +use crate::utils::{StyledExt as _, nav_key, paint_selectable_row, selectable_label_color}; +use gpui::prelude::FluentBuilder; +use gpui::{ + AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent, + ParentElement as _, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, + StyleRefinement, Styled as _, Window, div, +}; + +/// The change reporter, fired with the next selected row by pointer and keys. +type ChangeHandler = Rc, &mut Window, &mut App)>; +type EntriesFn = Box Vec>; + +/// One entry of a [`Sidebar`], a section header, a selectable row, or custom content. +#[must_use] +pub enum SidebarEntry { + /// A non-selectable section label. + Header { + label: SharedString, + prefix: Option, + suffix: Option, + }, + /// A selectable row. + Row { + key: ElementId, + label: SharedString, + detail: Option, + prefix: Option, + suffix: Option, + disabled: bool, + }, + /// Custom content occupying a slot in the list. + Custom(AnyElement), +} + +impl SidebarEntry { + /// Creates a section header. + pub fn header(label: L) -> Self + where + L: Into, + { + Self::Header { + label: label.into(), + prefix: None, + suffix: None, + } + } + + /// Creates a selectable row shown as `label`, identified by `key`. + pub fn row(key: K, label: L) -> Self + where + K: Into, + L: Into, + { + Self::Row { + key: key.into(), + label: label.into(), + detail: None, + prefix: None, + suffix: None, + disabled: false, + } + } + + /// Wraps custom content occupying a slot in the list. + pub fn custom(element: E) -> Self + where + E: IntoElement, + { + Self::Custom(element.into_any_element()) + } + + /// Shows muted trailing text. + pub fn detail(mut self, detail: D) -> Self + where + D: Into, + { + if let Self::Row { + detail: row_detail, .. + } = &mut self + { + *row_detail = Some(detail.into()); + } + self + } + + /// Shows an element leading the entry. + pub fn prefix(mut self, prefix: E) -> Self + where + E: IntoElement, + { + if let Self::Row { prefix: slot, .. } | Self::Header { prefix: slot, .. } = &mut self { + *slot = Some(prefix.into_any_element()); + } + self + } + + /// Shows an element trailing the entry. + pub fn suffix(mut self, suffix: E) -> Self + where + E: IntoElement, + { + if let Self::Row { suffix: slot, .. } | Self::Header { suffix: slot, .. } = &mut self { + *slot = Some(suffix.into_any_element()); + } + self + } + + /// Renders the row dimmed; clicks and keyboard skip it. + pub fn disabled(mut self, disabled: bool) -> Self { + if let Self::Row { + disabled: row_disabled, + .. + } = &mut self + { + *row_disabled = disabled; + } + self + } +} + +// SidebarEntry is a data builder, not an element, adopt the combinators explicitly. +impl FluentBuilder for SidebarEntry {} + +/// A sidebar. +#[derive(IntoElement)] +#[must_use] +pub struct Sidebar { + id: ElementId, + selected: Option, + transparent: bool, + grain: bool, + border_right: bool, + padded: bool, + width: Pixels, + a11y_label: Option, + on_change: Option, + entries: Option, + style: StyleRefinement, +} + +impl Sidebar { + /// Creates a sidebar with nothing selected. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + selected: None, + transparent: false, + grain: false, + border_right: true, + padded: true, + width: SIDEBAR_DEFAULT_WIDTH, + a11y_label: None, + on_change: None, + entries: None, + style: StyleRefinement::default(), + } + } + + /// Sets the current selection. + pub fn selected(mut self, selected: Option) -> Self { + self.selected = selected; + self + } + + /// Paints translucent material fills so the window's native backdrop shows through. + pub fn transparent(mut self, transparent: bool) -> Self { + self.transparent = transparent; + self + } + + /// Whether translucent material fills are painted. + pub fn is_transparent(&self) -> bool { + self.transparent + } + + /// Textures the material with a film-grain overlay; it renders only while + /// the sidebar paints one. + pub fn grain(mut self, grain: bool) -> Self { + self.grain = grain; + self + } + + /// Paints a hairline border on the sidebar's right edge. + pub fn border_right(mut self, border_right: bool) -> Self { + self.border_right = border_right; + self + } + + /// Whether the right-edge border is painted. + pub fn has_border_right(&self) -> bool { + self.border_right + } + + /// Insets the entry list from the sidebar's edges; the scrollbar stays on the edge. + pub fn padded(mut self, padded: bool) -> Self { + self.padded = padded; + self + } + + /// Whether the entry list is inset from the sidebar's edges. + pub fn is_padded(&self) -> bool { + self.padded + } + + /// Sets the sidebar's width, overriding the default. + pub fn width(mut self, width: W) -> Self + where + W: Into, + { + self.width = width.into(); + self + } + + /// Reports the next selected row, from clicks and keys alike. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(Option, &mut Window, &mut App) + 'static, + { + self.on_change = Some(Rc::new(handler)); + self + } + + /// Sets the entries, the closure runs during render and must not mutate entities or notify. + pub fn entries(mut self, entries: F) -> Self + where + F: Fn(&mut Window, &mut App) -> Vec + 'static, + { + self.entries = Some(Box::new(entries)); + self + } + + /// Overrides the accessibility label, which defaults to the id. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } +} + +impl gpui::Styled for Sidebar { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Sidebar { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let Self { + id, + selected, + transparent: material, + grain, + border_right, + padded, + width, + a11y_label, + on_change, + entries, + style, + } = self; + + let label = a11y_label.unwrap_or_else(|| SharedString::from(id.to_string())); + let debug_id = id.clone(); + + let entries = match entries { + Some(build) => build(window, cx), + None => Vec::new(), + }; + + // Headers and custom entries are never selectable, only enabled rows are. + let selectable: Vec = entries + .iter() + .enumerate() + .filter(|(_, entry)| match entry { + SidebarEntry::Row { disabled, .. } => !disabled, + SidebarEntry::Header { .. } | SidebarEntry::Custom(_) => false, + }) + .map(|(index, _)| index) + .collect(); + + let focus = crate::utils::focus_handle(&id, window, cx); + let scroll = window.with_element_namespace(id.clone(), |window| { + window + .use_keyed_state("scroll", cx, |_, _| gpui::ScrollHandle::new()) + .clone() + }); + let scroll_area_id = (id.clone(), "entries"); + + let row_count = entries + .iter() + .filter(|entry| matches!(entry, SidebarEntry::Row { .. })) + .count(); + let mut row_position = 0usize; + + let children: Vec = entries + .into_iter() + .enumerate() + .map(|(index, entry)| { + let is_row = matches!(entry, SidebarEntry::Row { .. }); + + if is_row { + row_position += 1; + } + + let (position_in_set, size_of_set) = if is_row { + (row_position, row_count) + } else { + (0, 0) + }; + + entry.render_entry( + cx, + index, + position_in_set, + size_of_set, + selected == Some(index), + material, + &on_change, + &focus, + ) + }) + .collect(); + + let body = div() + .id((id.clone(), "list")) + .flex_1() + .min_h_0() + .track_focus(&focus) + .focusable() + .tab_stop(true) + .role(Role::List) + .aria_label(label) + .on_key_down({ + let on_change = on_change.clone(); + move |event: &KeyDownEvent, window, cx| { + if nav_key(&selectable, selected, &event.keystroke.key, |next| { + if let Some(on_change) = &on_change { + on_change(next, window, cx); + } + }) { + cx.stop_propagation(); + } + } + }) + .child( + ScrollArea::new(scroll_area_id) + .handle(scroll.read(cx).clone()) + .h_full() + .child( + div() + .flex() + .flex_col() + .gap_0p5() + .when(padded, |content| content.p_2()) + .children(children), + ), + ) + .into_any_element(); + + let theme = cx.theme(); + + div() + .id(id.clone()) + .debug_selector(move || format!("sidebar-{debug_id}")) + .h_full() + .w(width) + .flex() + .flex_col() + .map(|sidebar| { + if material { + sidebar.bg(theme.material.background) + } else { + sidebar.bg(theme.colors.sidebar) + } + }) + .text_size(theme.sizes.medium.text_size) + .refine_style(&style) + .when(border_right, |sidebar| { + sidebar + .border_r(BORDER_WIDTH) + .border_color(theme.colors.border) + }) + .child(body) + .when(material && grain, |sidebar| sidebar.child(grain_overlay())) + } +} + +impl SidebarEntry { + #[allow(clippy::too_many_arguments)] + fn render_entry( + self, + cx: &App, + index: usize, + position_in_set: usize, + size_of_set: usize, + selected: bool, + material: bool, + on_change: &Option, + focus: &FocusHandle, + ) -> AnyElement { + let theme = cx.theme(); + + match self { + SidebarEntry::Header { + label, + prefix, + suffix, + } => { + // The id is required for the role to surface in the a11y tree. + div() + .id(("sidebar-header".into(), label.clone())) + .flex() + .items_center() + .gap_2() + .px_2() + .pt_2() + .pb_1() + .typeset(TextRole::Headline, cx) + .text_color(theme.colors.muted_foreground) + .role(Role::Heading) + .when_some(prefix, |header, prefix| header.child(prefix)) + .child( + div() + .flex_1() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .child(label), + ) + .when_some(suffix, |header, suffix| header.child(suffix)) + .into_any_element() + } + SidebarEntry::Custom(element) => element, + SidebarEntry::Row { + key, + label, + detail, + prefix, + suffix, + disabled: row_disabled, + } => { + let label_color = selectable_label_color(cx, selected, row_disabled); + + div() + .id((key.clone(), "sidebar-row")) + .flex() + .items_center() + .gap_2() + .px_2() + .py_1() + .min_h(theme.sizes.medium.control_height) + .rounded(theme.radius.sm) + .role(Role::ListItem) + .aria_selected(selected) + .aria_position_in_set(position_in_set) + .aria_size_of_set(size_of_set) + .map(|row| { + if material && !row_disabled { + if selected { + row.bg(theme.material.selection) + } else { + row.hover(|row| row.bg(theme.material.hover)) + } + } else { + paint_selectable_row(cx, row, selected, row_disabled) + } + }) + .when(!row_disabled, |row| { + row.cursor_pointer().on_click({ + let on_change = on_change.clone(); + let focus = focus.clone(); + move |_, window, cx| { + window.focus(&focus, cx); + if let Some(on_change) = &on_change { + on_change(Some(index), window, cx); + } + } + }) + }) + .when_some(prefix, |row, prefix| row.child(prefix)) + .child( + div() + .flex_1() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .text_color(label_color) + .child(label), + ) + .when_some(detail, |row, detail| { + row.child( + div() + .flex_none() + .typeset(TextRole::Subheadline, cx) + .text_color(if selected { + theme.colors.primary_foreground + } else { + theme.colors.muted_foreground + }) + .child(detail), + ) + }) + .when_some(suffix, |row, suffix| row.child(suffix)) + .into_any_element() + } + } + } +} diff --git a/crates/ui/src/data/tabs.rs b/crates/ui/src/data/tabs.rs new file mode 100644 index 0000000..080f54e --- /dev/null +++ b/crates/ui/src/data/tabs.rs @@ -0,0 +1,1224 @@ +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +use crate::components::button::{Button, ButtonVariant}; +use crate::components::common::{Sizable as _, v_flex}; +use crate::components::popover::Popover; +use crate::components::scroll_area::{ScrollArea, ScrollAxes}; +use crate::components::spinner::Spinner; +use crate::components::tooltip::Tooltip; +use crate::icons::IconRole; +use crate::theme::{ActiveTheme as _, POPUP_MAX_HEIGHT, Size, TAB_INDICATOR_WIDTH}; +use crate::utils::{StyledExt as _, adjacent_selectable}; +use gpui::prelude::FluentBuilder; +use gpui::{ + AnyElement, App, AppContext as _, Bounds, ClickEvent, Context, Div, ElementId, Global, + InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, ParentElement as _, Pixels, + Point, Render, RenderOnce, Role, SharedString, Stateful, StatefulInteractiveElement as _, + StyleRefinement, Styled as _, Window, canvas, div, px, relative, +}; + +/// Reports the next selected tab by pointer and keys. +type ChangeHandler = Rc; +/// Reports the tab's index by its close control. +type CloseHandler = Rc; +/// Reports a tab moved from one index to another by a drag. +type ReorderHandler = Rc; +/// Decorates the rendered tab, e.g. to attach a drag payload. +type TabWrap = Box) -> AnyElement>; +type TabsFn = Box Vec>; +/// The open-state reporter of the overflow popover. +type OpenHandler = Rc; +/// Identifies one strip's measurements across windows. +type MeasureKey = (u64, String); +/// Shared per-frame state that lets tab canvases read the strip's bounds. +type RootBoundsCell = Rc>>>; + +/// One inline tab's geometry relative to the strip's left edge. +#[derive(Clone, Copy, Default)] +struct TabMeasure { + left: Pixels, + width: Pixels, +} + +/// A strip's geometry captured the previous frame. +#[derive(Clone, Default)] +struct StripMeasure { + container_width: Pixels, + trigger_width: Option, + tabs: HashMap, +} + +/// The capture context handed to inline tabs, only in popover mode. +#[derive(Clone)] +struct MeasureFrame { + key: MeasureKey, + root_bounds: RootBoundsCell, +} + +/// Measurements read a frame late, so strips render one frame behind a resize. +#[derive(Default)] +struct TabsMeasurements { + strips: HashMap, +} + +impl Global for TabsMeasurements {} + +impl TabsMeasurements { + fn record_container(&mut self, key: &MeasureKey, width: Pixels) { + self.strips.entry(key.clone()).or_default().container_width = width; + } + + fn record_trigger(&mut self, key: &MeasureKey, width: Pixels) { + self.strips.entry(key.clone()).or_default().trigger_width = Some(width); + } + + fn record_tab(&mut self, key: &MeasureKey, tab: String, measure: TabMeasure) { + self.strips + .entry(key.clone()) + .or_default() + .tabs + .insert(tab, measure); + } +} + +/// Everything a tab needs to draw and interact, shared across a strip's slots. +#[derive(Clone)] +struct StripCtx { + id: ElementId, + selected: usize, + variant: TabsVariant, + on_change: Option, + on_close: Option, + on_reorder: Option, + focus: gpui::FocusHandle, + measure: Option, + /// Whether tabs drag onto each other to reorder; requires `on_reorder`. + draggable: bool, + /// The tab drag gesture's live state, for the drop indicator. + drop_at: gpui::Entity, +} + +impl StripCtx { + /// The context for tabs drawn inside a popover: no measurement, no dragging. + fn for_popover(&self) -> Self { + Self { + measure: None, + draggable: false, + ..self.clone() + } + } +} + +/// The index the tab at `from` occupies once dropped before the tab at `onto`, +/// or `None` when the drop is a no-op. +fn reorder_target(from: usize, onto: usize) -> Option { + match from.cmp(&onto) { + std::cmp::Ordering::Equal => None, + std::cmp::Ordering::Less => Some(onto - 1), + std::cmp::Ordering::Greater => Some(onto), + } +} + +/// Displacement before a tab drag locks to an axis: horizontal reorders, +/// vertical cancels the reorder, like a browser tab strip. +const TAB_DRAG_AXIS_LOCK: Pixels = px(6.0); + +/// One tab drag gesture's live state. +#[derive(Clone, Copy, Default, PartialEq)] +struct TabDrop { + /// The tab the drag currently hovers, for the drop indicator. + onto: Option, + /// Where the drag's first move landed, anchoring the axis lock. + origin: Option>, + /// Whether the gesture locked as a horizontal (`Some(true)`) or vertical + /// (`Some(false)`) drag; `None` until it moved [`TAB_DRAG_AXIS_LOCK`]. + horizontal: Option, +} + +impl TabDrop { + /// Whether the gesture locked as a vertical drag, canceling the reorder. + fn canceled(&self) -> bool { + self.horizontal == Some(false) + } +} + +/// One slot of a strip: a lone tab, or same-kind tabs collapsed into a group chip. +enum StripItem { + /// A tab outside any two-member kind group, at its original index. + Single(usize, Tab), + /// Tabs of one kind collapsed into a chip, at the first member's index. + Group { + kind: SharedString, + /// The collapsed tabs with their original indices. + members: Vec<(usize, Tab)>, + }, +} + +impl StripItem { + /// The key the strip's geometry records the item under. + fn measure_key(&self, tabs_id: &ElementId) -> String { + match self { + StripItem::Single(_, tab) => tab.key.to_string(), + StripItem::Group { kind, .. } => group_key(tabs_id, kind).to_string(), + } + } +} + +/// The group chip's identity for one strip and kind. +fn group_key(tabs_id: &ElementId, kind: &SharedString) -> ElementId { + SharedString::from(format!("{tabs_id}-tabs-group-{kind}")).into() +} + +/// The payload dragged when reordering a tab. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TabDrag { + /// The dragged tab's index into the `tabs` vec. + pub index: usize, +} + +/// The floating pill that follows the cursor while a tab is dragged. +struct TabDragPreview { + label: SharedString, +} + +impl Render for TabDragPreview { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = cx.theme(); + div() + .px_2() + .py_1() + .rounded(theme.radius.control) + .border_1() + .border_color(theme.colors.border) + .bg(theme.colors.background) + .text_size(theme.sizes.medium.text_size) + .text_color(theme.colors.foreground) + .shadow(theme.elevations.control.shadows()) + .child(self.label.clone()) + } +} + +/// The visual language of a [`Tabs`] strip. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum TabsVariant { + #[default] + Underline, + Pill, +} + +/// One tab of a [`Tabs`] strip. +#[must_use] +pub struct Tab { + /// The stable identity for element state; must survive reordering. + key: ElementId, + label: SharedString, + lead: Option, + busy: bool, + disabled: bool, + closeable: bool, + pinned: bool, + kind: Option, + wrap: Option, +} + +impl Tab { + /// Creates a tab shown as `label`, identified by `key`. + pub fn new(key: K, label: L) -> Self + where + K: Into, + L: Into, + { + Self { + key: key.into(), + label: label.into(), + lead: None, + busy: false, + disabled: false, + closeable: false, + pinned: false, + kind: None, + wrap: None, + } + } + + /// Sets the leading element, e.g. an icon or an avatar. + pub fn lead(mut self, lead: E) -> Self + where + E: IntoElement + 'static, + { + self.lead = Some(lead.into_any_element()); + self + } + + /// Shows the loading slot. + pub fn busy(mut self, busy: bool) -> Self { + self.busy = busy; + self + } + + /// Renders the tab dimmed; clicks and keyboard skip it. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + + /// Shows a close control that reports the tab through [`Tabs::on_close`]. + pub fn closeable(mut self, closeable: bool) -> Self { + self.closeable = closeable; + self + } + + /// Draws the tab with the active treatment at all times, selected or not. + pub fn pinned(mut self, pinned: bool) -> Self { + self.pinned = pinned; + self + } + + /// Sets the kind the tab belongs to; same-kind tabs collapse into one group. + pub fn kind(mut self, kind: K) -> Self + where + K: Into, + { + self.kind = Some(kind.into()); + self + } + + /// Hands the rendered tab through `wrap`, e.g. to attach a drag payload. + pub fn wrap(mut self, wrap: F) -> Self + where + F: FnOnce(Stateful

) -> AnyElement + 'static, + { + self.wrap = Some(Box::new(wrap)); + self + } +} + +// Tab is a data builder, not an element, adopt the combinators explicitly. +impl FluentBuilder for Tab {} + +/// A tab strip. +#[derive(IntoElement)] +#[must_use] +pub struct Tabs { + id: ElementId, + selected: usize, + variant: TabsVariant, + overflow_scroll: bool, + overflow_popover: bool, + overflow_open: bool, + draggable: bool, + a11y_label: Option, + on_change: Option, + on_close: Option, + on_reorder: Option, + on_overflow_open: Option, + tabs: Option, + style: StyleRefinement, +} + +impl Tabs { + /// Creates a strip selecting the first tab. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + selected: 0, + variant: TabsVariant::default(), + overflow_scroll: false, + overflow_popover: false, + overflow_open: false, + draggable: false, + a11y_label: None, + on_change: None, + on_close: None, + on_reorder: None, + on_overflow_open: None, + tabs: None, + style: StyleRefinement::default(), + } + } + + /// Sets the current selection, as an index into the `tabs` vec — not a tab key. + pub fn selected(mut self, selected: usize) -> Self { + self.selected = selected; + self + } + + /// Sets the strip's visual language. + pub fn variant(mut self, variant: TabsVariant) -> Self { + self.variant = variant; + self + } + + /// Scrolls the strip horizontally when the tabs overflow. + pub fn overflow_scroll(mut self, overflow_scroll: bool) -> Self { + self.overflow_scroll = overflow_scroll; + self + } + + /// Shows a popover of the tabs that do not fit, via a trigger at the strip's end. + pub fn overflow_popover(mut self, overflow_popover: bool) -> Self { + self.overflow_popover = overflow_popover; + self + } + + /// The overflow popover's current open state; read only in [`Self::overflow_popover`] mode. + pub fn overflow_open(mut self, overflow_open: bool) -> Self { + self.overflow_open = overflow_open; + self + } + + /// Lets tabs be dragged onto each other to reorder them. + pub fn draggable(mut self, draggable: bool) -> Self { + self.draggable = draggable; + self + } + + /// Reports the overflow popover's next open state, from its trigger, dismissals, and selection. + pub fn on_overflow_open(mut self, handler: F) -> Self + where + F: Fn(bool, &mut Window, &mut App) + 'static, + { + self.on_overflow_open = Some(Rc::new(handler)); + self + } + + /// Reports the next selected tab, as an index into the `tabs` vec — not a tab key; indices shift on reorder. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(usize, &mut Window, &mut App) + 'static, + { + self.on_change = Some(Rc::new(handler)); + self + } + + /// Reports a closed tab, as an index into the `tabs` vec — not a tab key; indices shift on reorder. + pub fn on_close(mut self, handler: F) -> Self + where + F: Fn(usize, &mut Window, &mut App) + 'static, + { + self.on_close = Some(Rc::new(handler)); + self + } + + /// Reports a tab moved by a drag. + pub fn on_reorder(mut self, handler: F) -> Self + where + F: Fn(usize, usize, &mut Window, &mut App) + 'static, + { + self.on_reorder = Some(Rc::new(handler)); + self + } + + /// Sets the tabs; the closure runs during render and must not mutate entities or notify. + pub fn tabs(mut self, tabs: F) -> Self + where + F: Fn(&mut Window, &mut App) -> Vec + 'static, + { + self.tabs = Some(Box::new(tabs)); + self + } + + /// Overrides the accessibility label, which defaults to the id. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// The number of items that fit before the popover trigger, from last frame's geometry. + fn inline_count(tabs_id: &ElementId, items: &[StripItem], measure: &StripMeasure) -> usize { + let limit = measure.container_width - measure.trigger_width.unwrap_or(Pixels::ZERO); + let mut count = 0; + for item in items { + let Some(entry) = measure.tabs.get(&item.measure_key(tabs_id)) else { + return items.len(); + }; + if entry.left + entry.width > limit { + break; + } + count += 1; + } + count + } + + fn render_overflow_popover( + ctx: &StripCtx, + overflow_items: Vec, + open: bool, + on_overflow_open: Option, + ) -> Popover { + let id = ctx.id.clone(); + let trigger_id = id.clone(); + let on_change = ctx.on_change.clone(); + + let row_change: Option = match (on_change, on_overflow_open.clone()) { + (Some(on_change), Some(dismiss)) => Some(Rc::new(move |index, window, cx| { + on_change(index, window, cx); + dismiss(false, window, cx); + })), + (None, Some(dismiss)) => Some(Rc::new(move |_, window, cx| { + dismiss(false, window, cx); + })), + (on_change, None) => on_change, + }; + + let row_ctx = StripCtx { + on_change: row_change, + ..ctx.for_popover() + }; + + Popover::new((id.clone(), "tabs-overflow")) + .open(open) + .on_change({ + let on_overflow_open = on_overflow_open.clone(); + move |next, window, cx| { + if let Some(on_overflow_open) = &on_overflow_open { + on_overflow_open(next, window, cx); + } + } + }) + .trigger(move |_, _| { + Button::new((trigger_id.clone(), "tabs-overflow-trigger")) + .icon(IconRole::More) + .variant(ButtonVariant::Ghost) + .small() + .accessibility_label("More tabs") + .on_click({ + let on_overflow_open = on_overflow_open.clone(); + move |event, window, cx| { + // Pointer clicks toggle inside Popover; only the keyboard path lands here. + if let ClickEvent::Keyboard(_) = event + && let Some(on_overflow_open) = &on_overflow_open + { + on_overflow_open(!open, window, cx); + } + } + }) + .into_any_element() + }) + .content(move |_, cx| { + let rows: Vec = overflow_items + .into_iter() + .flat_map(|item| match item { + StripItem::Single(index, tab) => { + vec![tab.render_tab(&row_ctx, cx, index)] + } + // A group that ran out of room lists its members inline. + StripItem::Group { members, .. } => members + .into_iter() + .map(|(index, tab)| tab.render_tab(&row_ctx, cx, index)) + .collect::>(), + }) + .collect(); + + ScrollArea::new((id.clone(), "tabs-overflow-list")) + .axes(ScrollAxes::Vertical) + .max_h(POPUP_MAX_HEIGHT) + .child(v_flex().gap_0p5().p_1().children(rows)) + .into_any_element() + }) + } + + /// Collapses same-kind tabs (two or more) into group chips, keeping strip order. + fn group_by_kind(tabs: Vec) -> Vec { + let mut counts: HashMap = HashMap::new(); + for tab in &tabs { + if let Some(kind) = &tab.kind { + *counts.entry(kind.clone()).or_default() += 1; + } + } + + let mut items: Vec = Vec::new(); + let mut group_slots: HashMap = HashMap::new(); + + for (index, tab) in tabs.into_iter().enumerate() { + let grouped_kind = tab + .kind + .clone() + .filter(|kind| counts.get(kind).copied().unwrap_or(0) >= 2); + + match grouped_kind { + Some(kind) => match group_slots.get(&kind).copied() { + Some(slot) => { + if let StripItem::Group { members, .. } = &mut items[slot] { + members.push((index, tab)); + } + } + None => { + group_slots.insert(kind.clone(), items.len()); + items.push(StripItem::Group { + kind, + members: vec![(index, tab)], + }); + } + }, + None => items.push(StripItem::Single(index, tab)), + } + } + + items + } + + /// Renders a group chip labeled with the kind and its member count. + fn render_group_tab( + ctx: &StripCtx, + kind: SharedString, + members: Vec<(usize, Tab)>, + window: &mut Window, + cx: &mut App, + ) -> AnyElement { + let tabs_id = ctx.id.clone(); + let count = members.len(); + let selected = members.iter().any(|(index, _)| *index == ctx.selected); + // A pinned member keeps the chip in the active treatment, selected or not. + let active = selected || members.iter().any(|(_, tab)| tab.pinned); + + let open = window + .use_keyed_state((group_key(&tabs_id, &kind), "open"), cx, |_, _| false) + .clone(); + + let theme = cx.theme(); + let metrics = theme.sizes.resolve(Size::default()); + let small = theme.sizes.small; + + let label_color = match ctx.variant { + TabsVariant::Underline => { + if active { + theme.ramps.primary.base + } else { + theme.colors.foreground + } + } + TabsVariant::Pill => theme.colors.foreground, + }; + + let group_key = group_key(&tabs_id, &kind); + let chip = div() + .id((group_key.clone(), "group-tab")) + .debug_selector({ + let tabs_id = tabs_id.clone(); + let label = kind.clone(); + move || format!("{tabs_id}-group-{label}") + }) + .flex() + .items_center() + .gap_2() + .cursor_pointer() + .role(Role::Tab) + .aria_selected(selected) + .aria_label(SharedString::from(format!("{kind}, {count} tabs"))) + .text_color(label_color) + .when(!active, |chip| { + chip.hover(|chip| chip.bg(theme.colors.muted)) + }) + .map(|chip| match ctx.variant { + TabsVariant::Underline => chip + .px_2() + .py_1() + .rounded_tl(theme.radius.sm) + .rounded_tr(theme.radius.sm) + .border_b(TAB_INDICATOR_WIDTH) + .border_color(gpui::transparent_black()) + .when(active, |chip| chip.border_color(theme.ramps.primary.base)), + TabsVariant::Pill => chip + .h(small.control_height + metrics.plate_inset * 2.0) + .px(metrics.dense_padding_x) + .pr(metrics.plate_inset) + .rounded(theme.radius.control) + .when(active, |chip| { + chip.bg(theme.colors.background) + .shadow(theme.elevations.control.shadows()) + }), + }) + .child(SharedString::from(format!("{kind} ({count})"))) + .when(ctx.variant == TabsVariant::Pill, |chip| { + chip.child(div().flex_none().w(metrics.padding_x * 1.5)) + }) + .when_some(ctx.measure.clone(), |chip, measure| { + let key = measure.key.clone(); + let root_bounds = measure.root_bounds.clone(); + let item_key = group_key.to_string(); + chip.child( + canvas( + move |bounds, _, cx| { + let root = root_bounds.borrow(); + if let Some(root) = root.as_ref() { + cx.default_global::().record_tab( + &key, + item_key, + TabMeasure { + left: bounds.origin.x - root.origin.x, + width: bounds.size.width, + }, + ); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ) + }); + + // Selecting a row also dismisses the popover, mirroring the overflow popover. + let row_change: Option = { + let open = open.clone(); + let on_change = ctx.on_change.clone(); + Some(Rc::new(move |index, window, cx| { + open.update(cx, |open, cx| { + *open = false; + cx.notify(); + }); + if let Some(on_change) = &on_change { + on_change(index, window, cx); + } + })) + }; + + let row_ctx = StripCtx { + on_change: row_change, + ..ctx.for_popover() + }; + + Popover::new((group_key.clone(), "group-popover")) + .open(*open.read(cx)) + .on_change({ + let open = open.clone(); + move |next, _, cx| { + open.update(cx, |open, cx| { + *open = next; + cx.notify(); + }); + } + }) + .trigger(move |_, _| chip.into_any_element()) + .content(move |_, cx| { + let rows: Vec = members + .into_iter() + .map(|(index, tab)| tab.render_tab(&row_ctx, cx, index)) + .collect(); + + ScrollArea::new((group_key.clone(), "tabs-group-list")) + .axes(ScrollAxes::Vertical) + .max_h(POPUP_MAX_HEIGHT) + .child(v_flex().gap_0p5().p_1().children(rows)) + .into_any_element() + }) + .into_any_element() + } +} + +impl gpui::Styled for Tabs { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Tabs { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let tabs = match self.tabs { + Some(build) => build(window, cx), + None => Vec::new(), + }; + let mut items = Self::group_by_kind(tabs); + + let selectable: Vec = items + .iter() + .flat_map(|item| match item { + StripItem::Single(index, tab) => (!tab.disabled) + .then_some(*index) + .into_iter() + .collect::>(), + StripItem::Group { members, .. } => members + .iter() + .filter(|(_, tab)| !tab.disabled) + .map(|(index, _)| *index) + .collect::>(), + }) + .collect(); + + let focus = crate::utils::focus_handle(&self.id, window, cx); + // Theme reads end here, so the strip's group chips can take `cx` mutably. + let (medium_text_size, border_color, shadow_bleed) = { + let theme = cx.theme(); + let shadow_bleed = match self.variant { + TabsVariant::Pill => theme.elevations.control.bleed(), + TabsVariant::Underline => Pixels::ZERO, + }; + ( + theme.sizes.medium.text_size, + theme.colors.border, + shadow_bleed, + ) + }; + + let label = self + .a11y_label + .clone() + .unwrap_or_else(|| SharedString::from(self.id.to_string())); + + let measure_key: MeasureKey = ( + window.window_handle().window_id().as_u64(), + self.id.to_string(), + ); + + let measure = if self.overflow_popover { + cx.try_global::() + .and_then(|cache| cache.strips.get(&measure_key).cloned()) + } else { + None + }; + + let inline_count = measure + .as_ref() + .map(|measure| Self::inline_count(&self.id, &items, measure)) + .unwrap_or(items.len()); + let overflow_items = items.split_off(inline_count); + + let measure_frame = self.overflow_popover.then(|| MeasureFrame { + key: measure_key.clone(), + root_bounds: Rc::new(RefCell::new(None)), + }); + + let drop_at = window + .use_keyed_state((self.id.clone(), "tab-drop"), cx, |_, _| TabDrop::default()) + .clone(); + + let ctx = StripCtx { + id: self.id.clone(), + selected: self.selected, + variant: self.variant, + on_change: self.on_change.clone(), + on_close: self.on_close.clone(), + on_reorder: self.on_reorder.clone(), + focus: focus.clone(), + measure: measure_frame.clone(), + draggable: self.draggable && self.on_reorder.is_some(), + drop_at, + }; + + let strip: Vec = items + .into_iter() + .map(|item| match item { + StripItem::Single(index, tab) => tab.render_tab(&ctx, cx, index), + StripItem::Group { kind, members } => { + Self::render_group_tab(&ctx, kind, members, window, cx) + } + }) + .collect(); + + let popover = (self.overflow_popover && measure.is_some() && !overflow_items.is_empty()) + .then(|| { + Self::render_overflow_popover( + &ctx, + overflow_items, + self.overflow_open, + self.on_overflow_open.clone(), + ) + }); + + div() + .id(self.id.clone()) + .flex() + .text_size(medium_text_size) + .refine_style(&self.style) + .track_focus(&focus) + .focusable() + .tab_stop(true) + .role(Role::TabList) + .aria_label(label) + .on_key_down({ + let selected = self.selected; + let on_change = self.on_change.clone(); + move |event: &KeyDownEvent, window, cx| { + let target = match event.keystroke.key.as_str() { + "right" => adjacent_selectable(&selectable, Some(selected), true), + "left" => adjacent_selectable(&selectable, Some(selected), false), + "home" => selectable.first().copied(), + "end" => selectable.last().copied(), + _ => return, + }; + if let Some(next) = target + && next != selected + && let Some(on_change) = &on_change + { + on_change(next, window, cx); + } + cx.stop_propagation(); + } + }) + .when(ctx.draggable, |root| { + root.on_drag_move::({ + let drop_at = ctx.drop_at.clone(); + move |event, _, cx| { + let position = event.event.position; + let outside = !event.bounds.contains(&position); + drop_at.update(cx, |drop, cx| { + let origin = drop.origin.get_or_insert(position); + if drop.horizontal.is_none() { + let dx = (position.x - origin.x).abs(); + let dy = (position.y - origin.y).abs(); + if dx.max(dy) > TAB_DRAG_AXIS_LOCK { + drop.horizontal = Some(dx >= dy); + } + } + if (outside || drop.canceled()) && drop.onto.is_some() { + drop.onto = None; + cx.notify(); + } + }); + } + }) + // A drop over the strip's gaps lands on the last hovered slot. + .on_drop::({ + let drop_at = ctx.drop_at.clone(); + let on_reorder = ctx.on_reorder.clone(); + move |drag, window, cx| { + let onto = drop_at.read(cx).onto; + let canceled = drop_at.read(cx).canceled(); + drop_at.update(cx, |drop, cx| { + if drop.onto.is_some() { + drop.onto = None; + cx.notify(); + } + }); + if let (Some(onto), Some(on_reorder)) = (onto, on_reorder.as_ref()) + && !canceled + && let Some(to) = reorder_target(drag.index, onto) + { + on_reorder(drag.index, to, window, cx); + } + } + }) + }) + .map(|root| match self.variant { + TabsVariant::Underline => root.gap_1().border_b_1().border_color(border_color), + TabsVariant::Pill => root.items_center().gap_1(), + }) + .map(|root| { + if self.overflow_popover { + let Some(root_bounds) = measure_frame.map(|frame| frame.root_bounds) else { + return root.children(strip); + }; + let container_canvas = canvas( + { + let key = measure_key.clone(); + move |bounds, _, cx| { + cx.default_global::() + .record_container(&key, bounds.size.width); + *root_bounds.borrow_mut() = Some(bounds); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset(shadow_bleed); + let trigger_canvas = canvas( + { + let key = measure_key; + move |bounds, _, cx| { + cx.default_global::() + .record_trigger(&key, bounds.size.width); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(); + + let control = match popover { + Some(popover) => div().flex_none().relative().child(popover), + None => div().flex_none().relative().child( + div().w(measure + .as_ref() + .and_then(|measure| measure.trigger_width) + .unwrap_or(Pixels::ZERO)), + ), + }; + + root.min_w_0() + .flex_grow(1.0) + .overflow_hidden() + .p(shadow_bleed) + .m(-shadow_bleed) + .child(container_canvas) + .child( + div() + .flex_none() + .flex() + .gap_1() + .when(self.variant == TabsVariant::Pill, |row| row.items_center()) + .children(strip), + ) + .child(control.child(trigger_canvas)) + } else if self.overflow_scroll { + root.min_w_0() + .overflow_x_scroll() + .p(shadow_bleed) + .m(-shadow_bleed) + .child( + div() + .flex_none() + .flex() + .gap_1() + .when(self.variant == TabsVariant::Pill, |row| row.items_center()) + .children(strip), + ) + } else { + root.children(strip) + } + }) + } +} + +impl Tab { + fn render_tab(mut self, ctx: &StripCtx, cx: &App, index: usize) -> AnyElement { + let selected = index == ctx.selected; + // A pinned tab always wears the active treatment, selected or not. + let active = selected || self.pinned; + + let theme = cx.theme(); + let metrics = theme.sizes.resolve(Size::default()); + let small = theme.sizes.small; + + let label_color = match ctx.variant { + TabsVariant::Underline => { + if self.disabled { + theme.colors.muted_foreground + } else if active { + theme.ramps.primary.base + } else { + theme.colors.foreground + } + } + TabsVariant::Pill => { + if self.disabled { + theme.colors.muted_foreground + } else { + theme.colors.foreground + } + } + }; + + let close = (self.closeable && ctx.on_close.is_some() && !self.disabled) + .then(|| self.render_tab_close(&ctx.id, index, &ctx.on_close)); + + let strip_tab = div() + .id((self.key.clone(), "tab")) + .debug_selector({ + let tabs_id = ctx.id.clone(); + let label = self.label.clone(); + move || format!("{tabs_id}-tab-{}", label) + }) + .flex() + .items_center() + .gap_2() + .role(Role::Tab) + .aria_selected(selected) + .text_color(label_color) + .line_height(relative(1.0)) + .when(!self.disabled && !active, |strip_tab| { + strip_tab.hover(|strip_tab| strip_tab.bg(theme.colors.muted)) + }) + .map(|strip_tab| match ctx.variant { + TabsVariant::Underline => strip_tab + .px_2() + .py_1() + .rounded_tl(theme.radius.sm) + .rounded_tr(theme.radius.sm) + .border_b(TAB_INDICATOR_WIDTH) + .border_color(gpui::transparent_black()) + .when(active, |strip_tab| { + strip_tab.border_color(theme.ramps.primary.base) + }), + TabsVariant::Pill => strip_tab + .h(small.control_height + metrics.plate_inset * 2.0) + .px(metrics.dense_padding_x) + .pr(metrics.plate_inset) + .rounded(theme.radius.control) + .when(active, |strip_tab| { + strip_tab + .bg(theme.colors.background) + .shadow(theme.elevations.control.shadows()) + }), + }) + .when_some(self.lead.take(), |strip_tab, lead| strip_tab.child(lead)) + .child(div().flex_grow(1.0).child(self.label.clone())) + .when(ctx.variant == TabsVariant::Pill, |strip_tab| { + strip_tab.child(div().flex_none().w(metrics.padding_x * 1.5)) + }) + .when(self.busy && !self.disabled, |strip_tab| { + strip_tab.child( + Spinner::new((self.key.clone(), "tab-busy")) + .small() + .accessibility_label("Loading"), + ) + }) + .when_some(close, |strip_tab, close| strip_tab.child(close)) + .when( + { + let drop = ctx.drop_at.read(cx); + drop.onto == Some(index) && !drop.canceled() + }, + |strip_tab| { + strip_tab.child( + div() + .absolute() + .left_0() + .top(TAB_INDICATOR_WIDTH) + .bottom(TAB_INDICATOR_WIDTH) + .w(TAB_INDICATOR_WIDTH) + .rounded(theme.radius.sm) + .bg(theme.ramps.primary.base), + ) + }, + ) + .when_some(ctx.measure.clone(), |strip_tab, measure| { + let key = measure.key.clone(); + let root_bounds = measure.root_bounds.clone(); + let tab_key = self.key.to_string(); + strip_tab.child( + canvas( + move |bounds, _, cx| { + let root = root_bounds.borrow(); + if let Some(root) = root.as_ref() { + cx.default_global::().record_tab( + &key, + tab_key, + TabMeasure { + left: bounds.origin.x - root.origin.x, + width: bounds.size.width, + }, + ); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ) + }) + .when(!self.disabled, |strip_tab| { + strip_tab.cursor_pointer().on_click({ + let selected = ctx.selected; + let on_change = ctx.on_change.clone(); + let focus = ctx.focus.clone(); + move |_, window, cx| { + window.focus(&focus, cx); + if index != selected + && let Some(on_change) = &on_change + { + on_change(index, window, cx); + } + } + }) + }) + .when(ctx.draggable && !self.disabled, |strip_tab| { + strip_tab + .on_mouse_down(MouseButton::Left, { + let drop_at = ctx.drop_at.clone(); + move |event, _, cx| { + cx.stop_propagation(); + drop_at.update(cx, |drop, cx| { + let fresh = TabDrop { + origin: Some(event.position), + ..TabDrop::default() + }; + if *drop != fresh { + *drop = fresh; + cx.notify(); + } + }); + } + }) + .on_drag(TabDrag { index }, { + let label = self.label.clone(); + move |_, _, _, cx| { + cx.new(|_| TabDragPreview { + label: label.clone(), + }) + } + }) + .drag_over::({ + let drop_at = ctx.drop_at.clone(); + move |style, drag, _, cx| { + let drop = *drop_at.read(cx); + let hovered = drag.index != index && !drop.canceled(); + drop_at.update(cx, |drop, cx| match (hovered, drop.onto) { + (true, current) if current != Some(index) => { + drop.onto = Some(index); + cx.notify(); + } + (false, Some(_)) => { + drop.onto = None; + cx.notify(); + } + _ => {} + }); + style + } + }) + .on_drop::({ + let on_reorder = ctx.on_reorder.clone(); + let drop_at = ctx.drop_at.clone(); + move |drag, window, cx| { + let canceled = drop_at.read(cx).canceled(); + drop_at.update(cx, |drop, cx| { + if drop.onto.is_some() { + drop.onto = None; + cx.notify(); + } + }); + let target = (!canceled) + .then(|| reorder_target(drag.index, index)) + .flatten(); + if let (Some(to), Some(on_reorder)) = (target, on_reorder.as_ref()) { + on_reorder(drag.index, to, window, cx); + } + } + }) + }); + + match self.wrap { + Some(wrap) => wrap(strip_tab), + None => strip_tab.into_any_element(), + } + } + + fn render_tab_close( + &self, + tabs_id: &ElementId, + index: usize, + on_close: &Option, + ) -> AnyElement { + Button::new((self.key.clone(), "tab-close")) + .icon(IconRole::Close) + .variant(ButtonVariant::Ghost) + .xsmall() + .tab_stop(false) + .debug_selector({ + let tabs_id = tabs_id.clone(); + let label = self.label.clone(); + move || format!("{tabs_id}-close-{}", label) + }) + .tooltip(Tooltip::text("Close")) + .accessibility_label(SharedString::from(format!("Close {}", self.label))) + .on_click({ + let on_close = on_close.clone(); + move |_, window, cx| { + cx.stop_propagation(); + if let Some(on_close) = &on_close { + on_close(index, window, cx); + } + } + }) + .into_any_element() + } +} diff --git a/crates/ui/src/data/tree.rs b/crates/ui/src/data/tree.rs new file mode 100644 index 0000000..9311a73 --- /dev/null +++ b/crates/ui/src/data/tree.rs @@ -0,0 +1,476 @@ +use std::rc::Rc; + +use crate::icons::{Icon, IconRole, icon}; +use crate::theme::ActiveTheme as _; +use crate::utils::{StyledExt as _, nav_key, paint_selectable_row, selectable_label_color}; +use gpui::prelude::FluentBuilder; +use gpui::{ + AnyElement, App, ElementId, FocusHandle, InteractiveElement as _, IntoElement, KeyDownEvent, + ParentElement as _, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, + StyleRefinement, Styled as _, Window, div, +}; + +/// The change reporter, fired with the next selection by pointer and keys. +type ChangeHandler = Rc, &mut Window, &mut App)>; +/// The disclosure reporter, fired with the toggled row's index. +type DisclosureHandler = Rc; +type ItemsFn = Box Vec>; + +/// Tree item. +#[derive(Clone)] +#[must_use] +pub struct TreeItem { + key: ElementId, + label: SharedString, + icon: Option, + depth: usize, + expandable: bool, + expanded: bool, + disabled: bool, +} + +impl TreeItem { + /// Creates a leaf row shown as `label` at the root depth, identified by `key`. + pub fn new(key: K, label: L) -> Self + where + K: Into, + L: Into, + { + Self { + key: key.into(), + label: label.into(), + icon: None, + depth: 0, + expandable: false, + expanded: false, + disabled: false, + } + } + + /// Shows a custom icon leading the label. + pub fn icon(mut self, icon: I) -> Self + where + I: Into, + { + self.icon = Some(icon.into()); + self + } + + /// Nests the row one level per count. + pub fn depth(mut self, depth: usize) -> Self { + self.depth = depth; + self + } + + /// Marks the row as having children. + pub fn expandable(mut self, expandable: bool) -> Self { + self.expandable = expandable; + self + } + + /// Sets the row's disclosure state. + pub fn expanded(mut self, expanded: bool) -> Self { + self.expanded = expanded; + self + } + + /// Renders the row dimmed; clicks and keyboard skip it. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } +} + +// TreeItem is a data builder, not an element, adopt the combinators explicitly. +impl FluentBuilder for TreeItem {} + +/// A tree. +#[derive(IntoElement)] +#[must_use] +pub struct Tree { + id: ElementId, + selected: Option, + a11y_label: Option, + on_change: Option, + on_disclosure: Option, + items: Option, + style: StyleRefinement, +} + +impl Tree { + /// Creates a tree with nothing selected. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + selected: None, + a11y_label: None, + on_change: None, + on_disclosure: None, + items: None, + style: StyleRefinement::default(), + } + } + + /// Sets the current selection. + pub fn selected(mut self, selected: Option) -> Self { + self.selected = selected; + self + } + + /// Reports the next selection, from clicks and keys alike. + pub fn on_change(mut self, handler: F) -> Self + where + F: Fn(Option, &mut Window, &mut App) + 'static, + { + self.on_change = Some(Rc::new(handler)); + self + } + + /// Reports the row whose disclosure the user toggled. + pub fn on_disclosure(mut self, handler: F) -> Self + where + F: Fn(usize, &mut Window, &mut App) + 'static, + { + self.on_disclosure = Some(Rc::new(handler)); + self + } + + /// Sets the visible rows; the closure runs during render and must not mutate entities or notify. + pub fn items(mut self, items: F) -> Self + where + F: Fn(&mut Window, &mut App) -> Vec + 'static, + { + self.items = Some(Box::new(items)); + self + } + + /// Overrides the accessibility label, which defaults to the id. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// Maps each visible row to its 1-based position-in-set and set size among its siblings. + fn sibling_sets(items: &[TreeItem]) -> Vec<(usize, usize)> { + let mut sets = vec![(0usize, 0usize); items.len()]; + // Open sibling runs along the ancestry path, deeper runs above shallower ones. + let mut runs: Vec<(usize, Vec)> = Vec::new(); + + for (index, item) in items.iter().enumerate() { + while runs + .last() + .is_some_and(|(run_depth, _)| *run_depth > item.depth) + { + if let Some((_, pending)) = runs.pop() { + Self::stamp_sibling_run(&mut sets, pending); + } + } + + match runs.last_mut() { + // A row at the running depth extends the open sibling run. + Some((run_depth, pending)) if *run_depth == item.depth => pending.push(index), + _ => runs.push((item.depth, vec![index])), + } + } + + for (_, pending) in runs { + Self::stamp_sibling_run(&mut sets, pending); + } + + sets + } + + fn stamp_sibling_run(sets: &mut [(usize, usize)], pending: Vec) { + let size_of_set = pending.len(); + for (position, index) in pending.into_iter().enumerate() { + if let Some(set) = sets.get_mut(index) { + *set = (position + 1, size_of_set); + } + } + } + + /// The nearest row above `index` with a smaller depth. + fn parent_of(items: &[TreeItem], index: usize) -> Option { + let depth = items.get(index)?.depth; + items[..index] + .iter() + .rposition(|candidate| candidate.depth < depth) + } + + /// The first selectable row deeper than `index`, when its branch is open. + fn first_descendant(items: &[TreeItem], selectable: &[usize], index: usize) -> Option { + let depth = items.get(index)?.depth; + selectable.iter().copied().find(|candidate| { + *candidate > index && items.get(*candidate).is_some_and(|row| row.depth > depth) + }) + } +} + +impl gpui::Styled for Tree { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Tree { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let items = match self.items { + Some(build) => build(window, cx), + None => Vec::new(), + }; + + let selectable: Vec = items + .iter() + .enumerate() + .filter(|(_, item)| !item.disabled) + .map(|(index, _)| index) + .collect(); + + let focus = crate::utils::focus_handle(&self.id, window, cx); + let theme = cx.theme(); + + let label = self + .a11y_label + .clone() + .unwrap_or_else(|| SharedString::from(self.id.to_string())); + + let sibling_sets = Self::sibling_sets(&items); + + let rows: Vec = items + .iter() + .enumerate() + .map(|(index, item)| { + let (position_in_set, size_of_set) = sibling_sets[index]; + item.render_row( + cx, + index, + position_in_set, + size_of_set, + self.selected == Some(index), + &self.on_change, + &self.on_disclosure, + &focus, + ) + }) + .collect(); + + div() + .id(self.id) + .flex() + .flex_col() + .gap_0p5() + .text_size(theme.sizes.medium.text_size) + .refine_style(&self.style) + .track_focus(&focus) + .focusable() + .tab_stop(true) + .role(Role::Tree) + .aria_label(label) + .on_key_down({ + let selected = self.selected; + let on_change = self.on_change.clone(); + let on_disclosure = self.on_disclosure.clone(); + + move |event: &KeyDownEvent, window, cx| { + if nav_key(&selectable, selected, &event.keystroke.key, |next| { + if let Some(on_change) = &on_change { + on_change(next, window, cx); + } + }) { + cx.stop_propagation(); + return; + } + match event.keystroke.key.as_str() { + "left" | "right" => { + let expanding = event.keystroke.key == "right"; + let mut disclose = None; + let mut target = None; + + if let Some(index) = selected + && let Some(item) = items.get(index) + && !item.disabled + { + if item.expandable && item.expanded != expanding { + disclose = Some(index); + } else if expanding { + target = Self::first_descendant(&items, &selectable, index); + } else { + target = Self::parent_of(&items, index) + .filter(|parent| selectable.contains(parent)); + } + } + + if let Some(index) = disclose + && let Some(on_disclosure) = &on_disclosure + { + on_disclosure(index, window, cx); + } else if let Some(next) = target + && let Some(on_change) = &on_change + { + on_change(Some(next), window, cx); + } + } + _ => return, + } + cx.stop_propagation(); + } + }) + .children(rows) + } +} + +impl TreeItem { + #[allow(clippy::too_many_arguments)] + fn render_row( + &self, + cx: &App, + index: usize, + position_in_set: usize, + size_of_set: usize, + selected: bool, + on_change: &Option, + on_disclosure: &Option, + focus: &FocusHandle, + ) -> AnyElement { + let theme = cx.theme(); + let label_color = selectable_label_color(cx, selected, self.disabled); + let disabled = self.disabled; + + let depth = u32::try_from(self.depth).unwrap_or(u32::MAX) as f32; + let indent = theme.sizes.medium.padding_x * if self.depth == 0 { 0.5 } else { depth + 1.0 }; + + div() + .id((self.key.clone(), "tree-item")) + .relative() + .flex() + .items_center() + .gap_2() + .pl(indent) + .pr_2() + .py_1() + .min_h(theme.sizes.medium.control_height) + .rounded(theme.radius.sm) + .role(Role::TreeItem) + .aria_selected(selected) + .aria_level(self.depth + 1) + .aria_position_in_set(position_in_set) + .aria_size_of_set(size_of_set) + .when(self.expandable, |row| row.aria_expanded(self.expanded)) + .map(|row| paint_selectable_row(cx, row, selected, disabled)) + .when(!disabled, |row| { + row.cursor_pointer().on_click({ + let on_change = on_change.clone(); + let on_disclosure = on_disclosure.clone(); + let expandable = self.expandable; + let focus = focus.clone(); + + move |_, window, cx| { + window.focus(&focus, cx); + if let Some(on_change) = &on_change { + on_change(Some(index), window, cx); + } + // A folder row toggles with its own click, not just its chevron. + if expandable && let Some(on_disclosure) = &on_disclosure { + on_disclosure(index, window, cx); + } + } + }) + }) + .children((0..self.depth).map(|level| { + let step = u32::try_from(level).unwrap_or(u32::MAX) as f32; + div() + .absolute() + .left(theme.sizes.medium.padding_x * (step + 0.5)) + .top_0() + .bottom_0() + .border_l_1() + .border_color(theme.colors.border) + })) + .child(self.render_disclosure(cx, selected)) + .when_some( + self.icon + .clone() + .or_else(|| (!self.expandable).then(|| icon(IconRole::File))), + |row, icon| row.child(icon.size(theme.sizes.medium.icon_size).color(label_color)), + ) + .child( + div() + .flex_1() + .text_color(label_color) + .child(self.label.clone()), + ) + .into_any_element() + } + + fn render_disclosure(&self, cx: &App, selected: bool) -> AnyElement { + let theme = cx.theme(); + let glyph_color = if self.disabled || !selected { + theme.colors.muted_foreground + } else { + theme.colors.primary_foreground + }; + + // Only expandable rows draw a chevron; the empty cell keeps labels aligned with folders. + div() + .flex_none() + .size(theme.sizes.medium.icon_size) + .flex() + .items_center() + .justify_center() + .when(self.expandable, |cell| { + cell.child( + icon(if self.expanded { + IconRole::ChevronDown + } else { + IconRole::ChevronRight + }) + .size(theme.sizes.medium.dense_icon_size) + .color(glyph_color), + ) + }) + .into_any_element() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn item(depth: usize) -> TreeItem { + TreeItem::new("item", "Item").depth(depth) + } + + #[test] + fn flat_rows_number_one_of_three() { + let sets = Tree::sibling_sets(&[item(0), item(0), item(0)]); + assert_eq!(sets, vec![(1, 3), (2, 3), (3, 3)]); + } + + #[test] + fn nested_rows_number_per_level() { + let sets = Tree::sibling_sets(&[item(0), item(1), item(2), item(1), item(0)]); + assert_eq!(sets, vec![(1, 2), (1, 2), (1, 1), (2, 2), (2, 2)]); + } + + #[test] + fn parent_skips_the_subtree_above() { + let rows = [item(0), item(1), item(2), item(1), item(0)]; + assert_eq!(Tree::parent_of(&rows, 3), Some(0)); + assert_eq!(Tree::parent_of(&rows, 2), Some(1)); + assert_eq!(Tree::parent_of(&rows, 0), None); + } + + #[test] + fn first_descendant_skips_disabled_rows() { + let rows = [item(0), item(1), item(1), item(0)]; + let selectable = vec![0, 2, 3]; + assert_eq!(Tree::first_descendant(&rows, &selectable, 0), Some(2)); + assert_eq!(Tree::first_descendant(&rows, &selectable, 2), None); + } +} diff --git a/crates/ui/src/editor/code.rs b/crates/ui/src/editor/code.rs new file mode 100644 index 0000000..92dce9a --- /dev/null +++ b/crates/ui/src/editor/code.rs @@ -0,0 +1,576 @@ +//! The code view: a virtualized, read-only rendering of highlighted source. +//! Rows render only when visible, the line-number gutter is part of each +//! row, and the overlay scrollbar is the core one. + +use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility}; +use crate::theme::{ + ActiveTheme as _, CODE_GUTTER_WIDTH, CODE_LINE_HEIGHT, ColorTokens, MONO_ADVANCE_RATIO, Ramps, + WASH_ALPHA_SOFT, +}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, Bounds, ClipboardItem, Context, ElementId, HighlightStyle, Hsla, InteractiveElement as _, + IntoElement, KeyBinding, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, + ParentElement as _, Pixels, Point, Render, ScrollStrategy, SharedString, + StatefulInteractiveElement as _, Styled as _, TextStyle, UniformListScrollHandle, Window, + actions, canvas, div, uniform_list, +}; + +use crate::editor::highlight::{HighlightedCode, Language, Role, highlight}; +use crate::editor::utils::gutter_cell; + +actions!(code_view, [Copy]); + +/// The key context the code view declares while it holds focus. +pub const CODE_VIEW_CONTEXT: &str = "CodeView"; + +/// Binds the code view's copy chord: cmd-c on macOS, ctrl-c elsewhere. +/// +/// Call once at startup. Without it, selection copy has no key. +pub fn bind_code_view_keys(cx: &mut App) { + let context = Some(CODE_VIEW_CONTEXT); + #[cfg(target_os = "macos")] + let copy = "cmd-c"; + #[cfg(not(target_os = "macos"))] + let copy = "ctrl-c"; + cx.bind_keys([KeyBinding::new(copy, Copy, context)]); +} + +/// A point in the source, in lines and characters (not bytes). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct SelectionPoint { + pub row: usize, + pub col: usize, +} + +impl SelectionPoint { + /// The earlier of two points, in document order. + fn earlier_than(&self, other: &Self) -> bool { + (self.row, self.col) <= (other.row, other.col) + } +} + +/// Retained state for a code view. +pub struct CodeViewState { + id: ElementId, + source: SharedString, + language: Language, + code: HighlightedCode, + handle: UniformListScrollHandle, + /// The hovered line, driving the active-line wash and number emphasis. + active_line: Option, + /// `(anchor, head)` in the order they were set. + selection: Option<(SelectionPoint, SelectionPoint)>, + /// Whether a drag that started on a row is still extending the selection. + selecting: bool, + focus_handle: gpui::FocusHandle, + a11y_label: Option, +} + +impl CodeViewState { + /// Builds the state, highlighting `source` with `language`. + pub fn new(id: I, source: S, language: Language, cx: &mut App) -> Self + where + I: Into, + S: Into, + { + let source = source.into(); + let code = highlight(&source, language); + + Self { + id: id.into(), + source, + language, + code, + handle: UniformListScrollHandle::new(), + active_line: None, + selection: None, + selecting: false, + focus_handle: cx.focus_handle().tab_stop(true), + a11y_label: None, + } + } + + /// Replaces the source and re-highlights it. + pub fn set_source(&mut self, source: S, language: Language, cx: &mut Context) + where + S: Into, + { + let source = source.into(); + + self.code = highlight(&source, language); + self.source = source; + self.language = language; + self.selection = None; + self.handle.scroll_to_item(0, ScrollStrategy::Top); + + cx.notify(); + } + + /// Replaces one line's text and re-highlights the file. + pub fn update_line(&mut self, line_ix: usize, text: T, cx: &mut Context) + where + T: AsRef, + { + let trailing_newline = self.source.ends_with('\n'); + let mut lines: Vec = self.source.lines().map(str::to_string).collect(); + let line_ix = line_ix.min(lines.len().saturating_sub(1)); + + let replacement: Vec = if text.as_ref().is_empty() { + vec![String::new()] + } else { + text.as_ref().lines().map(str::to_string).collect() + }; + + lines.splice(line_ix..line_ix + 1, replacement); + self.source = (lines.join("\n") + if trailing_newline { "\n" } else { "" }).into(); + + self.code = highlight(&self.source, self.language); + self.selection = None; + cx.notify(); + } + + /// The highlighted source text. + pub fn source(&self) -> &str { + &self.source + } + + /// The highlighted lines. + pub fn code(&self) -> &HighlightedCode { + &self.code + } + + /// Scrolls `line` to the top of the view. + pub fn scroll_to_line(&self, line: usize) { + self.handle.scroll_to_item( + line.min(self.code.lines.len().saturating_sub(1)), + ScrollStrategy::Top, + ); + } + + /// The line the pointer last hovered, if any. + pub fn active_line(&self) -> Option { + self.active_line + } + + /// Selects a range, endpoints in lines and characters. + pub fn select_range( + &mut self, + start: SelectionPoint, + end: SelectionPoint, + cx: &mut Context, + ) { + self.selection = if start.earlier_than(&end) { + Some((start, end)) + } else { + Some((end, start)) + }; + self.selecting = false; + cx.notify(); + } + + /// The selected range, endpoints in document order, when there is one. + pub fn selection(&self) -> Option<(SelectionPoint, SelectionPoint)> { + self.selection.map(|(anchor, head)| { + if anchor.earlier_than(&head) { + (anchor, head) + } else { + (head, anchor) + } + }) + } + + /// The selected text, or `None` when nothing is selected. + pub fn selected_text(&self) -> Option { + let (start, end) = self.selection()?; + + let lines: Vec<&str> = self.source.split('\n').collect(); + let mut selected = Vec::new(); + + for row in start.row..=end.row.min(lines.len().saturating_sub(1)) { + let line_chars: Vec = lines.get(row)?.chars().collect(); + let start_col = if row == start.row { + start.col.min(line_chars.len()) + } else { + 0 + }; + + let end_col = if row == end.row { + end.col.min(line_chars.len()) + } else { + line_chars.len() + }; + + selected.push(line_chars[start_col..end_col].iter().collect::()); + } + + (!selected.is_empty()).then(|| selected.join("\n")) + } + + // Overrides the accessibility label of the view. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// Maps a window position to a point in the source. + fn position_at( + &self, + bounds: Bounds, + position: Point, + scroll_y: Pixels, + line_height: Pixels, + char_width: Pixels, + text_x: Pixels, + ) -> SelectionPoint { + // Saturating so an empty document cannot invert the clamp. + let last_row = self.code.lines.len().saturating_sub(1); + let row = (((position.y - bounds.origin.y - scroll_y) / line_height).floor() as isize) + .clamp(0, last_row as isize) as usize; + + let chars = self.code.lines.get(row).map_or(0, |line| { + line.spans + .iter() + .map(|span| span.text.chars().count()) + .sum::() + }); + + let col = (((position.x - text_x) / char_width).round() as isize).clamp(0, chars as isize) + as usize; + + SelectionPoint { row, col } + } +} + +impl gpui::Focusable for CodeViewState { + fn focus_handle(&self, _: &App) -> gpui::FocusHandle { + self.focus_handle.clone() + } +} + +impl Render for CodeViewState { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = cx.theme(); + let colors = theme.colors; + let mono_font = theme.mono_font; + let text_size = theme.sizes.small.text_size; + let line_height = text_size * CODE_LINE_HEIGHT; + let char_width = text_size * MONO_ADVANCE_RATIO; + let root_font_size = theme.root_font_size; + + let id = self.id.clone(); + let state = cx.entity(); + let line_count = self.code.lines.len(); + let selection = self.selection(); + let gutter_width = CODE_GUTTER_WIDTH; + + let bounds_cell: std::rc::Rc>>> = + std::rc::Rc::new(std::cell::RefCell::new(None)); + + let rows = uniform_list((id.clone(), "rows"), line_count, { + let id = id.clone(); + let state = state.clone(); + move |range, _window, cx| { + let code = state.read(cx); + let active_line = code.active_line; + let theme = cx.theme(); + + range + .map(|line_ix| { + render_row( + code, + &id, + line_ix, + active_line == Some(line_ix), + selection, + theme.mono_font, + theme.colors, + theme.ramps, + theme.sizes.small.text_size, + line_height, + cx, + ) + }) + .collect() + } + }) + .track_scroll(&self.handle) + .h_full() + .w_full(); + + div() + .id((id.clone(), "view")) + .relative() + .size_full() + .text_size(text_size) + .font_family(mono_font) + .text_color(colors.foreground) + .key_context(CODE_VIEW_CONTEXT) + .track_focus(&self.focus_handle) + .on_mouse_down(MouseButton::Left, { + let state = state.clone(); + let bounds_cell = bounds_cell.clone(); + move |event: &MouseDownEvent, window: &mut Window, cx: &mut App| { + window.focus(&state.read(cx).focus_handle.clone(), cx); + + let bounds = bounds_cell.borrow(); + let Some(bounds) = bounds.as_ref() else { + return; + }; + + let text_x = bounds.origin.x + gutter_width + root_font_size; + let point = { + let code = state.read(cx); + code.position_at( + *bounds, + event.position, + ScrollbarHandle::offset(&code.handle).y, + line_height, + char_width, + text_x, + ) + }; + + state.update(cx, |state, cx| { + if event.modifiers.shift { + if let Some((anchor, _)) = state.selection { + state.selection = Some((anchor, point)); + } else { + state.selection = Some((point, point)); + } + } else { + state.selection = Some((point, point)); + } + state.selecting = true; + cx.notify(); + }); + } + }) + .on_mouse_move({ + let state = state.clone(); + let bounds_cell = bounds_cell.clone(); + move |event: &MouseMoveEvent, _window: &mut Window, cx: &mut App| { + let bounds = bounds_cell.borrow(); + let Some(bounds) = bounds.as_ref() else { + return; + }; + + let text_x = bounds.origin.x + gutter_width + root_font_size; + let point = { + let code = state.read(cx); + code.position_at( + *bounds, + event.position, + ScrollbarHandle::offset(&code.handle).y, + line_height, + char_width, + text_x, + ) + }; + + let selecting = state.read(cx).selecting; + if selecting { + let changed = state + .read(cx) + .selection + .map(|(_, head)| head != point) + .unwrap_or(true); + if changed { + state.update(cx, |state, cx| { + if let Some((anchor, _)) = state.selection { + state.selection = Some((anchor, point)); + } + cx.notify(); + }); + } + return; + } + + let changed = state.read(cx).active_line != Some(point.row); + if changed { + state.update(cx, |state, cx| { + state.active_line = Some(point.row); + cx.notify(); + }); + } + } + }) + .on_mouse_up(MouseButton::Left, { + let state = state.clone(); + move |_: &MouseUpEvent, _window: &mut Window, cx: &mut App| { + if state.read(cx).selecting { + state.update(cx, |state, cx| { + state.selecting = false; + cx.notify(); + }); + } + } + }) + .on_action({ + let state = state.clone(); + move |_: &Copy, _window, cx| { + if let Some(text) = state.read(cx).selected_text() { + cx.write_to_clipboard(ClipboardItem::new_string(text)); + } + } + }) + .child( + canvas( + { + let bounds_cell = bounds_cell.clone(); + move |bounds, _window, _cx| { + *bounds_cell.borrow_mut() = Some(bounds); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ) + .child(rows) + .child( + Scrollbar::vertical((self.id.clone(), "v-scrollbar"), self.handle.clone()) + .visibility(ScrollbarVisibility::Platform), + ) + .when_some(self.a11y_label.clone(), |view, label| { + view.aria_label(label) + }) + } +} + +#[allow(clippy::too_many_arguments)] +fn render_row( + code: &CodeViewState, + id: &ElementId, + line_ix: usize, + active: bool, + selection: Option<(SelectionPoint, SelectionPoint)>, + mono_font: &'static str, + colors: ColorTokens, + ramps: Ramps, + text_size: Pixels, + line_height: Pixels, + cx: &App, +) -> gpui::AnyElement { + let line = code.code().lines.get(line_ix); + + let mut text = String::new(); + for span in line.map_or(&[][..], |line| line.spans.as_slice()) { + text.push_str(&span.text); + } + + let char_count = text.chars().count(); + let mut roles = vec![Role::Text; char_count]; + let mut offset = 0usize; + + for span in line.map_or(&[][..], |line| line.spans.as_slice()) { + let chars = span.text.chars().count(); + for slot in &mut roles[offset..offset + chars] { + *slot = span.role; + } + offset += chars; + } + + let mut selected = vec![false; char_count]; + + if let Some((start, end)) = selection + && line_ix >= start.row + && line_ix <= end.row + { + let start_col = if line_ix == start.row { + start.col.min(char_count) + } else { + 0 + }; + + let end_col = if line_ix == end.row { + end.col.min(char_count) + } else { + char_count + }; + + for slot in &mut selected[start_col..end_col] { + *slot = true; + } + } + + let mut highlights: Vec<(std::ops::Range, HighlightStyle)> = Vec::new(); + let mut run_start = 0usize; + let mut run_end = 0usize; + let mut run_role = Role::Text; + let mut run_selected = false; + + for (char_ix, (byte_ix, character)) in text.char_indices().enumerate() { + let fresh = char_ix == 0 || roles[char_ix] != run_role || selected[char_ix] != run_selected; + if fresh { + if char_ix > 0 { + highlights.push(( + run_start..run_end, + run_role.run_style(run_selected, colors, ramps), + )); + } + run_start = byte_ix; + run_role = roles[char_ix]; + run_selected = selected[char_ix]; + } + run_end = byte_ix + character.len_utf8(); + } + + if run_end > run_start || !text.is_empty() { + highlights.push(( + run_start..run_end, + run_role.run_style(run_selected, colors, ramps), + )); + } + + let style = TextStyle { + color: colors.foreground, + font_family: SharedString::from(mono_font), + font_size: text_size.into(), + line_height: line_height.into(), + white_space: gpui::WhiteSpace::Nowrap, + ..Default::default() + }; + + div() + .debug_selector(move || format!("{id}-row-{line_ix}")) + .id(("code-row", line_ix)) + .w_full() + .h(line_height) + .flex() + .items_center() + .overflow_hidden() + .when(active, |row| { + row.bg(Hsla { + a: colors.muted.a * WASH_ALPHA_SOFT, + ..colors.muted + }) + }) + .child( + gutter_cell( + cx, + if active { + colors.foreground + } else { + colors.muted_foreground + }, + format!("{}", line_ix + 1), + ) + .justify_end() + .pr_2() + .whitespace_nowrap(), + ) + .child( + div() + .flex_1() + .min_w_0() + .ml_4() + .overflow_hidden() + .whitespace_nowrap() + .child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)), + ) + .into_any_element() +} diff --git a/crates/ui/src/editor/diff.rs b/crates/ui/src/editor/diff.rs new file mode 100644 index 0000000..758b6f5 --- /dev/null +++ b/crates/ui/src/editor/diff.rs @@ -0,0 +1,691 @@ +//! The diff view: a unified, syntax-highlighted rendering of two versions of +//! a file, in the style of the Pierre diff engine used by tangled.org: change +//! bars instead of markers, tinted number gutters, word-level intra-line +//! highlights and hunk separators. Rows reuse the code view's highlighting; +//! consumers that already hold a git diff can build [`DiffRow`]s themselves +//! instead of calling [`DiffViewState::diff_rows`]. + +use crate::components::scrollbar::{Scrollbar, ScrollbarHandle, ScrollbarVisibility}; +use crate::theme::{ActiveTheme as _, BORDER_WIDTH, CODE_GUTTER_WIDTH, MONO_ADVANCE_RATIO}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, Context, ElementId, HighlightStyle, InteractiveElement as _, IntoElement, + ListHorizontalSizingBehavior, ParentElement as _, Pixels, Render, ScrollStrategy, SharedString, + StatefulInteractiveElement as _, Styled as _, TextStyle, UniformListScrollHandle, Window, div, + point, uniform_list, +}; +use similar::{Change, ChangeTag, TextDiff}; + +use std::ops::Range; + +use crate::editor::highlight::{HighlightedCode, Language, Line, Role, highlight}; +use crate::editor::utils::{gutter_cell, wash, wash_gutter, wash_strong}; + +/// What a diff row did to the file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DiffRowKind { + /// Present in both versions. + Context, + /// Only in the new version. + Added, + /// Only in the old version. + Removed, + /// A hunk separator introducing the rows after it. + Hunk, +} + +/// One row of a unified diff: a diff line or a hunk separator. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DiffRow { + pub kind: DiffRowKind, + /// The highlighted line content; empty for hunk separators. + pub content: Line, + /// 1-based line number in the old version, when the row exists there. + pub old_number: Option, + /// 1-based line number in the new version, when the row exists there. + pub new_number: Option, + /// Byte ranges of intra-line word changes, tinted on changed rows. + pub changed_ranges: Vec>, + /// The `@@ -a,b +c,d @@` header, for hunk separator rows. + pub header: SharedString, + /// Unchanged lines collapsed into this separator row; zero elsewhere. + pub hidden_lines: usize, +} + +/// How changed rows are marked. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum DiffIndicators { + /// A two-pixel bar on the row's left edge. + #[default] + Bars, + /// Classic `+`/`-` glyphs in a marker column. + Classic, + /// Only the background washes. + None, +} + +/// How collapsed regions between hunks render. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum HunkSeparator { + /// The collapsed unchanged line count, centered. + #[default] + LineInfo, + /// The patch-style `@@ -a,b +c,d @@` header. + Metadata, + /// A minimal `···` bar. + Simple, +} + +/// Presentation options for the diff view. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DiffViewOptions { + pub indicators: DiffIndicators, + pub separator: HunkSeparator, + /// Whether the line-number gutter renders. + pub line_numbers: bool, +} + +impl Default for DiffViewOptions { + fn default() -> Self { + Self { + indicators: DiffIndicators::Bars, + separator: HunkSeparator::LineInfo, + line_numbers: true, + } + } +} + +impl DiffRow { + /// Assembles a diff line row from a `similar` change. + pub(crate) fn from_change( + change: &Change<&str>, + code: &HighlightedCode, + changed_ranges: Vec>, + ) -> DiffRow { + let content = match change.tag() { + ChangeTag::Equal => change + .new_index() + .and_then(|ix| code.lines.get(ix)) + .cloned() + .unwrap_or_default(), + ChangeTag::Delete => change + .old_index() + .and_then(|ix| code.lines.get(ix)) + .cloned() + .unwrap_or_default(), + ChangeTag::Insert => change + .new_index() + .and_then(|ix| code.lines.get(ix)) + .cloned() + .unwrap_or_default(), + }; + + let (old_number, new_number) = match change.tag() { + ChangeTag::Equal => ( + change.old_index().map(|ix| ix + 1), + change.new_index().map(|ix| ix + 1), + ), + ChangeTag::Delete => (change.old_index().map(|ix| ix + 1), None), + ChangeTag::Insert => (None, change.new_index().map(|ix| ix + 1)), + }; + + DiffRow { + kind: match change.tag() { + ChangeTag::Equal => DiffRowKind::Context, + ChangeTag::Delete => DiffRowKind::Removed, + ChangeTag::Insert => DiffRowKind::Added, + }, + content, + old_number, + new_number, + changed_ranges, + header: Default::default(), + hidden_lines: 0, + } + } + + /// The row's text length, in characters. + fn char_count(&self) -> usize { + self.content.text().chars().count() + } + + /// Stable element id: the kind and line numbers packed into one integer. + fn element_id(&self, hunk_ordinal: usize) -> ElementId { + let kind = match self.kind { + DiffRowKind::Context => 0u64, + DiffRowKind::Added => 1, + DiffRowKind::Removed => 2, + DiffRowKind::Hunk => { + return ElementId::named_usize("diff-hunk", hunk_ordinal); + } + }; + // Line numbers saturate at 2^31 so the two fields never overlap. + let old = self.old_number.unwrap_or(0).min((1 << 31) - 1) as u64; + let new = self.new_number.unwrap_or(0).min((1 << 31) - 1) as u64; + ElementId::named_usize("diff-row", ((kind << 62) | (old << 31) | new) as usize) + } +} + +/// Retained state for a diff view. +pub struct DiffViewState { + id: ElementId, + rows: Vec, + /// Cached per-row id and text length, parallel to `rows`. + row_layouts: Vec, + /// The row whose width drives horizontal scroll extent, `rows`-derived. + widest_row: Option, + options: DiffViewOptions, + /// Drives both scroll axes of the virtualized row list. + handle: UniformListScrollHandle, + a11y_label: Option, +} + +/// Cached per-row render data, computed once when the rows are set. +struct RowLayout { + id: ElementId, + char_count: usize, +} + +impl DiffViewState { + /// Builds the state, diffing `old` against `new`. + pub fn new(id: I, old: O, new: N, language: Language) -> Self + where + I: Into, + O: AsRef, + N: AsRef, + { + let mut state = Self { + id: id.into(), + rows: Vec::new(), + row_layouts: Vec::new(), + widest_row: None, + options: DiffViewOptions::default(), + handle: UniformListScrollHandle::new(), + a11y_label: None, + }; + state.set_rows(old, new, language); + state + } + + /// Replaces the rows, recomputing the per-row layout cache with them. + fn set_rows(&mut self, old: O, new: N, language: Language) + where + O: AsRef, + N: AsRef, + { + self.rows = Self::diff_rows(old.as_ref(), new.as_ref(), language); + + let mut hunk_ordinal = 0usize; + self.row_layouts = self + .rows + .iter() + .map(|row| { + let ordinal = if row.kind == DiffRowKind::Hunk { + hunk_ordinal += 1; + hunk_ordinal + } else { + 0 + }; + RowLayout { + id: row.element_id(ordinal), + char_count: row.char_count(), + } + }) + .collect(); + + self.widest_row = self + .rows + .iter() + .zip(&self.row_layouts) + .enumerate() + .filter(|(_, (row, _))| row.kind != DiffRowKind::Hunk) + .max_by_key(|(_, (_, layout))| layout.char_count) + .map(|(widest, _)| widest); + } + + /// Computes unified rows between two texts, highlighting every line with `language`. + pub fn diff_rows(old: &str, new: &str, language: Language) -> Vec { + let old_code = highlight(old, language); + let new_code = highlight(new, language); + let diff = TextDiff::from_lines(old, new); + + let mut rows = Vec::new(); + let mut collapsed_before = 0usize; + + for group in diff.grouped_ops(3) { + let (Some(first), Some(last)) = (group.first(), group.last()) else { + continue; + }; + + let old_range = first.old_range().start..last.old_range().end; + let new_range = first.new_range().start..last.new_range().end; + + // git prints the line before a pure insertion when the count is zero. + let old_start = if old_range.is_empty() { + old_range.start + } else { + old_range.start + 1 + }; + + let new_start = if new_range.is_empty() { + new_range.start + } else { + new_range.start + 1 + }; + + let collapsed = first.old_range().start.saturating_sub(collapsed_before); + if collapsed > 0 { + rows.push(DiffRow { + kind: DiffRowKind::Hunk, + content: Line::default(), + old_number: None, + new_number: None, + changed_ranges: Vec::new(), + header: format!( + "@@ -{},{} +{},{} @@", + old_start, + old_range.len(), + new_start, + new_range.len() + ) + .into(), + hidden_lines: collapsed, + }); + } + collapsed_before = last.old_range().end; + + for op in &group { + let changes: Vec<_> = diff.iter_changes(op).collect(); + let mut index = 0; + + while index < changes.len() { + if changes[index].tag() == ChangeTag::Equal { + rows.push(DiffRow::from_change(&changes[index], &new_code, Vec::new())); + index += 1; + continue; + } + + let deletions = changes[index..] + .iter() + .take_while(|change| change.tag() == ChangeTag::Delete) + .count(); + + let insertions = changes[index + deletions..] + .iter() + .take_while(|change| change.tag() == ChangeTag::Insert) + .count(); + + let mut deletion_ranges = vec![Vec::new(); deletions]; + let mut insertion_ranges = vec![Vec::new(); insertions]; + + for pair in 0..deletions.min(insertions) { + let old_text = changes[index + pair].value().trim_end_matches('\n'); + let new_text = changes[index + deletions + pair] + .value() + .trim_end_matches('\n'); + let words = TextDiff::from_words(old_text, new_text); + + let (mut old_offset, mut new_offset) = (0usize, 0usize); + + for word in words.iter_all_changes() { + let len = word.value().len(); + + match word.tag() { + ChangeTag::Delete => { + deletion_ranges[pair].push(old_offset..old_offset + len); + old_offset += len; + } + ChangeTag::Insert => { + insertion_ranges[pair].push(new_offset..new_offset + len); + new_offset += len; + } + ChangeTag::Equal => { + old_offset += len; + new_offset += len; + } + } + } + } + + for pair in 0..deletions { + rows.push(DiffRow::from_change( + &changes[index + pair], + &old_code, + deletion_ranges[pair].clone(), + )); + } + + for pair in 0..insertions { + rows.push(DiffRow::from_change( + &changes[index + deletions + pair], + &new_code, + insertion_ranges[pair].clone(), + )); + } + + index += deletions + insertions; + } + } + } + + rows + } + + /// Sets how changed rows are marked. + pub fn indicators(mut self, indicators: DiffIndicators) -> Self { + self.options.indicators = indicators; + self + } + + /// Sets how collapsed regions between hunks render. + pub fn hunk_separator(mut self, separator: HunkSeparator) -> Self { + self.options.separator = separator; + self + } + + /// Shows or hides the line-number gutter. + pub fn line_numbers(mut self, show: bool) -> Self { + self.options.line_numbers = show; + self + } + + /// Replaces the versions and re-diffs them. + pub fn set_versions(&mut self, old: O, new: N, language: Language, cx: &mut Context) + where + O: AsRef, + N: AsRef, + { + self.set_rows(old, new, language); + self.handle.scroll_to_item(0, ScrollStrategy::Top); + // The replaced versions rarely share the old width; start at the left. + let offset = ScrollbarHandle::offset(&self.handle); + ScrollbarHandle::set_offset(&self.handle, point(Pixels::ZERO, offset.y)); + cx.notify(); + } + + /// The diff rows. + pub fn rows(&self) -> &[DiffRow] { + &self.rows + } + + /// Scrolls the first added or removed row to the top of the view. + pub fn scroll_to_first_change(&self) { + let Some(row) = self + .rows + .iter() + .position(|row| matches!(row.kind, DiffRowKind::Added | DiffRowKind::Removed)) + else { + return; + }; + self.handle.scroll_to_item(row, ScrollStrategy::Top); + } + + /// Overrides the accessibility label of the view. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } +} + +impl Render for DiffViewState { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = cx.theme(); + let text_size = theme.sizes.small.text_size; + + let id = self.id.clone(); + let state = cx.entity(); + let row_count = self.rows.len(); + let options = self.options; + let widest_row = self.widest_row; + + let mut rows = uniform_list((id.clone(), "rows"), row_count, { + move |range, _window, cx| { + let diff = state.read(cx); + range + .map(|row_index| { + render_row( + &diff.rows[row_index], + &diff.row_layouts[row_index], + row_index, + options, + cx, + ) + }) + .collect() + } + }) + .with_horizontal_sizing_behavior(ListHorizontalSizingBehavior::Unconstrained) + .with_width_from_item(widest_row) + .track_scroll(&self.handle) + .h_full(); + + // Lock each gesture to its initial axis + rows.interactivity().base_style.restrict_scroll_to_axis = Some(true); + + div() + .id((id.clone(), "view")) + .relative() + .size_full() + .text_size(text_size) + .when_some(self.a11y_label.clone(), |view, label| { + view.aria_label(label) + }) + .child(rows) + .child( + Scrollbar::vertical((self.id.clone(), "v-scrollbar"), self.handle.clone()) + .visibility(ScrollbarVisibility::Platform), + ) + .child( + Scrollbar::horizontal((self.id.clone(), "h-scrollbar"), self.handle.clone()) + .visibility(ScrollbarVisibility::Platform), + ) + } +} + +fn render_row( + row: &DiffRow, + layout: &RowLayout, + row_index: usize, + options: DiffViewOptions, + cx: &App, +) -> gpui::AnyElement { + let theme = cx.theme(); + let mono_font = theme.mono_font; + let colors = theme.colors; + let ramps = theme.ramps; + let text_size = theme.sizes.small.text_size; + let line_height = text_size * 1.5; + let char_width = text_size * MONO_ADVANCE_RATIO; + + let frame = div() + .debug_selector(move || format!("diff-row-{row_index}")) + .id(layout.id.clone()) + .w_full() + .h(line_height) + .font_family(mono_font) + .text_size(text_size) + .overflow_hidden(); + + if row.kind == DiffRowKind::Hunk { + let content = match options.separator { + HunkSeparator::LineInfo => { + SharedString::from(format!("{} unchanged lines", row.hidden_lines)) + } + HunkSeparator::Metadata => row.header.clone(), + HunkSeparator::Simple => SharedString::from("···"), + }; + + return frame + .flex() + .items_center() + .text_color(colors.muted_foreground) + .when( + options.indicators == DiffIndicators::Classic, + |row_element| row_element.child(div().w(CODE_GUTTER_WIDTH).flex_none()), + ) + .when(options.line_numbers, |row_element| { + row_element.child(div().w(CODE_GUTTER_WIDTH).flex_none()) + }) + .when( + options.indicators == DiffIndicators::Bars && !options.line_numbers, + |row_element| { + row_element.child( + div() + .flex_none() + .border_l(BORDER_WIDTH * 4.0) + .border_color(gpui::transparent_black()), + ) + }, + ) + .child(div().flex_none().ml_2().child(content)) + .into_any_element(); + } + + let change_color = match row.kind { + DiffRowKind::Added => ramps.success.base, + DiffRowKind::Removed => ramps.destructive.base, + DiffRowKind::Context | DiffRowKind::Hunk => gpui::transparent_black(), + }; + + let wash = match row.kind { + DiffRowKind::Added => Some(wash(ramps.success.base)), + DiffRowKind::Removed => Some(wash(ramps.destructive.base)), + DiffRowKind::Context | DiffRowKind::Hunk => None, + }; + + let mut text = String::new(); + let mut spans: Vec<(Range, Role)> = Vec::new(); + + for span in &row.content.spans { + let start = text.len(); + text.push_str(&span.text); + if span.role != Role::Text { + spans.push((start..text.len(), span.role)); + } + } + + let mut boundaries: Vec = spans + .iter() + .flat_map(|(range, _)| [range.start, range.end]) + .chain( + row.changed_ranges + .iter() + .flat_map(|range| [range.start, range.end]), + ) + .collect(); + + boundaries.sort_unstable(); + boundaries.dedup(); + + let mut highlights: Vec<(std::ops::Range, HighlightStyle)> = Vec::new(); + let mut span_ix = 0; + + for window in boundaries.windows(2) { + let (start, end) = (window[0], window[1]); + while span_ix < spans.len() && spans[span_ix].0.end <= start { + span_ix += 1; + } + + let mut segment = HighlightStyle::default(); + if let Some((range, role)) = spans.get(span_ix) + && range.contains(&start) + && *role != Role::Text + { + segment = segment.highlight(HighlightStyle { + color: Some(role.color(colors, ramps)), + ..Default::default() + }); + } + + if row + .changed_ranges + .iter() + .any(|range| range.contains(&start)) + { + segment = segment.highlight(HighlightStyle { + background_color: Some(wash_strong(change_color)), + ..Default::default() + }); + } + + highlights.push((start..end, segment)); + } + + let style = TextStyle { + color: colors.foreground, + font_family: SharedString::from(mono_font), + font_size: text_size.into(), + line_height: line_height.into(), + ..Default::default() + }; + + frame + .flex() + .items_center() + .when_some(wash, |row_element, tint| row_element.bg(tint)) + .when( + options.indicators == DiffIndicators::Classic, + |row_element| { + row_element.child(gutter_cell( + cx, + if row.kind == DiffRowKind::Context { + gpui::transparent_black() + } else { + change_color + }, + match row.kind { + DiffRowKind::Added => "+", + DiffRowKind::Removed => "-", + _ => "", + }, + )) + }, + ) + .when(options.line_numbers, |row_element| { + row_element.child( + gutter_cell( + cx, + colors.muted_foreground, + row.new_number + .or(row.old_number) + .map(|number| number.to_string()) + .unwrap_or_default(), + ) + .w(CODE_GUTTER_WIDTH) + .whitespace_nowrap() + .bg(match row.kind { + DiffRowKind::Context => wash_gutter(&colors), + _ => wash_strong(change_color), + }) + .when(options.indicators == DiffIndicators::Bars, |number| { + number + .border_l(BORDER_WIDTH * 4.0) + .border_color(change_color) + }), + ) + }) + .when( + options.indicators == DiffIndicators::Bars && !options.line_numbers, + |row_element| { + row_element.child( + div() + .h_full() + .flex_none() + .border_l(BORDER_WIDTH * 4.0) + .border_color(change_color), + ) + }, + ) + .child( + div() + .flex_none() + .ml_2() + .w(char_width * layout.char_count as f32) + .whitespace_nowrap() + .child(gpui::StyledText::new(text).with_default_highlights(&style, highlights)), + ) + .into_any_element() +} diff --git a/crates/ui/src/editor/highlight.rs b/crates/ui/src/editor/highlight.rs new file mode 100644 index 0000000..016bb9c --- /dev/null +++ b/crates/ui/src/editor/highlight.rs @@ -0,0 +1,267 @@ +//! Tree-sitter highlighting: source text in, role-styled lines out. Roles +//! are resolved to theme colors at render time, so a theme change re-colors +//! code without re-parsing it. + +use crate::utils::ResultLogErr; +use gpui::SharedString; +use std::cell::RefCell; +use std::collections::HashMap; +#[cfg(not(target_arch = "wasm32"))] +use tree_sitter::StreamingIterator as _; + +#[cfg(not(target_arch = "wasm32"))] +thread_local! { + static HIGHLIGHTERS: RefCell>> = + RefCell::new(HashMap::new()); +} + +/// A grammar's parser and compiled highlight query. +#[cfg(not(target_arch = "wasm32"))] +struct Highlighter { + parser: tree_sitter::Parser, + query: tree_sitter::Query, + roles: Vec>, +} + +/// A language source can highlight as. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Language { + Plain, + Rust, + JavaScript, + TypeScript, + Python, +} + +/// The semantic role a span plays. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Role { + Text, + Keyword, + String, + Comment, + Function, + Type, + Number, + Constant, + Property, + Operator, + Punctuation, + Tag, + Escape, +} + +/// A run of text sharing one role. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Span { + pub text: SharedString, + pub role: Role, +} + +/// One rendered line of code. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct Line { + pub spans: Vec, +} + +impl Line { + /// The line's flat text, in character order. + pub fn text(&self) -> String { + let mut text = String::new(); + for span in &self.spans { + text.push_str(&span.text); + } + text + } +} + +/// Source text split into role-styled lines. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct HighlightedCode { + pub lines: Vec, +} + +/// Highlights `source` with `language`'s tree-sitter grammar. +#[cfg(not(target_arch = "wasm32"))] +pub fn highlight(source: &str, language: Language) -> HighlightedCode { + let Some((grammar, query_source)) = grammar_for(language) else { + return plain(source); + }; + + HIGHLIGHTERS.with(|cache| { + let mut cache = cache.borrow_mut(); + let highlighter = cache + .entry(language) + .or_insert_with(|| { + let mut parser = tree_sitter::Parser::new(); + parser.set_language(&grammar).log_err()?; + let query = tree_sitter::Query::new(&grammar, query_source).log_err()?; + let roles = query + .capture_names() + .iter() + .map(|name| role_for_capture(name)) + .collect(); + Some(Highlighter { + parser, + query, + roles, + }) + }) + .as_mut(); + + let Some(highlighter) = highlighter else { + return plain(source); + }; + + let Some(tree) = highlighter.parser.parse(source, None) else { + log::warn!("tree-sitter failed to parse {language:?}; rendering plain text"); + return plain(source); + }; + + // One role per byte; matches arrive in query order + let mut role_at = vec![None; source.len()]; + let mut cursor = tree_sitter::QueryCursor::new(); + let mut matches = cursor.matches(&highlighter.query, tree.root_node(), source.as_bytes()); + + while let Some(matched) = matches.next() { + for capture in matched.captures { + let Some(role) = highlighter + .roles + .get(capture.index as usize) + .copied() + .flatten() + else { + continue; + }; + for byte in capture.node.byte_range() { + if let Some(slot) = role_at.get_mut(byte) { + *slot = Some(role); + } + } + } + } + + build_lines(source, &role_at) + }) +} + +/// The web target has no tree-sitter parsers. +#[cfg(target_arch = "wasm32")] +pub fn highlight(source: &str, _language: Language) -> HighlightedCode { + plain(source) +} + +/// Source rendered without any grammar: plain text roles. +pub(crate) fn plain(source: &str) -> HighlightedCode { + build_lines(source, &[]) +} + +/// The grammar and its highlight query for a language, when compiled in. +#[cfg(not(target_arch = "wasm32"))] +fn grammar_for(language: Language) -> Option<(tree_sitter::Language, &'static str)> { + match language { + Language::Rust => rust_grammar(), + Language::TypeScript => typescript_grammar(), + Language::JavaScript => javascript_grammar(), + Language::Python => python_grammar(), + Language::Plain => None, + } +} + +/// The Rust grammar. +#[cfg(not(target_arch = "wasm32"))] +fn rust_grammar() -> Option<(tree_sitter::Language, &'static str)> { + Some(( + tree_sitter_rust::LANGUAGE.into(), + tree_sitter_rust::HIGHLIGHTS_QUERY, + )) +} + +/// The TypeScript grammar. +#[cfg(not(target_arch = "wasm32"))] +fn typescript_grammar() -> Option<(tree_sitter::Language, &'static str)> { + Some(( + tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(), + tree_sitter_typescript::HIGHLIGHTS_QUERY, + )) +} + +/// The JavaScript grammar. +#[cfg(not(target_arch = "wasm32"))] +fn javascript_grammar() -> Option<(tree_sitter::Language, &'static str)> { + Some(( + tree_sitter_javascript::LANGUAGE.into(), + tree_sitter_javascript::HIGHLIGHT_QUERY, + )) +} + +/// The Python grammar. +#[cfg(not(target_arch = "wasm32"))] +fn python_grammar() -> Option<(tree_sitter::Language, &'static str)> { + Some(( + tree_sitter_python::LANGUAGE.into(), + tree_sitter_python::HIGHLIGHTS_QUERY, + )) +} + +/// Maps a query capture name to a role; unmapped captures render as text. +fn role_for_capture(name: &str) -> Option { + match name.split('.').next()? { + "keyword" => Some(Role::Keyword), + "string" => Some(Role::String), + "escape" => Some(Role::Escape), + "comment" => Some(Role::Comment), + "function" | "method" => Some(Role::Function), + "type" | "attribute" => Some(Role::Type), + "number" => Some(Role::Number), + "constant" => Some(Role::Constant), + "property" => Some(Role::Property), + "operator" => Some(Role::Operator), + "punctuation" => Some(Role::Punctuation), + "tag" => Some(Role::Tag), + _ => None, + } +} + +/// Splits `source` into lines, grouping consecutive bytes that share a role into one span. +fn build_lines(source: &str, role_at: &[Option]) -> HighlightedCode { + let role_of = + |byte: usize| -> Role { role_at.get(byte).copied().flatten().unwrap_or(Role::Text) }; + + let mut lines = Vec::new(); + let mut spans: Vec = Vec::new(); + let mut text = String::new(); + let mut role = Role::Text; + + for (byte, character) in source.char_indices() { + let byte_role = role_of(byte); + if character == '\n' { + flush_run(&mut text, role, &mut spans); + lines.push(Line { + spans: std::mem::take(&mut spans), + }); + continue; + } + if byte_role != role && !text.is_empty() { + flush_run(&mut text, role, &mut spans); + } + role = byte_role; + text.push(character); + } + + flush_run(&mut text, role, &mut spans); + lines.push(Line { + spans: std::mem::take(&mut spans), + }); + + HighlightedCode { lines } +} + +fn flush_run(text: &mut String, role: Role, spans: &mut Vec) { + if !text.is_empty() { + spans.push(Span { + text: SharedString::from(std::mem::take(text)), + role, + }); + } +} diff --git a/crates/ui/src/editor/markdown.rs b/crates/ui/src/editor/markdown.rs new file mode 100644 index 0000000..569f601 --- /dev/null +++ b/crates/ui/src/editor/markdown.rs @@ -0,0 +1,2072 @@ +//! The markdown view: a read-only rendering of a markdown document as +//! formatted text. Parsing runs once per source change and produces blocks; +//! rendering virtualizes the visible blocks and resolves every style from +//! the theme at draw time. Images render inline or as standalone blocks; +//! text, code, and tables drag-select and copy; task checkboxes report +//! toggles and code blocks offer a copy action. Footnotes, math, and HTML +//! render nothing; long code lines clip rather than scroll. + +use crate::components::button::{Button, ButtonVariant}; +use crate::components::checkbox::Checkbox; +use crate::components::common::Sizable as _; +use crate::components::scrollbar::{Scrollbar, ScrollbarVisibility}; +use crate::theme::{ + ActiveTheme as _, BORDER_WIDTH, CODE_LINE_HEIGHT, CODE_OVERSCROLL_MAX, Size, TextRole, + Typeset as _, +}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + AnyElement, App, Bounds, ClipboardItem, Context, Div, Element, ElementId, Entity, FontStyle, + GlobalElementId, HighlightStyle, InspectorElementId, InteractiveElement as _, InteractiveText, + IntoElement, KeyBinding, LayoutId, ListAlignment, ListOffset, ListState, MouseButton, + MouseDownEvent, MouseMoveEvent, ObjectFit, ParentElement as _, Pixels, Refineable as _, Render, + SharedString, StatefulInteractiveElement as _, StrikethroughStyle, StyleRefinement, Styled, + StyledImage as _, StyledText, TextLayout, UnderlineStyle, Window, actions, div, img, list, px, + relative, +}; +use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd}; + +use std::borrow::Borrow as _; +use std::collections::HashMap; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::ops::Range; +use std::sync::Arc; + +use crate::editor::highlight::{HighlightedCode, Language, highlight, plain}; +use crate::editor::utils::code_line; + +/// The bottom padding between sibling blocks, in root font sizes. +const BLOCK_GAP: f32 = 0.75; +/// The tighter bottom padding between list items, in root font sizes. +const ITEM_GAP: f32 = 0.2; +/// The room a list marker column takes, in root font sizes. +const MARKER_WIDTH: f32 = 1.75; +/// The text inset behind a quote bar, in root font sizes. +const QUOTE_INSET: f32 = 1.0; +/// The indent each list level adds, in root font sizes. +const INDENT_STEP: f32 = 1.5; +/// The body line height. +const BODY_LINE_HEIGHT: f32 = 1.6; +/// The tallest a standalone image renders, in root font sizes. +const IMAGE_MAX_HEIGHT: f32 = 14.0; +/// The side of an inline image atom relative to the body text size. +const INLINE_IMAGE_SCALE: f32 = 1.15; +/// The key context the text view declares while it holds focus. +pub const TEXT_VIEW_CONTEXT: &str = "TextView"; + +/// The callback a view invokes when the user clicks a markdown link. +pub type LinkClickHandler = Arc; +/// The callback a view invokes when the user toggles a task checkbox. +pub type TaskToggleHandler = Arc; + +actions!(text_view, [Copy]); + +/// A heading level, 1 to 6. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MarkdownHeading { + H1, + H2, + H3, + H4, + H5, + H6, +} + +impl MarkdownHeading { + /// The level as a number, 1 to 6. + pub fn level(self) -> usize { + match self { + MarkdownHeading::H1 => 1, + MarkdownHeading::H2 => 2, + MarkdownHeading::H3 => 3, + MarkdownHeading::H4 => 4, + MarkdownHeading::H5 => 5, + MarkdownHeading::H6 => 6, + } + } +} + +/// The marker drawn before a list item. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ListMarker { + /// An unordered bullet. + Bullet, + /// An ordered item, carrying its number in the list. + Ordered(u64), + /// A task item, `true` when checked. + Task(bool), +} + +/// One inline item of a paragraph or list item: styled text or an image. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum InlineItem { + Text(InlineSpan), + Image { + source: SharedString, + alt: SharedString, + }, +} + +/// The inline style a text run carries. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum InlineStyle { + Text, + Emphasis, + Strong, + StrongEmphasis, + Strikethrough, + /// Inline code. + Code, + /// A link with its destination. + Link { + destination: SharedString, + }, +} + +/// One rendered block of a markdown document. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum MarkdownBlock { + Heading { + level: MarkdownHeading, + spans: Vec, + /// How many lists the heading's content sits under. + indent: usize, + /// Whether a blockquote wraps the heading. + quote: bool, + }, + Paragraph { + items: Vec, + /// How many lists the paragraph's content sits under. + indent: usize, + /// Whether a blockquote wraps the paragraph. + quote: bool, + }, + ListItem { + marker: ListMarker, + items: Vec, + /// How many lists wrap this item's list, zero for the outermost. + indent: usize, + quote: bool, + }, + /// An image that stands alone in its paragraph. + Image { + source: SharedString, + alt: SharedString, + /// How many lists the block sits under. + indent: usize, + /// Whether a blockquote wraps the block. + quote: bool, + }, + Code { + language: Option, + lines: HighlightedCode, + /// How many lists the block sits under. + indent: usize, + /// Whether a blockquote wraps the block. + quote: bool, + }, + ThematicBreak { + indent: usize, + quote: bool, + }, + Table { + table: MarkdownTable, + indent: usize, + quote: bool, + }, +} + +impl MarkdownBlock { + /// Hashes the block so element ids track content, not list position. + fn content_hash(&self) -> u64 { + let mut hasher = DefaultHasher::new(); + self.hash(&mut hasher); + hasher.finish() + } +} + +/// One run of inline text sharing a style. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct InlineSpan { + pub text: SharedString, + pub style: InlineStyle, +} + +/// One cell of a table row. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct MarkdownTableCell { + pub spans: Vec, +} + +/// A table row; the header row precedes the body rows. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct MarkdownTableRow { + pub cells: Vec, + pub header: bool, +} + +/// A table, header row first. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub struct MarkdownTable { + pub rows: Vec, +} + +/// Retained state for a markdown view. +pub struct MarkdownViewState { + id: ElementId, + source: SharedString, + blocks: Vec, + block_ids: Vec, + /// Whether fenced code blocks highlight with the code view's palette. + highlight_code: bool, + /// Drives the vertical scroll of the virtualized block list. + handle: ListState, + a11y_label: Option, + link_handler: Option, + task_toggle_handler: Option, + /// `(anchor, head)` in the order they were set, over the rendered text. + selection: Option<(usize, usize)>, + /// Whether a drag is still extending the selection. + selecting: bool, + focus_handle: Option, +} + +impl MarkdownViewState { + /// Builds the state, parsing `source`. + pub fn new(id: I, source: S) -> Self + where + I: Into, + S: Into, + { + let id = id.into(); + let source = source.into(); + let blocks = parse(&source, true); + let block_ids = Self::stable_block_ids(&id, &blocks); + let count = blocks.len(); + + Self { + id, + source, + blocks, + block_ids, + highlight_code: true, + handle: ListState::new(count, ListAlignment::Top, CODE_OVERSCROLL_MAX), + a11y_label: None, + link_handler: None, + task_toggle_handler: None, + selection: None, + selecting: false, + focus_handle: None, + } + } + + /// Renders fenced code blocks without the code view's highlighting. + pub fn plain_code(mut self) -> Self { + self.highlight_code = false; + self.reparse(); + self + } + + /// Replaces the source and re-parses it. + pub fn set_source(&mut self, source: S, cx: &mut Context) + where + S: Into, + { + let source = source.into(); + if self.source == source { + return; + } + self.source = source; + self.reparse(); + cx.notify(); + } + + fn reparse(&mut self) { + let blocks = parse(&self.source, self.highlight_code); + let block_ids = Self::stable_block_ids(&self.id, &blocks); + self.blocks = blocks; + self.block_ids = block_ids; + self.selection = None; + self.selecting = false; + self.handle.reset(self.blocks.len()); + self.handle.scroll_to_reveal_item(0); + } + + /// Ids built from the block's content hash plus an ordinal among blocks of equal content. + fn stable_block_ids(id: &ElementId, blocks: &[MarkdownBlock]) -> Vec { + let mut ids = Vec::with_capacity(blocks.len()); + let mut occurrences = HashMap::with_capacity(blocks.len()); + for block in blocks { + let hash = block.content_hash(); + let occurrence = *occurrences + .entry(hash) + .and_modify(|count| *count += 1) + .or_insert(0); + ids.push(ElementId::from(SharedString::from(format!( + "{id}-block-{hash:x}-{occurrence}" + )))); + } + ids + } + + /// The markdown source the view renders. + pub fn source(&self) -> &str { + &self.source + } + + /// The parsed blocks. + pub fn blocks(&self) -> &[MarkdownBlock] { + &self.blocks + } + + /// The stable element id of the block at `block_index`. + pub fn block_id(&self, block_index: usize) -> Option { + self.block_ids.get(block_index).cloned() + } + + /// Whether fenced code highlights with the code view's palette. + pub fn highlight_code(&self) -> bool { + self.highlight_code + } + + /// Scrolls `block` to the top of the view. + pub fn scroll_to_block(&self, block: usize) { + let item_ix = block.min(self.blocks.len().saturating_sub(1)); + self.handle.scroll_to(ListOffset { + item_ix, + offset_in_item: px(0.), + }); + } + + /// Overrides the accessibility label of the view. + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.a11y_label = Some(label.into()); + self + } + + /// Invokes `handler` when the user clicks a link, instead of opening it. + pub fn on_link_click(mut self, handler: F) -> Self + where + F: Fn(&SharedString, &mut Window, &mut App) + 'static, + { + self.link_handler = Some(Arc::new(handler)); + self + } + + /// Replaces the link click handler. + pub fn set_link_handler(&mut self, handler: LinkClickHandler) { + self.link_handler = Some(handler); + } + + /// Invokes `handler(block, checked)` when the user toggles a task checkbox. + pub fn on_task_toggle(mut self, handler: F) -> Self + where + F: Fn(usize, bool, &mut Window, &mut App) + 'static, + { + self.task_toggle_handler = Some(Arc::new(handler)); + self + } + + /// Replaces the task toggle handler. + pub fn set_task_toggle_handler(&mut self, handler: TaskToggleHandler) { + self.task_toggle_handler = Some(handler); + } + + /// Selects a range over the rendered text, endpoints in byte offsets. + pub fn select_range(&mut self, start: usize, end: usize, cx: &mut Context) { + self.selection = Some((start, end)); + self.selecting = false; + cx.notify(); + } + + /// The selected range over the rendered text, endpoints in document order, when there is one. + pub fn selection(&self) -> Option<(usize, usize)> { + let (anchor, head) = self.selection?; + Some(if anchor <= head { + (anchor, head) + } else { + (head, anchor) + }) + } + + /// The selected text, or `None` when nothing is selected. + pub fn selected_text(&self) -> Option { + let document = text_document(&self.blocks); + let (start, end) = self.selection()?; + let end = end.min(document.len); + let start = start.min(end); + Some(document.text(&self.blocks)[start..end].to_string()).filter(|text| !text.is_empty()) + } + + /// The focus handle the view claims on click, created on first use. + fn focus_handle(&mut self, cx: &mut App) -> gpui::FocusHandle { + self.focus_handle + .get_or_insert_with(|| cx.focus_handle().tab_stop(true)) + .clone() + } +} + +impl Render for MarkdownViewState { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let id = self.id.clone(); + let state = cx.entity(); + let focus_handle = self.focus_handle(cx); + let frame = std::rc::Rc::new(ViewFrame { + state: state.clone(), + link_handler: self.link_handler.clone(), + task_toggle: self.task_toggle_handler.clone(), + selection: self.selection(), + focus_handle, + pressed_on_piece: std::rc::Rc::new(std::cell::Cell::new(false)), + }); + let doc = std::rc::Rc::new(text_document(&self.blocks)); + + let blocks = list(self.handle.clone(), { + let frame = frame.clone(); + let doc = doc.clone(); + move |block_index, _window, cx| { + let view = state.read(cx); + match view + .blocks + .get(block_index) + .zip(view.block_ids.get(block_index)) + { + Some((block, block_id)) => { + let ctx = BlockContext { + frame: &frame, + doc: &doc, + block_index, + block_id, + }; + render_block(block, block_index, &ctx, cx) + } + None => div().into_any_element(), + } + } + }) + .size_full(); + + view_container(&frame) + .id((id.clone(), "view")) + .relative() + .size_full() + .child(blocks) + .child( + Scrollbar::vertical((self.id.clone(), "v-scrollbar"), self.handle.clone()) + .visibility(ScrollbarVisibility::Platform), + ) + .when_some(self.a11y_label.clone(), |view, label| { + view.aria_label(label) + }) + } +} + +/// The per-frame context the view's renderers wire themselves from. +struct ViewFrame { + state: Entity, + link_handler: Option, + task_toggle: Option, + /// The selection over the rendered text, endpoints in document order. + selection: Option<(usize, usize)>, + focus_handle: gpui::FocusHandle, + /// Set when a press landed on a piece. + pressed_on_piece: std::rc::Rc>, +} + +/// The per-block context, one per block as it renders. +struct BlockContext<'a> { + frame: &'a ViewFrame, + doc: &'a TextDocument, + block_index: usize, + block_id: &'a ElementId, +} + +impl BlockContext<'_> { + /// The block's pieces, in render order. + fn pieces(&self) -> &[TextPiece] { + let start = self + .doc + .pieces + .partition_point(|piece| piece.block_index < self.block_index); + + let count = self.doc.pieces[start..] + .iter() + .take_while(|piece| piece.block_index == self.block_index) + .count(); + + &self.doc.pieces[start..start + count] + } + + /// The piece at `offset`. + fn piece_context(&self, offset: usize) -> Option { + let piece = self.pieces().get(offset)?; + let selected = self.frame.selection.and_then(|(start, end)| { + let selected = start.max(piece.range.start)..end.min(piece.range.end); + (!selected.is_empty()) + .then(|| (selected.start - piece.range.start)..(selected.end - piece.range.start)) + }); + + Some(PieceContext { + state: self.frame.state.clone(), + link_handler: self.frame.link_handler.clone(), + doc_range: piece.range.clone(), + selected, + pressed_on_piece: self.frame.pressed_on_piece.clone(), + }) + } +} + +/// What one selectable text element wires itself from. +struct PieceContext { + state: Entity, + link_handler: Option, + /// The piece's byte range in the rendered text. + doc_range: Range, + /// The selection overlap, in piece-local bytes. + selected: Option>, + pressed_on_piece: std::rc::Rc>, +} + +/// One selectable stretch of rendered text. +#[derive(Clone, Debug)] +pub struct TextPiece { + /// The block the piece belongs to. + pub block_index: usize, + /// Which selectable unit of its block this is, in render order. + pub sub_index: usize, + /// The piece's byte range in the view's rendered text. + pub range: Range, +} + +/// The rendered text of a document: its selectable pieces and total length. +#[derive(Clone, Debug, Default)] +pub struct TextDocument { + /// The pieces, in document order. + pub pieces: Vec, + /// The rendered text length in bytes. + pub len: usize, +} + +impl TextDocument { + /// The rendered text, built on demand. + fn text(&self, blocks: &[MarkdownBlock]) -> String { + let mut out = String::with_capacity(self.len); + let mut piece_ix = 0; + + for (block_index, block) in blocks.iter().enumerate() { + if piece_ix >= self.pieces.len() || self.pieces[piece_ix].block_index != block_index { + continue; + } + + let block_end = self.pieces[piece_ix..] + .iter() + .position(|piece| piece.block_index != block_index) + .map_or(self.pieces.len(), |offset| piece_ix + offset); + let units = block_text_units(block); + + for piece in &self.pieces[piece_ix..block_end] { + let Some(unit) = units.get(piece.sub_index).filter(|unit| !unit.is_empty()) else { + continue; + }; + if !out.is_empty() { + out.push('\n'); + } + out.push_str(unit); + } + piece_ix = block_end; + } + + out + } +} + +/// An embeddable markdown text view: fit-content height, no scrolling. +pub struct TextView { + id: ElementId, + source: Option, + state: Option>, + link_handler: Option, + task_toggle_handler: Option, + style: StyleRefinement, +} + +impl TextView { + /// Renders `source`, keeping its parsed state across frames under `id`. + pub fn markdown(id: I, source: S) -> Self + where + I: Into, + S: Into, + { + Self { + id: id.into(), + source: Some(source.into()), + state: None, + link_handler: None, + task_toggle_handler: None, + style: StyleRefinement::default(), + } + } + + /// Wraps an owned state; its source drives what the view renders. + pub fn new(state: &Entity) -> Self { + Self { + id: ElementId::from(SharedString::from(format!("{}", state.entity_id()))), + source: None, + state: Some(state.clone()), + link_handler: None, + task_toggle_handler: None, + style: StyleRefinement::default(), + } + } + + /// Invokes `handler` when the user clicks a link, instead of opening it. + pub fn on_link_click(mut self, handler: F) -> Self + where + F: Fn(&SharedString, &mut Window, &mut App) + 'static, + { + self.link_handler = Some(Arc::new(handler)); + self + } + + /// Invokes `handler(block, checked)` when the user toggles a task checkbox. + pub fn on_task_toggle(mut self, handler: F) -> Self + where + F: Fn(usize, bool, &mut Window, &mut App) + 'static, + { + self.task_toggle_handler = Some(Arc::new(handler)); + self + } +} + +impl Styled for TextView { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl Element for TextView { + type RequestLayoutState = AnyElement; + type PrepaintState = (); + + fn id(&self) -> Option { + Some(self.id.clone()) + } + + fn source_location(&self) -> Option<&'static std::panic::Location<'static>> { + None + } + + fn request_layout( + &mut self, + _id: Option<&GlobalElementId>, + _inspector_id: Option<&InspectorElementId>, + window: &mut Window, + cx: &mut App, + ) -> (LayoutId, Self::RequestLayoutState) { + let state = match self.state.clone() { + Some(state) => state, + None => { + let view_id = self.id.clone(); + let source = self.source.clone().unwrap_or_default(); + let state_key = SharedString::from(format!("{}/state", self.id)); + window.use_keyed_state(state_key, cx, move |_, _| { + MarkdownViewState::new(view_id, source) + }) + } + }; + + let source = self.source.clone(); + let link_handler = self.link_handler.clone(); + let task_toggle = self.task_toggle_handler.clone(); + + let (selection, focus_handle) = + state.update(cx, |view, cx| (view.selection(), view.focus_handle(cx))); + + state.update(cx, |view, cx| { + if let Some(source) = source { + view.set_source(source, cx); + } + if let Some(link_handler) = link_handler { + view.set_link_handler(link_handler); + } + if let Some(task_toggle) = task_toggle { + view.set_task_toggle_handler(task_toggle); + } + }); + + let view = state.read(cx); + let frame = ViewFrame { + state: state.clone(), + link_handler: view.link_handler.clone(), + task_toggle: view.task_toggle_handler.clone(), + selection, + focus_handle, + pressed_on_piece: std::rc::Rc::new(std::cell::Cell::new(false)), + }; + let doc = text_document(&view.blocks); + + let mut element = render_blocks(&view.blocks, &frame, &doc, &view.block_ids, cx); + element.style().refine(&self.style); + + let mut element = element.into_any_element(); + let layout_id = element.request_layout(window, cx); + + (layout_id, element) + } + + fn prepaint( + &mut self, + _id: Option<&GlobalElementId>, + _inspector_id: Option<&InspectorElementId>, + _bounds: Bounds, + request_layout: &mut Self::RequestLayoutState, + window: &mut Window, + cx: &mut App, + ) { + request_layout.prepaint(window, cx); + } + + fn paint( + &mut self, + _id: Option<&GlobalElementId>, + _inspector_id: Option<&InspectorElementId>, + _bounds: Bounds, + request_layout: &mut Self::RequestLayoutState, + _prepaint: &mut Self::PrepaintState, + window: &mut Window, + cx: &mut App, + ) { + request_layout.paint(window, cx); + } +} + +/// One open list, tracking ordered numbering and an in-flight task marker. +struct ListFrame { + ordered: bool, + next_number: u64, + task: Option, +} + +/// Accumulates inline spans across inline events. +#[derive(Default)] +struct InlineBuilder { + runs: Vec<(String, InlineStyle)>, + styles: Vec>, +} + +impl InlineBuilder { + fn push_style(&mut self, style: Option) { + self.styles.push(style); + } + + fn pop_style(&mut self) { + self.styles.pop(); + } + + fn active(&self) -> InlineStyle { + let mut strong = false; + let mut emphasis = false; + + for style in self.styles.iter().rev().flatten() { + match style { + InlineStyle::Strong if emphasis => return InlineStyle::StrongEmphasis, + InlineStyle::Strong => strong = true, + InlineStyle::Emphasis if strong => return InlineStyle::StrongEmphasis, + InlineStyle::Emphasis => emphasis = true, + other => return other.clone(), + } + } + + match (strong, emphasis) { + (true, true) => InlineStyle::StrongEmphasis, + (true, false) => InlineStyle::Strong, + (false, true) => InlineStyle::Emphasis, + (false, false) => InlineStyle::Text, + } + } + + fn push_text(&mut self, text: &str) { + if text.is_empty() { + return; + } + let style = self.active(); + if let Some((run, run_style)) = self.runs.last_mut() + && *run_style == style + { + run.push_str(text); + return; + } + self.runs.push((text.to_string(), style)); + } + + /// Emits one span per contiguous style run. + fn finish(&mut self) -> Vec { + self.runs + .drain(..) + .map(|(text, style)| InlineSpan { + text: SharedString::from(text), + style, + }) + .collect() + } +} + +/// Binds the text view's copy chord: cmd-c on macOS, ctrl-c elsewhere. +/// +/// Call once at startup. Without it, selection copy has no key. +pub fn bind_text_view_keys(cx: &mut App) { + let context = Some(TEXT_VIEW_CONTEXT); + #[cfg(target_os = "macos")] + let copy = "cmd-c"; + #[cfg(not(target_os = "macos"))] + let copy = "ctrl-c"; + cx.bind_keys([KeyBinding::new(copy, Copy, context)]); +} + +/// The view's base container: selection wiring, focus, and copy. +fn view_container(frame: &ViewFrame) -> Div { + let clear_flag = frame.pressed_on_piece.clone(); + + div() + .w_full() + .flex() + .flex_col() + .key_context(TEXT_VIEW_CONTEXT) + .track_focus(&frame.focus_handle) + .on_action({ + let state = frame.state.clone(); + move |_: &Copy, _window, cx| { + if let Some(text) = state.read(cx).selected_text() { + cx.write_to_clipboard(ClipboardItem::new_string(text)); + } + } + }) + .on_mouse_down(MouseButton::Left, { + let state = frame.state.clone(); + move |_, window, cx| { + let focus_handle = state.update(cx, |view, cx| view.focus_handle(cx)); + window.focus(&focus_handle, cx); + if !clear_flag.replace(false) { + state.update(cx, |view, cx| { + if view.selection.take().is_some() { + cx.notify(); + } + }); + } + } + }) + .on_mouse_up(MouseButton::Left, { + let state = frame.state.clone(); + move |_, _, cx| { + if state.read(cx).selecting { + state.update(cx, |view, cx| { + view.selecting = false; + cx.notify(); + }); + } + } + }) +} + +/// Renders every block stacked, without virtualization or scrolling. +fn render_blocks( + blocks: &[MarkdownBlock], + frame: &ViewFrame, + doc: &TextDocument, + block_ids: &[ElementId], + cx: &App, +) -> Div { + view_container(frame).children(blocks.iter().zip(block_ids).enumerate().map( + |(block_index, (block, block_id))| { + let ctx = BlockContext { + frame, + doc, + block_index, + block_id, + }; + render_block(block, block_index, &ctx, cx) + }, + )) +} + +fn spans_text_of(spans: &[InlineSpan]) -> String { + spans.iter().map(|span| span.text.as_ref()).collect() +} + +/// The selectable text units of a block. +fn block_text_units(block: &MarkdownBlock) -> Vec { + match block { + MarkdownBlock::Heading { spans, .. } => vec![spans_text_of(spans)], + MarkdownBlock::Paragraph { items, .. } | MarkdownBlock::ListItem { items, .. } => { + let mut units: Vec = Vec::new(); + for item in items { + match item { + InlineItem::Text(span) => match units.last_mut() { + // Consecutive text items share the unit between images. + Some(unit) => unit.push_str(&span.text), + None => units.push(span.text.as_ref().to_string()), + }, + // An image starts the next unit; the render emits no + // element for it. + InlineItem::Image { .. } => units.push(String::new()), + } + } + units + } + MarkdownBlock::Code { lines, .. } => lines.lines.iter().map(|line| line.text()).collect(), + MarkdownBlock::Table { table, .. } => table + .rows + .iter() + .flat_map(|row| row.cells.iter()) + .map(|cell| spans_text_of(&cell.spans)) + .collect(), + MarkdownBlock::Image { .. } | MarkdownBlock::ThematicBreak { .. } => Vec::new(), + } +} + +/// Enumerates the selectable text pieces of `blocks`, in render order. +fn text_document(blocks: &[MarkdownBlock]) -> TextDocument { + let mut pieces = Vec::new(); + let mut len = 0usize; + + for (block_index, block) in blocks.iter().enumerate() { + // Paragraphs render no element for an empty unit. + let skip_empty = matches!( + block, + MarkdownBlock::Paragraph { .. } | MarkdownBlock::ListItem { .. } + ); + + for (sub_index, unit) in block_text_units(block).into_iter().enumerate() { + if unit.is_empty() && skip_empty { + continue; + } + + let mut range = len..len; + if !unit.is_empty() { + if len > 0 { + len += 1; // The newline that joins pieces. + } + range = len..len + unit.len(); + len = range.end; + } + + pieces.push(TextPiece { + block_index, + sub_index, + range, + }); + } + } + + TextDocument { pieces, len } +} + +/// The markdown extensions the view parses, on top of CommonMark. +fn options() -> Options { + let mut options = Options::empty(); + options.insert(Options::ENABLE_TABLES); + options.insert(Options::ENABLE_STRIKETHROUGH); + options.insert(Options::ENABLE_TASKLISTS); + options +} + +fn heading(level: HeadingLevel) -> MarkdownHeading { + match level { + HeadingLevel::H1 => MarkdownHeading::H1, + HeadingLevel::H2 => MarkdownHeading::H2, + HeadingLevel::H3 => MarkdownHeading::H3, + HeadingLevel::H4 => MarkdownHeading::H4, + HeadingLevel::H5 => MarkdownHeading::H5, + HeadingLevel::H6 => MarkdownHeading::H6, + } +} + +/// Parses `source` into blocks. +fn parse(source: &str, highlight_code: bool) -> Vec { + let mut blocks = Vec::new(); + let mut inline = InlineBuilder::default(); + let mut inline_items: Vec = Vec::new(); + let mut lists: Vec = Vec::new(); + // Whether each open list item already flushed content rows. + let mut items: Vec = Vec::new(); + let mut quote_depth = 0usize; + let mut table: Option> = None; + let mut code: Option = None; + // The fence info string arrives on Start, its text follows. + let mut code_language: Option = None; + // The image being parsed: its source and its alt text so far. + let mut image: Option<(SharedString, String)> = None; + + for event in Parser::new_ext(source, options()) { + match event { + Event::Start(tag) => match tag { + Tag::Paragraph | Tag::TableCell | Tag::Item => { + inline = InlineBuilder::default(); + inline_items = Vec::new(); + if matches!(tag, Tag::Item) { + // The marker is only in flight while its own item is open. + if let Some(frame) = lists.last_mut() { + frame.task = None; + } + items.push(false); + } + } + Tag::Heading { level, .. } => { + flush_item_inline( + &mut inline, + &mut inline_items, + &mut items, + &mut lists, + &mut blocks, + quote_depth, + ); + inline = InlineBuilder::default(); + inline_items = Vec::new(); + blocks.push(MarkdownBlock::Heading { + level: heading(level), + spans: Vec::new(), + indent: lists.len(), + quote: quote_depth > 0, + }); + } + Tag::BlockQuote(_) => { + flush_item_inline( + &mut inline, + &mut inline_items, + &mut items, + &mut lists, + &mut blocks, + quote_depth, + ); + quote_depth += 1; + } + Tag::List(start) => { + flush_item_inline( + &mut inline, + &mut inline_items, + &mut items, + &mut lists, + &mut blocks, + quote_depth, + ); + lists.push(ListFrame { + ordered: start.is_some(), + next_number: start.unwrap_or_default(), + task: None, + }); + } + Tag::CodeBlock(kind) => { + flush_item_inline( + &mut inline, + &mut inline_items, + &mut items, + &mut lists, + &mut blocks, + quote_depth, + ); + code = Some(String::new()); + if let CodeBlockKind::Fenced(info) = kind { + let info = info.trim(); + code_language = + (!info.is_empty()).then(|| SharedString::from(info.to_string())); + } + } + Tag::Table(_) => { + flush_item_inline( + &mut inline, + &mut inline_items, + &mut items, + &mut lists, + &mut blocks, + quote_depth, + ); + table = Some(Vec::new()) + } + Tag::TableHead => { + if let Some(rows) = &mut table { + rows.push(MarkdownTableRow { + cells: Vec::new(), + header: true, + }); + } + } + Tag::TableRow => { + if let Some(rows) = &mut table { + rows.push(MarkdownTableRow { + cells: Vec::new(), + header: false, + }); + } + } + Tag::Emphasis | Tag::Strong | Tag::Strikethrough => { + let style = match tag { + Tag::Emphasis => InlineStyle::Emphasis, + Tag::Strong => InlineStyle::Strong, + _ => InlineStyle::Strikethrough, + }; + inline.push_style(Some(style)); + } + Tag::Link { dest_url, .. } => inline.push_style(Some(InlineStyle::Link { + destination: SharedString::from(dest_url.to_string()), + })), + Tag::Image { dest_url, .. } => { + image = Some((SharedString::from(dest_url.to_string()), String::new())) + } + Tag::HtmlBlock | Tag::MetadataBlock(_) => {} + _ => {} + }, + Event::End(tag_end) => match tag_end { + TagEnd::Paragraph => { + let mut paragraph_items = std::mem::take(&mut inline_items); + for span in inline.finish() { + paragraph_items.push(InlineItem::Text(span)); + } + let quote = quote_depth > 0; + match items.last_mut() { + // The item's first paragraph carries its marker row. + Some(flushed @ false) => { + *flushed = true; + blocks.push(MarkdownBlock::ListItem { + marker: take_marker(&mut lists), + items: paragraph_items, + indent: lists.len().saturating_sub(1), + quote, + }); + } + _ => { + if let Some(item) = items.last_mut() { + *item = true; + } + push_paragraph_items(paragraph_items, lists.len(), quote, &mut blocks); + } + } + } + TagEnd::Heading(_) => { + let spans = inline.finish(); + if let Some(MarkdownBlock::Heading { spans: slots, .. }) = blocks.last_mut() { + *slots = spans; + } + } + TagEnd::BlockQuote(_) => quote_depth = quote_depth.saturating_sub(1), + TagEnd::List(_) => { + lists.pop(); + } + TagEnd::Item => { + let flushed = items.pop().unwrap_or(false); + let mut block_items = std::mem::take(&mut inline_items); + for span in inline.finish() { + block_items.push(InlineItem::Text(span)); + } + + if block_items.is_empty() && flushed { + continue; + } + + let indent = lists.len(); + let quote = quote_depth > 0; + + if flushed { + push_paragraph_items(block_items, indent, quote, &mut blocks); + } else { + blocks.push(MarkdownBlock::ListItem { + marker: take_marker(&mut lists), + items: block_items, + indent: indent.saturating_sub(1), + quote, + }); + } + } + TagEnd::CodeBlock => { + let built = code.take().unwrap_or_default(); + let text = built.trim_end_matches('\n'); + let language = code_language.take(); + let lines = match highlight_code + .then(|| language.as_deref().and_then(Language::from_fence_info)) + .flatten() + { + Some(grammar) => highlight(text, grammar), + None => plain(text), + }; + blocks.push(MarkdownBlock::Code { + language, + lines, + indent: lists.len(), + quote: quote_depth > 0, + }); + } + TagEnd::Table => { + if let Some(rows) = table.take() { + blocks.push(MarkdownBlock::Table { + table: MarkdownTable { rows }, + indent: lists.len(), + quote: quote_depth > 0, + }); + } + } + TagEnd::TableCell => { + let spans = inline.finish(); + let Some(rows) = &mut table else { + continue; + }; + let Some(row) = rows.last_mut() else { + continue; + }; + row.cells.push(MarkdownTableCell { spans }); + } + TagEnd::Image => { + if let Some((source, alt)) = image.take() { + let in_cell = table.is_some(); + let in_heading = matches!( + blocks.last(), + Some(MarkdownBlock::Heading { spans, .. }) if spans.is_empty() + ); + if in_cell || in_heading { + // Headings and table cells keep images as alt text. + inline.push_text(&alt); + } else { + for span in inline.finish() { + inline_items.push(InlineItem::Text(span)); + } + inline_items.push(InlineItem::Image { + source, + alt: SharedString::from(alt), + }); + } + } + } + TagEnd::Emphasis | TagEnd::Strong | TagEnd::Strikethrough | TagEnd::Link => { + inline.pop_style() + } + _ => {} + }, + Event::Text(text) => { + if let Some(buffer) = code.as_mut() { + buffer.push_str(&text); + } else if let Some((_, alt)) = &mut image { + alt.push_str(&text); + } else { + inline.push_text(&text); + } + } + Event::Code(text) => { + if let Some((_, alt)) = &mut image { + alt.push_str(&text); + } else { + inline.push_style(Some(InlineStyle::Code)); + inline.push_text(&text); + inline.pop_style(); + } + } + Event::SoftBreak | Event::HardBreak => { + if let Some((_, alt)) = &mut image { + alt.push(' '); + } else { + inline.push_text(" "); + } + } + Event::Rule => { + flush_item_inline( + &mut inline, + &mut inline_items, + &mut items, + &mut lists, + &mut blocks, + quote_depth, + ); + blocks.push(MarkdownBlock::ThematicBreak { + indent: lists.len(), + quote: quote_depth > 0, + }); + } + Event::TaskListMarker(checked) => { + if let Some(frame) = lists.last_mut() { + frame.task = Some(checked); + } + } + // Footnotes are disabled in the parser options. + Event::FootnoteReference(_) + | Event::InlineHtml(_) + | Event::Html(_) + | Event::InlineMath(_) + | Event::DisplayMath(_) => {} + } + } + + blocks +} + +/// Computes the current item's marker and advances ordered numbering. +fn take_marker(lists: &mut [ListFrame]) -> ListMarker { + let Some(frame) = lists.last_mut() else { + return ListMarker::Bullet; + }; + + let marker = match frame.task { + Some(checked) => ListMarker::Task(checked), + None if frame.ordered => ListMarker::Ordered(frame.next_number), + None => ListMarker::Bullet, + }; + + if frame.ordered { + frame.next_number += 1; + } + + marker +} + +/// Pushes `items` as standalone image blocks when they hold nothing but images. +fn push_paragraph_items( + items: Vec, + indent: usize, + quote: bool, + blocks: &mut Vec, +) { + let blank = |item: &InlineItem| match item { + InlineItem::Image { .. } => true, + InlineItem::Text(span) => span.text.chars().all(char::is_whitespace), + }; + let image_only = !items.is_empty() + && items + .iter() + .any(|item| matches!(item, InlineItem::Image { .. })) + && items.iter().all(blank); + if image_only { + for item in items { + if let InlineItem::Image { source, alt } = item { + blocks.push(MarkdownBlock::Image { + source, + alt, + indent, + quote, + }); + } + } + } else { + blocks.push(MarkdownBlock::Paragraph { + items, + indent, + quote, + }); + } +} + +/// Flushes an open tight item's inline text as its marker row. +fn flush_item_inline( + inline: &mut InlineBuilder, + inline_items: &mut Vec, + items: &mut [bool], + lists: &mut [ListFrame], + blocks: &mut Vec, + quote_depth: usize, +) { + let Some(item) = items.last_mut() else { + return; + }; + + let mut block_items = std::mem::take(inline_items); + for span in inline.finish() { + block_items.push(InlineItem::Text(span)); + } + + if block_items.is_empty() { + return; + } + *item = true; + + blocks.push(MarkdownBlock::ListItem { + marker: take_marker(lists), + items: block_items, + indent: lists.len().saturating_sub(1), + quote: quote_depth > 0, + }); +} + +/// Renders one parsed block as a list row. +fn render_block( + block: &MarkdownBlock, + block_index: usize, + ctx: &BlockContext, + cx: &App, +) -> AnyElement { + let theme = cx.theme(); + let gap = theme.root_font_size * BLOCK_GAP; + + match block { + MarkdownBlock::Heading { + level, + spans, + indent, + quote, + } => heading_row( + *level, + spans, + *indent, + *quote, + if block_index == 0 { px(0.) } else { gap * 0.5 }, + ctx, + cx, + ), + MarkdownBlock::Paragraph { + items, + indent, + quote, + } => text_row(items, *indent, *quote, gap, None, ctx, cx), + MarkdownBlock::ListItem { + marker, + items, + indent, + quote, + } => text_row( + items, + *indent, + *quote, + theme.root_font_size * ITEM_GAP, + Some(*marker), + ctx, + cx, + ), + MarkdownBlock::Image { + source, + alt, + indent, + quote, + } => image_row(source, alt, *indent, *quote, ctx, cx), + MarkdownBlock::Code { + language, + lines, + indent, + quote, + } => code_row(lines, language.as_ref(), *indent, *quote, ctx, cx), + MarkdownBlock::ThematicBreak { indent, quote } => rule_row(*indent, *quote, ctx, cx), + MarkdownBlock::Table { + table, + indent, + quote, + } => table_row(table, *indent, *quote, ctx, cx), + } +} + +/// The shared block frame: ambient text style, spacing, quote bar. +fn block_frame(quote: bool, top: Pixels, bottom: Pixels, id: &ElementId, cx: &App) -> Div { + let theme = cx.theme(); + div() + .debug_selector({ + let id = id.clone(); + move || id.to_string() + }) + .w_full() + .flex() + .flex_col() + .font_family(".SystemUIFont") + .text_size(theme.sizes.small.text_size) + .line_height(relative(BODY_LINE_HEIGHT)) + .text_color(theme.colors.foreground) + .pt(top) + .pb(bottom) + .when(quote, |frame| { + frame + .border_l(BORDER_WIDTH * 2.0) + .border_color(theme.colors.border) + .pl(theme.root_font_size * QUOTE_INSET) + }) +} + +/// Wraps the finished block in the list indent. +fn indented_frame(indent: usize, frame: Div, cx: &App) -> Div { + let indent_px = cx.theme().root_font_size * INDENT_STEP * indent as f32; + + if indent_px > px(0.) { + div().w_full().pl(indent_px).child(frame) + } else { + frame + } +} + +#[allow(clippy::too_many_arguments)] +fn heading_row( + level: MarkdownHeading, + spans: &[InlineSpan], + indent: usize, + quote: bool, + top: Pixels, + ctx: &BlockContext, + cx: &App, +) -> AnyElement { + let theme = cx.theme(); + let role = match level { + MarkdownHeading::H1 => TextRole::Title, + MarkdownHeading::H2 => TextRole::Title2, + MarkdownHeading::H3 => TextRole::Title3, + MarkdownHeading::H4 | MarkdownHeading::H5 | MarkdownHeading::H6 => TextRole::Headline, + }; + + indented_frame( + indent, + block_frame( + quote, + top, + theme.root_font_size * BLOCK_GAP, + ctx.block_id, + cx, + ) + .typeset(role, cx) + .child(text_child(spans, ctx.block_id, ctx.piece_context(0), cx)), + cx, + ) + .into_any_element() +} + +fn text_row( + items: &[InlineItem], + indent: usize, + quote: bool, + bottom: Pixels, + marker: Option, + ctx: &BlockContext, + cx: &App, +) -> AnyElement { + let theme = cx.theme(); + + indented_frame( + indent, + block_frame(quote, px(0.), bottom, ctx.block_id, cx).map(|frame| match marker { + Some(marker) => { + let line_height = theme.sizes.small.text_size * BODY_LINE_HEIGHT; + let marker_cell = div() + .flex_none() + .w(theme.root_font_size * MARKER_WIDTH) + .h(line_height) + .flex() + .items_center() + .justify_end() + .pr_1() + .child(match marker { + ListMarker::Bullet => div() + .size(theme.spacing.unit) + .rounded(theme.radius.full) + .bg(theme.colors.muted_foreground) + .into_any_element(), + ListMarker::Ordered(number) => div() + .text_color(theme.colors.muted_foreground) + .whitespace_nowrap() + .child(format!("{number}.")) + .into_any_element(), + ListMarker::Task(checked) => task_toggle(checked, item_text(items), ctx), + }); + + frame.child( + div().flex().items_start().child(marker_cell).child( + div() + .flex_1() + .min_w_0() + .child(paragraph_child(items, ctx, cx)), + ), + ) + } + None => frame.child(paragraph_child(items, ctx, cx)), + }), + cx, + ) + .into_any_element() +} + +/// The task marker: a checkbox that reports toggles when a handler is set. +fn task_toggle(checked: bool, label: SharedString, ctx: &BlockContext) -> AnyElement { + let block_index = ctx.block_index; + let selector = SharedString::from(format!("task-toggle-{block_index}")); + let checkbox = Checkbox::new((ctx.block_id.clone(), "task")) + .debug_selector(move || selector.to_string()) + .checked(checked) + .with_size(Size::Small) + .accessibility_label(label); + + match ctx.frame.task_toggle.clone() { + Some(handler) => checkbox + .on_change(move |next, window, cx| handler(block_index, next, window, cx)) + .into_any_element(), + None => checkbox.disabled(true).into_any_element(), + } +} + +/// The item's plain text, for the checkbox's accessibility label. +fn item_text(items: &[InlineItem]) -> SharedString { + let text = items + .iter() + .filter_map(|item| match item { + InlineItem::Text(span) => Some(span.text.as_ref()), + InlineItem::Image { .. } => None, + }) + .collect::>() + .join(""); + SharedString::from(text) +} + +/// Builds a paragraph's content. +fn paragraph_child(items: &[InlineItem], ctx: &BlockContext, cx: &App) -> AnyElement { + let has_image = items + .iter() + .any(|item| matches!(item, InlineItem::Image { .. })); + + if !has_image { + let spans = items.iter().filter_map(|item| match item { + InlineItem::Text(span) => Some(span), + InlineItem::Image { .. } => None, + }); + return text_child(spans, ctx.block_id, ctx.piece_context(0), cx); + } + + let theme = cx.theme(); + let side = theme.sizes.small.text_size * INLINE_IMAGE_SCALE; + let mut flow = div().flex().flex_wrap().items_center(); + let mut segment: Vec<&InlineSpan> = Vec::new(); + let mut segment_index = 0; + for item in items { + match item { + InlineItem::Text(span) => segment.push(span), + InlineItem::Image { source, .. } => { + if !segment.is_empty() { + flow = flow.child(text_child( + segment, + &text_segment_id(ctx.block_id, segment_index), + ctx.piece_context(segment_index), + cx, + )); + segment = Vec::new(); + segment_index += 1; + } + flow = flow.child( + img(source.clone()) + .size(side) + .object_fit(ObjectFit::ScaleDown) + .flex_none(), + ); + } + } + } + if !segment.is_empty() { + flow = flow.child(text_child( + segment, + &text_segment_id(ctx.block_id, segment_index), + ctx.piece_context(segment_index), + cx, + )); + } + flow.into_any_element() +} + +/// A standalone image block, capped in height. +fn image_row( + source: &SharedString, + alt: &SharedString, + indent: usize, + quote: bool, + ctx: &BlockContext, + cx: &App, +) -> AnyElement { + let theme = cx.theme(); + indented_frame( + indent, + block_frame( + quote, + px(0.), + theme.root_font_size * BLOCK_GAP, + ctx.block_id, + cx, + ) + .child( + img(source.clone()) + .max_h(theme.root_font_size * IMAGE_MAX_HEIGHT) + .max_w_full() + .rounded(theme.radius.control) + .overflow_hidden(), + ), + cx, + ) + .id((ctx.block_id.clone(), "image")) + .when(!alt.is_empty(), |frame| frame.aria_label(alt.clone())) + .into_any_element() +} + +/// The element id of one text segment of a paragraph with images. +fn text_segment_id(id: &ElementId, segment_index: usize) -> ElementId { + ElementId::from(SharedString::from(format!("{id}-text-{segment_index}"))) +} + +fn code_row( + lines: &HighlightedCode, + language: Option<&SharedString>, + indent: usize, + quote: bool, + ctx: &BlockContext, + cx: &App, +) -> AnyElement { + let theme = cx.theme(); + let text_size = theme.sizes.small.text_size; + let line_height = text_size * CODE_LINE_HEIGHT; + let plain = lines + .lines + .iter() + .map(|line| line.text()) + .collect::>() + .join("\n"); + + let actions_row = div() + .flex() + .items_center() + .justify_between() + .pb_1() + .when_some(language.cloned(), |row, language| { + row.child( + div() + .typeset(TextRole::Caption, cx) + .text_color(theme.colors.muted_foreground) + .child(language), + ) + }) + .child( + Button::new((ctx.block_id.clone(), "copy-code")) + .label("Copy") + .variant(ButtonVariant::Ghost) + .debug_selector(|| "copy-code".to_string()) + .on_click(move |_, _, cx| { + cx.write_to_clipboard(ClipboardItem::new_string(plain.clone())); + }), + ); + + let plate = div() + .w_full() + .flex() + .flex_col() + .rounded(theme.radius.control) + .bg(theme.colors.muted) + .p_2() + .font_family(theme.mono_font) + .text_size(text_size) + .line_height(relative(CODE_LINE_HEIGHT)) + .overflow_hidden() + .child(actions_row) + .children(lines.lines.iter().enumerate().map(|(line_ix, line)| { + let styled = code_line(line, theme.colors, theme.ramps); + let layout = styled.layout().clone(); + with_selection_handlers( + div() + .h(line_height) + .whitespace_nowrap() + .overflow_hidden() + .child(styled), + ctx.piece_context(line_ix), + layout, + ) + })); + + indented_frame( + indent, + block_frame( + quote, + px(0.), + theme.root_font_size * BLOCK_GAP, + ctx.block_id, + cx, + ) + .child(plate), + cx, + ) + .into_any_element() +} + +fn rule_row(indent: usize, quote: bool, ctx: &BlockContext, cx: &App) -> AnyElement { + let theme = cx.theme(); + indented_frame( + indent, + block_frame( + quote, + px(0.), + theme.root_font_size * BLOCK_GAP, + ctx.block_id, + cx, + ) + .child(div().h(BORDER_WIDTH).w_full().bg(theme.colors.border)), + cx, + ) + .into_any_element() +} + +fn table_row( + table: &MarkdownTable, + indent: usize, + quote: bool, + ctx: &BlockContext, + cx: &App, +) -> AnyElement { + let theme = cx.theme(); + let colors = theme.colors; + let width = table + .rows + .iter() + .map(|row| row.cells.len()) + .max() + .unwrap_or(0); + let row_count = table.rows.len(); + let mut cell_ix = 0usize; + + let grid = div() + .w_full() + .flex() + .flex_col() + .border_1() + .border_color(colors.border) + .rounded(theme.radius.control) + .overflow_hidden() + .children(table.rows.iter().enumerate().map(|(row_index, row)| { + div() + .w_full() + .flex() + .when(row_index + 1 < row_count, |row_element| { + row_element.border_b_1().border_color(colors.border) + }) + .when(row.header, |row_element| row_element.bg(colors.muted)) + .children( + row.cells + .iter() + .enumerate() + .map(|(column_index, cell)| { + let cell_id = ElementId::from(SharedString::from(format!( + "{}-cell-{row_index}-{column_index}", + ctx.block_id + ))); + let piece = ctx.piece_context(cell_ix); + cell_ix += 1; + div() + .flex_1() + .min_w_0() + .px_2() + .py_1() + .when(row.header, |cell_element| { + cell_element.font_weight(theme.typography.headline.weight) + }) + .child(text_child(&cell.spans, &cell_id, piece, cx)) + }) + // Ragged tables pad missing cells so rows align. + .chain( + (row.cells.len()..width) + .map(|_| div().flex_1().min_w_0().px_2().py_1()), + ), + ) + })); + + indented_frame( + indent, + block_frame( + quote, + px(0.), + theme.root_font_size * BLOCK_GAP, + ctx.block_id, + cx, + ) + .child(grid), + cx, + ) + .into_any_element() +} + +/// Attaches drag-selection handlers to `element` when it renders a piece. +fn with_selection_handlers(element: Div, piece: Option, layout: TextLayout) -> Div { + let Some(piece) = piece else { + return element; + }; + + let state = piece.state.clone(); + let doc_range = piece.doc_range.clone(); + let pressed_on_piece = piece.pressed_on_piece.clone(); + let layout_for_move = layout.clone(); + element + .on_mouse_down( + MouseButton::Left, + move |event: &MouseDownEvent, window: &mut Window, cx: &mut App| { + pressed_on_piece.set(true); + let focus_handle = state.update(cx, |view, cx| view.focus_handle(cx)); + window.focus(&focus_handle, cx); + + let local = match layout.index_for_position(event.position) { + Ok(index) | Err(index) => index, + }; + let index = doc_range.start + local; + state.update(cx, |view, cx| { + if event.modifiers.shift { + if let Some((anchor, _)) = view.selection { + view.selection = Some((anchor, index)); + } else { + view.selection = Some((index, index)); + } + } else { + view.selection = Some((index, index)); + } + view.selecting = true; + cx.notify(); + }); + }, + ) + .on_mouse_move({ + let state = piece.state.clone(); + let doc_range = piece.doc_range.clone(); + let layout = layout_for_move; + move |event: &MouseMoveEvent, _window: &mut Window, cx: &mut App| { + if !state.read(cx).selecting { + return; + } + let local = match layout.index_for_position(event.position) { + Ok(index) | Err(index) => index, + }; + let index = doc_range.start + local; + let changed = state + .read(cx) + .selection + .map(|(_, head)| head != index) + .unwrap_or(true); + if changed { + state.update(cx, |view, cx| { + if let Some((anchor, _)) = view.selection { + view.selection = Some((anchor, index)); + cx.notify(); + } + }); + } + } + }) + .on_mouse_up(MouseButton::Left, { + let state = piece.state.clone(); + move |_, _, cx| { + if state.read(cx).selecting { + state.update(cx, |view, cx| { + view.selecting = false; + cx.notify(); + }); + } + } + }) +} + +/// Builds the block's text element, selectable when it renders a piece. +fn text_child(spans: I, id: &ElementId, piece: Option, cx: &App) -> AnyElement +where + I: IntoIterator, + I::Item: std::borrow::Borrow, +{ + let theme = cx.theme(); + let mut text = String::new(); + let mut highlights: Vec<(Range, HighlightStyle)> = Vec::new(); + let mut family_overrides: Vec<(Range, SharedString)> = Vec::new(); + let mut link_ranges: Vec> = Vec::new(); + let mut destinations: Vec = Vec::new(); + + for span in spans { + let span = span.borrow(); + let start = text.len(); + text.push_str(&span.text); + + let range = start..text.len(); + + match &span.style { + InlineStyle::Text => {} + InlineStyle::Emphasis => highlights.push(( + range, + HighlightStyle { + font_style: Some(FontStyle::Italic), + ..Default::default() + }, + )), + InlineStyle::Strong => highlights.push(( + range, + HighlightStyle { + font_weight: Some(theme.typography.headline.weight), + ..Default::default() + }, + )), + InlineStyle::StrongEmphasis => highlights.push(( + range, + HighlightStyle { + font_style: Some(FontStyle::Italic), + font_weight: Some(theme.typography.headline.weight), + ..Default::default() + }, + )), + InlineStyle::Strikethrough => highlights.push(( + range, + HighlightStyle { + strikethrough: Some(StrikethroughStyle { + thickness: BORDER_WIDTH, + color: Some(theme.colors.muted_foreground), + }), + ..Default::default() + }, + )), + InlineStyle::Code => { + highlights.push(( + range.clone(), + HighlightStyle { + background_color: Some(theme.colors.muted), + ..Default::default() + }, + )); + family_overrides.push((range, SharedString::from(theme.mono_font))); + } + InlineStyle::Link { destination } => { + highlights.push(( + range.clone(), + HighlightStyle { + color: Some(theme.ramps.primary.base), + underline: Some(UnderlineStyle { + thickness: BORDER_WIDTH, + color: None, + wavy: false, + }), + ..Default::default() + }, + )); + link_ranges.push(range); + destinations.push(destination.clone()); + } + } + } + + if let Some(local) = piece.as_ref().and_then(|piece| piece.selected.clone()) { + highlights.push(( + local, + HighlightStyle { + background_color: Some(theme.colors.selection), + ..Default::default() + }, + )); + } + + let styled = StyledText::new(text) + .with_highlights(highlights) + .with_font_family_overrides(family_overrides); + let layout = styled.layout().clone(); + + let inner = if destinations.is_empty() { + styled.into_any_element() + } else { + let link_handler = piece.as_ref().and_then(|piece| piece.link_handler.clone()); + InteractiveText::new(id.clone(), styled) + .on_click(link_ranges, move |range_ix, window, cx| { + let Some(destination) = destinations.get(range_ix) else { + return; + }; + match link_handler.as_ref() { + Some(handler) => handler(destination, window, cx), + None => cx.open_url(destination.as_ref()), + } + }) + .into_any_element() + }; + + let mut element = div().child(inner); + if let Some(piece) = piece { + element = with_selection_handlers(element, Some(piece), layout); + } + element.into_any_element() +} diff --git a/crates/ui/src/editor/mod.rs b/crates/ui/src/editor/mod.rs new file mode 100644 index 0000000..0666282 --- /dev/null +++ b/crates/ui/src/editor/mod.rs @@ -0,0 +1,8 @@ +//! Read-only code surfaces: tree-sitter highlighted code views. + +pub mod code; +pub mod diff; +pub mod highlight; +pub mod markdown; + +mod utils; diff --git a/crates/ui/src/editor/utils.rs b/crates/ui/src/editor/utils.rs new file mode 100644 index 0000000..e65de4e --- /dev/null +++ b/crates/ui/src/editor/utils.rs @@ -0,0 +1,123 @@ +//! Shared helpers for the editor's views: gutter cells, role colors and run +//! styles, code line text, language mapping and change washes. + +use std::ops::Range; + +use crate::editor::highlight::{Language, Line}; +use crate::theme::{ActiveTheme as _, CODE_GUTTER_WIDTH, ColorTokens, Ramps}; +use crate::theme::{WASH_ALPHA, WASH_ALPHA_GUTTER, WASH_ALPHA_STRONG}; +use gpui::StyledText; +use gpui::{App, HighlightStyle, Hsla, IntoElement, ParentElement as _, Styled as _, div}; + +use crate::editor::highlight::Role; + +impl Role { + /// Maps the role to the theme's semantic palette. + pub(crate) fn color(self, colors: ColorTokens, ramps: Ramps) -> Hsla { + match self { + Role::Text => colors.foreground, + Role::Keyword => ramps.primary.base, + Role::String | Role::Escape => ramps.success.base, + Role::Comment | Role::Punctuation => colors.muted_foreground, + Role::Function | Role::Property => ramps.info.base, + Role::Type => ramps.warning.base, + Role::Number | Role::Constant => ramps.secondary.base, + Role::Operator => colors.foreground, + Role::Tag => ramps.destructive.base, + } + } + + /// Builds the highlight style for one run of a code view row. + pub(crate) fn run_style( + self, + selected: bool, + colors: ColorTokens, + ramps: Ramps, + ) -> HighlightStyle { + HighlightStyle { + color: Some(self.color(colors, ramps)), + background_color: selected.then_some(colors.selection), + ..Default::default() + } + } +} + +impl Language { + /// Maps a fence info string to a language. + pub(crate) fn from_fence_info(info: &str) -> Option { + match info.to_ascii_lowercase().as_str() { + "plain" | "text" | "txt" => Some(Language::Plain), + "rust" | "rs" => Some(Language::Rust), + "typescript" | "ts" => Some(Language::TypeScript), + "javascript" | "js" => Some(Language::JavaScript), + "python" | "py" => Some(Language::Python), + _ => None, + } + } +} + +/// A gutter cell sized to the whole row. +pub(crate) fn gutter_cell(cx: &App, color: Hsla, content: E) -> gpui::Div +where + E: IntoElement, +{ + let theme = cx.theme(); + + div() + .size(CODE_GUTTER_WIDTH) + .flex() + .items_center() + .justify_center() + .flex_none() + .font_family(theme.mono_font) + .text_size(theme.sizes.small.text_size) + .line_height(gpui::relative(1.0)) + .text_color(color) + .child(content) +} + +/// A change wash: the ramp color at the alpha rows tint with. +pub(crate) fn wash(color: Hsla) -> Hsla { + Hsla { + a: color.a * WASH_ALPHA, + ..color + } +} + +/// The stronger wash under number gutters and intra-line word changes. +pub(crate) fn wash_strong(color: Hsla) -> Hsla { + Hsla { + a: color.a * WASH_ALPHA_STRONG, + ..color + } +} + +/// The subtle wash that sets the number gutter off from the code. +pub(crate) fn wash_gutter(colors: &ColorTokens) -> Hsla { + Hsla { + a: colors.muted.a * WASH_ALPHA_GUTTER, + ..colors.muted + } +} + +/// One highlighted code line as styled text, roles resolved from the theme. +pub(crate) fn code_line(line: &Line, colors: ColorTokens, ramps: Ramps) -> StyledText { + let mut highlights: Vec<(Range, HighlightStyle)> = Vec::new(); + let mut offset = 0usize; + + for span in &line.spans { + let end = offset + span.text.len(); + if span.role != Role::Text { + highlights.push(( + offset..end, + HighlightStyle { + color: Some(span.role.color(colors, ramps)), + ..Default::default() + }, + )); + } + offset = end; + } + + StyledText::new(line.text()).with_highlights(highlights) +} diff --git a/crates/ui/src/icons/NOTICE.md b/crates/ui/src/icons/NOTICE.md new file mode 100644 index 0000000..f8466f1 --- /dev/null +++ b/crates/ui/src/icons/NOTICE.md @@ -0,0 +1,9 @@ +# Licenses + +## Bundled icons (`assets/*.svg`) + +Lucide, ISC License, © Lucide Contributors. Fetched from https://github.com/lucide-icons/lucide (main) on 2026-10-28 and 2026-11-13. These are the offline fallback glyphs, see https://lucide.dev/license. + +## Platform glyph sets (not bundled) + +SF Symbols (macOS) and Segoe Fluent Icons (Windows) are resolved through the operating system at runtime and are never extracted, modified, or redistributed. Freedesktop icons are loaded from the user's installed icon themes. diff --git a/crates/assets/assets/icons/a-large-small.svg b/crates/ui/src/icons/assets/a-large-small.svg similarity index 100% rename from crates/assets/assets/icons/a-large-small.svg rename to crates/ui/src/icons/assets/a-large-small.svg diff --git a/crates/assets/assets/icons/arrow-down.svg b/crates/ui/src/icons/assets/arrow-down.svg similarity index 100% rename from crates/assets/assets/icons/arrow-down.svg rename to crates/ui/src/icons/assets/arrow-down.svg diff --git a/crates/assets/assets/icons/arrow-left.svg b/crates/ui/src/icons/assets/arrow-left.svg similarity index 100% rename from crates/assets/assets/icons/arrow-left.svg rename to crates/ui/src/icons/assets/arrow-left.svg diff --git a/crates/assets/assets/icons/arrow-right.svg b/crates/ui/src/icons/assets/arrow-right.svg similarity index 100% rename from crates/assets/assets/icons/arrow-right.svg rename to crates/ui/src/icons/assets/arrow-right.svg diff --git a/crates/ui/src/icons/assets/arrow-up-down.svg b/crates/ui/src/icons/assets/arrow-up-down.svg new file mode 100644 index 0000000..c8d7f2f --- /dev/null +++ b/crates/ui/src/icons/assets/arrow-up-down.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/crates/assets/assets/icons/arrow-up.svg b/crates/ui/src/icons/assets/arrow-up.svg similarity index 100% rename from crates/assets/assets/icons/arrow-up.svg rename to crates/ui/src/icons/assets/arrow-up.svg diff --git a/crates/assets/assets/icons/asterisk.svg b/crates/ui/src/icons/assets/asterisk.svg similarity index 100% rename from crates/assets/assets/icons/asterisk.svg rename to crates/ui/src/icons/assets/asterisk.svg diff --git a/crates/assets/assets/icons/battery-charging.svg b/crates/ui/src/icons/assets/battery-charging.svg similarity index 100% rename from crates/assets/assets/icons/battery-charging.svg rename to crates/ui/src/icons/assets/battery-charging.svg diff --git a/crates/assets/assets/icons/battery-full.svg b/crates/ui/src/icons/assets/battery-full.svg similarity index 100% rename from crates/assets/assets/icons/battery-full.svg rename to crates/ui/src/icons/assets/battery-full.svg diff --git a/crates/assets/assets/icons/battery-low.svg b/crates/ui/src/icons/assets/battery-low.svg similarity index 100% rename from crates/assets/assets/icons/battery-low.svg rename to crates/ui/src/icons/assets/battery-low.svg diff --git a/crates/assets/assets/icons/battery-medium.svg b/crates/ui/src/icons/assets/battery-medium.svg similarity index 100% rename from crates/assets/assets/icons/battery-medium.svg rename to crates/ui/src/icons/assets/battery-medium.svg diff --git a/crates/assets/assets/icons/battery-warning.svg b/crates/ui/src/icons/assets/battery-warning.svg similarity index 100% rename from crates/assets/assets/icons/battery-warning.svg rename to crates/ui/src/icons/assets/battery-warning.svg diff --git a/crates/assets/assets/icons/battery.svg b/crates/ui/src/icons/assets/battery.svg similarity index 100% rename from crates/assets/assets/icons/battery.svg rename to crates/ui/src/icons/assets/battery.svg diff --git a/crates/assets/assets/icons/bell.svg b/crates/ui/src/icons/assets/bell.svg similarity index 100% rename from crates/assets/assets/icons/bell.svg rename to crates/ui/src/icons/assets/bell.svg diff --git a/crates/assets/assets/icons/book-open.svg b/crates/ui/src/icons/assets/book-open.svg similarity index 100% rename from crates/assets/assets/icons/book-open.svg rename to crates/ui/src/icons/assets/book-open.svg diff --git a/crates/assets/assets/icons/bot.svg b/crates/ui/src/icons/assets/bot.svg similarity index 100% rename from crates/assets/assets/icons/bot.svg rename to crates/ui/src/icons/assets/bot.svg diff --git a/crates/assets/assets/icons/building-2.svg b/crates/ui/src/icons/assets/building-2.svg similarity index 100% rename from crates/assets/assets/icons/building-2.svg rename to crates/ui/src/icons/assets/building-2.svg diff --git a/crates/assets/assets/icons/calendar.svg b/crates/ui/src/icons/assets/calendar.svg similarity index 100% rename from crates/assets/assets/icons/calendar.svg rename to crates/ui/src/icons/assets/calendar.svg diff --git a/crates/assets/assets/icons/case-sensitive.svg b/crates/ui/src/icons/assets/case-sensitive.svg similarity index 100% rename from crates/assets/assets/icons/case-sensitive.svg rename to crates/ui/src/icons/assets/case-sensitive.svg diff --git a/crates/assets/assets/icons/chart-pie.svg b/crates/ui/src/icons/assets/chart-pie.svg similarity index 100% rename from crates/assets/assets/icons/chart-pie.svg rename to crates/ui/src/icons/assets/chart-pie.svg diff --git a/crates/assets/assets/icons/check.svg b/crates/ui/src/icons/assets/check.svg similarity index 100% rename from crates/assets/assets/icons/check.svg rename to crates/ui/src/icons/assets/check.svg diff --git a/crates/assets/assets/icons/chevron-down.svg b/crates/ui/src/icons/assets/chevron-down.svg similarity index 100% rename from crates/assets/assets/icons/chevron-down.svg rename to crates/ui/src/icons/assets/chevron-down.svg diff --git a/crates/assets/assets/icons/chevron-left.svg b/crates/ui/src/icons/assets/chevron-left.svg similarity index 100% rename from crates/assets/assets/icons/chevron-left.svg rename to crates/ui/src/icons/assets/chevron-left.svg diff --git a/crates/assets/assets/icons/chevron-right.svg b/crates/ui/src/icons/assets/chevron-right.svg similarity index 100% rename from crates/assets/assets/icons/chevron-right.svg rename to crates/ui/src/icons/assets/chevron-right.svg diff --git a/crates/assets/assets/icons/chevron-up.svg b/crates/ui/src/icons/assets/chevron-up.svg similarity index 100% rename from crates/assets/assets/icons/chevron-up.svg rename to crates/ui/src/icons/assets/chevron-up.svg diff --git a/crates/assets/assets/icons/chevrons-up-down.svg b/crates/ui/src/icons/assets/chevrons-up-down.svg similarity index 100% rename from crates/assets/assets/icons/chevrons-up-down.svg rename to crates/ui/src/icons/assets/chevrons-up-down.svg diff --git a/crates/assets/assets/icons/circle-check.svg b/crates/ui/src/icons/assets/circle-check.svg similarity index 100% rename from crates/assets/assets/icons/circle-check.svg rename to crates/ui/src/icons/assets/circle-check.svg diff --git a/crates/assets/assets/icons/circle-plus.svg b/crates/ui/src/icons/assets/circle-plus.svg similarity index 100% rename from crates/assets/assets/icons/circle-plus.svg rename to crates/ui/src/icons/assets/circle-plus.svg diff --git a/crates/ui/src/icons/assets/circle-question-mark.svg b/crates/ui/src/icons/assets/circle-question-mark.svg new file mode 100644 index 0000000..1d9c175 --- /dev/null +++ b/crates/ui/src/icons/assets/circle-question-mark.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/assets/assets/icons/circle-user.svg b/crates/ui/src/icons/assets/circle-user.svg similarity index 100% rename from crates/assets/assets/icons/circle-user.svg rename to crates/ui/src/icons/assets/circle-user.svg diff --git a/crates/assets/assets/icons/circle-x.svg b/crates/ui/src/icons/assets/circle-x.svg similarity index 100% rename from crates/assets/assets/icons/circle-x.svg rename to crates/ui/src/icons/assets/circle-x.svg diff --git a/crates/ui/src/icons/assets/clipboard-paste.svg b/crates/ui/src/icons/assets/clipboard-paste.svg new file mode 100644 index 0000000..6ac5933 --- /dev/null +++ b/crates/ui/src/icons/assets/clipboard-paste.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/crates/ui/src/icons/assets/clock.svg b/crates/ui/src/icons/assets/clock.svg new file mode 100644 index 0000000..b6ae283 --- /dev/null +++ b/crates/ui/src/icons/assets/clock.svg @@ -0,0 +1,14 @@ + + + + diff --git a/crates/assets/assets/icons/close.svg b/crates/ui/src/icons/assets/close.svg similarity index 100% rename from crates/assets/assets/icons/close.svg rename to crates/ui/src/icons/assets/close.svg diff --git a/crates/assets/assets/icons/copy.svg b/crates/ui/src/icons/assets/copy.svg similarity index 100% rename from crates/assets/assets/icons/copy.svg rename to crates/ui/src/icons/assets/copy.svg diff --git a/crates/assets/assets/icons/cpu.svg b/crates/ui/src/icons/assets/cpu.svg similarity index 100% rename from crates/assets/assets/icons/cpu.svg rename to crates/ui/src/icons/assets/cpu.svg diff --git a/crates/assets/assets/icons/dash.svg b/crates/ui/src/icons/assets/dash.svg similarity index 100% rename from crates/assets/assets/icons/dash.svg rename to crates/ui/src/icons/assets/dash.svg diff --git a/crates/assets/assets/icons/delete.svg b/crates/ui/src/icons/assets/delete.svg similarity index 100% rename from crates/assets/assets/icons/delete.svg rename to crates/ui/src/icons/assets/delete.svg diff --git a/crates/ui/src/icons/assets/download.svg b/crates/ui/src/icons/assets/download.svg new file mode 100644 index 0000000..5c75527 --- /dev/null +++ b/crates/ui/src/icons/assets/download.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/assets/assets/icons/ellipsis-vertical.svg b/crates/ui/src/icons/assets/ellipsis-vertical.svg similarity index 100% rename from crates/assets/assets/icons/ellipsis-vertical.svg rename to crates/ui/src/icons/assets/ellipsis-vertical.svg diff --git a/crates/assets/assets/icons/ellipsis.svg b/crates/ui/src/icons/assets/ellipsis.svg similarity index 100% rename from crates/assets/assets/icons/ellipsis.svg rename to crates/ui/src/icons/assets/ellipsis.svg diff --git a/crates/assets/assets/icons/external-link.svg b/crates/ui/src/icons/assets/external-link.svg similarity index 100% rename from crates/assets/assets/icons/external-link.svg rename to crates/ui/src/icons/assets/external-link.svg diff --git a/crates/assets/assets/icons/eye-off.svg b/crates/ui/src/icons/assets/eye-off.svg similarity index 100% rename from crates/assets/assets/icons/eye-off.svg rename to crates/ui/src/icons/assets/eye-off.svg diff --git a/crates/assets/assets/icons/eye.svg b/crates/ui/src/icons/assets/eye.svg similarity index 100% rename from crates/assets/assets/icons/eye.svg rename to crates/ui/src/icons/assets/eye.svg diff --git a/crates/assets/assets/icons/file.svg b/crates/ui/src/icons/assets/file.svg similarity index 100% rename from crates/assets/assets/icons/file.svg rename to crates/ui/src/icons/assets/file.svg diff --git a/crates/assets/assets/icons/filter.svg b/crates/ui/src/icons/assets/filter.svg similarity index 100% rename from crates/assets/assets/icons/filter.svg rename to crates/ui/src/icons/assets/filter.svg diff --git a/crates/assets/assets/icons/folder-closed.svg b/crates/ui/src/icons/assets/folder-closed.svg similarity index 100% rename from crates/assets/assets/icons/folder-closed.svg rename to crates/ui/src/icons/assets/folder-closed.svg diff --git a/crates/assets/assets/icons/folder-open.svg b/crates/ui/src/icons/assets/folder-open.svg similarity index 100% rename from crates/assets/assets/icons/folder-open.svg rename to crates/ui/src/icons/assets/folder-open.svg diff --git a/crates/assets/assets/icons/folder.svg b/crates/ui/src/icons/assets/folder.svg similarity index 100% rename from crates/assets/assets/icons/folder.svg rename to crates/ui/src/icons/assets/folder.svg diff --git a/crates/assets/assets/icons/frame.svg b/crates/ui/src/icons/assets/frame.svg similarity index 100% rename from crates/assets/assets/icons/frame.svg rename to crates/ui/src/icons/assets/frame.svg diff --git a/crates/assets/assets/icons/gallery-vertical-end.svg b/crates/ui/src/icons/assets/gallery-vertical-end.svg similarity index 100% rename from crates/assets/assets/icons/gallery-vertical-end.svg rename to crates/ui/src/icons/assets/gallery-vertical-end.svg diff --git a/crates/assets/assets/icons/git-branch.svg b/crates/ui/src/icons/assets/git-branch.svg similarity index 100% rename from crates/assets/assets/icons/git-branch.svg rename to crates/ui/src/icons/assets/git-branch.svg diff --git a/crates/assets/assets/icons/git-clone.svg b/crates/ui/src/icons/assets/git-clone.svg similarity index 100% rename from crates/assets/assets/icons/git-clone.svg rename to crates/ui/src/icons/assets/git-clone.svg diff --git a/crates/assets/assets/icons/git-commit.svg b/crates/ui/src/icons/assets/git-commit.svg similarity index 100% rename from crates/assets/assets/icons/git-commit.svg rename to crates/ui/src/icons/assets/git-commit.svg diff --git a/crates/assets/assets/icons/git-file.svg b/crates/ui/src/icons/assets/git-file.svg similarity index 100% rename from crates/assets/assets/icons/git-file.svg rename to crates/ui/src/icons/assets/git-file.svg diff --git a/crates/assets/assets/icons/git-issue-close.svg b/crates/ui/src/icons/assets/git-issue-close.svg similarity index 100% rename from crates/assets/assets/icons/git-issue-close.svg rename to crates/ui/src/icons/assets/git-issue-close.svg diff --git a/crates/assets/assets/icons/git-issue-done.svg b/crates/ui/src/icons/assets/git-issue-done.svg similarity index 100% rename from crates/assets/assets/icons/git-issue-done.svg rename to crates/ui/src/icons/assets/git-issue-done.svg diff --git a/crates/assets/assets/icons/git-issue-ongoing.svg b/crates/ui/src/icons/assets/git-issue-ongoing.svg similarity index 100% rename from crates/assets/assets/icons/git-issue-ongoing.svg rename to crates/ui/src/icons/assets/git-issue-ongoing.svg diff --git a/crates/assets/assets/icons/git-issue-open.svg b/crates/ui/src/icons/assets/git-issue-open.svg similarity index 100% rename from crates/assets/assets/icons/git-issue-open.svg rename to crates/ui/src/icons/assets/git-issue-open.svg diff --git a/crates/assets/assets/icons/git-pull-request-closed.svg b/crates/ui/src/icons/assets/git-pull-request-closed.svg similarity index 100% rename from crates/assets/assets/icons/git-pull-request-closed.svg rename to crates/ui/src/icons/assets/git-pull-request-closed.svg diff --git a/crates/assets/assets/icons/git-pull-request-draft.svg b/crates/ui/src/icons/assets/git-pull-request-draft.svg similarity index 100% rename from crates/assets/assets/icons/git-pull-request-draft.svg rename to crates/ui/src/icons/assets/git-pull-request-draft.svg diff --git a/crates/assets/assets/icons/git-pull-request-merged.svg b/crates/ui/src/icons/assets/git-pull-request-merged.svg similarity index 100% rename from crates/assets/assets/icons/git-pull-request-merged.svg rename to crates/ui/src/icons/assets/git-pull-request-merged.svg diff --git a/crates/assets/assets/icons/git-pull-request.svg b/crates/ui/src/icons/assets/git-pull-request.svg similarity index 100% rename from crates/assets/assets/icons/git-pull-request.svg rename to crates/ui/src/icons/assets/git-pull-request.svg diff --git a/crates/assets/assets/icons/github.svg b/crates/ui/src/icons/assets/github.svg similarity index 100% rename from crates/assets/assets/icons/github.svg rename to crates/ui/src/icons/assets/github.svg diff --git a/crates/assets/assets/icons/global-on.svg b/crates/ui/src/icons/assets/global-on.svg similarity index 100% rename from crates/assets/assets/icons/global-on.svg rename to crates/ui/src/icons/assets/global-on.svg diff --git a/crates/assets/assets/icons/globe.svg b/crates/ui/src/icons/assets/globe.svg similarity index 100% rename from crates/assets/assets/icons/globe.svg rename to crates/ui/src/icons/assets/globe.svg diff --git a/crates/assets/assets/icons/grid.svg b/crates/ui/src/icons/assets/grid.svg similarity index 100% rename from crates/assets/assets/icons/grid.svg rename to crates/ui/src/icons/assets/grid.svg diff --git a/crates/assets/assets/icons/hard-drive.svg b/crates/ui/src/icons/assets/hard-drive.svg similarity index 100% rename from crates/assets/assets/icons/hard-drive.svg rename to crates/ui/src/icons/assets/hard-drive.svg diff --git a/crates/assets/assets/icons/heart-off.svg b/crates/ui/src/icons/assets/heart-off.svg similarity index 100% rename from crates/assets/assets/icons/heart-off.svg rename to crates/ui/src/icons/assets/heart-off.svg diff --git a/crates/assets/assets/icons/heart.svg b/crates/ui/src/icons/assets/heart.svg similarity index 100% rename from crates/assets/assets/icons/heart.svg rename to crates/ui/src/icons/assets/heart.svg diff --git a/crates/ui/src/icons/assets/house.svg b/crates/ui/src/icons/assets/house.svg new file mode 100644 index 0000000..10e4097 --- /dev/null +++ b/crates/ui/src/icons/assets/house.svg @@ -0,0 +1,14 @@ + + + + diff --git a/crates/ui/src/icons/assets/image.svg b/crates/ui/src/icons/assets/image.svg new file mode 100644 index 0000000..3241134 --- /dev/null +++ b/crates/ui/src/icons/assets/image.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/assets/assets/icons/inbox.svg b/crates/ui/src/icons/assets/inbox.svg similarity index 100% rename from crates/assets/assets/icons/inbox.svg rename to crates/ui/src/icons/assets/inbox.svg diff --git a/crates/assets/assets/icons/info.svg b/crates/ui/src/icons/assets/info.svg similarity index 100% rename from crates/assets/assets/icons/info.svg rename to crates/ui/src/icons/assets/info.svg diff --git a/crates/assets/assets/icons/init.svg b/crates/ui/src/icons/assets/init.svg similarity index 100% rename from crates/assets/assets/icons/init.svg rename to crates/ui/src/icons/assets/init.svg diff --git a/crates/assets/assets/icons/inspector.svg b/crates/ui/src/icons/assets/inspector.svg similarity index 100% rename from crates/assets/assets/icons/inspector.svg rename to crates/ui/src/icons/assets/inspector.svg diff --git a/crates/assets/assets/icons/layout-dashboard.svg b/crates/ui/src/icons/assets/layout-dashboard.svg similarity index 100% rename from crates/assets/assets/icons/layout-dashboard.svg rename to crates/ui/src/icons/assets/layout-dashboard.svg diff --git a/crates/ui/src/icons/assets/layout-grid.svg b/crates/ui/src/icons/assets/layout-grid.svg new file mode 100644 index 0000000..f8eca3a --- /dev/null +++ b/crates/ui/src/icons/assets/layout-grid.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/crates/ui/src/icons/assets/link.svg b/crates/ui/src/icons/assets/link.svg new file mode 100644 index 0000000..645e746 --- /dev/null +++ b/crates/ui/src/icons/assets/link.svg @@ -0,0 +1,14 @@ + + + + diff --git a/crates/ui/src/icons/assets/list.svg b/crates/ui/src/icons/assets/list.svg new file mode 100644 index 0000000..0d88fb1 --- /dev/null +++ b/crates/ui/src/icons/assets/list.svg @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/crates/assets/assets/icons/loader-circle.svg b/crates/ui/src/icons/assets/loader-circle.svg similarity index 100% rename from crates/assets/assets/icons/loader-circle.svg rename to crates/ui/src/icons/assets/loader-circle.svg diff --git a/crates/assets/assets/icons/loader.svg b/crates/ui/src/icons/assets/loader.svg similarity index 100% rename from crates/assets/assets/icons/loader.svg rename to crates/ui/src/icons/assets/loader.svg diff --git a/crates/ui/src/icons/assets/lock-open.svg b/crates/ui/src/icons/assets/lock-open.svg new file mode 100644 index 0000000..b236712 --- /dev/null +++ b/crates/ui/src/icons/assets/lock-open.svg @@ -0,0 +1,14 @@ + + + + diff --git a/crates/ui/src/icons/assets/lock.svg b/crates/ui/src/icons/assets/lock.svg new file mode 100644 index 0000000..b2b32d1 --- /dev/null +++ b/crates/ui/src/icons/assets/lock.svg @@ -0,0 +1,14 @@ + + + + diff --git a/crates/ui/src/icons/assets/mail.svg b/crates/ui/src/icons/assets/mail.svg new file mode 100644 index 0000000..4cff729 --- /dev/null +++ b/crates/ui/src/icons/assets/mail.svg @@ -0,0 +1,14 @@ + + + + diff --git a/crates/assets/assets/icons/map.svg b/crates/ui/src/icons/assets/map.svg similarity index 100% rename from crates/assets/assets/icons/map.svg rename to crates/ui/src/icons/assets/map.svg diff --git a/crates/assets/assets/icons/markdown.svg b/crates/ui/src/icons/assets/markdown.svg similarity index 100% rename from crates/assets/assets/icons/markdown.svg rename to crates/ui/src/icons/assets/markdown.svg diff --git a/crates/assets/assets/icons/maximize.svg b/crates/ui/src/icons/assets/maximize.svg similarity index 100% rename from crates/assets/assets/icons/maximize.svg rename to crates/ui/src/icons/assets/maximize.svg diff --git a/crates/assets/assets/icons/memory-stick.svg b/crates/ui/src/icons/assets/memory-stick.svg similarity index 100% rename from crates/assets/assets/icons/memory-stick.svg rename to crates/ui/src/icons/assets/memory-stick.svg diff --git a/crates/assets/assets/icons/menu.svg b/crates/ui/src/icons/assets/menu.svg similarity index 100% rename from crates/assets/assets/icons/menu.svg rename to crates/ui/src/icons/assets/menu.svg diff --git a/crates/ui/src/icons/assets/mic.svg b/crates/ui/src/icons/assets/mic.svg new file mode 100644 index 0000000..351c1b6 --- /dev/null +++ b/crates/ui/src/icons/assets/mic.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/assets/assets/icons/minimize.svg b/crates/ui/src/icons/assets/minimize.svg similarity index 100% rename from crates/assets/assets/icons/minimize.svg rename to crates/ui/src/icons/assets/minimize.svg diff --git a/crates/assets/assets/icons/minus.svg b/crates/ui/src/icons/assets/minus.svg similarity index 100% rename from crates/assets/assets/icons/minus.svg rename to crates/ui/src/icons/assets/minus.svg diff --git a/crates/assets/assets/icons/moon.svg b/crates/ui/src/icons/assets/moon.svg similarity index 100% rename from crates/assets/assets/icons/moon.svg rename to crates/ui/src/icons/assets/moon.svg diff --git a/crates/assets/assets/icons/network.svg b/crates/ui/src/icons/assets/network.svg similarity index 100% rename from crates/assets/assets/icons/network.svg rename to crates/ui/src/icons/assets/network.svg diff --git a/crates/assets/assets/icons/palette.svg b/crates/ui/src/icons/assets/palette.svg similarity index 100% rename from crates/assets/assets/icons/palette.svg rename to crates/ui/src/icons/assets/palette.svg diff --git a/crates/assets/assets/icons/panel-bottom-open.svg b/crates/ui/src/icons/assets/panel-bottom-open.svg similarity index 100% rename from crates/assets/assets/icons/panel-bottom-open.svg rename to crates/ui/src/icons/assets/panel-bottom-open.svg diff --git a/crates/assets/assets/icons/panel-bottom.svg b/crates/ui/src/icons/assets/panel-bottom.svg similarity index 100% rename from crates/assets/assets/icons/panel-bottom.svg rename to crates/ui/src/icons/assets/panel-bottom.svg diff --git a/crates/assets/assets/icons/panel-left-close.svg b/crates/ui/src/icons/assets/panel-left-close.svg similarity index 100% rename from crates/assets/assets/icons/panel-left-close.svg rename to crates/ui/src/icons/assets/panel-left-close.svg diff --git a/crates/assets/assets/icons/panel-left-open.svg b/crates/ui/src/icons/assets/panel-left-open.svg similarity index 100% rename from crates/assets/assets/icons/panel-left-open.svg rename to crates/ui/src/icons/assets/panel-left-open.svg diff --git a/crates/assets/assets/icons/panel-left.svg b/crates/ui/src/icons/assets/panel-left.svg similarity index 100% rename from crates/assets/assets/icons/panel-left.svg rename to crates/ui/src/icons/assets/panel-left.svg diff --git a/crates/assets/assets/icons/panel-right-close.svg b/crates/ui/src/icons/assets/panel-right-close.svg similarity index 100% rename from crates/assets/assets/icons/panel-right-close.svg rename to crates/ui/src/icons/assets/panel-right-close.svg diff --git a/crates/assets/assets/icons/panel-right-open.svg b/crates/ui/src/icons/assets/panel-right-open.svg similarity index 100% rename from crates/assets/assets/icons/panel-right-open.svg rename to crates/ui/src/icons/assets/panel-right-open.svg diff --git a/crates/assets/assets/icons/panel-right.svg b/crates/ui/src/icons/assets/panel-right.svg similarity index 100% rename from crates/assets/assets/icons/panel-right.svg rename to crates/ui/src/icons/assets/panel-right.svg diff --git a/crates/assets/assets/icons/pause.svg b/crates/ui/src/icons/assets/pause.svg similarity index 100% rename from crates/assets/assets/icons/pause.svg rename to crates/ui/src/icons/assets/pause.svg diff --git a/crates/ui/src/icons/assets/pencil.svg b/crates/ui/src/icons/assets/pencil.svg new file mode 100644 index 0000000..7384498 --- /dev/null +++ b/crates/ui/src/icons/assets/pencil.svg @@ -0,0 +1,14 @@ + + + + diff --git a/crates/ui/src/icons/assets/pin.svg b/crates/ui/src/icons/assets/pin.svg new file mode 100644 index 0000000..04bc7cb --- /dev/null +++ b/crates/ui/src/icons/assets/pin.svg @@ -0,0 +1,14 @@ + + + + diff --git a/crates/assets/assets/icons/play.svg b/crates/ui/src/icons/assets/play.svg similarity index 100% rename from crates/assets/assets/icons/play.svg rename to crates/ui/src/icons/assets/play.svg diff --git a/crates/assets/assets/icons/plus.svg b/crates/ui/src/icons/assets/plus.svg similarity index 100% rename from crates/assets/assets/icons/plus.svg rename to crates/ui/src/icons/assets/plus.svg diff --git a/crates/ui/src/icons/assets/printer.svg b/crates/ui/src/icons/assets/printer.svg new file mode 100644 index 0000000..dfa0a60 --- /dev/null +++ b/crates/ui/src/icons/assets/printer.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/assets/assets/icons/recent.svg b/crates/ui/src/icons/assets/recent.svg similarity index 100% rename from crates/assets/assets/icons/recent.svg rename to crates/ui/src/icons/assets/recent.svg diff --git a/crates/assets/assets/icons/redo-2.svg b/crates/ui/src/icons/assets/redo-2.svg similarity index 100% rename from crates/assets/assets/icons/redo-2.svg rename to crates/ui/src/icons/assets/redo-2.svg diff --git a/crates/assets/assets/icons/redo.svg b/crates/ui/src/icons/assets/redo.svg similarity index 100% rename from crates/assets/assets/icons/redo.svg rename to crates/ui/src/icons/assets/redo.svg diff --git a/crates/ui/src/icons/assets/refresh-cw.svg b/crates/ui/src/icons/assets/refresh-cw.svg new file mode 100644 index 0000000..c27b3a9 --- /dev/null +++ b/crates/ui/src/icons/assets/refresh-cw.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/crates/assets/assets/icons/refresh.svg b/crates/ui/src/icons/assets/refresh.svg similarity index 100% rename from crates/assets/assets/icons/refresh.svg rename to crates/ui/src/icons/assets/refresh.svg diff --git a/crates/assets/assets/icons/replace.svg b/crates/ui/src/icons/assets/replace.svg similarity index 100% rename from crates/assets/assets/icons/replace.svg rename to crates/ui/src/icons/assets/replace.svg diff --git a/crates/assets/assets/icons/resize-corner.svg b/crates/ui/src/icons/assets/resize-corner.svg similarity index 100% rename from crates/assets/assets/icons/resize-corner.svg rename to crates/ui/src/icons/assets/resize-corner.svg diff --git a/crates/ui/src/icons/assets/save.svg b/crates/ui/src/icons/assets/save.svg new file mode 100644 index 0000000..07af070 --- /dev/null +++ b/crates/ui/src/icons/assets/save.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/ui/src/icons/assets/scissors.svg b/crates/ui/src/icons/assets/scissors.svg new file mode 100644 index 0000000..f87bf20 --- /dev/null +++ b/crates/ui/src/icons/assets/scissors.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/crates/assets/assets/icons/search.svg b/crates/ui/src/icons/assets/search.svg similarity index 100% rename from crates/assets/assets/icons/search.svg rename to crates/ui/src/icons/assets/search.svg diff --git a/crates/ui/src/icons/assets/send.svg b/crates/ui/src/icons/assets/send.svg new file mode 100644 index 0000000..001843b --- /dev/null +++ b/crates/ui/src/icons/assets/send.svg @@ -0,0 +1,14 @@ + + + + diff --git a/crates/assets/assets/icons/settings-2.svg b/crates/ui/src/icons/assets/settings-2.svg similarity index 100% rename from crates/assets/assets/icons/settings-2.svg rename to crates/ui/src/icons/assets/settings-2.svg diff --git a/crates/assets/assets/icons/settings.svg b/crates/ui/src/icons/assets/settings.svg similarity index 100% rename from crates/assets/assets/icons/settings.svg rename to crates/ui/src/icons/assets/settings.svg diff --git a/crates/assets/assets/icons/share.svg b/crates/ui/src/icons/assets/share.svg similarity index 100% rename from crates/assets/assets/icons/share.svg rename to crates/ui/src/icons/assets/share.svg diff --git a/crates/assets/assets/icons/sort-ascending.svg b/crates/ui/src/icons/assets/sort-ascending.svg similarity index 100% rename from crates/assets/assets/icons/sort-ascending.svg rename to crates/ui/src/icons/assets/sort-ascending.svg diff --git a/crates/assets/assets/icons/sort-descending.svg b/crates/ui/src/icons/assets/sort-descending.svg similarity index 100% rename from crates/assets/assets/icons/sort-descending.svg rename to crates/ui/src/icons/assets/sort-descending.svg diff --git a/crates/assets/assets/icons/square-terminal.svg b/crates/ui/src/icons/assets/square-terminal.svg similarity index 100% rename from crates/assets/assets/icons/square-terminal.svg rename to crates/ui/src/icons/assets/square-terminal.svg diff --git a/crates/ui/src/icons/assets/square.svg b/crates/ui/src/icons/assets/square.svg new file mode 100644 index 0000000..7862733 --- /dev/null +++ b/crates/ui/src/icons/assets/square.svg @@ -0,0 +1,13 @@ + + + diff --git a/crates/assets/assets/icons/star-fill.svg b/crates/ui/src/icons/assets/star-fill.svg similarity index 100% rename from crates/assets/assets/icons/star-fill.svg rename to crates/ui/src/icons/assets/star-fill.svg diff --git a/crates/assets/assets/icons/star-off.svg b/crates/ui/src/icons/assets/star-off.svg similarity index 100% rename from crates/assets/assets/icons/star-off.svg rename to crates/ui/src/icons/assets/star-off.svg diff --git a/crates/assets/assets/icons/star.svg b/crates/ui/src/icons/assets/star.svg similarity index 100% rename from crates/assets/assets/icons/star.svg rename to crates/ui/src/icons/assets/star.svg diff --git a/crates/assets/assets/icons/sun.svg b/crates/ui/src/icons/assets/sun.svg similarity index 100% rename from crates/assets/assets/icons/sun.svg rename to crates/ui/src/icons/assets/sun.svg diff --git a/crates/assets/assets/icons/tag.svg b/crates/ui/src/icons/assets/tag.svg similarity index 100% rename from crates/assets/assets/icons/tag.svg rename to crates/ui/src/icons/assets/tag.svg diff --git a/crates/ui/src/icons/assets/text-align-center.svg b/crates/ui/src/icons/assets/text-align-center.svg new file mode 100644 index 0000000..a7b6d53 --- /dev/null +++ b/crates/ui/src/icons/assets/text-align-center.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/ui/src/icons/assets/text-align-end.svg b/crates/ui/src/icons/assets/text-align-end.svg new file mode 100644 index 0000000..fba40f3 --- /dev/null +++ b/crates/ui/src/icons/assets/text-align-end.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/ui/src/icons/assets/text-align-start.svg b/crates/ui/src/icons/assets/text-align-start.svg new file mode 100644 index 0000000..703d455 --- /dev/null +++ b/crates/ui/src/icons/assets/text-align-start.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/assets/assets/icons/thumbs-down.svg b/crates/ui/src/icons/assets/thumbs-down.svg similarity index 100% rename from crates/assets/assets/icons/thumbs-down.svg rename to crates/ui/src/icons/assets/thumbs-down.svg diff --git a/crates/assets/assets/icons/thumbs-up.svg b/crates/ui/src/icons/assets/thumbs-up.svg similarity index 100% rename from crates/assets/assets/icons/thumbs-up.svg rename to crates/ui/src/icons/assets/thumbs-up.svg diff --git a/crates/assets/assets/icons/trash.svg b/crates/ui/src/icons/assets/trash.svg similarity index 100% rename from crates/assets/assets/icons/trash.svg rename to crates/ui/src/icons/assets/trash.svg diff --git a/crates/assets/assets/icons/trending.svg b/crates/ui/src/icons/assets/trending.svg similarity index 100% rename from crates/assets/assets/icons/trending.svg rename to crates/ui/src/icons/assets/trending.svg diff --git a/crates/assets/assets/icons/triangle-alert.svg b/crates/ui/src/icons/assets/triangle-alert.svg similarity index 100% rename from crates/assets/assets/icons/triangle-alert.svg rename to crates/ui/src/icons/assets/triangle-alert.svg diff --git a/crates/assets/assets/icons/undo-2.svg b/crates/ui/src/icons/assets/undo-2.svg similarity index 100% rename from crates/assets/assets/icons/undo-2.svg rename to crates/ui/src/icons/assets/undo-2.svg diff --git a/crates/assets/assets/icons/undo.svg b/crates/ui/src/icons/assets/undo.svg similarity index 100% rename from crates/assets/assets/icons/undo.svg rename to crates/ui/src/icons/assets/undo.svg diff --git a/crates/assets/assets/icons/unlock.svg b/crates/ui/src/icons/assets/unlock.svg similarity index 100% rename from crates/assets/assets/icons/unlock.svg rename to crates/ui/src/icons/assets/unlock.svg diff --git a/crates/assets/assets/icons/user.svg b/crates/ui/src/icons/assets/user.svg similarity index 100% rename from crates/assets/assets/icons/user.svg rename to crates/ui/src/icons/assets/user.svg diff --git a/crates/ui/src/icons/assets/volume-2.svg b/crates/ui/src/icons/assets/volume-2.svg new file mode 100644 index 0000000..519e6cb --- /dev/null +++ b/crates/ui/src/icons/assets/volume-2.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/ui/src/icons/assets/volume-x.svg b/crates/ui/src/icons/assets/volume-x.svg new file mode 100644 index 0000000..3e26009 --- /dev/null +++ b/crates/ui/src/icons/assets/volume-x.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/assets/assets/icons/window-close.svg b/crates/ui/src/icons/assets/window-close.svg similarity index 100% rename from crates/assets/assets/icons/window-close.svg rename to crates/ui/src/icons/assets/window-close.svg diff --git a/crates/assets/assets/icons/window-maximize.svg b/crates/ui/src/icons/assets/window-maximize.svg similarity index 100% rename from crates/assets/assets/icons/window-maximize.svg rename to crates/ui/src/icons/assets/window-maximize.svg diff --git a/crates/assets/assets/icons/window-minimize.svg b/crates/ui/src/icons/assets/window-minimize.svg similarity index 100% rename from crates/assets/assets/icons/window-minimize.svg rename to crates/ui/src/icons/assets/window-minimize.svg diff --git a/crates/assets/assets/icons/window-restore.svg b/crates/ui/src/icons/assets/window-restore.svg similarity index 100% rename from crates/assets/assets/icons/window-restore.svg rename to crates/ui/src/icons/assets/window-restore.svg diff --git a/crates/ui/src/icons/assets/x.svg b/crates/ui/src/icons/assets/x.svg new file mode 100644 index 0000000..e317943 --- /dev/null +++ b/crates/ui/src/icons/assets/x.svg @@ -0,0 +1,14 @@ + + + + diff --git a/crates/ui/src/icons/assets/zoom-in.svg b/crates/ui/src/icons/assets/zoom-in.svg new file mode 100644 index 0000000..11173c0 --- /dev/null +++ b/crates/ui/src/icons/assets/zoom-in.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/crates/ui/src/icons/assets/zoom-out.svg b/crates/ui/src/icons/assets/zoom-out.svg new file mode 100644 index 0000000..70abec4 --- /dev/null +++ b/crates/ui/src/icons/assets/zoom-out.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/ui/src/icons/freedesktop.rs b/crates/ui/src/icons/freedesktop.rs new file mode 100644 index 0000000..38a201f --- /dev/null +++ b/crates/ui/src/icons/freedesktop.rs @@ -0,0 +1,429 @@ +//! Linux resolver: freedesktop icon-theme lookup (active theme → its +//! inherits → hicolor), painting the found SVG through gpui. The lookup is +//! pure, so fixtures run on every OS; theme discovery lives behind the Linux cfg. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock, PoisonError}; + +use gpui::SharedString; + +use crate::icons::IconRole; + +/// Directory-name ranking when matching the requested size. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum SizeScore { + Scalable, + Exact(u32), + Any, +} + +fn size_score(directory: &str, requested: u32) -> SizeScore { + if directory == "scalable" { + return SizeScore::Scalable; + } + let digits: String = directory.chars().take_while(char::is_ascii_digit).collect(); + match digits.parse::() { + Ok(found) => SizeScore::Exact(found.abs_diff(requested)), + Err(_) => SizeScore::Any, + } +} + +/// Walks the theme's inherits chain (capped) plus `hicolor`. +/// +/// Preferring the theme's own candidates over the fallback theme's. +pub(crate) fn lookup( + candidates: &[&str], + theme: &str, + requested: u32, + base_dirs: &[PathBuf], +) -> Option { + let mut themes = vec![theme.to_string()]; + let mut index = 0; + + while themes.len() < 5 && index < themes.len() { + if let Some(parents) = inherits(&themes[index], base_dirs) { + themes.extend(parents); + } + index += 1; + } + themes.push("hicolor".to_string()); + + for theme in &themes { + for name in candidates { + if let Some(path) = find_named(base_dirs, theme, name, requested) { + return Some(path); + } + } + } + + None +} + +fn inherits(theme: &str, base_dirs: &[PathBuf]) -> Option> { + let index = base_dirs + .iter() + .map(|base| base.join(theme).join("index.theme")) + .find(|index| index.is_file())?; + + let text = std::fs::read_to_string(index).ok()?; + let line = text + .lines() + .find(|line| line.trim().starts_with("Inherits="))?; + + Some( + line.trim() + .strip_prefix("Inherits=")? + .split(',') + .map(str::trim) + .filter(|name| !name.is_empty()) + .map(str::to_string) + .collect(), + ) +} + +fn find_named(base_dirs: &[PathBuf], theme: &str, name: &str, requested: u32) -> Option { + let mut best: Option<(SizeScore, PathBuf)> = None; + for base in base_dirs { + search_directory(&base.join(theme), name, requested, 0, &mut best); + } + best.map(|(_, path)| path) +} + +/// Search directory recursively with bounded depth. +fn search_directory( + directory: &Path, + name: &str, + requested: u32, + depth: usize, + best: &mut Option<(SizeScore, PathBuf)>, +) { + if depth > 2 { + return; + } + + let Ok(entries) = std::fs::read_dir(directory) else { + return; + }; + + let icon = format!("{name}.svg"); + + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + search_directory(&path, name, requested, depth + 1, best); + } else if path.file_name().is_some_and(|file| *file == *icon) { + let score = icon_score(&path, requested); + if best + .as_ref() + .is_none_or(|(best_score, _)| score < *best_score) + { + *best = Some((score, path)); + } + } + } +} + +/// Scores from the icon's parent and grandparent directory names, +/// whichever carries the size (`scalable`, `16x16`, `24`, etc.). +fn icon_score(path: &Path, requested: u32) -> SizeScore { + let parent = path + .parent() + .and_then(|parent| parent.file_name()) + .and_then(|name| name.to_str()); + + let grandparent = path + .parent() + .and_then(|parent| parent.parent()) + .and_then(|parent| parent.file_name()) + .and_then(|name| name.to_str()); + + [parent, grandparent] + .into_iter() + .flatten() + .map(|name| size_score(name, requested)) + .min() + .unwrap_or(SizeScore::Any) +} + +/// A resolved icon file and the asset key its bytes are served under. +struct CachedIcon { + path: PathBuf, + asset_key: SharedString, +} + +/// The discovered icons, cached for the process. +type IconCache = Mutex>>; + +pub(crate) fn cached_file(role: IconRole, requested: u32) -> Option { + cached_icon(role, requested, |icon| icon.path.clone()) +} + +/// The asset key a resolved freedesktop file is served under. +pub(crate) fn cached_asset_key(role: IconRole, requested: u32) -> Option { + cached_icon(role, requested, |icon| icon.asset_key.clone()) +} + +fn cached_icon(role: IconRole, requested: u32, project: P) -> Option +where + P: FnOnce(&CachedIcon) -> T, +{ + static CACHE: OnceLock = OnceLock::new(); + + let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); + // A poisoned lock means a lookup panicked; its stale data beats a panic. + let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner); + + cache + .entry((role.slug(), requested)) + .or_insert_with(|| { + lookup( + role.freedesktop_names(), + &active_theme(), + requested, + &base_dirs(), + ) + .map(|path| CachedIcon { + asset_key: SharedString::from(format!( + "icons/freedesktop/{}-{requested}.svg", + role.slug() + )), + path, + }) + }) + .as_ref() + .map(project) +} + +#[cfg(target_os = "linux")] +mod discovery { + use std::path::PathBuf; + + fn home_dir() -> Option { + std::env::var_os("HOME").map(PathBuf::from) + } + + /// `$HOME/.icons`, `$XDG_DATA_HOME/icons`, `$XDG_DATA_DIRS/icons`. + pub(crate) fn base_dirs() -> Vec { + let mut dirs = Vec::new(); + if let Some(home) = home_dir() { + dirs.push(home.join(".icons")); + dirs.push(home.join(".local/share/icons")); + } + let data_dirs = std::env::var("XDG_DATA_DIRS") + .unwrap_or_else(|_| "/usr/local/share:/usr/share".to_string()); + for data_dir in data_dirs.split(':').filter(|dir| !dir.is_empty()) { + dirs.push(PathBuf::from(data_dir).join("icons")); + } + dirs + } + + fn gsettings_icon_theme() -> Option { + let output = std::process::Command::new("gsettings") + .args(["get", "org.gnome.desktop.interface", "icon-theme"]) + .output() + .ok()?; + if !output.status.success() { + return None; + } + let value = String::from_utf8(output.stdout).ok()?; + Some(value.trim().trim_matches('\'').trim().to_string()) + } + + fn kdeglobals_icon_theme() -> Option { + let text = std::fs::read_to_string(home_dir()?.join(".config/kdeglobals")).ok()?; + let mut section = None; + for line in text.lines() { + let line = line.trim(); + if let Some(rest) = line.strip_prefix('[') { + section = Some(rest.split(']').next().unwrap_or(rest).trim().to_string()); + } else if section.as_deref() == Some("Icons") + && let Some((key, value)) = line.split_once('=') + && key.trim() == "Theme" + { + return Some(value.trim().to_string()); + } + } + None + } + + fn omarchy_icon_theme() -> Option { + let path = home_dir()?.join(".local/state/omarchy/current/theme/icons.theme"); + let text = std::fs::read_to_string(path).ok()?; + Some(text.trim().to_string()) + } + + pub(crate) fn active_theme() -> String { + omarchy_icon_theme() + .or_else(kdeglobals_icon_theme) + .or_else(gsettings_icon_theme) + .filter(|theme| !theme.is_empty()) + .unwrap_or_else(|| "Adwaita".to_string()) + } +} + +#[cfg(target_os = "linux")] +use discovery::{active_theme, base_dirs}; + +#[cfg(not(target_os = "linux"))] +fn active_theme() -> String { + "Adwaita".to_string() +} + +#[cfg(not(target_os = "linux"))] +fn base_dirs() -> Vec { + Vec::new() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(name: &str) -> PathBuf { + let root = + std::env::temp_dir().join(format!("gpui-native-icons-{name}-{}", std::process::id())); + // NotFound is the expected first run; anything else is a setup failure. + if let Err(error) = std::fs::remove_dir_all(&root) + && error.kind() != std::io::ErrorKind::NotFound + { + panic!("failed to clear scratch dir {root:?}: {error}"); + } + std::fs::create_dir_all(&root).expect("scratch dir"); + root + } + + fn write(path: &Path, contents: &str) { + std::fs::create_dir_all(path.parent().expect("parent")).expect("dirs"); + std::fs::write(path, contents).expect("write"); + } + + #[test] + fn the_theme_beats_hicolor() { + let base = scratch("precedence"); + write( + &base.join("mytheme/scalable/actions/object-select-symbolic.svg"), + "", + ); + write( + &base.join("hicolor/scalable/actions/object-select-symbolic.svg"), + "", + ); + + assert_eq!( + lookup( + &["object-select-symbolic"], + "mytheme", + 16, + std::slice::from_ref(&base) + ), + Some(base.join("mytheme/scalable/actions/object-select-symbolic.svg")) + ); + std::fs::remove_dir_all(&base).expect("cleanup"); + } + + #[test] + fn a_missing_glyph_falls_through_to_hicolor() { + let base = scratch("hicolor"); + write(&base.join("hicolor/24/actions/search.svg"), ""); + + assert_eq!( + lookup(&["search"], "breeze", 24, std::slice::from_ref(&base)), + Some(base.join("hicolor/24/actions/search.svg")) + ); + std::fs::remove_dir_all(&base).expect("cleanup"); + } + + #[test] + fn the_inherits_chain_is_walked() { + let base = scratch("inherits"); + write(&base.join("parent/scalable/actions/add.svg"), ""); + write( + &base.join("child/index.theme"), + "[Icon Theme]\nInherits=parent\n", + ); + + assert_eq!( + lookup(&["add"], "child", 16, std::slice::from_ref(&base)), + Some(base.join("parent/scalable/actions/add.svg")) + ); + std::fs::remove_dir_all(&base).expect("cleanup"); + } + + #[test] + fn scalable_wins_and_the_closest_size_wins_without_it() { + let base = scratch("sizes"); + write(&base.join("theme/16x16/actions/check.svg"), ""); + write(&base.join("theme/48x48/actions/check.svg"), ""); + write(&base.join("theme/scalable/actions/check.svg"), ""); + + assert_eq!( + lookup(&["check"], "theme", 16, std::slice::from_ref(&base)), + Some(base.join("theme/scalable/actions/check.svg")) + ); + + let base = scratch("sizes-plain"); + write(&base.join("theme/16x16/actions/check.svg"), ""); + write(&base.join("theme/48x48/actions/check.svg"), ""); + + assert_eq!( + lookup(&["check"], "theme", 16, std::slice::from_ref(&base)), + Some(base.join("theme/16x16/actions/check.svg")) + ); + std::fs::remove_dir_all(&base).expect("cleanup"); + } + + #[test] + fn both_theme_layouts_are_searched() { + let adwaita = scratch("layout-adwaita"); + write(&adwaita.join("theme/scalable/actions/check.svg"), ""); + assert_eq!( + lookup(&["check"], "theme", 16, std::slice::from_ref(&adwaita)), + Some(adwaita.join("theme/scalable/actions/check.svg")) + ); + + let breeze = scratch("layout-breeze"); + write(&breeze.join("theme/actions/16/check.svg"), ""); + assert_eq!( + lookup(&["check"], "theme", 16, std::slice::from_ref(&breeze)), + Some(breeze.join("theme/actions/16/check.svg")) + ); + std::fs::remove_dir_all(&adwaita).expect("cleanup"); + std::fs::remove_dir_all(&breeze).expect("cleanup"); + } + + #[test] + fn png_only_themes_are_skipped() { + let base = scratch("png"); + write(&base.join("theme/16x16/actions/check.png"), "png"); + + assert_eq!( + lookup(&["check"], "theme", 16, std::slice::from_ref(&base)), + None + ); + std::fs::remove_dir_all(&base).expect("cleanup"); + } + + #[test] + fn a_themes_second_candidate_beats_hicolors_first() { + let base = scratch("candidates"); + write( + &base.join("mytheme/scalable/actions/emblem-ok-symbolic.svg"), + "", + ); + write( + &base.join("hicolor/scalable/actions/object-select-symbolic.svg"), + "", + ); + + assert_eq!( + lookup( + &["object-select-symbolic", "emblem-ok-symbolic"], + "mytheme", + 16, + std::slice::from_ref(&base) + ), + Some(base.join("mytheme/scalable/actions/emblem-ok-symbolic.svg")) + ); + std::fs::remove_dir_all(&base).expect("cleanup"); + } +} diff --git a/crates/ui/src/icons/mod.rs b/crates/ui/src/icons/mod.rs new file mode 100644 index 0000000..6b7e3fa --- /dev/null +++ b/crates/ui/src/icons/mod.rs @@ -0,0 +1,895 @@ +//! Signed's icon set: semantic roles plus app glyphs, resolved per platform. + +use std::time::Duration; + +use gpui::prelude::FluentBuilder as _; +use gpui::{ + AnyElement, AssetSource, Hsla, IntoElement, ParentElement as _, Pixels, RenderOnce, + SharedString, Styled as _, TimedTransformation, Transformation, Window, div, px, svg, +}; + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +mod freedesktop; +#[cfg_attr(not(target_os = "windows"), allow(dead_code))] +mod segoe; + +const SMALL_ICON_SIZE: Pixels = px(14.0); +const DEFAULT_ICON_SIZE: Pixels = px(16.0); +const LARGE_ICON_SIZE: Pixels = px(20.0); +/// The spin presents at most this rate, rotating a sprite needs no more frames. +const SPIN_MAX_FPS: f32 = 60.0; + +/// The semantic glyphs UI components need. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum IconRole { + Check, + Close, + ChevronDown, + ChevronLeft, + ChevronRight, + ChevronUp, + Plus, + Minus, + Search, + Folder, + Warning, + Info, + Copy, + Eye, + EyeOff, + PanelLeft, + PanelRight, + WindowMinimize, + WindowMaximize, + WindowRestore, + Loader, + Microphone, + Stop, + Settings, + Refresh, + Undo, + Redo, + ZoomIn, + ZoomOut, + Trash, + Edit, + Save, + Download, + Share, + Send, + Print, + EnterFullScreen, + ExitFullScreen, + Cut, + Paste, + Sort, + Home, + Menu, + More, + Grid, + List, + File, + Image, + Calendar, + Clock, + User, + Lock, + Unlock, + Star, + Heart, + Pin, + Mail, + Link, + Play, + Pause, + Help, + Volume, + VolumeMuted, + AlignLeft, + AlignCenter, + AlignRight, + Sun, + Moon, + CirclePlus, + Filter, + GlobalOn, + GlobalOff, + GitFile, + GitCommit, + GitIssueDone, + GitIssueOpen, + GitIssueClosed, + GitIssueOngoing, + GitPullRequest, + GitPullRequestClosed, + GitPullRequestDraft, + GitPullRequestMerged, + GitClone, + GitBranch, + Tag, + Markdown, + Trending, + Recent, + Init, + EllipsisVertical, + ArrowUp, + Globe, + Inbox, +} + +impl IconRole { + pub fn all() -> &'static [Self] { + &[ + Self::Check, + Self::Close, + Self::ChevronDown, + Self::ChevronLeft, + Self::ChevronRight, + Self::ChevronUp, + Self::Plus, + Self::Minus, + Self::Search, + Self::Folder, + Self::Warning, + Self::Info, + Self::Copy, + Self::Eye, + Self::EyeOff, + Self::PanelLeft, + Self::PanelRight, + Self::WindowMinimize, + Self::WindowMaximize, + Self::WindowRestore, + Self::Loader, + Self::Microphone, + Self::Stop, + Self::Settings, + Self::Refresh, + Self::Undo, + Self::Redo, + Self::ZoomIn, + Self::ZoomOut, + Self::Trash, + Self::Edit, + Self::Save, + Self::Download, + Self::Share, + Self::Send, + Self::Print, + Self::EnterFullScreen, + Self::ExitFullScreen, + Self::Cut, + Self::Paste, + Self::Sort, + Self::Home, + Self::Menu, + Self::More, + Self::Grid, + Self::List, + Self::File, + Self::Image, + Self::Calendar, + Self::Clock, + Self::User, + Self::Lock, + Self::Unlock, + Self::Star, + Self::Heart, + Self::Pin, + Self::Mail, + Self::Link, + Self::Play, + Self::Pause, + Self::Help, + Self::Volume, + Self::VolumeMuted, + Self::AlignLeft, + Self::AlignCenter, + Self::AlignRight, + Self::Sun, + Self::Moon, + ] + } + + fn asset_path(self) -> &'static str { + match self { + Self::Check => "icons/check.svg", + Self::Close => "icons/x.svg", + Self::ChevronDown => "icons/chevron-down.svg", + Self::ChevronLeft => "icons/chevron-left.svg", + Self::ChevronRight => "icons/chevron-right.svg", + Self::ChevronUp => "icons/chevron-up.svg", + Self::Plus => "icons/plus.svg", + Self::Minus => "icons/minus.svg", + Self::Search => "icons/search.svg", + Self::Folder => "icons/folder.svg", + Self::Warning => "icons/triangle-alert.svg", + Self::Info => "icons/info.svg", + Self::Copy => "icons/copy.svg", + Self::Eye => "icons/eye.svg", + Self::EyeOff => "icons/eye-off.svg", + Self::PanelLeft => "icons/panel-left.svg", + Self::PanelRight => "icons/panel-right.svg", + Self::WindowMinimize => "icons/minus.svg", + Self::WindowMaximize => "icons/square.svg", + Self::WindowRestore => "icons/copy.svg", + Self::Loader => "icons/loader.svg", + Self::Microphone => "icons/mic.svg", + Self::Stop => "icons/square.svg", + Self::Settings => "icons/settings.svg", + Self::Refresh => "icons/refresh-cw.svg", + Self::Undo => "icons/undo-2.svg", + Self::Redo => "icons/redo-2.svg", + Self::ZoomIn => "icons/zoom-in.svg", + Self::ZoomOut => "icons/zoom-out.svg", + Self::Trash => "icons/trash.svg", + Self::Edit => "icons/pencil.svg", + Self::Save => "icons/save.svg", + Self::Download => "icons/download.svg", + Self::Share => "icons/share.svg", + Self::Send => "icons/send.svg", + Self::Print => "icons/printer.svg", + Self::EnterFullScreen => "icons/maximize.svg", + Self::ExitFullScreen => "icons/minimize.svg", + Self::Cut => "icons/scissors.svg", + Self::Paste => "icons/clipboard-paste.svg", + Self::Sort => "icons/arrow-up-down.svg", + Self::Home => "icons/house.svg", + Self::Menu => "icons/menu.svg", + Self::More => "icons/ellipsis.svg", + Self::Grid => "icons/layout-grid.svg", + Self::List => "icons/list.svg", + Self::File => "icons/file.svg", + Self::Image => "icons/image.svg", + Self::Calendar => "icons/calendar.svg", + Self::Clock => "icons/clock.svg", + Self::User => "icons/user.svg", + Self::Lock => "icons/lock.svg", + Self::Unlock => "icons/lock-open.svg", + Self::Star => "icons/star.svg", + Self::Heart => "icons/heart.svg", + Self::Pin => "icons/pin.svg", + Self::Mail => "icons/mail.svg", + Self::Link => "icons/link.svg", + Self::Play => "icons/play.svg", + Self::Pause => "icons/pause.svg", + Self::Help => "icons/circle-question-mark.svg", + Self::Volume => "icons/volume-2.svg", + Self::VolumeMuted => "icons/volume-x.svg", + Self::AlignLeft => "icons/text-align-start.svg", + Self::AlignCenter => "icons/text-align-center.svg", + Self::AlignRight => "icons/text-align-end.svg", + Self::Sun => "icons/sun.svg", + Self::Moon => "icons/moon.svg", + Self::CirclePlus => "icons/circle-plus.svg", + Self::Filter => "icons/filter.svg", + Self::GlobalOn => "icons/global-on.svg", + Self::GlobalOff => "icons/global-off.svg", + Self::GitFile => "icons/git-file.svg", + Self::GitCommit => "icons/git-commit.svg", + Self::GitIssueDone => "icons/git-issue-done.svg", + Self::GitIssueOpen => "icons/git-issue-open.svg", + Self::GitIssueClosed => "icons/git-issue-close.svg", + Self::GitIssueOngoing => "icons/git-issue-ongoing.svg", + Self::GitPullRequest => "icons/git-pull-request.svg", + Self::GitPullRequestClosed => "icons/git-pull-request-closed.svg", + Self::GitPullRequestDraft => "icons/git-pull-request-draft.svg", + Self::GitPullRequestMerged => "icons/git-pull-request-merged.svg", + Self::GitClone => "icons/git-clone.svg", + Self::GitBranch => "icons/git-branch.svg", + Self::Tag => "icons/tag.svg", + Self::Markdown => "icons/markdown.svg", + Self::Trending => "icons/trending.svg", + Self::Recent => "icons/recent.svg", + Self::Init => "icons/init.svg", + Self::EllipsisVertical => "icons/ellipsis-vertical.svg", + Self::ArrowUp => "icons/arrow-up.svg", + Self::Globe => "icons/globe.svg", + Self::Inbox => "icons/inbox.svg", + } + } + + /// The stable identifier used for element and debug ids. + pub fn slug(self) -> &'static str { + match self { + Self::Check => "check", + Self::Close => "close", + Self::ChevronDown => "chevron-down", + Self::ChevronLeft => "chevron-left", + Self::ChevronRight => "chevron-right", + Self::ChevronUp => "chevron-up", + Self::Plus => "plus", + Self::Minus => "minus", + Self::Search => "search", + Self::Folder => "folder", + Self::Warning => "warning", + Self::Info => "info", + Self::Copy => "copy", + Self::Eye => "eye", + Self::EyeOff => "eye-off", + Self::PanelLeft => "panel-left", + Self::PanelRight => "panel-right", + Self::WindowMinimize => "window-minimize", + Self::WindowMaximize => "window-maximize", + Self::WindowRestore => "window-restore", + Self::Loader => "loader", + Self::Microphone => "microphone", + Self::Stop => "stop", + Self::Settings => "settings", + Self::Refresh => "refresh", + Self::Undo => "undo", + Self::Redo => "redo", + Self::ZoomIn => "zoom-in", + Self::ZoomOut => "zoom-out", + Self::Trash => "trash", + Self::Edit => "edit", + Self::Save => "save", + Self::Download => "download", + Self::Share => "share", + Self::Send => "send", + Self::Print => "print", + Self::EnterFullScreen => "enter-full-screen", + Self::ExitFullScreen => "exit-full-screen", + Self::Cut => "cut", + Self::Paste => "paste", + Self::Sort => "sort", + Self::Home => "home", + Self::Menu => "menu", + Self::More => "more", + Self::Grid => "grid", + Self::List => "list", + Self::File => "file", + Self::Image => "image", + Self::Calendar => "calendar", + Self::Clock => "clock", + Self::User => "user", + Self::Lock => "lock", + Self::Unlock => "unlock", + Self::Star => "star", + Self::Heart => "heart", + Self::Pin => "pin", + Self::Mail => "mail", + Self::Link => "link", + Self::Play => "play", + Self::Pause => "pause", + Self::Help => "help", + Self::Volume => "volume", + Self::VolumeMuted => "volume-muted", + Self::AlignLeft => "align-left", + Self::AlignCenter => "align-center", + Self::AlignRight => "align-right", + Self::Sun => "sun", + Self::Moon => "moon", + Self::CirclePlus => "circle-plus", + Self::Filter => "filter", + Self::GlobalOn => "global-on", + Self::GlobalOff => "global-off", + Self::GitFile => "git-file", + Self::GitCommit => "git-commit", + Self::GitIssueDone => "git-issue-done", + Self::GitIssueOpen => "git-issue-open", + Self::GitIssueClosed => "git-issue-closed", + Self::GitIssueOngoing => "git-issue-ongoing", + Self::GitPullRequest => "git-pull-request", + Self::GitPullRequestClosed => "git-pull-request-closed", + Self::GitPullRequestDraft => "git-pull-request-draft", + Self::GitPullRequestMerged => "git-pull-request-merged", + Self::GitClone => "git-clone", + Self::GitBranch => "git-branch", + Self::Tag => "tag", + Self::Markdown => "markdown", + Self::Trending => "trending", + Self::Recent => "recent", + Self::Init => "init", + Self::EllipsisVertical => "ellipsis-vertical", + Self::ArrowUp => "arrow-up", + Self::Globe => "globe", + Self::Inbox => "inbox", + } + } + + /// Freedesktop names the role resolves through, best first. + /// + /// Symbolic names lead (Adwaita), with Breeze and legacy names as fallbacks. + fn freedesktop_names(self) -> &'static [&'static str] { + match self { + Self::Check => &[ + "object-select-symbolic", + "object-select", + "emblem-ok-symbolic", + "checkmark", + ], + Self::Close => &[ + "window-close-symbolic", + "window-close", + "close-symbolic", + "gtk-close", + ], + Self::ChevronDown => &[ + "pan-down-symbolic", + "pan-down", + "go-down-symbolic", + "arrow-down", + ], + Self::ChevronLeft => &[ + "pan-start-symbolic", + "pan-start", + "go-previous-symbolic", + "arrow-left", + ], + Self::ChevronRight => &[ + "pan-end-symbolic", + "pan-end", + "go-next-symbolic", + "arrow-right", + ], + Self::ChevronUp => &["pan-up-symbolic", "pan-up", "go-up-symbolic", "arrow-up"], + Self::Plus => &["list-add-symbolic", "list-add", "add"], + Self::Minus => &["list-remove-symbolic", "list-remove", "remove"], + Self::Search => &[ + "system-search-symbolic", + "system-search", + "search", + "edit-find", + ], + Self::Folder => &["folder-symbolic", "folder"], + Self::Warning => &["dialog-warning-symbolic", "dialog-warning", "warning"], + Self::Info => &["dialog-information-symbolic", "dialog-information", "info"], + Self::Copy => &["edit-copy-symbolic", "edit-copy"], + Self::Eye => &["view-visible-symbolic", "view-visible", "visibility", "eye"], + Self::EyeOff => &[ + "view-conceal-symbolic", + "view-hide-symbolic", + "view-hide", + "visibility-off", + "eye-off", + ], + Self::PanelLeft => &[ + "sidebar-expand-left", + "sidebar-show-symbolic", + "panel-left", + "sidebar-left", + ], + Self::PanelRight => &[ + "sidebar-expand-right", + "sidebar-show-right-symbolic", + "sidebar-show-symbolic", + "panel-right", + "sidebar-right", + ], + Self::WindowMinimize => &["window-minimize-symbolic", "window-minimize"], + Self::WindowMaximize => &["window-maximize-symbolic", "window-maximize"], + Self::WindowRestore => &["window-restore-symbolic", "window-restore"], + Self::Loader => &["process-working-symbolic", "process-working"], + Self::Microphone => &["audio-input-microphone-symbolic", "audio-input-microphone"], + Self::Stop => &["process-stop-symbolic", "process-stop"], + Self::Settings => &[ + "applications-system-symbolic", + "settings-symbolic", + "preferences-system-symbolic", + "system-run-symbolic", + ], + Self::Refresh => &["view-refresh-symbolic", "view-refresh"], + Self::Undo => &["edit-undo-symbolic", "edit-undo"], + Self::Redo => &["edit-redo-symbolic", "edit-redo"], + Self::ZoomIn => &["zoom-in-symbolic", "zoom-in"], + Self::ZoomOut => &["zoom-out-symbolic", "zoom-out"], + Self::Trash => &[ + "user-trash-symbolic", + "edit-delete-symbolic", + "user-trash", + "edit-delete", + ], + Self::Edit => &["document-edit-symbolic", "document-edit"], + Self::Save => &["document-save-symbolic", "document-save"], + Self::Download => &["folder-download-symbolic", "folder-download"], + Self::Share => &[ + "send-to-symbolic", + "emblem-shared-symbolic", + "emblem-shared", + ], + Self::Send => &["document-send-symbolic", "document-send"], + Self::Print => &[ + "printer-symbolic", + "document-print-symbolic", + "printer", + "document-print", + ], + Self::EnterFullScreen => &["view-fullscreen-symbolic", "view-fullscreen"], + Self::ExitFullScreen => &["view-restore-symbolic", "view-restore"], + Self::Cut => &["edit-cut-symbolic", "edit-cut"], + Self::Paste => &["edit-paste-symbolic", "edit-paste"], + Self::Sort => &[ + "view-sort-ascending-symbolic", + "view-sort-descending-symbolic", + "view-sort-ascending", + "view-sort-descending", + ], + Self::Home => &[ + "user-home-symbolic", + "go-home-symbolic", + "user-home", + "go-home", + ], + Self::Menu => &["open-menu-symbolic", "open-menu"], + Self::More => &[ + "view-more-horizontal-symbolic", + "view-more-symbolic", + "view-more-horizontal", + "view-more", + ], + Self::Grid => &["view-grid-symbolic", "view-app-grid-symbolic", "view-grid"], + Self::List => &[ + "view-list-symbolic", + "view-list-bullet-symbolic", + "view-list", + "view-list-bullet", + ], + Self::File => &[ + "text-x-generic-symbolic", + "text-x-generic", + "x-office-document-symbolic", + "x-office-document", + ], + Self::Image => &[ + "image-x-generic-symbolic", + "insert-image-symbolic", + "image-x-generic", + "insert-image", + ], + Self::Calendar => &["x-office-calendar-symbolic", "x-office-calendar"], + Self::Clock => &[ + "document-open-recent-symbolic", + "alarm-symbolic", + "clock-symbolic", + "document-open-recent", + ], + Self::User => &["avatar-default-symbolic", "avatar-default"], + Self::Lock => &[ + "changes-prevent-symbolic", + "changes-prevent", + "system-lock-screen-symbolic", + "system-lock-screen", + ], + Self::Unlock => &["changes-allow-symbolic", "changes-allow"], + Self::Star => &[ + "non-starred-symbolic", + "non-starred", + "starred-symbolic", + "starred", + ], + Self::Heart => &["emote-love-symbolic", "emote-love"], + Self::Pin => &["view-pin-symbolic", "view-pin"], + Self::Mail => &[ + "mail-unread-symbolic", + "mail-message-new-symbolic", + "mail-unread", + "mail-message-new", + ], + Self::Link => &["insert-link-symbolic", "insert-link"], + Self::Play => &["media-playback-start-symbolic", "media-playback-start"], + Self::Pause => &["media-playback-pause-symbolic", "media-playback-pause"], + Self::Help => &[ + "dialog-question-symbolic", + "system-help-symbolic", + "dialog-question", + "system-help", + ], + Self::Volume => &["audio-volume-high-symbolic", "audio-volume-high"], + Self::VolumeMuted => &["audio-volume-muted-symbolic", "audio-volume-muted"], + Self::AlignLeft => &["format-justify-left-symbolic", "format-justify-left"], + Self::AlignCenter => &["format-justify-center-symbolic", "format-justify-center"], + Self::AlignRight => &["format-justify-right-symbolic", "format-justify-right"], + Self::Sun => &[ + "weather-clear-symbolic", + "display-brightness-symbolic", + "weather-clear", + ], + Self::Moon => &["weather-clear-night-symbolic", "weather-clear-night"], + Self::CirclePlus + | Self::Filter + | Self::GlobalOn + | Self::GlobalOff + | Self::GitFile + | Self::GitCommit + | Self::GitIssueDone + | Self::GitIssueOpen + | Self::GitIssueClosed + | Self::GitIssueOngoing + | Self::GitPullRequest + | Self::GitPullRequestClosed + | Self::GitPullRequestDraft + | Self::GitPullRequestMerged + | Self::GitClone + | Self::GitBranch + | Self::Tag + | Self::Markdown + | Self::Trending + | Self::Recent + | Self::Init + | Self::EllipsisVertical + | Self::ArrowUp + | Self::Globe + | Self::Inbox => &[], + } + } +} + +/// A glyph named by an application's own icon set. +pub trait IconNamed { + /// The SVG asset path, e.g. `icons/commit.svg`. + fn path(self) -> SharedString; +} + +impl IconNamed for IconRole { + fn path(self) -> SharedString { + SharedString::from(self.asset_path()) + } +} + +/// The glyph an icon draws. +#[derive(Clone)] +enum Glyph { + Role(IconRole), + Named(SharedString), +} + +/// An icon element. Painted with the ambient text color unless a color is set. +#[derive(Clone, IntoElement)] +pub struct Icon { + glyph: Glyph, + size: Pixels, + color: Option, + transformation: Option, + rotation_period: Option, +} + +/// Creates an icon for the role at the default size. +pub fn icon(role: IconRole) -> Icon { + Icon { + glyph: Glyph::Role(role), + size: DEFAULT_ICON_SIZE, + color: None, + transformation: None, + rotation_period: None, + } +} + +impl Icon { + /// Creates an icon from an application-defined icon set. + pub fn named(named: I) -> Self + where + I: IconNamed, + { + Self { + glyph: Glyph::Named(named.path()), + size: DEFAULT_ICON_SIZE, + color: None, + transformation: None, + rotation_period: None, + } + } + + pub fn size(mut self, size: Pixels) -> Self { + self.size = size; + self + } + + /// The small size. + pub fn small(mut self) -> Self { + self.size = SMALL_ICON_SIZE; + self + } + + /// The default medium size. + pub fn medium(mut self) -> Self { + self.size = DEFAULT_ICON_SIZE; + self + } + + /// The large size. + pub fn large(mut self) -> Self { + self.size = LARGE_ICON_SIZE; + self + } + + pub fn color(mut self, color: Hsla) -> Self { + self.color = Some(color); + self + } + + /// An extra static SVG transformation. + pub fn with_transformation(mut self, transformation: Transformation) -> Self { + self.transformation = Some(transformation); + self + } + + /// Spins the icon clockwise, one full turn per `period`. + pub fn with_rotation_animation(mut self, period: Duration) -> Self { + self.rotation_period = Some(period); + self + } + + /// The asset key a resolved freedesktop file is served under. + #[cfg(target_os = "linux")] + fn freedesktop_asset_path(size: Pixels, role: &IconRole) -> Option { + let size = size.as_f32().max(1.0).round() as u32; + freedesktop::cached_asset_key(*role, size) + } + + /// Roles resolve per platform. + fn render_role( + size: Pixels, + color: Option, + transformation: Option, + rotation_period: Option, + role: IconRole, + ) -> AnyElement { + #[cfg(target_os = "windows")] + if let Some(glyph) = segoe::glyph(role) { + return Self::render_glyph(size, color, glyph).into_any_element(); + } + #[cfg(target_os = "linux")] + if let Some(path) = Self::freedesktop_asset_path(size, &role) { + return Self::render_svg_path(size, color, transformation, rotation_period, path) + .into_any_element(); + } + Self::render_svg_path( + size, + color, + transformation, + rotation_period, + SharedString::from(role.asset_path()), + ) + .into_any_element() + } + + /// Windows: the Segoe Fluent glyph drawn as text in the system font. + #[cfg(target_os = "windows")] + fn render_glyph(size: Pixels, color: Option, glyph: &'static str) -> AnyElement { + div() + .flex_none() + .size(size) + .flex() + .items_center() + .justify_center() + .child( + div() + .font_family(segoe::FONT_FAMILY) + .text_size(size) + .when_some(color, |el, color| el.text_color(color)) + .child(SharedString::new_static(glyph)), + ) + .into_any_element() + } + + fn render_svg_path( + size: Pixels, + color: Option, + transformation: Option, + rotation_period: Option, + path: SharedString, + ) -> AnyElement { + div() + .flex_none() + .size(size) + .child( + svg() + .size_full() + .path(path) + .when_some(color, |el, color| el.text_color(color)) + .when_some(transformation, |el, transformation| { + el.with_transformation(transformation) + }) + .when_some(rotation_period, |el, period| { + el.with_timed_transformation( + TimedTransformation::rotation( + period, + transformation.unwrap_or_default(), + ) + .with_max_fps(SPIN_MAX_FPS), + ) + }), + ) + .into_any_element() + } +} + +impl From for Icon +where + I: IconNamed, +{ + fn from(named: I) -> Self { + Icon::named(named) + } +} + +impl RenderOnce for Icon { + fn render(self, window: &mut Window, _cx: &mut gpui::App) -> impl IntoElement { + let Icon { + glyph, + size, + color, + transformation, + rotation_period, + } = self; + + let color = color.unwrap_or_else(|| window.text_style().color); + + match glyph { + Glyph::Named(path) => { + Self::render_svg_path(size, Some(color), transformation, rotation_period, path) + } + Glyph::Role(role) => { + Self::render_role(size, Some(color), transformation, rotation_period, role) + } + } + } +} + +/// The asset source serving the merged icon set. +#[derive(rust_embed::RustEmbed)] +#[folder = "src/icons/assets"] +#[exclude = "*.DS_Store"] +pub struct Assets; + +fn asset_bytes(path: &str) -> Option> { + let name = path.strip_prefix("icons/")?; + Assets::get(name).map(|file| file.data) +} + +fn freedesktop_file(path: &str) -> Option>> { + let rest = path.strip_prefix("icons/freedesktop/")?; + let stem = rest.strip_suffix(".svg")?; + let (slug, size) = stem.rsplit_once('-')?; + let size = size.parse::().ok()?; + let role = IconRole::all().iter().find(|role| role.slug() == slug)?; + freedesktop::cached_file(*role, size).map(std::fs::read) +} + +impl AssetSource for Assets { + fn load(&self, path: &str) -> gpui::Result>> { + if let Some(file) = freedesktop_file(path) { + let bytes = file.map_err(|error| { + anyhow::anyhow!("failed to read freedesktop icon {path}: {error}") + })?; + return Ok(Some(std::borrow::Cow::Owned(bytes))); + } + Ok(asset_bytes(path)) + } + + fn list(&self, path: &str) -> gpui::Result> { + Ok(Self::iter() + .map(|file| SharedString::from(format!("icons/{file}"))) + .filter(|file| file.starts_with(path)) + .collect()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_role_has_a_unique_slug() { + for (index, role) in IconRole::all().iter().enumerate() { + for other in &IconRole::all()[index + 1..] { + assert_ne!( + role.slug(), + other.slug(), + "{role:?} and {other:?} share a slug" + ); + } + } + } + + #[test] + fn every_role_resolves_to_a_bundled_asset() { + for role in IconRole::all() { + assert!( + asset_bytes(role.asset_path()).is_some(), + "missing bundled asset for {role:?}" + ); + } + } +} diff --git a/crates/ui/src/icons/segoe.rs b/crates/ui/src/icons/segoe.rs new file mode 100644 index 0000000..02605ff --- /dev/null +++ b/crates/ui/src/icons/segoe.rs @@ -0,0 +1,124 @@ +//! Windows resolver: each role maps to a Segoe Fluent Icons codepoint, +//! rendered as text in the system font (never bundled). + +use crate::icons::IconRole; + +/// The Segoe Fluent Icons glyph for the role. +pub(crate) fn glyph(role: IconRole) -> Option<&'static str> { + let glyph = match role { + IconRole::Check => "\u{E73E}", // CheckMark + IconRole::Close => "\u{E8BB}", // ChromeClose + IconRole::ChevronDown => "\u{E70D}", // ChevronDown + IconRole::ChevronLeft => "\u{E76B}", // ChevronLeft + IconRole::ChevronRight => "\u{E76C}", // ChevronRight + IconRole::ChevronUp => "\u{E70E}", // ChevronUp + IconRole::Plus => "\u{E710}", // Add + IconRole::Minus => "\u{E738}", // Remove + IconRole::Search => "\u{E721}", // Search + IconRole::Folder => "\u{E8B7}", // Folder + IconRole::Warning => "\u{E7BA}", // Warning + IconRole::Info => "\u{E946}", // Info + IconRole::Copy => "\u{E8C8}", // Copy + IconRole::Eye => "\u{E7B3}", // RedEye + IconRole::EyeOff => "\u{ED1A}", // Hide + IconRole::PanelLeft => "\u{E90C}", // DockLeft + IconRole::PanelRight => "\u{E90D}", // DockRight + IconRole::WindowMinimize => "\u{E921}", // ChromeMinimize + IconRole::WindowMaximize => "\u{E922}", // ChromeMaximize + IconRole::WindowRestore => "\u{E923}", // ChromeRestore + IconRole::Microphone => "\u{E720}", // Microphone + IconRole::Stop => "\u{E71A}", // Stop + IconRole::Settings => "\u{E713}", // Settings + IconRole::Refresh => "\u{E72C}", // Refresh + IconRole::Undo => "\u{E7A7}", // Undo + IconRole::Redo => "\u{E7A6}", // Redo + IconRole::ZoomIn => "\u{E8A3}", // ZoomIn + IconRole::ZoomOut => "\u{E71F}", // ZoomOut + IconRole::Trash => "\u{E74D}", // Delete + IconRole::Edit => "\u{E70F}", // Edit + IconRole::Save => "\u{E74E}", // Save + IconRole::Download => "\u{E896}", // Download + IconRole::Share => "\u{E72D}", // Share + IconRole::Send => "\u{E724}", // Send + IconRole::Print => "\u{E749}", // Print + IconRole::EnterFullScreen => "\u{E740}", // FullScreen + IconRole::ExitFullScreen => "\u{E73F}", // BackToWindow + IconRole::Cut => "\u{E8C6}", // Cut + IconRole::Paste => "\u{E77F}", // Paste + IconRole::Sort => "\u{E8CB}", // Sort + IconRole::Home => "\u{E80F}", // Home + IconRole::Menu => "\u{E700}", // GlobalNavButton + IconRole::More => "\u{E712}", // More + IconRole::Grid => "\u{ECA5}", // Tiles + IconRole::List => "\u{EA37}", // List + IconRole::File => "\u{E8A5}", // Document + IconRole::Image => "\u{E8B9}", // Picture + IconRole::Calendar => "\u{E787}", // Calendar + IconRole::Clock => "\u{E917}", // Clock + IconRole::User => "\u{E77B}", // Contact + IconRole::Lock => "\u{E72E}", // Lock + IconRole::Unlock => "\u{E785}", // Unlock + IconRole::Star => "\u{E734}", // FavoriteStar + IconRole::Heart => "\u{EB51}", // Heart + IconRole::Pin => "\u{E718}", // Pin + IconRole::Mail => "\u{E715}", // Mail + IconRole::Link => "\u{E71B}", // Link + IconRole::Play => "\u{E768}", // Play + IconRole::Pause => "\u{E769}", // Pause + IconRole::Help => "\u{E897}", // Help + IconRole::Volume => "\u{E767}", // Volume + IconRole::VolumeMuted => "\u{E74F}", // Mute + IconRole::AlignLeft => "\u{E8E4}", // AlignLeft + IconRole::AlignCenter => "\u{E8E3}", // AlignCenter + IconRole::AlignRight => "\u{E8E2}", // AlignRight + IconRole::Sun => "\u{E706}", // Brightness + IconRole::Moon => "\u{E708}", // QuietHours + // No Segoe spinner glyph, the icon falls back to the bundled SVG. + IconRole::Loader => return None, + // App glyphs have no system equivalent, they always draw the bundled SVG. + IconRole::CirclePlus + | IconRole::Filter + | IconRole::GlobalOn + | IconRole::GlobalOff + | IconRole::GitFile + | IconRole::GitCommit + | IconRole::GitIssueDone + | IconRole::GitIssueOpen + | IconRole::GitIssueClosed + | IconRole::GitIssueOngoing + | IconRole::GitPullRequest + | IconRole::GitPullRequestClosed + | IconRole::GitPullRequestDraft + | IconRole::GitPullRequestMerged + | IconRole::GitClone + | IconRole::GitBranch + | IconRole::Tag + | IconRole::Markdown + | IconRole::Trending + | IconRole::Recent + | IconRole::Init + | IconRole::EllipsisVertical + | IconRole::ArrowUp + | IconRole::Globe + | IconRole::Inbox => return None, + }; + Some(glyph) +} + +/// The system font the codepoints resolve against (Windows 11+). +pub(crate) const FONT_FAMILY: &str = "Segoe Fluent Icons"; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_role_maps_a_codepoint_or_falls_back_to_the_bundled_svg() { + for role in crate::icons::IconRole::all() { + assert!( + glyph(*role).is_some() || crate::icons::asset_bytes(role.asset_path()).is_some(), + "no Segoe codepoint or bundled asset for {role:?}" + ); + } + } +} diff --git a/crates/ui/src/layout/mod.rs b/crates/ui/src/layout/mod.rs new file mode 100644 index 0000000..5e2c377 --- /dev/null +++ b/crates/ui/src/layout/mod.rs @@ -0,0 +1,10 @@ +//! Application window layout: a titlebar over a panel row. + +pub mod panel; +pub mod resizable; +pub mod resize_handle; +pub mod shell; +pub mod titlebar; +pub mod window_controls; + +mod window_frame; diff --git a/crates/ui/src/layout/panel.rs b/crates/ui/src/layout/panel.rs new file mode 100644 index 0000000..9120738 --- /dev/null +++ b/crates/ui/src/layout/panel.rs @@ -0,0 +1,173 @@ +//! The panel row: the window's main content, island-style over the app +//! background. It can split once into two half-width panels with a drag +//! divider between them; dragging the seam resizes the panels and a +//! double-click restores the half split. + +use std::sync::Arc; + +use crate::theme::ActiveTheme as _; +use crate::utils::StyledExt as _; +use gpui::{ + AnyElement, AnyView, App, Axis, Div, ElementId, Entity, IntoElement, ParentElement as _, + Render, RenderOnce, SharedString, StyleRefinement, Styled as _, Window, div, +}; + +use crate::layout::resizable::{Resizable, ResizableState}; + +/// A user-defined panel the row can show. +#[allow(unused_variables)] +pub trait Panel: Render + 'static { + /// The kind the panel belongs to; same-kind panels group in the tab bar. + fn kind(&self, cx: &App) -> Option { + None + } +} + +/// An object-safe handle to a panel, so apps can hold panels by kind. +#[allow(unused_variables)] +pub trait PanelView: 'static { + /// The panel's view. + fn view(&self) -> AnyView; + + /// The panel's kind, read live from the panel. + fn kind(&self, cx: &App) -> Option { + None + } +} + +impl PanelView for Entity { + fn view(&self) -> AnyView { + self.clone().into() + } + + fn kind(&self, cx: &App) -> Option { + self.read(cx).kind(cx) + } +} + +impl PanelView for Arc

{ + fn view(&self) -> AnyView { + (**self).view() + } + + fn kind(&self, cx: &App) -> Option { + (**self).kind(cx) + } +} + +/// The layout the cached panel content lays out with. +fn content_style() -> StyleRefinement { + StyleRefinement::default().size_full() +} + +/// The island chrome every panel paints. +fn island(panel: Div, cx: &App) -> Div { + let theme = cx.theme(); + let colors = theme.colors; + + panel + .size_full() + .bg(colors.background) + .border_1() + .border_color(colors.border) + .rounded(theme.radius.overlay) + .overflow_hidden() +} + +/// The panel row drawn under the titlebar. +#[derive(IntoElement)] +#[must_use] +pub struct PanelRow { + id: ElementId, + main: Option, + split: Option, + style: StyleRefinement, +} + +impl PanelRow { + /// Creates the panel row. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + main: None, + split: None, + style: StyleRefinement::default(), + } + } + + /// Sets the main panel's content. + pub fn main

(mut self, main: P) -> Self + where + P: PanelView, + { + self.main = Some(main.view().cached(content_style()).into_any_element()); + self + } + + /// Splits the row into two half-width panels. + pub fn split

(mut self, panel: P) -> Self + where + P: PanelView, + { + self.split = Some(panel.view().cached(content_style()).into_any_element()); + self + } +} + +impl gpui::Styled for PanelRow { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for PanelRow { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let id = self.id.clone(); + let gutter = cx.theme().spacing.unit * 2.0; + + let main = island( + div() + .size_full() + .child(self.main.unwrap_or_else(|| div().into_any_element())), + cx, + ); + + let row = match self.split { + Some(split) => { + let sizes = window.with_element_namespace(id.clone(), |window| { + window + .use_keyed_state("panel-sizes", cx, |_, _| ResizableState::default()) + .clone() + }); + let extent = window.viewport_size().width - gutter * 2.0; + + if sizes.read(cx).sizes().is_empty() { + sizes.update(cx, |state, cx| { + state.set_pane_width(0, (extent - gutter) / 2.0, cx) + }); + } + + div().w_full().h_full().child( + Resizable::new((id.clone(), "split"), sizes) + .axis(Axis::Horizontal) + .pane(main) + .pane(island(div().size_full().child(split), cx)) + .h_full(), + ) + } + None => div().w_full().h_full().child(main), + }; + + div() + .flex_1() + .min_w_0() + .h_full() + .p_2() + .pt_1() + .refine_style(&self.style) + .child(row) + } +} diff --git a/crates/ui/src/layout/resizable.rs b/crates/ui/src/layout/resizable.rs new file mode 100644 index 0000000..113bd41 --- /dev/null +++ b/crates/ui/src/layout/resizable.rs @@ -0,0 +1,312 @@ +//! The resizable group: stacked panes with drag dividers, outside the dock. + +use crate::theme::{PANE_DEFAULT_SIZE, PANE_MIN_SIZE}; +use crate::utils::StyledExt as _; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + AnyElement, App, AppContext as _, Axis, Bounds, Context, ElementId, Entity, + InteractiveElement as _, IntoElement, ParentElement as _, Pixels, RenderOnce, SharedString, + StyleRefinement, Styled, Window, canvas, div, px, +}; + +use crate::layout::resize_handle::ResizeHandle; + +type DebugSelector = std::rc::Rc String>; + +/// The retained pane sizes of one resizable group. +#[derive(Default)] +pub struct ResizableState { + /// Sizes of every pane except the remainder pane, which fills what's left. + sizes: Vec, + /// The group's main-axis extent, captured at paint for drag clamping. + measured: Option, +} + +impl ResizableState { + /// Creates state whose panes start at the default size. + pub fn new(cx: &mut App) -> Entity { + cx.new(|_| Self::default()) + } + + /// The stored size of each fixed pane; the remainder pane isn't listed. + pub fn sizes(&self) -> &[Pixels] { + &self.sizes + } + + /// Restores pane sizes, e.g. from a persisted layout. + pub fn set_sizes(&mut self, sizes: I, cx: &mut Context) + where + I: IntoIterator, + { + self.sizes = sizes.into_iter().collect(); + cx.notify(); + } + + /// Records the group's measured extent, notifying only when it changes. + fn set_measured(&mut self, extent: Pixels, cx: &mut Context) { + if self.measured != Some(extent) { + self.measured = Some(extent); + cx.notify(); + } + } + + /// The equal split of the measured extent, or the default pane size unmeasured. + fn equal_split(&self, pane_count: usize) -> Pixels { + match self.measured { + // usize can exceed f32's exact integer range; bound it via u32 before casting. + Some(extent) => extent / u32::try_from(pane_count).unwrap_or(u32::MAX) as f32, + None => PANE_DEFAULT_SIZE, + } + } + + /// The size pane `ix` renders at: its stored size, or the equal split. + fn pane_size(&self, ix: usize, pane_count: usize) -> Pixels { + self.sizes + .get(ix) + .copied() + .unwrap_or_else(|| self.equal_split(pane_count)) + } + + /// Applies a drag at divider `ix` (between pane ix and ix+1). + fn resize(&mut self, ix: usize, delta: Pixels, mins: &[Pixels], cx: &mut Context) { + let Some(&floor) = mins.get(ix) else { + return; + }; + + let pane_count = mins.len(); + + let previous = self.pane_size(ix, pane_count); + let mut size = previous + delta; + size = size.max(floor); + + if let Some(extent) = self.measured { + let floors = mins + .iter() + .enumerate() + .filter(|(j, _)| *j != ix) + .fold(px(0.), |sum, (_, min)| sum + *min); + let ceiling = extent - floors; + size = size.min(ceiling); + } + + // Earlier panes hold the equal split they already render at, + // so the first drag does not snap them to a backfilled default. + let backfill = self.equal_split(pane_count); + while self.sizes.len() <= ix { + self.sizes.push(backfill); + } + + self.sizes[ix] = size; + + // A drag clamped at its floor or ceiling lands here on every mouse move, + // only a change to the rendered size is worth a frame. + if size != previous { + cx.notify(); + } + } + + /// Sets pane `ix`'s width, backfilling earlier panes. + pub fn set_pane_width(&mut self, ix: usize, width: Pixels, cx: &mut Context) { + while self.sizes.len() <= ix { + self.sizes.push(width); + } + if self.sizes[ix] != width { + self.sizes[ix] = width; + cx.notify(); + } + } + + /// Restores pane `ix` to the equal split, as a double-click does. + fn reset_pane(&mut self, ix: usize, pane_count: usize, cx: &mut Context) { + let split = self.equal_split(pane_count); + while self.sizes.len() <= ix { + self.sizes.push(split); + } + self.sizes[ix] = split; + cx.notify(); + } +} + +/// One pane of a resizable group: its content and its drag floor. +#[must_use] +pub struct ResizablePane { + content: AnyElement, + min: Pixels, +} + +impl ResizablePane { + /// The floor a pane keeps while dragging unless the caller lowers it. + pub const DEFAULT_MIN: Pixels = PANE_MIN_SIZE; + + /// Wraps this element as a pane. + pub fn new(content: E) -> Self + where + E: IntoElement, + { + Self { + content: content.into_any_element(), + min: Self::DEFAULT_MIN, + } + } + + /// Sets the floor this pane keeps while dragging. + pub fn min(mut self, min: Pixels) -> Self { + self.min = min; + self + } +} + +/// A group of panes stacked along one axis, separated by drag dividers. +#[derive(IntoElement)] +#[must_use] +pub struct Resizable { + id: ElementId, + state: Entity, + axis: Axis, + panes: Vec, + debug_selector: Option, + style: StyleRefinement, +} + +impl Resizable { + /// Creates a group stacking its panes vertically, bound to `state`. + pub fn new(id: I, state: Entity) -> Self + where + I: Into, + { + Self { + id: id.into(), + state, + axis: Axis::Vertical, + panes: Vec::new(), + debug_selector: None, + style: StyleRefinement::default(), + } + } + + /// Sets the axis the panes stack along. + pub fn axis(mut self, axis: Axis) -> Self { + self.axis = axis; + self + } + + /// Adds a pane with the default drag floor. + pub fn pane(mut self, content: E) -> Self + where + E: IntoElement, + { + self.panes.push(ResizablePane::new(content)); + self + } + + /// Adds a pane that can't be dragged below `min`. + pub fn pane_with_min(mut self, content: E, min: Pixels) -> Self + where + E: IntoElement, + { + self.panes.push(ResizablePane::new(content).min(min)); + self + } + + /// Sets the debug-bounds selector of each pane, suffixed with its index. + pub fn debug_selector(mut self, selector: F) -> Self + where + F: Fn() -> String + 'static, + { + self.debug_selector = Some(std::rc::Rc::new(selector)); + self + } +} + +impl Styled for Resizable { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Resizable { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let axis = self.axis; + let state = self.state.clone(); + + let pane_count = self.panes.len(); + let mins: Vec = self.panes.iter().map(|pane| pane.min).collect(); + let debug_selector = self.debug_selector; + + let sizes: Vec = (0..pane_count) + .map(|ix| state.read(cx).pane_size(ix, pane_count)) + .collect(); + + div() + .flex() + .overflow_hidden() + .when(axis == Axis::Vertical, |group| group.flex_col()) + .when(axis == Axis::Horizontal, |group| group.flex_row()) + .refine_style(&self.style) + .children(self.panes.into_iter().enumerate().flat_map(|(ix, pane)| { + let remainder = ix + 1 == pane_count; + let pane_element = div() + .overflow_hidden() + .when(remainder, |pane_element| { + pane_element + .flex_1() + .when(axis == Axis::Vertical, |p| p.min_h(pane.min)) + .when(axis == Axis::Horizontal, |p| p.min_w(pane.min)) + }) + .when(!remainder, |pane_element| { + pane_element + .flex_none() + .when(axis == Axis::Vertical, |p| p.h(sizes[ix]).w_full()) + .when(axis == Axis::Horizontal, |p| p.w(sizes[ix]).h_full()) + }) + .when_some(debug_selector.clone(), |pane_element, selector| { + let prefix = selector(); + pane_element.debug_selector(move || format!("{prefix}-{ix}")) + }) + .child(pane.content) + .into_any_element(); + + let divider = (!remainder).then(|| { + // The positional index is a stable id: panes are append-only, never reordered. + ResizeHandle::new(SharedString::from(format!("{}-divider-{ix}", self.id))) + .axis(axis) + .on_resize({ + let state = state.clone(); + let mins = mins.clone(); + move |delta, _, cx| { + state.update(cx, |state, cx| state.resize(ix, delta, &mins, cx)); + } + }) + .on_reset({ + let state = state.clone(); + let mins = mins.clone(); + move |_, cx| { + state.update(cx, |state, cx| state.reset_pane(ix, mins.len(), cx)); + } + }) + .into_any_element() + }); + + std::iter::once(pane_element).chain(divider) + })) + .when(pane_count > 0, |group| { + group.child( + canvas( + { + let state = state.clone(); + move |bounds: Bounds, _, cx: &mut App| { + let extent = match axis { + Axis::Vertical => bounds.size.height, + Axis::Horizontal => bounds.size.width, + }; + state.update(cx, |state, cx| state.set_measured(extent, cx)); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .inset_0(), + ) + }) + } +} diff --git a/crates/ui/src/layout/resize_handle.rs b/crates/ui/src/layout/resize_handle.rs new file mode 100644 index 0000000..17a3f86 --- /dev/null +++ b/crates/ui/src/layout/resize_handle.rs @@ -0,0 +1,319 @@ +//! The drag divider: a thin handle in the gap between panels that resizes +//! them. It shows its hairline only while hovered or dragged. + +use std::rc::Rc; + +use crate::theme::{ + ActiveTheme as _, BORDER_WIDTH, DISABLED_OPACITY, HAIRLINE_WIDTH, RESIZE_KEYBOARD_STEP, +}; +use crate::utils::{StyledExt as _, focus_handle, focus_ring}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, Axis, Bounds, CursorStyle, DispatchPhase, ElementId, HitboxBehavior, + InteractiveElement as _, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent, + MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Point, RenderOnce, Role, + SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _, Window, canvas, + deferred, div, fill, point, px, +}; + +/// How far one keyboard arrow step moves the seam. +const KEYBOARD_STEP: Pixels = RESIZE_KEYBOARD_STEP; + +type ResizeHandler = Rc; +type ResetHandler = Rc; + +/// The pointer drag state, keyed to the handle's element id. +#[derive(Clone, Copy)] +struct DragState { + dragging: bool, + last: Point, +} + +/// A thin drag divider that resizes the adjacent region. +#[derive(IntoElement)] +#[must_use] +pub struct ResizeHandle { + id: ElementId, + /// The axis the drag moves along: a vertical seam drags horizontally. + axis: Axis, + disabled: bool, + accessibility_label: Option, + on_resize: Option, + on_reset: Option, + style: StyleRefinement, +} + +impl ResizeHandle { + /// Creates a horizontal resize handle (a vertical seam). + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + axis: Axis::Horizontal, + disabled: false, + accessibility_label: None, + on_resize: None, + on_reset: None, + style: StyleRefinement::default(), + } + } + + /// Sets the axis the drag moves along. + pub fn axis(mut self, axis: Axis) -> Self { + self.axis = axis; + self + } + + /// Renders the handle inert and dimmed. + pub fn disabled(mut self, disabled: bool) -> Self { + self.disabled = disabled; + self + } + + /// Overrides the accessibility label, which defaults to "Resize". + pub fn accessibility_label(mut self, label: L) -> Self + where + L: Into, + { + self.accessibility_label = Some(label.into()); + self + } + + /// Runs for every pointer movement while the seam is dragged. + pub fn on_resize(mut self, handler: F) -> Self + where + F: Fn(Pixels, &mut Window, &mut App) + 'static, + { + self.on_resize = Some(Rc::new(handler)); + self + } + + /// Runs when the seam is double-clicked, to restore the default size. + pub fn on_reset(mut self, handler: F) -> Self + where + F: Fn(&mut Window, &mut App) + 'static, + { + self.on_reset = Some(Rc::new(handler)); + self + } +} + +impl gpui::Styled for ResizeHandle { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for ResizeHandle { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let ring = theme.colors.ring; + let thickness = theme.spacing.unit * 2.0; + + let label = self + .accessibility_label + .clone() + .unwrap_or_else(|| SharedString::from("Resize")); + + let drag = window.with_element_namespace(self.id.clone(), |window| { + window + .use_keyed_state("resize-drag", cx, |_, _| DragState { + dragging: false, + last: point(px(0.), px(0.)), + }) + .clone() + }); + + let focus = focus_handle(&self.id, window, cx); + let dragging = drag.read(cx).dragging; + let axis = self.axis; + let disabled = self.disabled; + + let cursor = match axis { + Axis::Horizontal => CursorStyle::ResizeLeftRight, + Axis::Vertical => CursorStyle::ResizeUpDown, + }; + + let on_reset = self.on_reset; + + deferred( + div() + .id(self.id.clone()) + .debug_selector(|| "resize-handle".to_string()) + .role(Role::Splitter) + .aria_label(label) + .flex_none() + .when(axis == Axis::Horizontal, |handle| { + handle.w(thickness).h_full() + }) + .when(axis == Axis::Vertical, |handle| { + handle.w_full().h(thickness) + }) + .refine_style(&self.style) + .when(self.disabled, |handle| handle.opacity(DISABLED_OPACITY)) + .when(!self.disabled, |handle| { + handle + .track_focus(&focus) + .focusable() + .tab_stop(true) + .focus_visible(|style| style.shadow(focus_ring(ring))) + .on_mouse_down_out({ + let focus = focus.clone(); + move |_, window, cx| { + if focus.is_focused(window) { + window.blur(cx); + } + } + }) + .on_mouse_down(MouseButton::Left, { + let drag = drag.clone(); + let focus = focus.clone(); + + move |event: &MouseDownEvent, window, cx| { + window.focus(&focus, cx); + cx.stop_propagation(); + + if event.click_count >= 2 { + drag.update(cx, |drag, cx| { + drag.dragging = false; + cx.notify(); + }); + if let Some(on_reset) = on_reset.clone() { + on_reset(window, cx); + } + return; + } + + drag.update(cx, |drag, cx| { + drag.dragging = true; + drag.last = event.position; + cx.notify(); + }); + } + }) + .on_key_down({ + let on_resize = self.on_resize.clone(); + move |event: &KeyDownEvent, window, cx| { + let delta = match (axis, event.keystroke.key.as_str()) { + (Axis::Horizontal, "left") => Some(-KEYBOARD_STEP), + (Axis::Horizontal, "right") => Some(KEYBOARD_STEP), + (Axis::Vertical, "up") => Some(-KEYBOARD_STEP), + (Axis::Vertical, "down") => Some(KEYBOARD_STEP), + _ => None, + }; + if let Some(delta) = delta { + cx.stop_propagation(); + if let Some(on_resize) = on_resize.clone() { + on_resize(delta, window, cx); + } + } + } + }) + }) + .child( + canvas( + { + move |bounds, window, _| { + let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal); + (hitbox, bounds) + } + }, + { + let drag = drag.clone(); + let on_resize = self.on_resize.clone(); + move |_, (hitbox, bounds), window, _cx| { + let hovered = hitbox.is_hovered(window); + + if !disabled { + window.set_cursor_style(cursor, &hitbox); + } + + if disabled || !(dragging || hovered) { + return; + } + + let line = match axis { + Axis::Horizontal => { + let x = bounds.center().x - HAIRLINE_WIDTH; + Bounds::from_corners( + point(x, bounds.top()), + point(x + BORDER_WIDTH, bounds.bottom()), + ) + } + Axis::Vertical => { + let y = bounds.center().y - HAIRLINE_WIDTH; + Bounds::from_corners( + point(bounds.left(), y), + point(bounds.right(), y + BORDER_WIDTH), + ) + } + }; + + window.paint_quad(fill(line, ring)); + + window.on_mouse_event({ + let drag = drag.clone(); + let on_resize = on_resize.clone(); + move |event: &MouseMoveEvent, phase, window, cx| { + if phase != DispatchPhase::Bubble { + return; + } + + let (dragging, last) = { + let drag = drag.read(cx); + (drag.dragging, drag.last) + }; + + if !dragging { + return; + } + + if event.pressed_button != Some(MouseButton::Left) { + drag.update(cx, |drag, cx| { + drag.dragging = false; + cx.notify(); + }); + return; + } + + let delta = match axis { + Axis::Horizontal => event.position.x - last.x, + Axis::Vertical => event.position.y - last.y, + }; + + drag.update(cx, |drag, _| drag.last = event.position); + + if let Some(on_resize) = on_resize.clone() { + on_resize(delta, window, cx); + } + } + }); + + window.on_mouse_event({ + let drag = drag.clone(); + move |event: &MouseUpEvent, phase, _, cx| { + if phase != DispatchPhase::Bubble + || event.button != MouseButton::Left + { + return; + } + + if drag.read(cx).dragging { + drag.update(cx, |drag, cx| { + drag.dragging = false; + cx.notify(); + }); + } + } + }); + } + }, + ) + .absolute() + .inset_0(), + ), + ) + } +} diff --git a/crates/ui/src/layout/shell.rs b/crates/ui/src/layout/shell.rs new file mode 100644 index 0000000..c142dd3 --- /dev/null +++ b/crates/ui/src/layout/shell.rs @@ -0,0 +1,134 @@ +//! The application shell: the titlebar above the panel row, wrapped in the +//! client-side window frame, with the toast and alert overlays mounted at +//! the window root. + +use crate::components::alert::{Alerts, AlertsView}; +use crate::components::grain::grain as grain_overlay; +use crate::components::toast::{Toasts, ToastsView}; +use crate::theme::ActiveTheme as _; +use crate::utils::{StyledExt as _, v_flex}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + AnyElement, App, ElementId, Entity, IntoElement, ParentElement as _, RenderOnce, + StyleRefinement, Styled as _, Window, div, +}; + +use crate::layout::titlebar::Titlebar; +use crate::layout::window_frame::frame; + +/// The application shell. +#[derive(IntoElement)] +#[must_use] +pub struct Shell { + id: ElementId, + titlebar: Option, + panel: Option, + transparent: bool, + grain: bool, + toasts: Option>, + alerts: Option>, + style: StyleRefinement, +} + +impl Shell { + /// Creates the shell. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + titlebar: None, + panel: None, + transparent: false, + grain: false, + toasts: None, + alerts: None, + style: StyleRefinement::default(), + } + } + + /// Sets the titlebar drawn above the panel row. + pub fn titlebar(mut self, titlebar: Titlebar) -> Self { + self.titlebar = Some(titlebar); + self + } + + /// Sets the panel row filling the rest of the window. + pub fn panel(mut self, panel: E) -> Self + where + E: IntoElement, + { + self.panel = Some(panel.into_any_element()); + self + } + + /// Paints the app background with the translucent material fill. + pub fn transparent(mut self, transparent: bool) -> Self { + self.transparent = transparent; + self + } + + /// Textures the app background with a film-grain overlay. + pub fn grain(mut self, grain: bool) -> Self { + self.grain = grain; + self + } + + /// Hosts the toast overlay raised on `toasts`. + pub fn toasts(mut self, toasts: Entity) -> Self { + self.toasts = Some(toasts); + self + } + + /// Hosts the alert overlay stacked on `alerts`. + pub fn alerts(mut self, alerts: Entity) -> Self { + self.alerts = Some(alerts); + self + } +} + +impl gpui::Styled for Shell { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for Shell { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let id = self.id.clone(); + let theme = cx.theme(); + + let background = if self.transparent { + theme.material.background + } else { + theme.colors.muted + }; + + let layout = v_flex() + .w_full() + .h_full() + .overflow_hidden() + .bg(background) + .refine_style(&self.style) + .when(self.transparent && self.grain, |layout| { + layout.child(grain_overlay()) + }); + + let layout = layout + .when_some(self.titlebar, |layout, titlebar| { + layout.child(titlebar.transparent(self.transparent)) + }) + .child(self.panel.unwrap_or_else(|| div().into_any_element())); + + let frame = frame(layout, window, cx); + + frame + .when_some(self.toasts, |frame, toasts| { + frame.child(ToastsView::new((id.clone(), "toasts"), toasts)) + }) + .when_some(self.alerts, |frame, alerts| { + frame.child(AlertsView::new((id, "alerts"), alerts)) + }) + } +} diff --git a/crates/ui/src/layout/titlebar.rs b/crates/ui/src/layout/titlebar.rs new file mode 100644 index 0000000..6e55ef8 --- /dev/null +++ b/crates/ui/src/layout/titlebar.rs @@ -0,0 +1,142 @@ +//! The window titlebar: the full-width strip drawn above the panel row — +//! the prefix, tab bar, and suffix in the middle, the platform's window +//! controls at macOS's leading edge and every other platform's trailing +//! edge. The bar itself moves the window, tab bar included; the prefix and +//! suffix opt out, so a press on a control never starts a drag. + +use crate::theme::{ActiveTheme as _, Size, TRAFFIC_LIGHT_PAD}; +use crate::utils::{StyledExt as _, h_flex}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce, + SharedString, StyleRefinement, Styled as _, Window, +}; + +use crate::layout::window_controls::{WindowControls, titlebar_strip}; + +/// The window's titlebar. +#[derive(IntoElement)] +#[must_use] +pub struct Titlebar { + id: ElementId, + prefix: Vec, + tab_bar: Option, + suffix: Vec, + transparent: bool, + style: StyleRefinement, +} + +impl Titlebar { + /// Creates the titlebar. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { + id: id.into(), + prefix: Vec::new(), + tab_bar: None, + suffix: Vec::new(), + transparent: false, + style: StyleRefinement::default(), + } + } + + /// Sets the tab bar drawn between the prefix and the suffix. + pub fn tab_bar(mut self, tab_bar: E) -> Self + where + E: IntoElement, + { + self.tab_bar = Some(tab_bar.into_any_element()); + self + } + + /// Sets the element drawn after the tab bar, before the trailing window controls. + pub fn suffix(mut self, suffix: E) -> Self + where + E: IntoElement, + { + self.suffix = vec![suffix.into_any_element()]; + self + } + + /// Leaves the strip unpainted so the shell's material backdrop shows through. + pub(crate) fn transparent(mut self, transparent: bool) -> Self { + self.transparent = transparent; + self + } +} + +impl gpui::Styled for Titlebar { + fn style(&mut self) -> &mut StyleRefinement { + &mut self.style + } +} + +impl ParentElement for Titlebar { + fn extend(&mut self, elements: impl IntoIterator) { + self.prefix.extend(elements); + } +} + +impl RenderOnce for Titlebar { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + let height = theme.titlebar_height; + let padding_x = theme.sizes.resolve(Size::default()).dense_padding_x; + + let id = self.id; + let bar_id = SharedString::from(format!("{id}-bar")); + + titlebar_strip( + h_flex() + .id(id.clone()) + .debug_selector(move || bar_id.to_string()) + .flex_none() + .w_full() + .h(height) + .gap_2() + .when(!self.transparent, |bar| bar.bg(theme.colors.muted)) + .px(padding_x) + .refine_style(&self.style) + .when(cfg!(target_os = "macos"), |bar| bar.pl(TRAFFIC_LIGHT_PAD)) + .when(!self.prefix.is_empty(), |bar| { + bar.child( + h_flex() + .occlude() + .flex_none() + .h_full() + .items_center() + .gap_1() + .children(self.prefix), + ) + }) + .when_some(self.tab_bar, |bar, tab_bar| { + bar.child( + h_flex() + .flex_1() + .min_w_0() + .h_full() + .overflow_hidden() + .when(cfg!(target_os = "windows"), |slot| slot.occlude()) + .child(tab_bar), + ) + }) + .when(!self.suffix.is_empty(), |bar| { + bar.child( + h_flex() + .occlude() + .flex_none() + .h_full() + .items_center() + .gap_1() + .children(self.suffix), + ) + }), + (id.clone(), "drag"), + window, + cx, + ) + .child(WindowControls::new((id, "window-controls"))) + } +} diff --git a/crates/ui/src/layout/window_controls.rs b/crates/ui/src/layout/window_controls.rs new file mode 100644 index 0000000..97303a4 --- /dev/null +++ b/crates/ui/src/layout/window_controls.rs @@ -0,0 +1,316 @@ +//! The window controls: minimize, maximize/restore, close — in the platform's +//! own dress and behavior. Titlebar strips are app-owned: they move the +//! window themselves via [`titlebar_strip`], so a dragged tab or button press +//! never moves it; macOS draws its traffic lights in the shell's reserved pad +//! and needs no controls of ours. + +use gpui::WindowControlArea; +use gpui::{App, ClickEvent, Div, ElementId, IntoElement, RenderOnce, Stateful, Window, div}; +use gpui::{InteractiveElement as _, MouseButton, StatefulInteractiveElement as _}; + +#[cfg(any(target_os = "windows", target_os = "linux"))] +use crate::icons::{IconRole, icon}; +#[cfg(any(target_os = "windows", target_os = "linux"))] +use crate::theme::ActiveTheme as _; +#[cfg(any(target_os = "windows", target_os = "linux"))] +use gpui::Styled as _; +#[cfg(any(target_os = "windows", target_os = "linux"))] +use gpui::prelude::FluentBuilder as _; +#[cfg(any(target_os = "windows", target_os = "linux"))] +use gpui::{AnyElement, ParentElement as _}; + +/// macOS traffic-lights zone: the pad a leading titlebar strip reserves. +pub use crate::theme::TRAFFIC_LIGHT_PAD; +#[cfg(target_os = "windows")] +use crate::theme::{ + WINDOWS_CAPTION_WIDTH as CAPTION_WIDTH, WINDOWS_CLOSE_FOREGROUND, WINDOWS_CLOSE_HOVER, + WINDOWS_CLOSE_PRESSED, +}; +#[cfg(target_os = "linux")] +use gpui::Decorations; +#[cfg(any(target_os = "windows", target_os = "linux"))] +use gpui::SharedString; + +/// The window controls for the trailing end of a titlebar strip. +#[derive(IntoElement)] +pub struct WindowControls { + id: ElementId, +} + +impl WindowControls { + /// Creates the controls row. + pub fn new(id: I) -> Self + where + I: Into, + { + Self { id: id.into() } + } +} + +impl RenderOnce for WindowControls { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let id = self.id.clone(); + + #[cfg(target_os = "macos")] + let controls = { + // macOS draws native traffic lights in the shell's reserved pad; nothing to render. + let _ = (id, window, cx); + div() + }; + + #[cfg(target_os = "windows")] + let controls = { + let controls = window.window_controls(); + div() + .flex_none() + .flex() + .flex_row() + .h_full() + .when(controls.minimize, |row| { + row.child(caption_button( + cx, + SharedString::from(format!("{id}-minimize")), + IconRole::WindowMinimize, + WindowControlArea::Min, + window.is_minimizable(), + false, + )) + }) + .when(controls.maximize, |row| { + row.child(caption_button( + cx, + SharedString::from(format!("{id}-maximize")), + if window.is_maximized() { + IconRole::WindowRestore + } else { + IconRole::WindowMaximize + }, + WindowControlArea::Max, + window.is_resizable(), + false, + )) + }) + .child(caption_button( + cx, + SharedString::from(format!("{id}-close")), + IconRole::Close, + WindowControlArea::Close, + true, + true, + )) + }; + + #[cfg(target_os = "linux")] + let controls = { + let controls = window.window_controls(); + let client_decorated = + matches!(window.window_decorations(), Decorations::Client { .. }); + + div() + .flex_none() + .flex() + .flex_row() + .items_center() + .gap_1() + .when(client_decorated && controls.minimize, |row| { + row.child(circle_button( + cx, + SharedString::from(format!("{id}-minimize")), + IconRole::WindowMinimize, + window.is_minimizable(), + |window, _cx| window.minimize_window(), + )) + }) + .when(client_decorated && controls.maximize, |row| { + row.child(circle_button( + cx, + SharedString::from(format!("{id}-maximize")), + if window.is_maximized() { + IconRole::WindowRestore + } else { + IconRole::WindowMaximize + }, + window.is_resizable(), + |window, _cx| window.zoom_window(), + )) + }) + .when(client_decorated, |row| { + row.child(circle_button( + cx, + SharedString::from(format!("{id}-close")), + IconRole::Close, + true, + |window, _cx| window.remove_window(), + )) + }) + }; + + #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))] + let controls = { + let _ = (id, window, cx); + div() + }; + + controls + } +} + +/// Double-click on a titlebar strip maximizes where the platform does not do it. +fn maximize_on_double_click() -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static { + move |event, window, _cx| { + if event.click_count() != 2 { + return; + } + #[cfg(target_os = "macos")] + window.titlebar_double_click(); + #[cfg(target_os = "linux")] + window.zoom_window(); + // Windows handles titlebar double-click natively via WindowControlArea::Drag. + #[cfg(target_os = "windows")] + { + let _ = (event, window); + } + #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] + { + let _ = (event, window); + } + } +} + +/// Makes an element a titlebar strip; `id` keys its drag state, which +/// `use_state` would otherwise share among every strip in the window. +pub fn titlebar_strip( + this: Stateful

, + id: I, + window: &mut Window, + cx: &mut App, +) -> Stateful
+where + I: Into, +{ + let should_move = window.use_keyed_state(id.into(), cx, |_, _| false); + this.window_control_area(WindowControlArea::Drag) + .on_mouse_down_out(window.listener_for(&should_move, |should_move, _, _, _| { + *should_move = false; + })) + .on_mouse_down( + MouseButton::Left, + window.listener_for(&should_move, |should_move, _, _, _| { + *should_move = true; + }), + ) + .on_mouse_up( + MouseButton::Left, + window.listener_for(&should_move, |should_move, _, _, _| { + *should_move = false; + }), + ) + .on_mouse_move( + window.listener_for(&should_move, |should_move, _, window, cx| { + if *should_move { + *should_move = false; + if !cx.has_active_drag() { + window.start_window_move(); + } + } + }), + ) + .on_click(maximize_on_double_click()) +} + +/// One Windows caption button. +#[cfg(target_os = "windows")] +fn caption_button( + cx: &App, + id: ElementId, + role: IconRole, + area: WindowControlArea, + enabled: bool, + close: bool, +) -> AnyElement { + let theme = cx.theme(); + let glyph_size = theme.sizes.small.dense_icon_size; + + let hover = if close { + WINDOWS_CLOSE_HOVER + } else { + theme.colors.muted_hover + }; + + div() + .id(id) + .debug_selector({ + let id = SharedString::from(format!("window-control-{}", role.slug())); + move || id.to_string() + }) + .occlude() + .flex() + .items_center() + .justify_center() + .w(CAPTION_WIDTH) + .h_full() + .window_control_area(area) + .text_color(if enabled { + theme.colors.foreground + } else { + theme.colors.muted_foreground + }) + .when(enabled, |button| { + button + .cursor_pointer() + .hover(|hovered| { + hovered.bg(hover).text_color(if close { + WINDOWS_CLOSE_FOREGROUND + } else { + theme.colors.foreground + }) + }) + .active(|pressed| { + pressed + .bg(if close { + WINDOWS_CLOSE_PRESSED + } else { + theme.ramps.secondary.pressed + }) + .text_color(theme.colors.foreground) + }) + }) + .child(icon(role).size(glyph_size)) + .into_any_element() +} + +/// Adwaita's headerbar control: a small circle around a symbolic glyph. +#[cfg(target_os = "linux")] +fn circle_button(cx: &App, id: I, role: IconRole, enabled: bool, action: F) -> AnyElement +where + I: Into, + F: Fn(&mut Window, &mut App) + 'static, +{ + let theme = cx.theme(); + let small = theme.sizes.small; + + div() + .id(id) + .debug_selector(move || format!("window-control-{}", role.slug())) + .flex() + .items_center() + .justify_center() + .size(small.control_height) + .rounded(theme.radius.full) + .text_color(if enabled { + theme.colors.foreground + } else { + theme.colors.muted_foreground + }) + .when(enabled, |button| { + button + .cursor_pointer() + .hover(|hovered| hovered.bg(theme.colors.muted_hover)) + .on_click(move |_, window, cx| { + cx.stop_propagation(); + action(window, cx); + }) + }) + .child(icon(role).size(small.dense_icon_size)) + .into_any_element() +} diff --git a/crates/ui/src/layout/window_frame.rs b/crates/ui/src/layout/window_frame.rs new file mode 100644 index 0000000..d21a88f --- /dev/null +++ b/crates/ui/src/layout/window_frame.rs @@ -0,0 +1,175 @@ +//! The client-side window frame: the border, corners, shadow, and resize +//! edges of a window the system does not decorate. + +use crate::theme::{ActiveTheme as _, BORDER_WIDTH, INACTIVE_SHADOW_OPACITY, WINDOW_RESIZE_INSET}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, Bounds, BoxShadow, CursorStyle, Decorations, Div, HitboxBehavior, InteractiveElement as _, + IntoElement, MouseButton, ParentElement as _, Pixels, Point, ResizeEdge, Size, Styled as _, + Tiling, Window, canvas, div, point, px, size, +}; + +/// Wraps a window's root in the frame it owes. +pub fn frame(child: E, window: &mut Window, cx: &App) -> Div +where + E: IntoElement, +{ + let Decorations::Client { tiling } = window.window_decorations() else { + return div().size_full().child(child); + }; + + let tiling = if window.is_maximized() { + Tiling::tiled() + } else { + tiling + }; + + let inset = WINDOW_RESIZE_INSET; + let border = cx.theme().colors.border; + let radius = cx.theme().radius.overlay; + + let shadow = frame_shadow(cx, window.is_window_active()); + window.set_client_inset(inset); + + div() + .size_full() + .child( + canvas( + move |_, window, _| { + let size = window.window_bounds().get_bounds().size; + bands(size, inset) + .into_iter() + .filter(|(edge, _)| live(*edge, tiling)) + .map(|(edge, band)| { + (edge, window.insert_hitbox(band, HitboxBehavior::Normal)) + }) + .collect::>() + }, + |_, bands, window, _| { + for (edge, band) in bands { + window.set_cursor_style(cursor(edge), &band); + } + }, + ) + .absolute() + .size_full(), + ) + .when(!tiling.top, |frame| frame.pt(inset)) + .when(!tiling.bottom, |frame| frame.pb(inset)) + .when(!tiling.left, |frame| frame.pl(inset)) + .when(!tiling.right, |frame| frame.pr(inset)) + .on_mouse_down(MouseButton::Left, move |event, window, _| { + let size = window.window_bounds().get_bounds().size; + if let Some(edge) = + resize_edge(event.position, inset, size).filter(|edge| live(*edge, tiling)) + { + window.start_window_resize(edge); + } + }) + .child( + div() + .size_full() + .overflow_hidden() + .border_color(border) + .when(!tiling.top, |surface| surface.border_t(BORDER_WIDTH)) + .when(!tiling.bottom, |surface| surface.border_b(BORDER_WIDTH)) + .when(!tiling.left, |surface| surface.border_l(BORDER_WIDTH)) + .when(!tiling.right, |surface| surface.border_r(BORDER_WIDTH)) + .when(!(tiling.top || tiling.left), |surface| { + surface.rounded_tl(radius) + }) + .when(!(tiling.top || tiling.right), |surface| { + surface.rounded_tr(radius) + }) + .when(!(tiling.bottom || tiling.left), |surface| { + surface.rounded_bl(radius) + }) + .when(!(tiling.bottom || tiling.right), |surface| { + surface.rounded_br(radius) + }) + .when(!tiling.is_tiled(), |surface| surface.shadow(shadow)) + .child(child), + ) +} + +/// The dialog elevation's shadow, dimmed while the window is inactive. +fn frame_shadow(cx: &App, active: bool) -> Vec { + let opacity = if active { 1.0 } else { INACTIVE_SHADOW_OPACITY }; + cx.theme() + .elevations + .dialog + .shadows() + .iter() + .map(|shadow| { + let mut dimmed = shadow.clone(); + dimmed.color.a *= opacity; + dimmed + }) + .collect() +} + +/// Which edge a press at `pos` resizes, or `None` for a press on the content. +fn resize_edge(pos: Point, inset: Pixels, size: Size) -> Option { + let (top, bottom) = (pos.y < inset, pos.y > size.height - inset); + let (left, right) = (pos.x < inset, pos.x > size.width - inset); + + Some(match (top, bottom, left, right) { + (true, _, true, _) => ResizeEdge::TopLeft, + (true, _, _, true) => ResizeEdge::TopRight, + (_, true, true, _) => ResizeEdge::BottomLeft, + (_, true, _, true) => ResizeEdge::BottomRight, + (true, ..) => ResizeEdge::Top, + (_, true, ..) => ResizeEdge::Bottom, + (_, _, true, _) => ResizeEdge::Left, + (_, _, _, true) => ResizeEdge::Right, + _ => return None, + }) +} + +/// The eight bands, as the rects [`resize_edge`] classifies to. +fn bands(window: Size, inset: Pixels) -> [(ResizeEdge, Bounds); 8] { + let band = |x: Pixels, y: Pixels, width: Pixels, height: Pixels| Bounds { + origin: point(x, y), + size: size(width, height), + }; + + let (far_x, far_y) = (window.width - inset, window.height - inset); + let (span_x, span_y) = (window.width - inset - inset, window.height - inset - inset); + let zero = px(0.0); + + [ + (ResizeEdge::TopLeft, band(zero, zero, inset, inset)), + (ResizeEdge::TopRight, band(far_x, zero, inset, inset)), + (ResizeEdge::BottomLeft, band(zero, far_y, inset, inset)), + (ResizeEdge::BottomRight, band(far_x, far_y, inset, inset)), + (ResizeEdge::Top, band(inset, zero, span_x, inset)), + (ResizeEdge::Bottom, band(inset, far_y, span_x, inset)), + (ResizeEdge::Left, band(zero, inset, inset, span_y)), + (ResizeEdge::Right, band(far_x, inset, inset, span_y)), + ] +} + +/// Whether `edge` resizes: none of the sides it touches is flush. +fn live(edge: ResizeEdge, tiling: Tiling) -> bool { + let (top, bottom, left, right) = match edge { + ResizeEdge::Top => (true, false, false, false), + ResizeEdge::Bottom => (false, true, false, false), + ResizeEdge::Left => (false, false, true, false), + ResizeEdge::Right => (false, false, false, true), + ResizeEdge::TopLeft => (true, false, true, false), + ResizeEdge::TopRight => (true, false, false, true), + ResizeEdge::BottomLeft => (false, true, true, false), + ResizeEdge::BottomRight => (false, true, false, true), + }; + !(top && tiling.top || bottom && tiling.bottom || left && tiling.left || right && tiling.right) +} + +/// The pointer an edge shows. +fn cursor(edge: ResizeEdge) -> CursorStyle { + match edge { + ResizeEdge::Top | ResizeEdge::Bottom => CursorStyle::ResizeUpDown, + ResizeEdge::Left | ResizeEdge::Right => CursorStyle::ResizeLeftRight, + ResizeEdge::TopLeft | ResizeEdge::BottomRight => CursorStyle::ResizeUpLeftDownRight, + ResizeEdge::TopRight | ResizeEdge::BottomLeft => CursorStyle::ResizeUpRightDownLeft, + } +} diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs new file mode 100644 index 0000000..ce4a201 --- /dev/null +++ b/crates/ui/src/lib.rs @@ -0,0 +1,24 @@ +//! Signed's native GPUI layer: theme, icons, components, layout, and editor. + +pub mod components; +pub mod data; +pub mod editor; +pub mod icons; +pub mod layout; +pub mod theme; +pub mod utils; + +pub use components::*; +pub use icons::{Assets, Icon, IconRole}; + +use gpui::App; + +/// Initializes the theme and every key binding the UI layer owns. +pub fn init(cx: &mut App) { + theme::Theme::init(cx); + components::input::bind_input_keys(cx, None); + components::combobox::bind_combobox_keys(cx); + components::command_palette::bind_command_palette_keys(cx); + editor::code::bind_code_view_keys(cx); + editor::markdown::bind_text_view_keys(cx); +} diff --git a/crates/ui/src/theme/colors.rs b/crates/ui/src/theme/colors.rs new file mode 100644 index 0000000..583867e --- /dev/null +++ b/crates/ui/src/theme/colors.rs @@ -0,0 +1,170 @@ +//! Semantic color roles. This module is the only place in the workspace +//! allowed to hold color literals. + +use gpui::{Hsla, hsla, rgb}; + +use crate::theme::{ + DEFAULT_TRANSPARENCY, MIN_MATERIAL_FILL_DARK, MIN_MATERIAL_FILL_LIGHT, ThemeVariant, +}; + +fn hex(hex: u32) -> Hsla { + rgb(hex).into() +} + +/// The dim scrim behind modal layers; always a translucent black. +pub(crate) fn scrim(alpha: f32) -> Hsla { + hsla(0., 0., 0., alpha) +} + +/// The semantic color roles components paint from. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ColorTokens { + pub background: Hsla, + pub foreground: Hsla, + pub surface: Hsla, + pub surface_foreground: Hsla, + /// The docked sidebar's backdrop. + pub sidebar: Hsla, + pub primary: Hsla, + pub primary_foreground: Hsla, + pub secondary: Hsla, + pub secondary_foreground: Hsla, + pub muted: Hsla, + pub muted_hover: Hsla, + pub muted_foreground: Hsla, + pub accent: Hsla, + pub accent_foreground: Hsla, + pub destructive: Hsla, + pub destructive_foreground: Hsla, + pub success: Hsla, + pub success_foreground: Hsla, + pub warning: Hsla, + pub warning_foreground: Hsla, + pub info: Hsla, + pub info_foreground: Hsla, + pub border: Hsla, + pub input: Hsla, + pub ring: Hsla, + pub selection: Hsla, + /// The scrim behind modal layers, translucent in every theme. + pub overlay: Hsla, + /// The overlay scrollbar thumb, translucent over scrolling content. + pub scrollbar_thumb: Hsla, +} + +impl ColorTokens { + /// Neutral light palette; the fallback when no system theme applies. + pub fn light() -> Self { + Self { + background: hex(0xffffff), + foreground: hex(0x18181b), + surface: hex(0xfafafa), + surface_foreground: hex(0x18181b), + sidebar: hex(0xf4f4f5), + primary: hex(0x2563eb), + primary_foreground: hex(0xffffff), + secondary: hex(0xf4f4f5), + secondary_foreground: hex(0x18181b), + muted: hex(0xf4f4f5), + muted_hover: hex(0xe4e4e7), + muted_foreground: hex(0x71717a), + accent: hex(0x2563eb), + accent_foreground: hex(0xffffff), + destructive: hex(0xdc2626), + destructive_foreground: hex(0xffffff), + success: hex(0x16a34a), + success_foreground: hex(0xffffff), + warning: hex(0xd97706), + warning_foreground: hex(0xffffff), + info: hex(0x0284c7), + info_foreground: hex(0xffffff), + border: hex(0xe4e4e7), + input: hex(0xffffff), + ring: hex(0x2563eb), + selection: hex(0xdbeafe), + overlay: scrim(0.25), + // macOS light overlay thumbs are translucent black. + scrollbar_thumb: hsla(0., 0., 0., 0.25), + } + } + + /// Neutral dark palette; the fallback when no system theme applies. + pub fn dark() -> Self { + Self { + background: hex(0x09090b), + foreground: hex(0xfafafa), + surface: hex(0x18181b), + surface_foreground: hex(0xfafafa), + sidebar: hex(0x18181b), + primary: hex(0x3b82f6), + primary_foreground: hex(0xffffff), + secondary: hex(0x27272a), + secondary_foreground: hex(0xfafafa), + muted: hex(0x27272a), + muted_hover: hex(0x3f3f46), + muted_foreground: hex(0xa1a1aa), + accent: hex(0x3b82f6), + accent_foreground: hex(0xffffff), + destructive: hex(0xef4444), + destructive_foreground: hex(0xffffff), + success: hex(0x22c55e), + success_foreground: hex(0x052e16), + warning: hex(0xf59e0b), + warning_foreground: hex(0x451a03), + info: hex(0x38bdf8), + info_foreground: hex(0x082f49), + border: hex(0x27272a), + input: hex(0x09090b), + ring: hex(0x3b82f6), + selection: hex(0x1e3a8a), + overlay: scrim(0.45), + // macOS dark overlay thumbs are translucent light gray. + scrollbar_thumb: hsla(0., 0., 1., 0.3), + } + } +} + +/// The translucent paints surfaces lay over a native window material. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MaterialTokens { + /// The window-sized fill the material shows through. + pub background: Hsla, + /// The hover wash over material surfaces. + pub hover: Hsla, + /// The selected-row fill over material surfaces. + pub selection: Hsla, +} + +impl MaterialTokens { + /// Derives the material paints from the resolved palette. + pub(crate) fn derive( + colors: &ColorTokens, + selection: Hsla, + variant: ThemeVariant, + translucent: bool, + transparency: Option, + ) -> Self { + if !translucent { + return Self { + background: colors.background, + hover: colors.muted, + selection, + }; + } + + let level = transparency.unwrap_or(DEFAULT_TRANSPARENCY) as f32 / 100.0; + + let floor = match variant { + ThemeVariant::Light => MIN_MATERIAL_FILL_LIGHT, + ThemeVariant::Dark => MIN_MATERIAL_FILL_DARK, + }; + + Self { + // The fill eases toward a floor instead of zero. + background: colors.background.alpha(1.0 - level * (1.0 - floor)), + // A foreground wash keeps hover visible over any backdrop hue. + hover: colors.foreground.alpha(0.06), + selection: selection.alpha(0.85), + } + } +} diff --git a/crates/ui/src/theme/definition.rs b/crates/ui/src/theme/definition.rs new file mode 100644 index 0000000..2b1dbeb --- /dev/null +++ b/crates/ui/src/theme/definition.rs @@ -0,0 +1,274 @@ +//! Sparse theme definitions: the shared schema for bundled presets and +//! user theme files. Any field may be omitted; omitted fields fall through +//! to the system theme, then to the neutral presets. + +use gpui::{Hsla, Rgba}; +use serde::Deserialize; + +use crate::theme::ThemeVariant; + +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +pub struct ThemeDefinition { + mode: Option, + control_radius: Option, + overlay_radius: Option, + sm_radius: Option, + accent: Option, + accent_foreground: Option, + background: Option, + foreground: Option, + surface: Option, + surface_foreground: Option, + sidebar: Option, + primary: Option, + primary_foreground: Option, + secondary: Option, + secondary_foreground: Option, + muted: Option, + muted_hover: Option, + muted_foreground: Option, + destructive: Option, + destructive_foreground: Option, + success: Option, + success_foreground: Option, + warning: Option, + warning_foreground: Option, + info: Option, + info_foreground: Option, + border: Option, + input: Option, + ring: Option, + selection: Option, + overlay: Option, + scrollbar_thumb: Option, +} + +impl ThemeDefinition { + pub fn parse_toml(source: &str) -> anyhow::Result { + Ok(toml::from_str(source)?) + } + + pub fn mode(&self) -> Option { + self.mode + } + + pub fn control_radius(&self) -> Option { + self.control_radius + } + + pub fn overlay_radius(&self) -> Option { + self.overlay_radius + } + + pub fn sm_radius(&self) -> Option { + self.sm_radius + } + + pub fn accent(&self) -> Option { + self.color(&self.accent, "accent") + } + + pub fn accent_foreground(&self) -> Option { + self.color(&self.accent_foreground, "accent_foreground") + } + + pub fn background(&self) -> Option { + self.color(&self.background, "background") + } + + pub fn foreground(&self) -> Option { + self.color(&self.foreground, "foreground") + } + + pub fn surface(&self) -> Option { + self.color(&self.surface, "surface") + } + + pub fn surface_foreground(&self) -> Option { + self.color(&self.surface_foreground, "surface_foreground") + } + + pub fn sidebar(&self) -> Option { + self.color(&self.sidebar, "sidebar") + } + + pub fn primary(&self) -> Option { + self.color(&self.primary, "primary") + } + + pub fn primary_foreground(&self) -> Option { + self.color(&self.primary_foreground, "primary_foreground") + } + + pub fn secondary(&self) -> Option { + self.color(&self.secondary, "secondary") + } + + pub fn secondary_foreground(&self) -> Option { + self.color(&self.secondary_foreground, "secondary_foreground") + } + + pub fn muted(&self) -> Option { + self.color(&self.muted, "muted") + } + + pub fn muted_hover(&self) -> Option { + self.color(&self.muted_hover, "muted_hover") + } + + pub fn muted_foreground(&self) -> Option { + self.color(&self.muted_foreground, "muted_foreground") + } + + pub fn destructive(&self) -> Option { + self.color(&self.destructive, "destructive") + } + + pub fn destructive_foreground(&self) -> Option { + self.color(&self.destructive_foreground, "destructive_foreground") + } + + pub fn success(&self) -> Option { + self.color(&self.success, "success") + } + + pub fn success_foreground(&self) -> Option { + self.color(&self.success_foreground, "success_foreground") + } + + pub fn warning(&self) -> Option { + self.color(&self.warning, "warning") + } + + pub fn warning_foreground(&self) -> Option { + self.color(&self.warning_foreground, "warning_foreground") + } + + pub fn info(&self) -> Option { + self.color(&self.info, "info") + } + + pub fn info_foreground(&self) -> Option { + self.color(&self.info_foreground, "info_foreground") + } + + pub fn border(&self) -> Option { + self.color(&self.border, "border") + } + + pub fn input(&self) -> Option { + self.color(&self.input, "input") + } + + pub fn ring(&self) -> Option { + self.color(&self.ring, "ring") + } + + pub fn selection(&self) -> Option { + self.color(&self.selection, "selection") + } + + pub fn overlay(&self) -> Option { + self.color(&self.overlay, "overlay") + } + + pub fn scrollbar_thumb(&self) -> Option { + self.color(&self.scrollbar_thumb, "scrollbar_thumb") + } + + /// Parses a color field, warning when a stated value is malformed. + fn color(&self, field: &Option, role: &str) -> Option { + let value = field.as_deref()?; + match parse_hex(value) { + Some(color) => Some(color), + None => { + log::warn!("theme definition {role} is not #rgb/#rrggbb: {value:?}"); + None + } + } + } +} + +/// Parses `#rgb` or `#rrggbb` into an opaque color. +pub(crate) fn parse_hex(value: &str) -> Option { + let digits = value.strip_prefix('#')?; + let expand = |channels: [f32; 3]| Some(expand_rgb([channels[0], channels[1], channels[2]])); + + match digits.len() { + 3 => { + let mut channels = [0u8; 3]; + for (i, byte) in channels.iter_mut().enumerate() { + *byte = u8::from_str_radix(&digits[i..i + 1], 16).ok()?; + } + expand([ + channels[0] as f32 / 15.0, + channels[1] as f32 / 15.0, + channels[2] as f32 / 15.0, + ]) + } + 6 => { + let mut channels = [0u8; 3]; + for (i, byte) in channels.iter_mut().enumerate() { + *byte = u8::from_str_radix(&digits[i * 2..i * 2 + 2], 16).ok()?; + } + expand([ + channels[0] as f32 / 255.0, + channels[1] as f32 / 255.0, + channels[2] as f32 / 255.0, + ]) + } + _ => None, + } +} + +fn expand_rgb([r, g, b]: [f32; 3]) -> Hsla { + Hsla::from(Rgba { r, g, b, a: 1.0 }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_six_and_three_digit_hex() { + let Rgba { r, g, b, a } = Rgba::from(parse_hex("#7aa2f7").unwrap()); + assert!((r - 0x7a as f32 / 255.0).abs() < 0.001); + assert!((g - 0xa2 as f32 / 255.0).abs() < 0.001); + assert!((b - 0xf7 as f32 / 255.0).abs() < 0.001); + assert_eq!(a, 1.0); + + // Compare in RGB space: Rgba -> Hsla -> Rgba is lossy at low saturation. + let short = Rgba::from(parse_hex("#f00").unwrap()); + assert!((short.r - 1.0).abs() < 0.001); + assert!(short.g.abs() < 0.001); + assert!(short.b.abs() < 0.001); + } + + #[test] + fn rejects_malformed_values() { + assert!(parse_hex("").is_none()); + assert!(parse_hex("#12").is_none()); + assert!(parse_hex("#12345").is_none()); + assert!(parse_hex("#zzzzzz").is_none()); + assert!(parse_hex("7aa2f7").is_none()); + } + + #[test] + fn parses_a_full_definition() { + let def = ThemeDefinition::parse_toml( + "mode = \"dark\"\naccent = \"#7aa2f7\"\nbackground = \"#1a1b26\"\ninfo = \"#38bdf8\"\noverlay_radius = 15.0\nsm_radius = 6.0\n", + ) + .unwrap(); + assert_eq!(def.mode(), Some(crate::theme::ThemeVariant::Dark)); + assert!(def.accent().is_some()); + assert!(def.info().is_some()); + assert!(def.foreground().is_none()); + assert_eq!(def.overlay_radius(), Some(15.0)); + assert_eq!(def.sm_radius(), Some(6.0)); + } + + #[test] + fn an_invalid_mode_fails_the_parse_instead_of_being_ignored() { + assert!(ThemeDefinition::parse_toml("mode = \"blue\"\n").is_err()); + } +} diff --git a/crates/ui/src/theme/mod.rs b/crates/ui/src/theme/mod.rs new file mode 100644 index 0000000..d025219 --- /dev/null +++ b/crates/ui/src/theme/mod.rs @@ -0,0 +1,789 @@ +//! The theme engine: reads the running system theme, resolves it through +//! presets and overrides, and installs the tokens every component paints +//! from. +//! +//! Pipeline (plan §4.5): `ThemeSource` snapshot → `resolve` overlay chain → +//! `Theme` global → all windows repaint. Watchers re-run the pipeline on +//! real OS change events. + +mod colors; +mod definition; +mod presets; +mod ramps; +mod resolve; +mod source; +mod system; +mod typography; + +pub use colors::{ColorTokens, MaterialTokens}; +pub use definition::ThemeDefinition; +pub use ramps::{AccentShades, Oklch}; +pub use resolve::{Ramps, ResolvedTheme}; +pub use system::{AccessibilityPreferences, SourceKind, SystemTheme}; +pub use typography::{TextRole, TypeMetrics, Typeset, Typography}; + +use gpui::{ + App, Global, Hsla, Pixels, SpringConfig, WindowAppearance, WindowBackgroundAppearance, hsla, px, +}; +use std::time::Duration; + +/// The hairline width of the control border every button and field paints. +pub const BORDER_WIDTH: Pixels = px(1.0); +/// The underline and drop indicators a tab strip paints. +pub const TAB_INDICATOR_WIDTH: Pixels = px(2.0); +/// Opacity applied to disabled controls. +pub const DISABLED_OPACITY: f32 = 0.5; +/// The focus ring's ink alpha. +pub const FOCUS_RING_ALPHA: f32 = 0.5; +/// The narrowest a popover may grow. +pub const POPOVER_MIN_WIDTH: Pixels = px(128.0); +/// The default minimum width of a dialog. +pub const DIALOG_MIN_WIDTH: Pixels = px(384.0); +/// The default minimum width of a menu. +pub const MENU_MIN_WIDTH: Pixels = px(224.0); +/// The width of the pushed-alert stack. +pub const ALERT_STACK_WIDTH: Pixels = px(320.0); +/// The accent edge of an inline alert. +pub const ALERT_EDGE_WIDTH: Pixels = px(6.0); +/// The default width of a combobox trigger. +pub const COMBOBOX_WIDTH: Pixels = px(192.0); +/// The narrowest a combobox trigger may shrink. +pub const COMBOBOX_MIN_WIDTH: Pixels = px(96.0); +/// The width of a code view's line-number gutter. +pub const CODE_GUTTER_WIDTH: Pixels = px(40.0); +/// The width of the speech waveform strip. +pub const SPEECH_WAVEFORM_WIDTH: Pixels = px(96.0); +/// The line-height ratio of monospace code. +pub const CODE_LINE_HEIGHT: f32 = 1.5; +/// The tallest an anchored popup's list may grow. +pub const POPUP_MAX_HEIGHT: Pixels = px(320.0); +/// The widest a tooltip may grow. +pub const TOOLTIP_MAX_WIDTH: Pixels = px(360.0); +/// How far a tooltip sits from the pointer. +pub const TOOLTIP_OFFSET: Pixels = px(1.0); +/// The caret's thickness. +pub const CARET_WIDTH: Pixels = px(1.5); +/// The IME preedit underline's thickness. +pub const UNDERLINE_WIDTH: Pixels = px(1.0); +/// How far one wheel line scrolls, as a multiple of the line height. +pub const WHEEL_LINE_HEIGHT: f32 = 20.0; +/// How far one keyboard arrow step moves a resize seam. +pub const RESIZE_KEYBOARD_STEP: Pixels = px(32.0); +/// The inset around a window's edge that starts a resize gesture. +pub const WINDOW_RESIZE_INSET: Pixels = px(4.0); +/// The pad macOS reserves for its traffic lights at a strip's leading edge. +pub const TRAFFIC_LIGHT_PAD: Pixels = px(78.0); +/// The width of a Windows caption button. +pub const WINDOWS_CAPTION_WIDTH: Pixels = px(36.0); +/// Windows paints its caption close-button hover red in every theme. +pub const WINDOWS_CLOSE_HOVER: Hsla = hsla(0.986043, 0.863406, 0.488235, 1.0); +/// The close-button hover dimmed while pressed. +pub const WINDOWS_CLOSE_PRESSED: Hsla = hsla(0.986043, 0.863406, 0.488235, 0.8); +/// The close glyph's color over the red hover. +pub const WINDOWS_CLOSE_FOREGROUND: Hsla = gpui::white(); +/// The width a sidebar opens at. +pub const SIDEBAR_DEFAULT_WIDTH: Pixels = px(240.0); +/// The narrowest a sidebar may be dragged. +pub const SIDEBAR_MIN_WIDTH: Pixels = px(160.0); +/// The widest a sidebar may be dragged. +pub const SIDEBAR_MAX_WIDTH: Pixels = px(480.0); +/// The size a pane starts at before its group has measured the extent. +pub const PANE_DEFAULT_SIZE: Pixels = px(200.0); +/// The floor a pane keeps while dragging unless the caller lowers it. +pub const PANE_MIN_SIZE: Pixels = px(48.0); +/// The hairline a resize seam paints on a shared boundary. +pub const HAIRLINE_WIDTH: Pixels = px(0.5); +/// How much of the window shadow's strength survives losing focus. +pub const INACTIVE_SHADOW_OPACITY: f32 = 0.7; +/// The spread of the keyboard focus ring. +pub const FOCUS_RING_SPREAD: Pixels = px(3.0); +/// How far a pushed alert slides in on entry. +pub const ENTER_SLIDE_DISTANCE: Pixels = px(24.0); +/// The widest a toast may grow. +pub const TOAST_MAX_WIDTH: Pixels = px(480.0); +/// One revolution of the spinner. +pub const SPINNER_PERIOD: Duration = Duration::from_millis(800); +/// One sweep of the indeterminate progress bar. +pub const PROGRESS_ANIMATION_PERIOD: Duration = Duration::from_millis(1500); +/// How long an autohide scrollbar thumb stays fully visible before fading. +pub const SCROLLBAR_AUTOHIDE_DELAY: Duration = Duration::from_millis(700); +/// How long the autohide scrollbar's fade runs. +pub const SCROLLBAR_FADE_DURATION: Duration = Duration::from_millis(250); +/// How much a change wash tints the rows it covers. +pub const WASH_ALPHA: f32 = 0.14; +/// The stronger wash under number gutters and intra-line word changes. +pub const WASH_ALPHA_STRONG: f32 = 0.34; +/// The subtle wash that sets the number gutter off from the code. +pub const WASH_ALPHA_GUTTER: f32 = 0.18; +/// The soft wash that marks the active code row. +pub const WASH_ALPHA_SOFT: f32 = 0.45; +/// How far a scrolling list renders past its viewport. +pub const CODE_OVERSCROLL_MAX: Pixels = px(400.0); +/// The spring every control's toggle and segment animations ride. +pub const CONTROL_SPRING: SpringConfig = SpringConfig::new(500., 35., 1.); +/// The monospace advance estimate as a share of the text size. +pub const MONO_ADVANCE_RATIO: f32 = 0.62; +/// How much a pixel avatar's tint washes over its background. +pub const PIXEL_AVATAR_TINT_ALPHA: f32 = 0.16; +/// Pixel avatar cell lightness multipliers. +pub const PIXEL_AVATAR_LIGHT_LIFT: f32 = 1.6; +pub const PIXEL_AVATAR_LIGHT_CAP: f32 = 0.95; +pub const PIXEL_AVATAR_DARK_FACTOR: f32 = 0.45; +pub const PIXEL_AVATAR_DARK_FLOOR: f32 = 0.18; +/// The default window material transparency, as a percent (0 opaque, 100 the lightest fill). +pub const DEFAULT_TRANSPARENCY: u8 = 80; +/// The light-mode floor of the material fill. +pub const MIN_MATERIAL_FILL_LIGHT: f32 = 0.45; +/// The dark-mode floor of the material fill. +pub const MIN_MATERIAL_FILL_DARK: f32 = 0.15; +/// The opacity of the grain overlay's noise. +pub const GRAIN_ALPHA: f32 = 0.08; + +/// Light or dark, resolved from the system appearance. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ThemeVariant { + #[default] + Light, + Dark, +} + +impl ThemeVariant { + fn from_appearance(appearance: WindowAppearance) -> Self { + match appearance { + WindowAppearance::Light | WindowAppearance::VibrantLight => Self::Light, + WindowAppearance::Dark | WindowAppearance::VibrantDark => Self::Dark, + } + } + + /// Classifies a surface by its lightness, for platforms that state no mode. + pub fn by_lightness(background: Hsla) -> Self { + if background.l >= 0.5 { + Self::Light + } else { + Self::Dark + } + } +} + +/// A named control size class. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Size { + XSmall, + Small, + /// The default. + #[default] + Medium, + Large, +} + +/// The resolved theme, installed as the app-wide global. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Theme { + pub variant: ThemeVariant, + pub colors: ColorTokens, + /// The translucent paints over the window's native material. + pub material: MaterialTokens, + pub ramps: Ramps, + pub radius: Radius, + pub spacing: Spacing, + pub elevations: Elevations, + /// Overlay transition timing; gpui's animation primitives do the rest. + pub motion: Motion, + /// Overlay scrollbar geometry. + pub scrollbar: Scrollbar, + /// The height the window's titlebar strips draw at. + pub titlebar_height: Pixels, + /// The theme's root font size; rem-based sizing scales with it. + pub root_font_size: Pixels, + /// The monospace family, for code surfaces. + pub mono_font: &'static str, + /// The type ladder, resolved at the root font size. + pub typography: Typography, + pub sizes: SizeTable, + pub accessibility: AccessibilityPreferences, + /// The material a window should open with, after accessibility. + pub window_background: WindowBackgroundAppearance, +} + +impl Global for Theme {} + +impl Theme { + /// Reads the theme global. Panics before `init`. + pub fn global(cx: &App) -> &Self { + cx.global::() + } + + fn from_resolved(resolved: ResolvedTheme) -> Self { + Self { + variant: resolved.variant, + colors: resolved.colors, + material: resolved.material, + ramps: resolved.ramps, + radius: resolved.radius, + spacing: resolved.spacing, + elevations: resolved.elevations, + motion: resolved.motion, + scrollbar: resolved.scrollbar, + titlebar_height: resolved.titlebar_height, + root_font_size: resolved.root_font_size, + mono_font: resolved.mono_font, + typography: resolved.typography, + sizes: resolved.sizes, + accessibility: resolved.accessibility, + window_background: resolved.window_background, + } + } + + /// Installs the engine global, its platform watchers, and the initial resolved theme. + pub fn init(cx: &mut App) { + let mut engine = ThemeEngine { + source: source::platform_source(), + mode_override: None, + preset: None, + custom: None, + }; + engine.source.install_watchers(cx.to_async()); + cx.set_global(engine); + reapply(cx); + } + + /// Synchronizes the theme from the window's appearance. + pub fn sync_from_window(window: &mut gpui::Window, cx: &mut App) { + let window_variant = ThemeVariant::from_appearance(window.appearance()); + let theme = cx.global::(); + let engine = cx.global::(); + if engine.mode_override.is_none() && theme.variant != window_variant { + reapply(cx); + } + } + + /// Sizes the window's rem to the theme's root font size. + pub fn sync_window_rem_size(window: &mut gpui::Window, cx: &App) { + let theme = cx.global::(); + window.set_rem_size(theme.root_font_size); + } +} + +/// Corner radii components paint from; grows one class at a time. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Radius { + /// Small controls: checkbox and radio indicators. + pub sm: Pixels, + pub control: Pixels, + /// Floating layers: popovers, menus, dialogs. + pub overlay: Pixels, + /// Pill and circle shapes. + pub full: Pixels, +} + +impl Default for Radius { + fn default() -> Self { + Self { + sm: px(4.), + control: px(6.), + overlay: px(10.), + full: px(9999.), + } + } +} + +/// The spacing rhythm: paddings and gaps step by this unit. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Spacing { + pub unit: Pixels, +} + +/// One layer of a floating panel's drop shadow. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Shadow { + pub offset_x: Pixels, + pub offset_y: Pixels, + pub blur_radius: Pixels, + pub spread_radius: Pixels, + /// Translucent black, like every native overlay shadow. + pub color: Hsla, +} + +impl Shadow { + fn none() -> Self { + Self { + offset_x: px(0.), + offset_y: px(0.), + blur_radius: px(0.), + spread_radius: px(0.), + color: colors::scrim(0.), + } + } + + fn black(offset_x: f32, offset_y: f32, blur_radius: f32, alpha: f32) -> Self { + Self { + offset_x: px(offset_x), + offset_y: px(offset_y), + blur_radius: px(blur_radius), + spread_radius: px(0.), + color: colors::scrim(alpha), + } + } +} + +/// The drop shadow stack of a floating layer. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Elevation { + /// Key shadow first, ambient grounding second. + pub layers: [Shadow; 2], +} + +impl Elevation { + /// No shadow: dark floating layers separate by border. + fn none() -> Self { + Self { + layers: [Shadow::none(), Shadow::none()], + } + } + + fn single(key: Shadow) -> Self { + Self { + layers: [key, Shadow::none()], + } + } + + fn layered(key: Shadow, ambient: Shadow) -> Self { + Self { + layers: [key, ambient], + } + } + + /// How far the shadow layers paint past the element's bounds. + pub fn bleed(self) -> Pixels { + self.layers.iter().fold(px(0.), |bleed, layer| { + if layer.color.a > 0. { + bleed.max( + layer.offset_x.abs().max(layer.offset_y.abs()) + + layer.blur_radius + + layer.spread_radius, + ) + } else { + bleed + } + }) + } + + /// The gpui shadow list an overlay panel paints with. + pub fn shadows(self) -> Vec { + self.layers + .iter() + .filter(|layer| layer.color.a > 0.) + .map(|layer| gpui::BoxShadow { + color: layer.color, + offset: gpui::point(layer.offset_x, layer.offset_y), + blur_radius: layer.blur_radius, + spread_radius: layer.spread_radius, + inset: false, + }) + .collect() + } +} + +/// The drop shadows of each floating layer class. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Elevations { + /// Popovers, menus, and pushed alerts ride above content. + pub popover: Elevation, + /// Modal dialogs sit higher with a wider one. + pub dialog: Elevation, + /// Raised plates inside controls — a selected segmented segment. + pub control: Elevation, +} + +impl Elevations { + pub(crate) fn for_variant(variant: ThemeVariant) -> Self { + if variant == ThemeVariant::Dark { + return Self { + popover: Elevation::none(), + dialog: Elevation::none(), + control: Elevation::single(Shadow::black(0., 1., 2., 0.25)), + }; + } + + Self { + popover: Elevation::layered( + Shadow::black(0., 4., 24., 0.12), + Shadow::black(0., 1., 1., 0.05), + ), + dialog: Elevation::layered( + Shadow::black(0., 8., 40., 0.14), + Shadow::black(0., 1., 2., 0.06), + ), + control: Elevation::single(Shadow::black(0., 1., 2., 0.1)), + } + } +} + +/// Overlay transition timings. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Motion { + /// The enter transition of popovers, menus, and dialogs. + pub overlay: Duration, +} + +impl Default for Motion { + fn default() -> Self { + Self { + overlay: Duration::from_millis(200), + } + } +} + +/// Overlay scrollbar presentation. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Scrollbar { + /// The painted thumb's thickness. + pub width: Pixels, + /// Edge padding between the thumb and the viewport it floats over. + pub inset: Pixels, + /// The thumb never shrinks below this length, so it stays grabbable. + pub min_thumb: Pixels, + /// Whether the platform's scrollbars hide while idle. + pub autohide: bool, +} + +impl Default for Scrollbar { + fn default() -> Self { + Self { + width: px(8.), + inset: px(2.), + min_thumb: px(24.), + autohide: false, + } + } +} + +/// The control metrics for one size class. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ControlMetrics { + /// Push buttons, toggles, and field rows. + pub control_height: Pixels, + /// Text fields; slightly taller than buttons, as native fields are. + pub input_height: Pixels, + /// Horizontal padding inside controls. + pub padding_x: Pixels, + /// Label text size. + pub text_size: Pixels, + /// Icons and on/off indicators. + pub icon_size: Pixels, + /// Icons inline with dense content — menu rows, badges, chevrons. + pub dense_icon_size: Pixels, + /// Selection indicators — checkboxes, radios, and switch knobs. + pub indicator_size: Pixels, + /// Avatars. + pub avatar_size: Pixels, + /// Dense label text. + pub caption_size: Pixels, + /// Tight horizontal padding inside pills, segments, fields, and icon-only buttons. + pub dense_padding_x: Pixels, + /// The inset between a control's edge and a raised inner plate. + pub plate_inset: Pixels, + /// The band height of multi-segment strips. + pub strip_height: Pixels, + /// The height of one menu row. + pub menu_item_height: Pixels, + /// Switch track height, width, and knob size. + pub switch_height: Pixels, + pub switch_width: Pixels, + pub switch_knob: Pixels, +} + +/// The control metrics for every size class. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SizeTable { + pub xsmall: ControlMetrics, + pub small: ControlMetrics, + pub medium: ControlMetrics, + pub large: ControlMetrics, +} + +impl SizeTable { + pub fn with_root_font_size(rem_size: Pixels) -> Self { + struct ClassFactors { + control_height: f32, + input_height: f32, + padding_x: f32, + text_size: f32, + icon_size: f32, + dense_icon_size: f32, + indicator_size: f32, + avatar_size: f32, + caption_size: f32, + dense_padding_x: f32, + plate_inset: f32, + strip_height: f32, + menu_item_height: f32, + switch_height: f32, + switch_width: f32, + switch_knob: f32, + } + + let xsmall = ClassFactors { + control_height: 1.25, + input_height: 1.25, + padding_x: 0.25, + text_size: 0.6875, + icon_size: 0.625, + dense_icon_size: 0.5, + indicator_size: 0.625, + avatar_size: 1.125, + caption_size: 0.625, + dense_padding_x: 0.25, + plate_inset: 0.0, + strip_height: 1.25, + menu_item_height: 1.25, + switch_height: 0.875, + switch_width: 1.5, + switch_knob: 0.5, + }; + + let small = ClassFactors { + control_height: 1.75, + input_height: 1.75, + padding_x: 0.5, + text_size: 0.75, + icon_size: 0.875, + dense_icon_size: 0.75, + indicator_size: 0.875, + avatar_size: 1.5, + caption_size: 0.75, + dense_padding_x: 0.5, + plate_inset: 0.125, + strip_height: 1.75, + menu_item_height: 1.75, + switch_height: 1.125, + switch_width: 2.0, + switch_knob: 0.75, + }; + + let medium = ClassFactors { + control_height: 2.0, + input_height: 2.0, + padding_x: 0.75, + text_size: 0.875, + icon_size: 1.0, + dense_icon_size: 0.75, + indicator_size: 1.0, + avatar_size: 2.0, + caption_size: 0.75, + dense_padding_x: 0.5, + plate_inset: 0.125, + strip_height: 2.0, + menu_item_height: 2.0, + switch_height: 1.25, + switch_width: 2.25, + switch_knob: 0.875, + }; + + let large = ClassFactors { + control_height: 2.5, + input_height: 2.5, + padding_x: 1.0, + text_size: 1.0, + icon_size: 1.25, + dense_icon_size: 0.9375, + indicator_size: 1.25, + avatar_size: 2.5, + caption_size: 0.875, + dense_padding_x: 0.75, + plate_inset: 0.1875, + strip_height: 2.5, + menu_item_height: 2.25, + switch_height: 1.5, + switch_width: 2.75, + switch_knob: 1.125, + }; + + let metrics = |f: &ClassFactors| ControlMetrics { + control_height: rem_size * f.control_height, + input_height: rem_size * f.input_height, + padding_x: rem_size * f.padding_x, + text_size: rem_size * f.text_size, + icon_size: rem_size * f.icon_size, + dense_icon_size: rem_size * f.dense_icon_size, + indicator_size: rem_size * f.indicator_size, + avatar_size: rem_size * f.avatar_size, + caption_size: rem_size * f.caption_size, + dense_padding_x: rem_size * f.dense_padding_x, + plate_inset: rem_size * f.plate_inset, + strip_height: rem_size * f.strip_height, + menu_item_height: rem_size * f.menu_item_height, + switch_height: rem_size * f.switch_height, + switch_width: rem_size * f.switch_width, + switch_knob: rem_size * f.switch_knob, + }; + + Self { + xsmall: metrics(&xsmall), + small: metrics(&small), + medium: metrics(&medium), + large: metrics(&large), + } + } + + /// The metrics for `size`. + pub fn resolve(&self, size: Size) -> ControlMetrics { + match size { + Size::XSmall => self.xsmall, + Size::Small => self.small, + Size::Medium => self.medium, + Size::Large => self.large, + } + } +} + +/// User customizations layered over the resolved theme. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct CustomTheme { + pub root_font_size: Option, + pub sm_radius: Option, + pub control_radius: Option, + pub overlay_radius: Option, + pub popover_elevation: Option, + pub dialog_elevation: Option, + pub control_elevation: Option, + /// Window material transparency as a percent (0 opaque, 100 pure blur). + /// + /// Note: windows platform is not supported + pub transparency: Option, +} + +/// The engine's knobs and its platform source. +struct ThemeEngine { + source: Box, + mode_override: Option, + preset: Option<(&'static str, ThemeDefinition)>, + custom: Option, +} + +impl Global for ThemeEngine {} + +/// Reads the resolved theme global from any app context. +pub trait ActiveTheme { + fn theme(&self) -> &Theme; +} + +impl ActiveTheme for App { + fn theme(&self) -> &Theme { + Theme::global(self) + } +} + +/// Reapplies the theme to the application. +pub(crate) fn reapply(cx: &mut App) { + let (preset, mode_override, custom, system) = { + let engine = cx.global::(); + let system_appearance = ThemeVariant::from_appearance(cx.window_appearance()); + let preset = engine.preset.as_ref().map(|(_, def)| def.clone()); + let mode_override = engine.mode_override; + let custom = engine.custom; + let variant = mode_override + .or(preset.as_ref().and_then(|def| def.mode())) + .unwrap_or(system_appearance); + ( + preset, + mode_override, + custom, + engine.source.snapshot(variant), + ) + }; + + let resolved = resolve::resolve(&system, preset.as_ref(), mode_override, custom); + + cx.set_reduce_motion(resolved.accessibility.reduce_motion); + cx.set_global(Theme::from_resolved(resolved)); + cx.refresh_windows(); +} + +/// Forces a variant, independent of the OS. `None` follows the system. +pub fn set_mode_override(variant: Option, cx: &mut App) { + let engine = cx.global_mut::(); + engine.mode_override = variant; + reapply(cx); +} + +/// Installs a built-in preset, or `None` to follow the system again. +pub fn set_preset(name: Option<&str>, cx: &mut App) -> anyhow::Result<()> { + let preset = name + .map(|name| { + presets::builtin(name).ok_or_else(|| { + anyhow::anyhow!( + "unknown preset: {name}; available: {}", + presets::preset_names().collect::>().join(", ") + ) + }) + }) + .transpose()?; + let engine = cx.global_mut::(); + engine.preset = preset; + reapply(cx); + Ok(()) +} + +/// Installs the user's custom theme, or `None` to follow the current scheme. +pub fn set_custom_theme(custom: Option, cx: &mut App) { + let engine = cx.global_mut::(); + engine.custom = custom; + reapply(cx); +} + +/// The variant the mode override forces, if any. +pub fn mode_override(cx: &App) -> Option { + let engine = cx.global::(); + engine.mode_override +} + +/// The installed custom theme, if any. +pub fn custom_theme(cx: &App) -> Option { + let engine = cx.global::(); + engine.custom +} + +/// The active preset name, if one is installed. +pub fn active_preset(cx: &App) -> Option<&'static str> { + let engine = cx.global::(); + engine.preset.as_ref().map(|(name, _)| *name) +} + +/// Clears the mode override and preset; the theme follows the system again. +pub fn follow_system(cx: &mut App) { + let engine = cx.global_mut::(); + engine.mode_override = None; + engine.preset = None; + reapply(cx); +} + +/// Which adapter produced the current system snapshot. +pub fn detected_source(cx: &App) -> &'static str { + let engine = cx.global::(); + engine.source.label() +} + +#[cfg(test)] +mod tests { + use super::*; + use gpui::Rgba; + + #[test] + fn the_windows_close_colors_match_the_legacy_hex() { + let hover = Hsla::from(gpui::rgba(0xE81123FF)); + let pressed = hover.opacity(0.8); + for (token, expected) in [ + (WINDOWS_CLOSE_HOVER, hover), + (WINDOWS_CLOSE_PRESSED, pressed), + ] { + let (token, expected) = (Rgba::from(token), Rgba::from(expected)); + assert!((token.r - expected.r).abs() < 1e-4); + assert!((token.g - expected.g).abs() < 1e-4); + assert!((token.b - expected.b).abs() < 1e-4); + assert!((token.a - expected.a).abs() < 1e-4); + } + assert_eq!(WINDOWS_CLOSE_FOREGROUND, gpui::white()); + } +} diff --git a/crates/ui/src/theme/presets.rs b/crates/ui/src/theme/presets.rs new file mode 100644 index 0000000..3411844 --- /dev/null +++ b/crates/ui/src/theme/presets.rs @@ -0,0 +1,40 @@ +//! Built-in `ThemeDefinition` presets (D11). + +use crate::theme::definition::ThemeDefinition; + +/// The bundled presets: `(name, TOML source)`. Enumeration and lookup both +/// read this one table. +const PRESETS: &[(&str, &str)] = &[("tokyo-night", include_str!("presets/tokyo-night.toml"))]; + +/// Every bundled preset's name. +pub fn preset_names() -> impl Iterator { + PRESETS.iter().map(|(name, _)| *name) +} + +/// Parses the named preset, returning its static name and definition. +pub fn builtin(name: &str) -> Option<(&'static str, ThemeDefinition)> { + let (name, source) = PRESETS + .iter() + .find(|(candidate, _)| *candidate == name) + .copied()?; + match ThemeDefinition::parse_toml(source) { + Ok(definition) => Some((name, definition)), + Err(error) => { + log::error!("bundled preset {name} failed to parse: {error}"); + None + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_name_table_and_lookup_agree() { + for name in preset_names() { + assert!(builtin(name).is_some(), "{name} fails to parse"); + } + assert!(builtin("no-such-preset").is_none()); + } +} diff --git a/crates/ui/src/theme/presets/tokyo-night.toml b/crates/ui/src/theme/presets/tokyo-night.toml new file mode 100644 index 0000000..696a5c2 --- /dev/null +++ b/crates/ui/src/theme/presets/tokyo-night.toml @@ -0,0 +1,21 @@ +# Tokyo Night. Schema shared with user theme files. + +mode = "dark" +background = "#1a1b26" +foreground = "#c0caf5" +surface = "#1f2335" +surface_foreground = "#c0caf5" +primary = "#7aa2f7" +primary_foreground = "#16161e" +secondary = "#292e42" +secondary_foreground = "#c0caf5" +muted = "#292e42" +muted_foreground = "#a9b1d6" +accent = "#7aa2f7" +accent_foreground = "#16161e" +destructive = "#f7768e" +destructive_foreground = "#16161e" +border = "#292e42" +input = "#292e42" +ring = "#7aa2f7" +selection = "#33467c" diff --git a/crates/ui/src/theme/ramps.rs b/crates/ui/src/theme/ramps.rs new file mode 100644 index 0000000..35318ba --- /dev/null +++ b/crates/ui/src/theme/ramps.rs @@ -0,0 +1,274 @@ +//! OKLCH color math for accent-ramp derivation and contrast-aware +//! foreground selection. Matrices follow Björn Ottosson's OKLab reference. +// The reference matrices are quoted at their published precision; f32 +// truncation is deliberate, not a mistake. +#![allow(clippy::excessive_precision)] + +use gpui::{Hsla, Rgba}; + +/// A color in the OKLCH space (perceptually uniform): +/// lightness, chroma, hue in degrees, plus the alpha carried through unchanged. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Oklch { + pub l: f32, + pub c: f32, + pub h: f32, + pub a: f32, +} + +impl Oklch { + pub fn from_hsla(color: Hsla) -> Self { + let Rgba { r, g, b, a } = Rgba::from(color); + let (l, c, h) = rgb_to_oklch(r, g, b); + Self { l, c, h, a } + } + + pub fn to_hsla(self) -> Hsla { + let (r, g, b) = oklch_to_rgb(self.l, self.c, self.h); + Hsla::from(Rgba { r, g, b, a: self.a }) + } + + /// Shifts lightness by `amount` (positive is lighter), + /// and scales chroma by `chroma_scale`, preserving hue and alpha. + pub fn shifted(self, amount: f32, chroma_scale: f32) -> Self { + Self { + l: (self.l + amount).clamp(0.0, 1.0), + c: (self.c * chroma_scale).max(0.0), + h: self.h, + a: self.a, + } + } +} + +/// Mixes `a` toward `b` by `t` in OKLCH, taking the shortest arc between hues. +/// +/// `t = 0` returns `a`, `t = 1` returns `b`. +pub fn mix(a: Oklch, b: Oklch, t: f32) -> Oklch { + let mut dh = b.h - a.h; + + if dh > 180.0 { + dh -= 360.0; + } else if dh < -180.0 { + dh += 360.0; + } + + Oklch { + l: a.l + (b.l - a.l) * t, + c: a.c + (b.c - a.c) * t, + h: (a.h + dh * t + 360.0) % 360.0, + a: a.a + (b.a - a.a) * t, + } +} + +fn rgb_to_oklch(r: f32, g: f32, b: f32) -> (f32, f32, f32) { + let (r, g, b) = (linearize(r), linearize(g), linearize(b)); + let l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b; + let m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b; + let s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b; + + let (l_, m_, s_) = (cbrt(l), cbrt(m), cbrt(s)); + let lab_l = 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_; + let lab_a = 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_; + let lab_b = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_; + + let c = (lab_a * lab_a + lab_b * lab_b).sqrt(); + let mut h = lab_b.atan2(lab_a).to_degrees(); + + if h < 0.0 { + h += 360.0; + } + + (lab_l, c, h) +} + +fn oklch_to_rgb(l: f32, c: f32, h: f32) -> (f32, f32, f32) { + let hr = h.to_radians(); + let lab_a = c * hr.cos(); + let lab_b = c * hr.sin(); + + let l_ = l + 0.3963377774 * lab_a + 0.2158037573 * lab_b; + let m_ = l - 0.1055613458 * lab_a - 0.0638541728 * lab_b; + let s_ = l - 0.0894841775 * lab_a - 1.2914855480 * lab_b; + + let l = l_ * l_ * l_; + let m = m_ * m_ * m_; + let s = s_ * s_ * s_; + + let r = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s; + let g = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s; + let b = -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s; + + (delinearize(r), delinearize(g), delinearize(b)) +} + +fn linearize(c: f32) -> f32 { + if c <= 0.04045 { + c / 12.92 + } else { + ((c + 0.055) / 1.055).powf(2.4) + } +} + +fn delinearize(c: f32) -> f32 { + if c <= 0.0031308 { + c * 12.92 + } else { + 1.055 * c.powf(1.0 / 2.4) - 0.055 + } +} + +fn cbrt(v: f32) -> f32 { + if v >= 0.0 { v.cbrt() } else { -(-v).cbrt() } +} + +/// Calculate the foreground color that provides sufficient contrast against the background. +pub fn contrast_foreground(background: Hsla) -> Hsla { + const MIN_CONTRAST: f32 = 3.0; + + let Rgba { r, g, b, .. } = Rgba::from(background); + + let luminance = 0.2126 * linearize(r) + 0.7152 * linearize(g) + 0.0722 * linearize(b); + let white_contrast = 1.05 / (luminance + 0.05); + let black_contrast = (luminance + 0.05) / 0.05; + + let white = Hsla::from(Rgba { + r: 1.0, + g: 1.0, + b: 1.0, + a: 1.0, + }); + + let black = Hsla::from(Rgba { + r: 0.0, + g: 0.0, + b: 0.0, + a: 1.0, + }); + + if white_contrast >= MIN_CONTRAST || white_contrast >= black_contrast { + white + } else { + black + } +} + +/// The state shades components paint from for one accent color. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct AccentShades { + pub base: Hsla, + pub hover: Hsla, + pub pressed: Hsla, + pub subtle: Hsla, + pub foreground: Hsla, +} + +/// Derives hover/pressed/subtle shades for an accent against its background. +/// +/// Where a platform states ramps (WinUI, KDE) those are used instead, +/// every other platform derives its shades here. +pub fn derive_shades(accent: Hsla, background: Hsla, is_dark: bool) -> AccentShades { + let accent_ok = Oklch::from_hsla(accent); + let step = if is_dark { 0.05 } else { -0.05 }; + let bg = Oklch::from_hsla(background); + AccentShades { + base: accent, + hover: accent_ok.shifted(step, 1.05).to_hsla(), + pressed: accent_ok.shifted(step * 2.0, 1.1).to_hsla(), + subtle: mix(accent_ok, bg, 0.88).to_hsla(), + foreground: contrast_foreground(accent), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use gpui::rgb; + + fn hsla(hex: u32) -> Hsla { + Hsla::from(rgb(hex)) + } + + #[test] + fn white_and_black_have_extreme_lightness_and_no_chroma() { + let white = Oklch::from_hsla(hsla(0xffffff)); + assert!((white.l - 1.0).abs() < 0.001, "white L = {}", white.l); + assert!(white.c < 0.001, "white C = {}", white.c); + + let black = Oklch::from_hsla(hsla(0x000000)); + assert!(black.l.abs() < 0.001, "black L = {}", black.l); + } + + #[test] + fn oklch_round_trips_within_one_step_of_eight_bit_color() { + for hex in [0x2563eb, 0xdc2626, 0x7aa2f7, 0x1a1b26, 0xf7768e] { + let ok = Oklch::from_hsla(hsla(hex)); + let Rgba { r, g, b, .. } = Rgba::from(ok.to_hsla()); + let (er, eg, eb) = { + let expected = Rgba::from(hsla(hex)); + (expected.r, expected.g, expected.b) + }; + assert!((r - er).abs() < 1.0 / 255.0, "{hex:06x} r {r} vs {er}"); + assert!((g - eg).abs() < 1.0 / 255.0, "{hex:06x} g {g} vs {eg}"); + assert!((b - eb).abs() < 1.0 / 255.0, "{hex:06x} b {b} vs {eb}"); + } + } + + #[test] + fn shades_move_toward_the_background_in_light_mode() { + let accent = hsla(0x2563eb); + let background = hsla(0xffffff); + let shades = derive_shades(accent, background, false); + let hover_l = Oklch::from_hsla(shades.hover).l; + let base_l = Oklch::from_hsla(accent).l; + assert!( + hover_l < base_l, + "light-mode hover darkens: {hover_l} vs {base_l}" + ); + + let dark_shades = derive_shades(accent, hsla(0x09090b), true); + let dark_hover_l = Oklch::from_hsla(dark_shades.hover).l; + assert!(dark_hover_l > base_l, "dark-mode hover lightens"); + } + + #[test] + fn subtle_stays_between_accent_and_background() { + let accent = Oklch::from_hsla(hsla(0x2563eb)); + let background = Oklch::from_hsla(hsla(0xffffff)); + let subtle = Oklch::from_hsla(derive_shades(hsla(0x2563eb), hsla(0xffffff), false).subtle); + assert!(subtle.l > accent.l && subtle.l < background.l); + } + + #[test] + fn contrast_foreground_follows_native_fill_conventions() { + // Dark fills get white. + assert_eq!(contrast_foreground(hsla(0x101010)), hsla(0xffffff)); + // macOS blue accent keeps white, like AppKit, even though black has + // the higher raw WCAG ratio. + assert_eq!(contrast_foreground(hsla(0x007aff)), hsla(0xffffff)); + // Light fills — white fails the 3:1 bar and black wins. + assert_eq!(contrast_foreground(hsla(0xefefef)), hsla(0x000000)); + assert_eq!(contrast_foreground(hsla(0xffd60a)), hsla(0x000000)); + } + + #[test] + fn mix_takes_the_shortest_arc_around_the_hue_wheel() { + let a = Oklch { + l: 0.5, + c: 0.1, + h: 350.0, + a: 1.0, + }; + let b = Oklch { + l: 0.5, + c: 0.1, + h: 10.0, + a: 1.0, + }; + let mid = mix(a, b, 0.5); + assert!( + mid.h < 10.0 || mid.h > 350.0, + "mid hue should cross 0/360, got {}", + mid.h + ); + } +} diff --git a/crates/ui/src/theme/resolve.rs b/crates/ui/src/theme/resolve.rs new file mode 100644 index 0000000..51dab15 --- /dev/null +++ b/crates/ui/src/theme/resolve.rs @@ -0,0 +1,804 @@ +use crate::theme::definition::ThemeDefinition; +use crate::theme::ramps::{AccentShades, Oklch, contrast_foreground, derive_shades, mix}; +use crate::theme::system::{SourceKind, SystemTheme}; +use crate::theme::{ + ColorTokens, CustomTheme, Elevations, MaterialTokens, Motion, Radius, Scrollbar, SizeTable, + Spacing, ThemeVariant, Typography, +}; +use gpui::{WindowBackgroundAppearance, px}; + +/// Derived state shades for the colors that get pressed and hovered. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Ramps { + pub primary: AccentShades, + pub secondary: AccentShades, + pub destructive: AccentShades, + pub success: AccentShades, + pub warning: AccentShades, + pub info: AccentShades, +} + +/// Everything a component paints from, after the overlay chain. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ResolvedTheme { + pub variant: ThemeVariant, + pub colors: ColorTokens, + /// The translucent paints over the window's native material. + pub material: MaterialTokens, + pub ramps: Ramps, + pub radius: Radius, + pub spacing: Spacing, + pub elevations: Elevations, + pub motion: Motion, + pub scrollbar: Scrollbar, + /// The height the window's titlebar strips draw at. + pub titlebar_height: gpui::Pixels, + /// The theme's root font size. + pub root_font_size: gpui::Pixels, + /// The monospace family, for code surfaces. + pub mono_font: &'static str, + /// The type ladder, resolved at the root font size. + pub typography: Typography, + pub sizes: SizeTable, + pub accessibility: crate::theme::system::AccessibilityPreferences, + /// The material a window should open with, after accessibility. + pub window_background: WindowBackgroundAppearance, +} + +/// Overlay order (later wins): +/// neutral base → system → preset definition → custom theme. +pub(crate) fn resolve( + system: &SystemTheme, + preset: Option<&ThemeDefinition>, + mode_override: Option, + custom: Option, +) -> ResolvedTheme { + let custom = custom.unwrap_or_default(); + + let variant = mode_override + .or(preset.and_then(|def| def.mode())) + .unwrap_or(system.variant); + + let base = match variant { + ThemeVariant::Light => ColorTokens::light(), + ThemeVariant::Dark => ColorTokens::dark(), + }; + + let def_color = |field: fn(&ThemeDefinition) -> Option| preset.and_then(field); + + let accent = def_color(|d| d.accent()) + .or(system.accent) + .unwrap_or(base.accent); + let primary = def_color(|d| d.primary()).unwrap_or(accent); + let destructive = def_color(|d| d.destructive()).unwrap_or(base.destructive); + let success = def_color(|d| d.success()).unwrap_or(base.success); + let warning = def_color(|d| d.warning()).unwrap_or(base.warning); + let info = def_color(|d| d.info()).unwrap_or(base.info); + + let mut colors = ColorTokens { + background: def_color(|d| d.background()).unwrap_or(base.background), + foreground: def_color(|d| d.foreground()).unwrap_or(base.foreground), + surface: def_color(|d| d.surface()).unwrap_or(base.surface), + surface_foreground: def_color(|d| d.surface_foreground()) + .unwrap_or(base.surface_foreground), + sidebar: def_color(|d| d.sidebar()).unwrap_or(base.sidebar), + primary, + primary_foreground: def_color(|d| d.primary_foreground()) + .unwrap_or_else(|| contrast_foreground(primary)), + secondary: def_color(|d| d.secondary()).unwrap_or(base.secondary), + secondary_foreground: def_color(|d| d.secondary_foreground()) + .unwrap_or(base.secondary_foreground), + muted: def_color(|d| d.muted()).unwrap_or(base.muted), + muted_hover: def_color(|d| d.muted_hover()).unwrap_or(base.muted_hover), + muted_foreground: def_color(|d| d.muted_foreground()).unwrap_or(base.muted_foreground), + accent, + accent_foreground: def_color(|d| d.accent_foreground()) + .unwrap_or_else(|| contrast_foreground(accent)), + destructive, + destructive_foreground: def_color(|d| d.destructive_foreground()) + .unwrap_or_else(|| contrast_foreground(destructive)), + success, + success_foreground: def_color(|d| d.success_foreground()) + .unwrap_or_else(|| contrast_foreground(success)), + warning, + warning_foreground: def_color(|d| d.warning_foreground()) + .unwrap_or_else(|| contrast_foreground(warning)), + info, + info_foreground: def_color(|d| d.info_foreground()) + .unwrap_or_else(|| contrast_foreground(info)), + border: def_color(|d| d.border()).unwrap_or(base.border), + input: def_color(|d| d.input()).unwrap_or(base.input), + ring: def_color(|d| d.ring()).unwrap_or(accent), + selection: def_color(|d| d.selection()).unwrap_or(base.selection), + overlay: def_color(|d| d.overlay()).unwrap_or(base.overlay), + scrollbar_thumb: def_color(|d| d.scrollbar_thumb()).unwrap_or(base.scrollbar_thumb), + }; + + // The knob scales the fill over a platform-stated blur. + let transparency = custom + .transparency + .map(|level| level.min(100)) + .filter(|_| system.source != SourceKind::Windows && system.window_background.is_some()); + + // Reduced transparency forces the window opaque. + let window_background = if system.accessibility.reduce_transparency || transparency == Some(0) { + WindowBackgroundAppearance::Opaque + } else { + system + .window_background + .unwrap_or(WindowBackgroundAppearance::Opaque) + }; + + let accessibility = system.accessibility; + if accessibility.high_contrast { + colors.border = mix( + Oklch::from_hsla(colors.border), + Oklch::from_hsla(colors.foreground), + 0.35, + ) + .to_hsla(); + } + + // A custom theme's stated font size wins over the 16px design root. + let root_font_size = custom.root_font_size.unwrap_or(px(16.)); + let sizes = SizeTable::with_root_font_size(root_font_size); + let titlebar_height = root_font_size * 2.5; + + let mut radius = Radius::default(); + + if let Some(control) = custom + .control_radius + .or(preset.and_then(|def| def.control_radius()).map(px)) + { + radius.control = control; + } + + if let Some(overlay) = custom + .overlay_radius + .or(preset.and_then(|def| def.overlay_radius()).map(px)) + { + radius.overlay = overlay; + } + + if let Some(sm) = custom + .sm_radius + .or(preset.and_then(|def| def.sm_radius()).map(px)) + { + radius.sm = sm; + } + + let ramps = Ramps { + primary: derive_shades(primary, colors.background, variant == ThemeVariant::Dark), + secondary: derive_shades( + colors.secondary, + colors.background, + variant == ThemeVariant::Dark, + ), + destructive: derive_shades( + destructive, + colors.background, + variant == ThemeVariant::Dark, + ), + success: derive_shades(success, colors.background, variant == ThemeVariant::Dark), + warning: derive_shades(warning, colors.background, variant == ThemeVariant::Dark), + info: derive_shades(info, colors.background, variant == ThemeVariant::Dark), + }; + + if def_color(|d| d.selection()).is_none() { + colors.selection = ramps.primary.subtle; + } + + let material = MaterialTokens::derive( + &colors, + ramps.primary.base, + variant, + window_background != WindowBackgroundAppearance::Opaque, + transparency, + ); + + let default_elevations = Elevations::for_variant(variant); + let elevations = Elevations { + popover: custom + .popover_elevation + .unwrap_or(default_elevations.popover), + dialog: custom.dialog_elevation.unwrap_or(default_elevations.dialog), + control: custom + .control_elevation + .unwrap_or(default_elevations.control), + }; + + ResolvedTheme { + variant, + ramps, + colors, + material, + radius, + spacing: Spacing { + unit: root_font_size * 0.25, + }, + elevations, + motion: Motion::default(), + scrollbar: Scrollbar { + autohide: system.source.scrollbar_autohide(), + ..Scrollbar::default() + }, + titlebar_height, + root_font_size, + mono_font: mono_font(), + typography: Typography::resolve(root_font_size), + sizes, + accessibility, + window_background, + } +} + +/// The platform's monospace family, for code surfaces. +fn mono_font() -> &'static str { + if cfg!(target_os = "macos") { + "Menlo" + } else if cfg!(target_os = "windows") { + "Consolas" + } else { + "monospace" + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::theme::system::{AccessibilityPreferences, SourceKind}; + use crate::theme::{Elevation, Shadow}; + use gpui::{Rgba, WindowBackgroundAppearance, rgb}; + + fn hsla(hex: u32) -> gpui::Hsla { + gpui::Hsla::from(rgb(hex)) + } + + fn system(variant: ThemeVariant, accent: Option) -> SystemTheme { + SystemTheme { + variant, + accent, + accessibility: AccessibilityPreferences::default(), + window_background: None, + source: SourceKind::Macos, + } + } + + #[test] + fn empty_system_resolves_to_the_neutral_fallback() { + for variant in [ThemeVariant::Light, ThemeVariant::Dark] { + let resolved = resolve( + &SystemTheme { + source: SourceKind::Fallback, + ..system(variant, None) + }, + None, + None, + None, + ); + let base = match variant { + ThemeVariant::Light => ColorTokens::light(), + ThemeVariant::Dark => ColorTokens::dark(), + }; + assert_eq!(resolved.colors.background, base.background); + assert_eq!(resolved.colors.accent, base.accent); + assert_eq!(resolved.colors.ring, base.accent); + assert_eq!(resolved.ramps.primary.base, base.primary); + assert_eq!(resolved.ramps.secondary.base, base.secondary); + assert_eq!(resolved.colors.selection, resolved.ramps.primary.subtle); + assert_eq!(resolved.radius.sm, px(4.)); + assert_eq!(resolved.radius.control, px(6.)); + assert_eq!(resolved.radius.overlay, px(10.)); + assert_eq!(resolved.root_font_size, px(16.)); + assert_eq!(resolved.sizes.medium.control_height, px(32.)); + assert_eq!(resolved.sizes.medium.input_height, px(32.)); + assert_eq!(resolved.sizes.medium.text_size, px(14.)); + assert_eq!(resolved.sizes.xsmall.control_height, px(20.)); + assert_eq!(resolved.sizes.xsmall.input_height, px(20.)); + assert_eq!(resolved.sizes.xsmall.text_size, px(11.)); + assert_eq!(resolved.sizes.xsmall.icon_size, px(10.)); + assert_eq!(resolved.sizes.xsmall.indicator_size, px(10.)); + assert_eq!(resolved.sizes.xsmall.avatar_size, px(18.)); + assert_eq!(resolved.sizes.xsmall.caption_size, px(10.)); + assert_eq!(resolved.sizes.xsmall.dense_padding_x, px(4.)); + assert_eq!(resolved.sizes.xsmall.plate_inset, px(0.)); + assert_eq!(resolved.sizes.xsmall.menu_item_height, px(20.)); + assert_eq!(resolved.sizes.xsmall.switch_height, px(14.)); + assert_eq!(resolved.sizes.xsmall.switch_width, px(24.)); + assert_eq!(resolved.sizes.xsmall.switch_knob, px(8.)); + assert_eq!(resolved.sizes.small.control_height, px(28.)); + assert_eq!(resolved.sizes.small.text_size, px(12.)); + assert_eq!(resolved.sizes.small.avatar_size, px(24.)); + assert_eq!(resolved.sizes.medium.avatar_size, px(32.)); + assert_eq!(resolved.sizes.large.avatar_size, px(40.)); + assert_eq!(resolved.sizes.small.caption_size, px(12.)); + assert_eq!(resolved.sizes.medium.caption_size, px(12.)); + assert_eq!(resolved.sizes.large.caption_size, px(14.)); + assert_eq!(resolved.sizes.medium.dense_padding_x, px(8.)); + assert_eq!(resolved.sizes.medium.plate_inset, px(2.)); + assert_eq!(resolved.sizes.medium.strip_height, px(32.)); + assert_eq!(resolved.sizes.medium.icon_size, px(16.)); + assert_eq!(resolved.sizes.medium.indicator_size, px(16.)); + assert_eq!(resolved.sizes.medium.menu_item_height, px(32.)); + assert_eq!(resolved.sizes.large.control_height, px(40.)); + assert_eq!(resolved.sizes.large.text_size, px(16.)); + assert_eq!(resolved.sizes.medium.switch_height, px(20.)); + assert_eq!(resolved.sizes.medium.switch_width, px(36.)); + assert_eq!(resolved.sizes.medium.switch_knob, px(14.)); + assert_eq!(resolved.spacing.unit, px(4.)); + assert_eq!(resolved.titlebar_height, px(40.)); + assert_eq!(resolved.typography.body.size, px(16.)); + } + } + + #[test] + fn scrollbar_autohide_follows_the_platform_source() { + let mut stated = system(ThemeVariant::Dark, None); + stated.source = SourceKind::Macos; + assert!(resolve(&stated, None, None, None).scrollbar.autohide); + + stated.source = SourceKind::Gnome; + assert!(resolve(&stated, None, None, None).scrollbar.autohide); + + stated.source = SourceKind::Omarchy; + assert!(resolve(&stated, None, None, None).scrollbar.autohide); + + stated.source = SourceKind::Windows; + assert!(!resolve(&stated, None, None, None).scrollbar.autohide); + + stated.source = SourceKind::Kde; + assert!(!resolve(&stated, None, None, None).scrollbar.autohide); + + stated.source = SourceKind::Fallback; + assert!(!resolve(&stated, None, None, None).scrollbar.autohide); + } + + #[test] + fn accent_drives_primary_ring_and_selection() { + let red = hsla(0xdc2626); + let resolved = resolve(&system(ThemeVariant::Light, Some(red)), None, None, None); + assert_eq!(resolved.colors.accent, red); + assert_eq!(resolved.colors.primary, red); + assert_eq!(resolved.colors.ring, red); + assert_eq!(resolved.ramps.primary.base, red); + assert_eq!(resolved.colors.selection, resolved.ramps.primary.subtle); + + let base = ColorTokens::light(); + assert_eq!(resolved.colors.background, base.background); + assert_eq!(resolved.colors.foreground, base.foreground); + assert_eq!(resolved.colors.border, base.border); + } + + #[test] + fn every_source_resolves_the_same_tokens() { + let mut stated = system(ThemeVariant::Dark, None); + stated.accent = Some(hsla(0x7aa2f7)); + stated.window_background = Some(WindowBackgroundAppearance::Blurred); + let sources = [ + SourceKind::Fallback, + SourceKind::Macos, + SourceKind::Windows, + SourceKind::Gnome, + SourceKind::Kde, + SourceKind::Omarchy, + ]; + + let first = resolve( + &SystemTheme { + source: sources[0], + ..stated + }, + None, + None, + None, + ); + for source in &sources[1..] { + let next = resolve( + &SystemTheme { + source: *source, + ..stated + }, + None, + None, + None, + ); + assert_eq!(next.colors, first.colors, "{source:?}"); + assert_eq!(next.radius, first.radius, "{source:?}"); + assert_eq!(next.spacing, first.spacing, "{source:?}"); + assert_eq!(next.elevations, first.elevations, "{source:?}"); + assert_eq!(next.titlebar_height, first.titlebar_height, "{source:?}"); + assert_eq!(next.root_font_size, first.root_font_size, "{source:?}"); + assert_eq!(next.typography, first.typography, "{source:?}"); + assert_eq!(next.sizes, first.sizes, "{source:?}"); + } + } + + #[test] + fn the_radius_ladder_follows_custom_values_with_preset_priority() { + let resolved = resolve(&system(ThemeVariant::Light, None), None, None, None); + assert_eq!(resolved.radius.sm, px(4.)); + assert_eq!(resolved.radius.control, px(6.)); + assert_eq!(resolved.radius.overlay, px(10.)); + + let def = ThemeDefinition::parse_toml("overlay_radius = 12.0\n").unwrap(); + let overridden = resolve(&system(ThemeVariant::Light, None), Some(&def), None, None); + assert_eq!(overridden.radius.overlay, px(12.)); + assert_eq!(overridden.radius.sm, px(4.)); + + let custom = CustomTheme { + sm_radius: Some(px(2.)), + control_radius: Some(px(9.)), + ..CustomTheme::default() + }; + let custom = resolve( + &system(ThemeVariant::Light, None), + Some(&def), + None, + Some(custom), + ); + assert_eq!(custom.radius.sm, px(2.)); + assert_eq!(custom.radius.control, px(9.)); + assert_eq!(custom.radius.overlay, px(12.)); + } + + #[test] + fn elevations_follow_the_variant() { + let light = resolve(&system(ThemeVariant::Light, None), None, None, None); + assert_eq!(light.elevations.popover.shadows().len(), 2); + assert_eq!(light.elevations.dialog.shadows().len(), 2); + assert_eq!(light.elevations.control.shadows().len(), 1); + + let dark = resolve(&system(ThemeVariant::Dark, None), None, None, None); + assert!(dark.elevations.popover.shadows().is_empty()); + assert!(dark.elevations.dialog.shadows().is_empty()); + assert_eq!(dark.elevations.control.shadows().len(), 1); + } + + #[test] + fn the_platforms_window_material_resolves_into_the_theme() { + let mut stated = system(ThemeVariant::Light, None); + stated.window_background = Some(WindowBackgroundAppearance::MicaBackdrop); + let resolved = resolve(&stated, None, None, None); + + assert_eq!( + resolved.window_background, + WindowBackgroundAppearance::MicaBackdrop + ); + // Material surfaces stay translucent over the stated backdrop. + assert!(resolved.material.background.a < resolved.colors.background.a); + assert!(resolved.material.selection.a < 1.0); + + let unstated = resolve(&system(ThemeVariant::Light, None), None, None, None); + assert_eq!( + unstated.window_background, + WindowBackgroundAppearance::Opaque + ); + assert_eq!(unstated.material.background, unstated.colors.background); + assert_eq!(unstated.material.hover, unstated.colors.muted); + assert_eq!(unstated.material.selection, unstated.ramps.primary.base); + } + + #[test] + fn reduced_transparency_forces_an_opaque_window_and_material() { + let mut stated = system(ThemeVariant::Dark, None); + stated.window_background = Some(WindowBackgroundAppearance::Blurred); + stated.accessibility.reduce_transparency = true; + let resolved = resolve(&stated, None, None, None); + + assert_eq!( + resolved.window_background, + WindowBackgroundAppearance::Opaque + ); + assert_eq!(resolved.material.background, resolved.colors.background); + assert_eq!(resolved.material.hover, resolved.colors.muted); + assert_eq!(resolved.material.selection, resolved.ramps.primary.base); + } + + #[test] + fn a_custom_transparency_level_scales_the_material_fill() { + let mut stated = system(ThemeVariant::Dark, None); + stated.window_background = Some(WindowBackgroundAppearance::Blurred); + let custom = CustomTheme { + transparency: Some(80), + ..CustomTheme::default() + }; + let resolved = resolve(&stated, None, None, Some(custom)); + + assert_eq!( + resolved.window_background, + WindowBackgroundAppearance::Blurred + ); + assert!((resolved.material.background.a - 0.32).abs() < 1e-6); + + // Levels past 100 clamp, bottoming out at the dark floor. + let clamped = resolve( + &stated, + None, + None, + Some(CustomTheme { + transparency: Some(150), + ..CustomTheme::default() + }), + ); + assert!((clamped.material.background.a - 0.15).abs() < 1e-6); + } + + #[test] + fn light_mode_keeps_a_heavier_fill_at_full_transparency() { + let mut light_system = system(ThemeVariant::Light, None); + light_system.window_background = Some(WindowBackgroundAppearance::Blurred); + let mut dark_system = system(ThemeVariant::Dark, None); + dark_system.window_background = Some(WindowBackgroundAppearance::Blurred); + let maxed = CustomTheme { + transparency: Some(100), + ..CustomTheme::default() + }; + let light = resolve(&light_system, None, None, Some(maxed)); + let dark = resolve(&dark_system, None, None, Some(maxed)); + + assert!((light.material.background.a - 0.45).abs() < 1e-6); + assert!((dark.material.background.a - 0.15).abs() < 1e-6); + } + + #[test] + fn transparency_zero_opens_an_opaque_window() { + let mut stated = system(ThemeVariant::Dark, None); + stated.window_background = Some(WindowBackgroundAppearance::Blurred); + let resolved = resolve( + &stated, + None, + None, + Some(CustomTheme { + transparency: Some(0), + ..CustomTheme::default() + }), + ); + + assert_eq!( + resolved.window_background, + WindowBackgroundAppearance::Opaque + ); + assert_eq!(resolved.material.background, resolved.colors.background); + assert_eq!(resolved.material.hover, resolved.colors.muted); + assert_eq!(resolved.material.selection, resolved.ramps.primary.base); + } + + #[test] + fn the_transparency_knob_skips_windows_and_platforms_without_a_material() { + let mut windows = system(ThemeVariant::Dark, None); + windows.source = SourceKind::Windows; + windows.window_background = Some(WindowBackgroundAppearance::MicaBackdrop); + let resolved_windows = resolve( + &windows, + None, + None, + Some(CustomTheme { + transparency: Some(100), + ..CustomTheme::default() + }), + ); + + assert_eq!( + resolved_windows.window_background, + WindowBackgroundAppearance::MicaBackdrop + ); + // The knob's value is ignored on Windows; the default drives the fill. + let unset = resolve(&windows, None, None, None); + assert_eq!( + resolved_windows.material.background, + unset.material.background + ); + + let mut unstated = system(ThemeVariant::Dark, None); + unstated.window_background = None; + let resolved_unstated = resolve( + &unstated, + None, + None, + Some(CustomTheme { + transparency: Some(100), + ..CustomTheme::default() + }), + ); + + assert_eq!( + resolved_unstated.window_background, + WindowBackgroundAppearance::Opaque + ); + assert_eq!( + resolved_unstated.material.background, + resolved_unstated.colors.background + ); + } + + #[test] + fn overlay_is_translucent_and_overridable() { + let light = resolve(&system(ThemeVariant::Light, None), None, None, None); + let dark = resolve(&system(ThemeVariant::Dark, None), None, None, None); + + // Both scrims are translucent black; dark is denser for contrast. + assert!(light.colors.overlay.a > 0.0 && light.colors.overlay.a < 0.5); + assert!(dark.colors.overlay.a > light.colors.overlay.a); + + let def = ThemeDefinition::parse_toml("overlay = \"#000000\"").unwrap(); + let overridden = resolve(&system(ThemeVariant::Light, None), Some(&def), None, None); + assert_eq!(overridden.colors.overlay, hsla(0x000000)); + assert_eq!(overridden.colors.overlay.a, 1.0); + } + + #[test] + fn elevations_and_motion_resolve_with_defaults() { + let resolved = resolve(&system(ThemeVariant::Light, None), None, None, None); + + // The popover shadow is softer and tighter than the dialog's. + assert!( + resolved.elevations.popover.layers[0].blur_radius + < resolved.elevations.dialog.layers[0].blur_radius + ); + assert!(resolved.motion.overlay > std::time::Duration::ZERO); + let shadows = resolved.elevations.popover.shadows(); + assert_eq!(shadows.len(), 2); + assert!(!shadows[0].inset); + } + + #[test] + fn preset_beats_system_and_the_mode_override_beats_everything() { + let def = ThemeDefinition::parse_toml( + "mode = \"dark\"\nbackground = \"#1a1b26\"\naccent = \"#7aa2f7\"\ncontrol_radius = 12.0\n", + ) + .unwrap(); + let resolved = resolve(&system(ThemeVariant::Light, None), Some(&def), None, None); + assert_eq!(resolved.variant, ThemeVariant::Dark); + // Compare in RGB space: Hsla round-trips are lossy at low saturation. + let bg = Rgba::from(resolved.colors.background); + assert!((bg.r - 0x1a as f32 / 255.0).abs() < 0.001); + assert!((bg.b - 0x26 as f32 / 255.0).abs() < 0.001); + let accent = Rgba::from(resolved.colors.accent); + assert!((accent.r - 0x7a as f32 / 255.0).abs() < 0.001); + // And the metric override beats the radius default. + assert_eq!(resolved.radius.control, px(12.)); + + let forced = resolve( + &system(ThemeVariant::Light, None), + Some(&def), + Some(ThemeVariant::Light), + None, + ); + assert_eq!(forced.variant, ThemeVariant::Light); + // The override flips the variant (and with it the base roles), but + // the preset's explicit background still wins over the base. + let forced_bg = Rgba::from(forced.colors.background); + assert!((forced_bg.r - 0x1a as f32 / 255.0).abs() < 0.001); + } + + #[test] + fn an_accent_only_override_derives_foregrounds_and_ramps() { + let def = ThemeDefinition::parse_toml("mode = \"dark\"\naccent = \"#7aa2f7\"\n").unwrap(); + let resolved = resolve(&system(ThemeVariant::Dark, None), Some(&def), None, None); + // The definition sets accent only; primary follows it, and both + // foregrounds derive from their own color. + let accent = Rgba::from(resolved.colors.accent); + assert!((accent.r - 0x7a as f32 / 255.0).abs() < 0.001); + assert_eq!(resolved.colors.primary, resolved.colors.accent); + assert_eq!(resolved.colors.ring, resolved.colors.accent); + assert_eq!(resolved.colors.selection, resolved.ramps.primary.subtle); + assert_eq!(resolved.ramps.primary.base, resolved.colors.primary); + assert_eq!(resolved.ramps.destructive.base, resolved.colors.destructive); + assert_ne!(resolved.ramps.primary.hover, resolved.ramps.primary.base); + assert_ne!(resolved.ramps.primary.subtle, resolved.ramps.primary.base); + } + + #[test] + fn system_accent_becomes_primary() { + let resolved = resolve( + &system(ThemeVariant::Dark, Some(hsla(0x7aa2f7))), + None, + None, + None, + ); + let primary = Rgba::from(resolved.colors.primary); + assert!((primary.r - 0x7a as f32 / 255.0).abs() < 0.001); + assert_eq!(resolved.ramps.primary.base, resolved.colors.primary); + assert_eq!( + resolved.colors.primary_foreground, + resolved.colors.accent_foreground + ); + } + + #[test] + fn high_contrast_sharpens_the_border_toward_the_foreground() { + let mut a11y = AccessibilityPreferences::default(); + let plain = resolve(&system(ThemeVariant::Dark, None), None, None, None); + a11y.high_contrast = true; + let contrasted = resolve( + &SystemTheme { + accessibility: a11y, + ..system(ThemeVariant::Dark, None) + }, + None, + None, + None, + ); + let plain_border = Oklch::from_hsla(plain.colors.border); + let contrasted_border = Oklch::from_hsla(contrasted.colors.border); + let foreground_l = Oklch::from_hsla(plain.colors.foreground).l; + assert!((contrasted_border.l - foreground_l).abs() < (plain_border.l - foreground_l).abs()); + } + + #[test] + fn every_resolved_role_is_distinct_enough_to_paint_with() { + for variant in [ThemeVariant::Light, ThemeVariant::Dark] { + let resolved = resolve(&system(variant, None), None, None, None); + assert_ne!(resolved.colors.background, resolved.colors.foreground); + assert_ne!(resolved.colors.border, resolved.colors.background); + assert_ne!(resolved.colors.muted_foreground, resolved.colors.foreground); + assert!(resolved.colors.ring != resolved.colors.background); + } + } + + #[test] + fn info_stays_calm_when_the_accent_warms_up() { + // The whole point of the info role: a warm platform accent (GNOME + // red, Omarchy red themes) must not make Info toasts read as Danger. + let red_accent = hsla(0xdc2626); + let resolved = resolve( + &system(ThemeVariant::Dark, Some(red_accent)), + None, + None, + None, + ); + assert_eq!(resolved.ramps.primary.base, red_accent); + assert_ne!(resolved.colors.info, resolved.colors.destructive); + assert_ne!(resolved.ramps.info.base, resolved.ramps.destructive.base); + } + + #[test] + fn info_follows_the_preset() { + let def = ThemeDefinition::parse_toml("info = \"#0ea5e9\"\n").unwrap(); + let resolved = resolve(&system(ThemeVariant::Dark, None), Some(&def), None, None); + assert_eq!(resolved.colors.info, hsla(0x0ea5e9)); + assert_eq!(resolved.ramps.info.base, hsla(0x0ea5e9)); + } + + #[test] + fn a_custom_theme_beats_the_preset_and_defaults() { + let def = ThemeDefinition::parse_toml("overlay_radius = 12.0\n").unwrap(); + let popover = Elevation::single(Shadow::black(0., 2., 8., 0.3)); + let custom = CustomTheme { + sm_radius: Some(px(2.)), + control_radius: Some(px(4.)), + popover_elevation: Some(popover), + ..CustomTheme::default() + }; + let resolved = resolve( + &system(ThemeVariant::Light, None), + Some(&def), + None, + Some(custom), + ); + assert_eq!(resolved.radius.control, px(4.)); + assert_eq!(resolved.radius.sm, px(2.)); + // Fields the custom theme leaves unstated keep the resolved values. + assert_eq!(resolved.radius.overlay, px(12.)); + assert_eq!(resolved.elevations.popover, popover); + let defaults = Elevations::for_variant(ThemeVariant::Light); + assert_eq!(resolved.elevations.dialog, defaults.dialog); + assert_eq!(resolved.elevations.control, defaults.control); + } + + #[test] + fn a_custom_root_font_size_rescales_the_table() { + let custom = CustomTheme { + root_font_size: Some(px(20.)), + ..CustomTheme::default() + }; + let resolved = resolve(&system(ThemeVariant::Light, None), None, None, Some(custom)); + assert_eq!(resolved.root_font_size, px(20.)); + assert_eq!(resolved.sizes.medium.control_height, px(40.)); + assert_eq!(resolved.sizes.medium.text_size, px(17.5)); + assert_eq!(resolved.spacing.unit, px(5.)); + assert_eq!(resolved.titlebar_height, px(50.)); + assert_eq!(resolved.typography.body.size, px(20.)); + assert_eq!(resolved.typography.large_title.size, px(30.)); + } +} diff --git a/crates/ui/src/theme/source.rs b/crates/ui/src/theme/source.rs new file mode 100644 index 0000000..b037427 --- /dev/null +++ b/crates/ui/src/theme/source.rs @@ -0,0 +1,64 @@ +//! Platform adapters behind one seam: `snapshot()` reads the running +//! system, `install_watchers()` forwards real change events. + +use gpui::AsyncApp; + +use crate::theme::ThemeVariant; +use crate::theme::system::SystemTheme; + +pub(crate) trait ThemeSource: 'static { + fn snapshot(&self, variant: ThemeVariant) -> SystemTheme; + fn install_watchers(&mut self, _async_cx: AsyncApp) {} + fn label(&self) -> &'static str; +} + +/// Narrows an f64 color component to f32, clamping to the 0..=1 range and +/// mapping non-finite values to 0.0 rather than truncating garbage silently. +pub(crate) fn narrow_component(value: f64) -> f32 { + if value.is_finite() { + value.clamp(0.0, 1.0) as f32 + } else { + 0.0 + } +} + +#[cfg(target_os = "macos")] +pub(crate) fn platform_source() -> Box { + Box::new(macos::MacosSource::default()) +} + +#[cfg(target_os = "linux")] +pub(crate) fn platform_source() -> Box { + linux::platform_source() +} + +#[cfg(target_os = "windows")] +pub(crate) fn platform_source() -> Box { + windows::platform_source() +} + +#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))] +pub(crate) fn platform_source() -> Box { + Box::new(fallback::FallbackSource) +} + +#[cfg(target_os = "macos")] +pub(crate) mod macos; + +#[cfg(target_os = "linux")] +pub(crate) mod linux; + +#[cfg(target_os = "windows")] +pub(crate) mod windows; + +#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))] +pub(crate) mod signal; + +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +pub(crate) mod kde; +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +pub(crate) mod omarchy; +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +pub(crate) mod portal; + +pub(crate) mod fallback; diff --git a/crates/ui/src/theme/source/fallback.rs b/crates/ui/src/theme/source/fallback.rs new file mode 100644 index 0000000..f857ffa --- /dev/null +++ b/crates/ui/src/theme/source/fallback.rs @@ -0,0 +1,20 @@ +//! The adapter for unknown systems: +//! no colors of its own, resolution degrades to the neutral presets. + +use super::ThemeSource; +use crate::theme::ThemeVariant; +use crate::theme::system::SystemTheme; + +// Constructed only by `platform_source` on platforms without their own adapter. +#[cfg_attr(any(target_os = "macos", target_os = "linux"), allow(dead_code))] +pub(crate) struct FallbackSource; + +impl ThemeSource for FallbackSource { + fn snapshot(&self, variant: ThemeVariant) -> SystemTheme { + SystemTheme::fallback(variant) + } + + fn label(&self) -> &'static str { + crate::theme::system::SourceKind::Fallback.label() + } +} diff --git a/crates/ui/src/theme/source/kde.rs b/crates/ui/src/theme/source/kde.rs new file mode 100644 index 0000000..448d19d --- /dev/null +++ b/crates/ui/src/theme/source/kde.rs @@ -0,0 +1,255 @@ +//! KDE adapter: reads the color groups Plasma writes into `~/.config/kdeglobals` +//! (plus the Plasma 6.2+ `[General] AccentColor`). The parse is pure, so +//! fixtures run on every OS; the IO lives behind the Linux cfg. + +use std::collections::HashMap; + +use gpui::Hsla; + +use crate::theme::system::{SourceKind, SystemTheme}; + +/// The accent and window background stated in kdeglobals. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct KdeScheme { + pub(crate) accent: Option, + pub(crate) background: Option, +} + +impl KdeScheme { + /// Parses kdeglobals text. + pub(crate) fn parse(text: &str) -> Self { + let groups = parse_groups(text); + + let background = groups + .get("Colors:Window") + .and_then(|group| group_color(group, "BackgroundNormal")); + + let accent = groups + .get("General") + .and_then(|group| group.get("AccentColor")) + .and_then(|value| color_list(value)); + + Self { accent, background } + } + + pub(crate) fn into_system( + self, + accessibility: crate::theme::system::AccessibilityPreferences, + portal_accent: Option, + portal_variant: Option, + ) -> SystemTheme { + SystemTheme { + // The portal states the mode on Plasma 5.21+. + // + // Older setups fall back to the scheme's background lightness. + variant: portal_variant + .or(self + .background + .map(crate::theme::ThemeVariant::by_lightness)) + .unwrap_or(crate::theme::ThemeVariant::Light), + accent: self.accent.or(portal_accent), + accessibility, + window_background: None, + source: SourceKind::Kde, + } + } +} + +fn parse_groups(text: &str) -> HashMap<&str, HashMap<&str, &str>> { + let mut groups: HashMap<&str, HashMap<&str, &str>> = HashMap::new(); + let mut section: Option<&str> = None; + + for line in text.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + if let Some(rest) = line.strip_prefix('[') { + section = Some(rest.split(']').next().unwrap_or(rest)); + continue; + } + if let (Some(section), Some((key, value))) = (section, line.split_once('=')) { + groups + .entry(section) + .or_default() + .insert(key.trim(), value.trim()); + } + } + + groups +} + +fn group_color<'a>(group: &'a HashMap<&'a str, &'a str>, key: &str) -> Option { + color_list(group.get(key)?) +} + +/// Parses `r,g,b[,a]` with components in 0..=255. +fn color_list(value: &str) -> Option { + let mut components = value.split(',').map(str::trim); + let red = components.next()?.parse::().ok()?; + let green = components.next()?.parse::().ok()?; + let blue = components.next()?.parse::().ok()?; + let alpha = components.next().and_then(|a| a.parse::().ok()); + if !(0.0..=255.0).contains(&red) + || !(0.0..=255.0).contains(&green) + || !(0.0..=255.0).contains(&blue) + { + return None; + } + let scale = |component: f32| component / 255.0; + + Some(Hsla::from(gpui::Rgba { + r: scale(red), + g: scale(green), + b: scale(blue), + a: alpha.map(|a| a / 255.0).unwrap_or(1.0), + })) +} + +#[cfg(target_os = "linux")] +pub(crate) mod io { + use std::path::PathBuf; + + use super::KdeScheme; + + fn kdeglobals_path() -> Option { + Some( + std::env::var_os("HOME") + .map(PathBuf::from)? + .join(".config/kdeglobals"), + ) + } + + pub(crate) fn read_current() -> Option { + let text = std::fs::read_to_string(kdeglobals_path()?).ok()?; + Some(KdeScheme::parse(&text)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const BREEZE_DARK: &str = "\ +[Colors:Button] +BackgroundAlternate=30,87,116 +BackgroundNormal=41,44,48 +DecorationFocus=61,174,233 +DecorationHover=61,174,233 +ForegroundInactive=161,169,177 +ForegroundNegative=218,68,83 +ForegroundNormal=252,252,252 +ForegroundPositive=39,174,96 + +[Colors:Selection] +BackgroundNormal=61,174,233 +DecorationFocus=61,174,233 +ForegroundNormal=252,252,252 + +[Colors:View] +BackgroundNormal=20,22,24 +BackgroundAlternate=29,31,34 +DecorationFocus=61,174,233 +DecorationHover=61,174,233 +ForegroundInactive=161,169,177 +ForegroundNormal=252,252,252 + +[Colors:Window] +BackgroundNormal=32,35,38 +DecorationFocus=61,174,233 +DecorationHover=61,174,233 +DecorationNormal=49,54,59 +ForegroundInactive=161,169,177 +ForegroundNegative=218,68,83 +ForegroundNormal=252,252,252 +ForegroundPositive=39,174,96 + +[General] +ColorScheme=BreezeDark +Name[de]=Breeze Dunkel + +[KDE] +contrast=4 + +[WM] +activeBackground=39,44,49 +"; + + #[test] + fn breeze_states_the_window_background() { + let scheme = KdeScheme::parse(BREEZE_DARK); + let scale = |component: u32| component as f32 / 255.0; + let background = scheme.background.expect("window background"); + + assert_eq!( + gpui::Rgba::from(background), + gpui::Rgba { + r: scale(32), + g: scale(35), + b: scale(38), + a: 1.0, + } + ); + } + + #[test] + fn localized_and_unrelated_keys_are_ignored() { + let scheme = KdeScheme::parse(BREEZE_DARK); + assert!(scheme.accent.is_none()); + } + + #[test] + fn a_stated_accent_reaches_the_system_theme() { + let text = + "[General]\nAccentColor=255,100,50\n[Colors:Window]\nBackgroundNormal=32,35,38\n"; + let scheme = KdeScheme::parse(text); + let system = scheme.into_system(Default::default(), None, None); + + let accent = system.accent.expect("stated accent"); + assert_eq!( + accent, + Hsla::from(gpui::Rgba { + r: 255.0 / 255.0, + g: 100.0 / 255.0, + b: 50.0 / 255.0, + a: 1.0, + }) + ); + assert_eq!(system.source, SourceKind::Kde); + assert_eq!(system.variant, crate::theme::ThemeVariant::Dark); + } + + #[test] + fn the_portal_accent_covers_the_unset_marker() { + let text = + "[General]\nAccentColor=-1,-1,-1\n[Colors:Window]\nBackgroundNormal=250,250,250\n"; + let scheme = KdeScheme::parse(text); + assert!(scheme.accent.is_none()); + + let portal_accent = Some(Hsla::from(gpui::rgb(0x3584e4))); + let system = scheme.into_system(Default::default(), portal_accent, None); + assert_eq!(system.accent, portal_accent); + assert_eq!(system.variant, crate::theme::ThemeVariant::Light); + } + + #[test] + fn the_portal_mode_beats_the_lightness_derivation() { + let text = "[Colors:Window]\nBackgroundNormal=32,35,38\n"; + let scheme = KdeScheme::parse(text); + let system = scheme.into_system( + Default::default(), + None, + Some(crate::theme::ThemeVariant::Light), + ); + assert_eq!(system.variant, crate::theme::ThemeVariant::Light); + } + + #[test] + fn color_components_outside_0_to_255_are_rejected() { + let above = KdeScheme::parse("[Colors:Window]\nBackgroundNormal=300,20,20\n"); + assert!(above.background.is_none()); + + let below = KdeScheme::parse("[Colors:Window]\nBackgroundNormal=-5,20,20\n"); + assert!(below.background.is_none()); + } +} diff --git a/crates/ui/src/theme/source/linux.rs b/crates/ui/src/theme/source/linux.rs new file mode 100644 index 0000000..94fc3e5 --- /dev/null +++ b/crates/ui/src/theme/source/linux.rs @@ -0,0 +1,330 @@ +//! Linux adapter selection: Omarchy → KDE → portal (GNOME/generic) → +//! fallback, per the plan's detection cascade. Omarchy and KDE state the mode +//! and accent; the portal supplements both with the accessibility flags; +//! `gsettings` covers sessions without a portal. + +use std::path::{Path, PathBuf}; + +use gpui::Hsla; +use notify::{RecursiveMode, Watcher}; + +use super::ThemeSource; +use super::kde; +use super::omarchy; +use super::portal; +use super::signal::ReapplySignal; + +use crate::theme::ThemeVariant; + +use crate::theme::system::{SourceKind, SystemTheme}; + +pub(crate) struct LinuxSource { + backend: Backend, + portal: Option, + gsettings: Option, + file_watcher: Option, + /// Keeps the main-thread channel loop alive. + _signal: Option, +} + +/// Which payload the source reads. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Backend { + Omarchy, + Kde, + Portal, + Fallback, +} + +fn home_dir() -> Option { + std::env::var_os("HOME").map(PathBuf::from) +} + +/// Whether the session runs on Wayland, where compositors state blur protocols. +fn wayland_session() -> bool { + std::env::var_os("WAYLAND_DISPLAY").is_some() + || std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland") +} + +fn detect(home: &Path, portal_reachable: bool, gsettings_reachable: bool) -> Backend { + let omarchy_marker = home + .join(".local/state/omarchy/current/theme.name") + .exists() + || home.join(".local/state/omarchy/current/theme").is_dir() + || home.join(".config/omarchy").is_dir(); + if omarchy_marker { + Backend::Omarchy + } else if home.join(".config/kdeglobals").exists() { + Backend::Kde + } else if portal_reachable || gsettings_reachable { + Backend::Portal + } else { + Backend::Fallback + } +} + +/// What `gsettings` states for GNOME sessions. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct GSettingsSnapshot { + variant: Option, + accent: Option, +} + +fn gsettings_value(args: &[&str]) -> Option { + let output = std::process::Command::new("gsettings") + .args(args) + .output() + .ok()?; + if !output.status.success() { + return None; + } + String::from_utf8(output.stdout).ok() +} + +/// The named accent colors GNOME ships (libadwaita's background variants). +fn accent_rgb(name: &str) -> Option { + let hex = match name { + "blue" => 0x3584e4, + "teal" => 0x2190a4, + "green" => 0x3a944a, + "yellow" => 0xc88800, + "orange" => 0xed5b00, + "red" => 0xe62d42, + "pink" => 0xd56199, + "purple" => 0x9141ac, + "slate" => 0x6f8396, + _ => return None, + }; + Some(Hsla::from(gpui::rgb(hex))) +} + +fn read_gsettings() -> Option { + let variant = gsettings_value(&["get", "org.gnome.desktop.interface", "color-scheme"]) + .and_then(|value| match value.trim().trim_matches('\'') { + "prefer-dark" => Some(ThemeVariant::Dark), + "prefer-light" => Some(ThemeVariant::Light), + _ => None, + }); + + let accent = gsettings_value(&["get", "org.gnome.desktop.interface", "accent-color"]) + .and_then(|value| accent_rgb(value.trim().trim_matches('\''))); + + if variant.is_none() && accent.is_none() { + return None; + } + Some(GSettingsSnapshot { variant, accent }) +} + +pub(crate) fn platform_source() -> Box { + let portal = portal::io::PortalClient::connect(); + let gsettings = read_gsettings(); + + let backend = home_dir() + .map(|home| detect(&home, portal.is_some(), gsettings.is_some())) + .unwrap_or(Backend::Fallback); + + Box::new(LinuxSource { + backend, + portal, + gsettings, + file_watcher: None, + _signal: None, + }) +} + +impl LinuxSource { + fn gnome_snapshot( + &self, + variant: ThemeVariant, + accent: Option, + accessibility: crate::theme::system::AccessibilityPreferences, + ) -> SystemTheme { + SystemTheme { + variant, + accent, + accessibility, + window_background: None, + source: SourceKind::Gnome, + } + } + + fn portal_snapshot( + &self, + variant: ThemeVariant, + portal_appearance: Option, + accessibility: crate::theme::system::AccessibilityPreferences, + ) -> SystemTheme { + if let Some(appearance) = portal_appearance { + return self.gnome_snapshot( + appearance.variant(variant), + appearance.accent, + accessibility, + ); + } + + if let Some(gsettings) = self.gsettings { + return self.gnome_snapshot( + gsettings.variant.unwrap_or(variant), + gsettings.accent, + accessibility, + ); + } + + SystemTheme::fallback(variant) + } +} + +impl ThemeSource for LinuxSource { + fn snapshot(&self, variant: ThemeVariant) -> SystemTheme { + let portal_appearance = self.portal.as_ref().map(|portal| portal.appearance()); + let accessibility = portal_appearance + .map(portal::Appearance::accessibility) + .unwrap_or_default(); + + match self.backend { + Backend::Omarchy => omarchy::io::read_current() + .map(|theme| { + let mut system = theme.into_system(accessibility); + // Hyprland blurs transparent surfaces on its own. + system.window_background = Some(gpui::WindowBackgroundAppearance::Blurred); + system + }) + .unwrap_or_else(|| SystemTheme::fallback(variant)), + Backend::Kde => kde::io::read_current() + .map(|scheme| { + let mut system = scheme.into_system( + accessibility, + portal_appearance.and_then(|appearance| appearance.accent), + portal_appearance.map(|appearance| appearance.variant(variant)), + ); + // KWin states the blur protocols; X11 compositors do not. + system.window_background = + wayland_session().then_some(gpui::WindowBackgroundAppearance::Blurred); + system + }) + .unwrap_or_else(|| SystemTheme::fallback(variant)), + Backend::Portal => self.portal_snapshot(variant, portal_appearance, accessibility), + Backend::Fallback => SystemTheme::fallback(variant), + } + } + + fn install_watchers(&mut self, async_cx: gpui::AsyncApp) { + let signal = ReapplySignal::install(&async_cx); + let file_signal = signal.sender(); + + if let Some(portal) = &self.portal { + portal.spawn_watch(signal.sender()); + } + + // Stored before any fallible step: an early return below + // must not drop and cancel the reapply loop. + self._signal = Some(signal); + + match self.backend { + Backend::Omarchy => { + let Some(current) = omarchy::io::current_dir() else { + return; + }; + + let watcher = notify::recommended_watcher( + move |event: std::result::Result| match event { + Ok(_) => ReapplySignal::poke(&file_signal), + Err(error) => log::warn!("theme: omarchy watch error: {error}"), + }, + ); + + match watcher { + Ok(mut watcher) => { + if let Err(error) = watcher.watch(¤t, RecursiveMode::NonRecursive) { + log::warn!("theme: omarchy watch failed: {error}"); + return; + } + self.file_watcher = Some(watcher); + } + Err(error) => log::warn!("theme: omarchy watcher unavailable: {error}"), + } + } + Backend::Kde => { + let Some(config) = home_dir().map(|home| home.join(".config")) else { + return; + }; + + let watcher = notify::recommended_watcher( + move |event: std::result::Result| match event { + Ok(event) => { + if event.paths.iter().any(|path| { + path.file_name().is_some_and(|name| name == "kdeglobals") + }) { + ReapplySignal::poke(&file_signal); + } + } + Err(error) => log::warn!("theme: kde watch error: {error}"), + }, + ); + match watcher { + Ok(mut watcher) => { + if let Err(error) = watcher.watch(&config, RecursiveMode::NonRecursive) { + log::warn!("theme: kde watch failed: {error}"); + return; + } + self.file_watcher = Some(watcher); + } + Err(error) => log::warn!("theme: kde watcher unavailable: {error}"), + } + } + Backend::Portal | Backend::Fallback => {} + } + } + + fn label(&self) -> &'static str { + match self.backend { + Backend::Omarchy => SourceKind::Omarchy.label(), + Backend::Kde => SourceKind::Kde.label(), + Backend::Portal => SourceKind::Gnome.label(), + Backend::Fallback => SourceKind::Fallback.label(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_detection_cascade_prefers_the_marker_files() { + let home = std::env::temp_dir().join(format!("signed-theme-detect-{}", std::process::id())); + std::fs::create_dir_all(&home).expect("temp home"); + assert_eq!(detect(&home, false, false), Backend::Fallback); + assert_eq!(detect(&home, false, true), Backend::Portal); + + std::fs::create_dir_all(home.join(".config/omarchy")).expect("omarchy marker"); + assert_eq!(detect(&home, false, false), Backend::Omarchy); + assert_eq!(detect(&home, true, true), Backend::Omarchy); + std::fs::remove_dir_all(home.join(".config/omarchy")).expect("remove marker"); + + std::fs::write(home.join(".config/kdeglobals"), "").expect("kdeglobals"); + assert_eq!(detect(&home, false, false), Backend::Kde); + assert_eq!(detect(&home, true, false), Backend::Kde); + std::fs::remove_dir_all(&home).expect("cleanup"); + } + + #[test] + fn the_gnome_snapshot_labels_gnome() { + let source = LinuxSource { + backend: Backend::Portal, + portal: None, + gsettings: None, + file_watcher: None, + _signal: None, + }; + let system = source.gnome_snapshot( + ThemeVariant::Light, + None, + crate::theme::system::AccessibilityPreferences::default(), + ); + + assert_eq!(system.source, SourceKind::Gnome); + assert_eq!(system.variant, ThemeVariant::Light); + assert_eq!(system.accent, None); + } +} diff --git a/crates/ui/src/theme/source/macos.rs b/crates/ui/src/theme/source/macos.rs new file mode 100644 index 0000000..4697c29 --- /dev/null +++ b/crates/ui/src/theme/source/macos.rs @@ -0,0 +1,158 @@ +//! macOS Adapter +//! +//! Reads the system accent and watches the system's color preferences. + +use objc2::rc::Retained; +use objc2::runtime::{AnyObject, NSObject}; +use objc2::{AnyThread, DefinedClass, define_class, msg_send, sel}; +use objc2_app_kit::{ + NSColor, NSColorSpace, NSWorkspace, NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification, +}; +use objc2_foundation::{ + NSDictionary, NSDistributedNotificationCenter, NSKeyValueObservingOptions, NSNotification, + NSNotificationName, NSObjectNSKeyValueObserverRegistration, NSString, NSUserDefaults, +}; + +use super::narrow_component; + +use super::ThemeSource; +use super::signal::ReapplySignal; +use crate::theme::ThemeVariant; +use crate::theme::system::{AccessibilityPreferences, SourceKind, SystemTheme}; + +// An observer that forwards distributed notifications and preference. +define_class!( + #[unsafe(super(NSObject))] + #[ivars = async_channel::Sender<()>] + struct ThemeObserver; + + impl ThemeObserver { + #[unsafe(method(themeDidChange:))] + fn theme_did_change(&self, _notification: &NSNotification) { + ReapplySignal::poke(self.ivars()); + } + + #[unsafe(method(observeValueForKeyPath:ofObject:change:context:))] + fn observe_value_for_key_path( + &self, + _key_path: &NSString, + _object: Option<&AnyObject>, + _change: Option<&NSDictionary>, + _context: *mut core::ffi::c_void, + ) { + ReapplySignal::poke(self.ivars()); + } + } +); + +impl ThemeObserver { + fn new(reapply: async_channel::Sender<()>) -> Retained { + let this = Self::alloc().set_ivars(reapply); + unsafe { msg_send![super(this), init] } + } +} + +#[derive(Default)] +pub(crate) struct MacosSource { + /// The notification centers track, but do not retain, the observer. + _observer: Option>, + /// Keeps the reapply loop alive. + _signal: Option, +} + +impl MacosSource { + fn color_to_hsla(color: &NSColor) -> Option { + let srgb = NSColorSpace::sRGBColorSpace(); + let converted = color.colorUsingColorSpace(&srgb)?; + + Some(gpui::Hsla::from(gpui::Rgba { + r: narrow_component(converted.redComponent()), + g: narrow_component(converted.greenComponent()), + b: narrow_component(converted.blueComponent()), + a: narrow_component(converted.alphaComponent()), + })) + } +} + +impl ThemeSource for MacosSource { + fn snapshot(&self, variant: ThemeVariant) -> SystemTheme { + let workspace = NSWorkspace::sharedWorkspace(); + + let accessibility = AccessibilityPreferences { + high_contrast: workspace.accessibilityDisplayShouldIncreaseContrast(), + reduce_motion: workspace.accessibilityDisplayShouldReduceMotion(), + reduce_transparency: workspace.accessibilityDisplayShouldReduceTransparency(), + }; + + SystemTheme { + variant, + accent: Self::color_to_hsla(&NSColor::controlAccentColor()), + accessibility, + // macOS blurs what is behind the window natively. + window_background: Some(gpui::WindowBackgroundAppearance::Blurred), + source: SourceKind::Macos, + } + } + + /// Re-runs the resolve pipeline when the system's theme changes. + fn install_watchers(&mut self, async_cx: gpui::AsyncApp) { + let signal = ReapplySignal::install(&async_cx); + let observer = ThemeObserver::new(signal.sender()); + + let center = NSDistributedNotificationCenter::defaultCenter(); + for name in [ + "AppleColorPreferencesChangedNotification", + "AppleInterfaceThemeChangedNotification", + ] { + let name = NSNotificationName::from_str(name); + // SAFETY: the observer is retained past every delivery. + unsafe { + center.addObserver_selector_name_object( + &observer, + sel!(themeDidChange:), + Some(&name), + None, + ); + } + } + + let defaults = NSUserDefaults::standardUserDefaults(); + for key in [ + "AppleAccentColor", + "AppleAquaColorVariant", + "AppleInterfaceStyle", + ] { + let key = NSString::from_str(key); + // SAFETY: as above + unsafe { + defaults.addObserver_forKeyPath_options_context( + &observer, + &key, + NSKeyValueObservingOptions::empty(), + core::ptr::null_mut(), + ); + } + } + + let workspace_center = NSWorkspace::sharedWorkspace().notificationCenter(); + let accessibility_name = + unsafe { NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification }; + + // SAFETY: as above. + unsafe { + workspace_center.addObserver_selector_name_object( + &observer, + sel!(themeDidChange:), + Some(accessibility_name), + None, + ); + } + + self._observer = Some(observer); + self._signal = Some(signal); + } + + fn label(&self) -> &'static str { + SourceKind::Macos.label() + } +} diff --git a/crates/ui/src/theme/source/omarchy.rs b/crates/ui/src/theme/source/omarchy.rs new file mode 100644 index 0000000..de14e2a --- /dev/null +++ b/crates/ui/src/theme/source/omarchy.rs @@ -0,0 +1,170 @@ +//! Omarchy adapter: reads the current theme's `colors.toml` from the state +//! directory (`~/.local/state/omarchy/current/theme/`). The parse is pure, +//! so fixtures run on every OS; the IO lives behind the Linux cfg. + +use gpui::Hsla; +use toml::Table; + +use crate::theme::system::{SourceKind, SystemTheme}; +use crate::theme::{AccessibilityPreferences, ThemeVariant}; + +/// The mode and accent Omarchy deploys with the current theme. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct OmarchyTheme { + pub(crate) variant: ThemeVariant, + pub(crate) accent: Option, +} + +impl OmarchyTheme { + pub(crate) fn parse(text: &str) -> Option { + let table = text.parse::().ok()?; + + let background = hex_color(&table, "background")?; + + let variant = table + .get("mode") + .and_then(toml::Value::as_str) + .and_then(mode_variant) + .unwrap_or_else(|| ThemeVariant::by_lightness(background)); + + let accent = hex_color(&table, "accent").or_else(|| hex_color(&table, "color4")); + + Some(Self { variant, accent }) + } + + pub(crate) fn into_system(self, accessibility: AccessibilityPreferences) -> SystemTheme { + SystemTheme { + variant: self.variant, + accent: self.accent, + accessibility, + window_background: None, + source: SourceKind::Omarchy, + } + } +} + +fn mode_variant(mode: &str) -> Option { + match mode { + "dark" => Some(ThemeVariant::Dark), + "light" => Some(ThemeVariant::Light), + _ => None, + } +} + +fn hex_color(table: &Table, key: &str) -> Option { + let value = table.get(key)?.as_str()?; + let digits = value.trim().strip_prefix('#')?; + if digits.len() != 6 { + return None; + } + let hex = u32::from_str_radix(digits, 16).ok()?; + Some(Hsla::from(gpui::rgb(hex))) +} + +#[cfg(target_os = "linux")] +pub(crate) mod io { + use std::path::PathBuf; + + use super::OmarchyTheme; + + fn home_dir() -> Option { + std::env::var_os("HOME").map(PathBuf::from) + } + + /// The directory theme-set swaps on every theme change. + pub(crate) fn current_dir() -> Option { + Some(home_dir()?.join(".local/state/omarchy/current")) + } + + pub(crate) fn read_current() -> Option { + let text = std::fs::read_to_string( + home_dir()?.join(".local/state/omarchy/current/theme/colors.toml"), + ) + .ok()?; + OmarchyTheme::parse(&text) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const TOKYO_NIGHT: &str = "\ +mode = \"dark\" + +accent = \"#7aa2f7\" +selection = \"#292e42\" +muted = \"#414868\" + +background = \"#1a1b26\" +dark_background = \"#13141c\" +darker_background = \"#0e0e14\" +lighter_background = \"#24283b\" + +foreground = \"#a9b1d6\" +dark_foreground = \"#565f89\" + +red = \"#f7768e\" +yellow = \"#e0af68\" +orange = \"#eb927b\" +green = \"#9ece6a\" +"; + + const ANSI_GENERATED: &str = "\ +accent = \"#0060ff\" +selection = \"#c1c8d2\" + +background = \"#e8e8ec\" +foreground = \"#251f32\" + +color0 = \"#e8e8ec\" +color1 = \"#ab2833\" +color2 = \"#3f7c38\" +color3 = \"#8f6235\" +color4 = \"#0060ff\" +color5 = \"#8d439d\" +color6 = \"#3e7d96\" +color7 = \"#251f32\" +color8 = \"#625e6a\" +color9 = \"#cd3d45\" +color10 = \"#44a540\" +color11 = \"#c18a41\" +color12 = \"#278aff\" +color13 = \"#a659b9\" +color14 = \"#4b9fc0\" +color15 = \"#635d6f\" +"; + + #[test] + fn semantic_keys_state_the_mode_and_accent() { + let theme = OmarchyTheme::parse(TOKYO_NIGHT).expect("tokyo-night parses"); + + assert_eq!(theme.variant, ThemeVariant::Dark); + assert_eq!(theme.accent, Some(Hsla::from(gpui::rgb(0x7aa2f7)))); + } + + #[test] + fn ansi_fallback_derives_the_variant_from_the_background() { + let theme = OmarchyTheme::parse(ANSI_GENERATED).expect("ANSI palette parses"); + + assert_eq!(theme.variant, ThemeVariant::Light); + assert_eq!(theme.accent, Some(Hsla::from(gpui::rgb(0x0060ff)))); + } + + #[test] + fn a_stated_mode_beats_the_derivation() { + let text = "mode = \"light\"\naccent = \"#7aa2f7\"\nbackground = \"#1a1b26\"\nforeground = \"#a9b1d6\"\n"; + let theme = OmarchyTheme::parse(text).expect("parses"); + assert_eq!(theme.variant, ThemeVariant::Light); + } + + #[test] + fn the_system_snapshot_keeps_only_mode_and_accent() { + let theme = OmarchyTheme::parse(TOKYO_NIGHT).expect("parses"); + let system = theme.into_system(Default::default()); + + assert_eq!(system.variant, ThemeVariant::Dark); + assert_eq!(system.accent, theme.accent); + assert_eq!(system.source, SourceKind::Omarchy); + } +} diff --git a/crates/ui/src/theme/source/portal.rs b/crates/ui/src/theme/source/portal.rs new file mode 100644 index 0000000..1b7b14a --- /dev/null +++ b/crates/ui/src/theme/source/portal.rs @@ -0,0 +1,230 @@ +//! The xdg-desktop-portal Settings reader (`org.freedesktop.appearance`). +//! GTK and GNOME toolkits take these values from the same place, so this is +//! the canonical source on generic Linux. The value mapping is pure and +//! fixture-tested on every OS; the DBus client lives behind the Linux cfg. + +use gpui::Hsla; + +use super::narrow_component; + +use crate::theme::{ThemeVariant, system::AccessibilityPreferences}; + +/// The raw portal values, already converted off the DBus wire types. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct AppearanceValues { + /// 0 = no preference, 1 = prefer dark, 2 = prefer light. + pub(crate) color_scheme: Option, + /// The `accent-color` sRGB tuple, each component in 0..1. + pub(crate) accent_rgb: Option<(f64, f64, f64)>, + /// 0 = normal, 1 = higher. + pub(crate) contrast: Option, + /// 0 = no preference, 1 = reduced. + pub(crate) reduced_motion: Option, +} + +impl AppearanceValues { + pub(crate) fn decode(self) -> Appearance { + Appearance { + color_scheme: self.color_scheme, + accent: self.accent_rgb.map(|(r, g, b)| { + Hsla::from(gpui::Rgba { + r: narrow_component(r), + g: narrow_component(g), + b: narrow_component(b), + a: 1.0, + }) + }), + contrast: self.contrast.unwrap_or(0), + reduced_motion: self.reduced_motion.unwrap_or(0), + } + } +} + +/// What the portal states under `org.freedesktop.appearance`. +/// +/// Per the portal spec, unknown values read as unset. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct Appearance { + pub(crate) color_scheme: Option, + pub(crate) accent: Option, + pub(crate) contrast: u32, + pub(crate) reduced_motion: u32, +} + +impl Appearance { + pub(crate) fn variant(&self, no_preference: ThemeVariant) -> ThemeVariant { + match self.color_scheme { + Some(1) => ThemeVariant::Dark, + Some(2) => ThemeVariant::Light, + _ => no_preference, + } + } + + pub(crate) fn accessibility(self) -> AccessibilityPreferences { + AccessibilityPreferences { + high_contrast: self.contrast >= 1, + reduce_motion: self.reduced_motion >= 1, + reduce_transparency: false, + } + } +} + +#[cfg(target_os = "linux")] +pub(crate) mod io { + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + + use zbus::blocking::{Connection, Proxy}; + use zbus::zvariant::OwnedValue; + + use super::{Appearance, AppearanceValues}; + + type AppearanceCache = Arc>; + + const SERVICE: &str = "org.freedesktop.portal.Desktop"; + const PATH: &str = "/org/freedesktop/portal/desktop"; + const INTERFACE: &str = "org.freedesktop.portal.Settings"; + const NAMESPACE: &str = "org.freedesktop.appearance"; + + pub(crate) struct PortalClient { + appearance: AppearanceCache, + } + + impl PortalClient { + /// Reads the appearance once. + pub(crate) fn connect() -> Option { + let proxy = settings_proxy(Connection::session().ok()?)?; + let appearance = Arc::new(Mutex::new(read_appearance(&proxy)?)); + Some(Self { appearance }) + } + + /// The most recently read appearance. + pub(crate) fn appearance(&self) -> Appearance { + // A watch-thread panic must not crash the UI thread. + let cache = self.appearance.lock(); + *cache.unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Forwards portal `SettingChanged` events to the reapply signal from a dedicated thread. + pub(crate) fn spawn_watch(&self, reapply_signal: async_channel::Sender<()>) { + let appearance = self.appearance.clone(); + + std::thread::spawn(move || { + let Some(connection) = Connection::session().ok() else { + log::warn!("theme: portal watch skipped, no session bus"); + return; + }; + + let Some(proxy) = settings_proxy(connection) else { + log::warn!("theme: portal watch skipped, settings proxy unavailable"); + return; + }; + + let Ok(signals) = proxy.receive_signal("SettingChanged") else { + log::warn!("theme: portal watch skipped, signal subscription failed"); + return; + }; + + for message in signals { + let Ok((namespace, _key, _value)) = + message.body().deserialize::<(String, String, OwnedValue)>() + else { + continue; + }; + + if namespace != NAMESPACE { + continue; + } + + match read_appearance(&proxy) { + Some(latest) => { + let mut cache = appearance + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + *cache = latest; + super::super::signal::ReapplySignal::poke(&reapply_signal); + } + None => log::warn!("theme: portal read failed on SettingChanged"), + } + } + }); + } + } + + fn settings_proxy(connection: Connection) -> Option> { + Proxy::new(&connection, SERVICE, PATH, INTERFACE).ok() + } + + fn read_appearance(proxy: &Proxy<'static>) -> Option { + let values: HashMap> = + proxy.call("ReadAll", &([NAMESPACE],)).ok()?; + + let namespace = values.get(NAMESPACE)?; + let field = |key: &str| namespace.get(key); + + Some( + AppearanceValues { + color_scheme: field("color-scheme") + .and_then(|value| u32::try_from(value.clone()).ok()), + accent_rgb: field("accent-color") + .and_then(|value| <(f64, f64, f64)>::try_from(value.clone()).ok()), + contrast: field("contrast").and_then(|value| u32::try_from(value.clone()).ok()), + reduced_motion: field("reduced-motion") + .and_then(|value| u32::try_from(value.clone()).ok()), + } + .decode(), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_full_appearance_decodes() { + let appearance = AppearanceValues { + color_scheme: Some(1), + accent_rgb: Some((0.48, 0.62, 0.89)), + contrast: Some(0), + reduced_motion: Some(0), + } + .decode(); + + assert_eq!( + appearance.variant(crate::theme::ThemeVariant::Light), + crate::theme::ThemeVariant::Dark + ); + let accent = appearance.accent.expect("accent decodes"); + let rgba = gpui::Rgba::from(accent); + assert!(rgba.b > rgba.r); + } + + #[test] + fn no_preference_yields_the_callers_variant() { + let appearance = AppearanceValues { + color_scheme: Some(0), + ..AppearanceValues::default() + } + .decode(); + assert_eq!( + appearance.variant(crate::theme::ThemeVariant::Light), + crate::theme::ThemeVariant::Light + ); + } + + #[test] + fn accessibility_flags_forward() { + let accessibility = AppearanceValues { + contrast: Some(1), + reduced_motion: Some(1), + ..AppearanceValues::default() + } + .decode() + .accessibility(); + + assert!(accessibility.high_contrast); + assert!(accessibility.reduce_motion); + assert!(!accessibility.reduce_transparency); + } +} diff --git a/crates/ui/src/theme/source/signal.rs b/crates/ui/src/theme/source/signal.rs new file mode 100644 index 0000000..16dd700 --- /dev/null +++ b/crates/ui/src/theme/source/signal.rs @@ -0,0 +1,41 @@ +//! Wakes the main-thread resolve pipeline from watcher threads, which hold +//! no gpui context (the pinned gpui's `AsyncApp` is not `Send`). + +use gpui::{AsyncApp, Task}; + +pub(crate) struct ReapplySignal { + sender: async_channel::Sender<()>, + _task: Task<()>, +} + +impl ReapplySignal { + pub(crate) fn install(async_cx: &AsyncApp) -> Self { + let executor = async_cx.foreground_executor().clone(); + let async_cx = async_cx.clone(); + + let (sender, events) = async_channel::unbounded::<()>(); + + let task = executor.spawn(async move { + while events.recv().await.is_ok() { + async_cx.update(crate::theme::reapply); + } + }); + + Self { + sender, + _task: task, + } + } + + /// A clone for a watcher thread to poke the pipeline with. + pub(crate) fn sender(&self) -> async_channel::Sender<()> { + self.sender.clone() + } + + /// Pokes the pipeline from a thread holding a [`Self::sender`] clone. + pub(crate) fn poke(sender: &async_channel::Sender<()>) { + if let Err(error) = sender.try_send(()) { + log::warn!("theme: reapply signal failed: {error}"); + } + } +} diff --git a/crates/ui/src/theme/source/windows.rs b/crates/ui/src/theme/source/windows.rs new file mode 100644 index 0000000..87a6f9b --- /dev/null +++ b/crates/ui/src/theme/source/windows.rs @@ -0,0 +1,208 @@ +//! Windows 11 adapter: WinRT `UISettings` accent and background with a +//! `Personalize` registry fallback, watched through `ColorValuesChanged`, +//! `AdvancedEffectsEnabledChanged`, and `HighContrastChanged`. + +use windows::Foundation::TypedEventHandler; +use windows::UI::ViewManagement::{AccessibilitySettings, UIColorType, UISettings}; +use windows::Win32::Foundation::RPC_E_CHANGED_MODE; +use windows::Win32::System::Com::{COINIT_APARTMENTTHREADED, CoInitializeEx}; +use windows::core::IInspectable; + +use super::ThemeSource; +use super::signal::ReapplySignal; +use crate::theme::ThemeVariant; +use crate::theme::system::{AccessibilityPreferences, SourceKind, SystemTheme}; + +/// The `Personalize` registry values and the OS build number. +#[derive(Clone, Copy, Debug, Default)] +struct RegistrySettings { + apps_use_light_theme: Option, + enable_transparency: Option, + current_build: Option, +} + +impl RegistrySettings { + fn read() -> Self { + let personalize = || { + windows_registry::CURRENT_USER + .open(r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize") + }; + let current_version = || { + windows_registry::LOCAL_MACHINE.open(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion") + }; + Self { + apps_use_light_theme: personalize() + .and_then(|key| key.get_u32("AppsUseLightTheme")) + .ok() + .map(|value| value != 0), + enable_transparency: personalize() + .and_then(|key| key.get_u32("EnableTransparency")) + .ok() + .map(|value| value != 0), + current_build: current_version() + .and_then(|key| key.get_string("CurrentBuildNumber")) + .ok() + .and_then(|build| build.parse::().ok()), + } + } +} + +pub(crate) struct WindowsSource { + ui_settings: UISettings, + accessibility_settings: AccessibilitySettings, + registry: RegistrySettings, + /// Keeps the main-thread channel loop alive. + _signal: Option, +} + +pub(crate) fn platform_source() -> Box { + // SAFETY: WinRT activation requires COM on this thread; the STA matches + // the UI thread's message pump, and RPC_E_CHANGED_MODE means COM is + // already initialized in another apartment. + let initialized = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) }; + + if initialized.is_err() && initialized != RPC_E_CHANGED_MODE { + log::error!("theme: COM initialization failed: {initialized:?}"); + } + + match WindowsSource::new() { + Some(source) => Box::new(source), + None => { + log::warn!("theme: Windows system theme unavailable; using fallback"); + Box::new(super::fallback::FallbackSource) + } + } +} + +impl WindowsSource { + fn new() -> Option { + let ui_settings = match UISettings::new() { + Ok(ui_settings) => ui_settings, + Err(error) => { + log::warn!("theme: UISettings unavailable: {error}"); + return None; + } + }; + + let accessibility_settings = match AccessibilitySettings::new() { + Ok(accessibility_settings) => accessibility_settings, + Err(error) => { + log::warn!("theme: AccessibilitySettings unavailable: {error}"); + return None; + } + }; + + Some(Self { + ui_settings, + accessibility_settings, + registry: RegistrySettings::read(), + _signal: None, + }) + } + + fn color(&self, kind: UIColorType) -> Option { + let color = self.ui_settings.GetColorValue(kind).ok()?; + Some(gpui::Hsla::from(gpui::Rgba { + r: color.R as f32 / 255.0, + g: color.G as f32 / 255.0, + b: color.B as f32 / 255.0, + a: color.A as f32 / 255.0, + })) + } + + fn accessibility(&self) -> AccessibilityPreferences { + AccessibilityPreferences { + high_contrast: self.accessibility_settings.HighContrast().unwrap_or(false), + // Windows states animations separately in Win32; not read yet. + reduce_motion: false, + reduce_transparency: self + .registry + .enable_transparency + .map(|enabled| !enabled) + .unwrap_or(false), + } + } + + /// The native backdrop: Mica on Windows 11, acrylic on Windows 10 1809+. + fn window_material(&self) -> Option { + match self.registry.current_build { + // 22621: Windows 11 22H2, where the DWM backdrop types exist. + Some(build) if build >= 22621 => Some(gpui::WindowBackgroundAppearance::MicaBackdrop), + // 17763: Windows 10 1809, where acrylic blur-behind exists. + Some(build) if build >= 17763 => Some(gpui::WindowBackgroundAppearance::Blurred), + _ => None, + } + } +} + +impl ThemeSource for WindowsSource { + fn snapshot(&self, variant: ThemeVariant) -> SystemTheme { + let accent = self.color(UIColorType::Accent); + let background = self.color(UIColorType::Background); + + let variant = background + .map(ThemeVariant::by_lightness) + .or(self.registry.apps_use_light_theme.map(|light| { + if light { + ThemeVariant::Light + } else { + ThemeVariant::Dark + } + })) + .unwrap_or(variant); + + SystemTheme { + variant, + accent, + accessibility: self.accessibility(), + window_background: self.window_material(), + source: SourceKind::Windows, + } + } + + fn install_watchers(&mut self, async_cx: gpui::AsyncApp) { + let signal = ReapplySignal::install(&async_cx); + let color_signal = signal.sender(); + let color_handler = TypedEventHandler::::new(move |_, _| { + ReapplySignal::poke(&color_signal); + Ok(()) + }); + + if let Err(error) = self.ui_settings.ColorValuesChanged(&color_handler) { + log::warn!("theme: color change watch failed: {error}"); + } + + let effects_signal = signal.sender(); + let effects_handler = TypedEventHandler::::new(move |_, _| { + ReapplySignal::poke(&effects_signal); + Ok(()) + }); + + if let Err(error) = self + .ui_settings + .AdvancedEffectsEnabledChanged(&effects_handler) + { + log::warn!("theme: advanced effects watch failed: {error}"); + } + + let contrast_signal = signal.sender(); + let contrast_handler = + TypedEventHandler::::new(move |_, _| { + ReapplySignal::poke(&contrast_signal); + Ok(()) + }); + + if let Err(error) = self + .accessibility_settings + .HighContrastChanged(&contrast_handler) + { + log::warn!("theme: high contrast watch failed: {error}"); + } + + self._signal = Some(signal); + } + + fn label(&self) -> &'static str { + SourceKind::Windows.label() + } +} diff --git a/crates/ui/src/theme/system.rs b/crates/ui/src/theme/system.rs new file mode 100644 index 0000000..7334575 --- /dev/null +++ b/crates/ui/src/theme/system.rs @@ -0,0 +1,69 @@ +//! The normalized snapshot a platform adapter produces. + +use gpui::{Hsla, WindowBackgroundAppearance}; + +use crate::theme::ThemeVariant; + +/// Accessibility preferences read from the OS, forwarded into resolution. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct AccessibilityPreferences { + pub high_contrast: bool, + pub reduce_motion: bool, + pub reduce_transparency: bool, +} + +/// Which adapter produced a [`SystemTheme`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[cfg_attr(not(any(target_os = "linux", target_os = "windows")), allow(dead_code))] +pub enum SourceKind { + #[default] + Fallback, + Macos, + Omarchy, + Kde, + Gnome, + Windows, +} + +impl SourceKind { + pub fn label(self) -> &'static str { + match self { + Self::Fallback => "neutral fallback", + Self::Macos => "macOS (NSColor)", + Self::Omarchy => "Omarchy (colors.toml)", + Self::Kde => "KDE (kdeglobals)", + Self::Gnome => "GNOME (portal)", + Self::Windows => "Windows 11 (UISettings)", + } + } + + /// Overlay scrollbars hide while idle on macOS, GNOME, and Omarchy. + /// + /// Windows and KDE keep theirs drawn. + pub fn scrollbar_autohide(self) -> bool { + matches!(self, Self::Macos | Self::Omarchy | Self::Gnome) + } +} + +/// A normalized snapshot of the running system's theme. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SystemTheme { + pub variant: ThemeVariant, + pub accent: Option, + pub accessibility: AccessibilityPreferences, + /// The window material the platform natively applies, if any. + pub window_background: Option, + pub source: SourceKind, +} + +impl SystemTheme { + pub fn fallback(variant: ThemeVariant) -> Self { + Self { + variant, + accent: None, + accessibility: AccessibilityPreferences::default(), + window_background: None, + source: SourceKind::Fallback, + } + } +} diff --git a/crates/ui/src/theme/typography.rs b/crates/ui/src/theme/typography.rs new file mode 100644 index 0000000..18d4caf --- /dev/null +++ b/crates/ui/src/theme/typography.rs @@ -0,0 +1,209 @@ +//! One type ladder shared by every platform, scaled by the theme's root font +//! size. + +use gpui::{App, FontWeight, Pixels, Styled, px}; + +use crate::theme::ActiveTheme; + +/// The shared ladder at a 16px root: size, line height, then weight. +const LADDER: [Rung; 11] = [ + (24.0, 32.0, FontWeight::SEMIBOLD), + (20.0, 28.0, FontWeight::SEMIBOLD), + (18.0, 24.0, FontWeight::SEMIBOLD), + (16.0, 24.0, FontWeight::SEMIBOLD), + (14.0, 20.0, FontWeight::SEMIBOLD), + (16.0, 24.0, FontWeight::NORMAL), + (14.0, 20.0, FontWeight::NORMAL), + (14.0, 20.0, FontWeight::NORMAL), + (13.0, 18.0, FontWeight::NORMAL), + (12.0, 16.0, FontWeight::NORMAL), + (12.0, 16.0, FontWeight::MEDIUM), +]; + +/// One rung: size and line height at a 16px root, then the weight. +type Rung = (f32, f32, FontWeight); + +/// A role in the unified type ladder. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum TextRole { + /// The largest heading — hero panels, greeters, welcome screens. + LargeTitle, + /// Window and page titles. + Title, + /// Section titles. + Title2, + /// Sub-section and dialog headings. + Title3, + /// Body-sized emphasis — list row titles, group labels. + Headline, + /// Control labels and reading text. + Body, + /// Slightly smaller body text. + Callout, + /// Secondary lines under a body row. + Subheadline, + /// Hints and auxiliary notes. + Footnote, + /// Timestamps, badges, and dense metadata. + Caption, + /// Emphasized captions. + Caption2, +} + +/// One role as it paints: size, line height, and weight. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TypeMetrics { + pub size: Pixels, + pub line_height: Pixels, + pub weight: FontWeight, +} + +/// The unified type ladder, resolved at the theme's root font size. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Typography { + pub large_title: TypeMetrics, + pub title: TypeMetrics, + pub title2: TypeMetrics, + pub title3: TypeMetrics, + pub headline: TypeMetrics, + pub body: TypeMetrics, + pub callout: TypeMetrics, + pub subheadline: TypeMetrics, + pub footnote: TypeMetrics, + pub caption: TypeMetrics, + pub caption2: TypeMetrics, +} + +impl Typography { + pub(crate) fn resolve(root_font_size: Pixels) -> Self { + let scale = root_font_size / px(16.); + + let metrics = |(size, line_height, weight): Rung| TypeMetrics { + size: px(size) * scale, + line_height: px(line_height) * scale, + weight, + }; + + let [ + large_title, + title, + title2, + title3, + headline, + body, + callout, + subheadline, + footnote, + caption, + caption2, + ] = LADDER.map(metrics); + + Self { + large_title, + title, + title2, + title3, + headline, + body, + callout, + subheadline, + footnote, + caption, + caption2, + } + } + + /// The metrics for `role`. + pub fn get(&self, role: TextRole) -> TypeMetrics { + match role { + TextRole::LargeTitle => self.large_title, + TextRole::Title => self.title, + TextRole::Title2 => self.title2, + TextRole::Title3 => self.title3, + TextRole::Headline => self.headline, + TextRole::Body => self.body, + TextRole::Callout => self.callout, + TextRole::Subheadline => self.subheadline, + TextRole::Footnote => self.footnote, + TextRole::Caption => self.caption, + TextRole::Caption2 => self.caption2, + } + } +} + +/// Paints a [`TextRole`] from the resolved theme, on anything styled. +pub trait Typeset: Styled + Sized { + /// Sizes, leads, and weights the element as `role`. + fn typeset(self, role: TextRole, cx: &App) -> Self { + let theme = cx.theme(); + let metrics = theme.typography.get(role); + self.text_size(metrics.size) + .line_height(metrics.line_height) + .font_weight(metrics.weight) + } +} + +impl Typeset for E {} + +#[cfg(test)] +mod tests { + use super::*; + + fn typography(root_font_size: f32) -> Typography { + Typography::resolve(px(root_font_size)) + } + + #[test] + fn the_unified_ladder_matches_the_base_contract() { + let typography = typography(16.0); + let expected = [ + (TextRole::LargeTitle, 24.0, 32.0, FontWeight::SEMIBOLD), + (TextRole::Title, 20.0, 28.0, FontWeight::SEMIBOLD), + (TextRole::Title2, 18.0, 24.0, FontWeight::SEMIBOLD), + (TextRole::Title3, 16.0, 24.0, FontWeight::SEMIBOLD), + (TextRole::Headline, 14.0, 20.0, FontWeight::SEMIBOLD), + (TextRole::Body, 16.0, 24.0, FontWeight::NORMAL), + (TextRole::Callout, 14.0, 20.0, FontWeight::NORMAL), + (TextRole::Subheadline, 14.0, 20.0, FontWeight::NORMAL), + (TextRole::Footnote, 13.0, 18.0, FontWeight::NORMAL), + (TextRole::Caption, 12.0, 16.0, FontWeight::NORMAL), + (TextRole::Caption2, 12.0, 16.0, FontWeight::MEDIUM), + ]; + for (role, size, line_height, weight) in expected { + assert_eq!( + typography.get(role), + TypeMetrics { + size: px(size), + line_height: px(line_height), + weight, + }, + "{role:?}" + ); + } + } + + #[test] + fn the_ladder_scales_from_a_16px_root() { + let base = typography(16.0); + let raised = typography(20.0); + for role in [ + TextRole::LargeTitle, + TextRole::Title, + TextRole::Title2, + TextRole::Title3, + TextRole::Headline, + TextRole::Body, + TextRole::Callout, + TextRole::Subheadline, + TextRole::Footnote, + TextRole::Caption, + TextRole::Caption2, + ] { + let base = base.get(role); + let raised = raised.get(role); + assert!((raised.size - base.size * 1.25).abs() < px(0.01)); + assert!((raised.line_height - base.line_height * 1.25).abs() < px(0.01)); + assert_eq!(raised.weight, base.weight); + } + } +} diff --git a/crates/ui/src/utils.rs b/crates/ui/src/utils.rs new file mode 100644 index 0000000..c244aab --- /dev/null +++ b/crates/ui/src/utils.rs @@ -0,0 +1,171 @@ +use crate::theme::{ActiveTheme as _, FOCUS_RING_ALPHA, FOCUS_RING_SPREAD}; +use gpui::prelude::FluentBuilder as _; +use gpui::{ + App, Bounds, BoxShadow, Div, ElementId, FocusHandle, Global, Hsla, IntoElement, Pixels, + Refineable as _, StatefulInteractiveElement, StyleRefinement, Styled, Window, WindowId, div, + px, +}; +use std::collections::HashMap; + +/// A row whose children center on the cross axis. +#[must_use] +pub fn h_flex() -> Div { + div().flex().flex_row().items_center() +} + +/// A column whose children stack on the main axis. +#[must_use] +pub fn v_flex() -> Div { + div().flex().flex_col() +} + +/// Logs the error and yields the success value, if any. +pub trait ResultLogErr { + /// Logs the error and yields the success value, if any. + fn log_err(self) -> Option; +} + +impl ResultLogErr for Result { + fn log_err(self) -> Option { + match self { + Ok(value) => Some(value), + Err(error) => { + log::warn!("{error}"); + None + } + } + } +} + +/// Extensions over [`Styled`], shared by the components. +pub trait StyledExt: Styled + Sized { + #[must_use] + fn refine_style(mut self, style: &StyleRefinement) -> Self { + self.style().refine(style); + self + } +} + +impl StyledExt for E {} + +/// Returns a focus handle for the given element ID. +pub fn focus_handle(id: &ElementId, window: &mut Window, cx: &mut App) -> FocusHandle { + window + .with_element_namespace(id.clone(), |window| { + window.use_keyed_state("focus-handle", cx, |_, cx| cx.focus_handle()) + }) + .read(cx) + .clone() +} + +/// The painted bounds of elements that tooltips anchor to, per window and element id. +/// Entries are never evicted: bounds are bounded by live windows, though long-lived processes minting dynamic per-item ids could accumulate. +#[derive(Default)] +struct AnchorBoundsRegistry(HashMap<(WindowId, ElementId), Bounds>); + +impl Global for AnchorBoundsRegistry {} + +impl AnchorBoundsRegistry { + fn record(&mut self, window: WindowId, id: ElementId, bounds: Bounds) { + self.0.insert((window, id), bounds); + } + + fn get(&self, window: WindowId, id: &ElementId) -> Option> { + self.0.get(&(window, id.clone())).copied() + } +} + +/// The last bounds an element painted at, in the given window. +pub fn anchor_bounds(window: WindowId, id: &ElementId, cx: &App) -> Option> { + cx.try_global::() + .and_then(|registry| registry.get(window, id)) +} + +/// A canvas prepaint closure recording the element's painted bounds. +pub fn record_anchor_bounds( + id: ElementId, +) -> impl Fn(Bounds, &mut Window, &mut App) + 'static { + move |bounds, window, cx| { + let window_id = window.window_handle().window_id(); + cx.default_global::() + .record(window_id, id.clone(), bounds); + } +} + +/// Returns a focus ring shadow with the given color at half ink. +pub fn focus_ring(color: Hsla) -> Vec { + vec![ + BoxShadow::new(px(0.), px(0.), color.alpha(FOCUS_RING_ALPHA)) + .spread_radius(FOCUS_RING_SPREAD), + ] +} + +/// The next selectable row in the direction, or `None` at the ends. +pub fn adjacent_selectable( + selectable: &[usize], + selected: Option, + forward: bool, +) -> Option { + if forward { + selectable + .iter() + .copied() + .find(|index| Some(*index) > selected) + } else { + selectable + .iter() + .copied() + .rev() + .find(|index| Some(*index) < selected) + } +} + +/// Whether the given key is a vertical navigation key. +pub fn nav_key(selectable: &[usize], selected: Option, key: &str, select: S) -> bool +where + S: FnOnce(Option), +{ + let target = match key { + "down" => adjacent_selectable(selectable, selected, true), + "up" => adjacent_selectable(selectable, selected, false), + "home" => selectable.first().copied(), + "end" => selectable.last().copied(), + _ => return false, + }; + if let Some(next) = target + && Some(next) != selected + { + select(Some(next)); + } + true +} + +/// A selectable row's label and icon color. +pub fn selectable_label_color(cx: &App, selected: bool, disabled: bool) -> Hsla { + let theme = cx.theme(); + if disabled { + theme.colors.muted_foreground + } else if selected { + theme.colors.primary_foreground + } else { + theme.colors.foreground + } +} + +/// A selectable row's background. +#[must_use] +pub fn paint_selectable_row(cx: &App, row: R, selected: bool, disabled: bool) -> R +where + R: IntoElement + Styled + StatefulInteractiveElement, +{ + let theme = cx.theme(); + row.map(|row| { + if disabled { + row + } else if selected { + row.bg(theme.ramps.primary.base) + } else { + row.hover(|row| row.bg(theme.colors.muted)) + } + }) +} diff --git a/crates/ui/tests/panel.rs b/crates/ui/tests/panel.rs new file mode 100644 index 0000000..2fe2f3a --- /dev/null +++ b/crates/ui/tests/panel.rs @@ -0,0 +1,152 @@ +//! The panel row: the main island fills the window; splitting makes two +//! half-width islands with a drag divider that resizes them. + +use gpui::{ + AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, Modifiers, MouseButton, + MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _, Render, SharedString, + Styled as _, TestAppContext, VisualTestContext, Window, div, point, px, size, +}; +use ui::layout::panel::{Panel, PanelRow}; +use ui::theme::Theme; + +const WINDOW_WIDTH: f32 = 1024.0; +const WINDOW_HEIGHT: f32 = 768.0; + +/// A full-size marker the tests measure through its debug selector. +struct TagView { + selector: SharedString, +} + +impl TagView { + fn new(selector: &'static str) -> Self { + Self { + selector: SharedString::from(selector), + } + } +} + +impl Render for TagView { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + let selector = self.selector.clone(); + div() + .debug_selector(move || selector.to_string()) + .size_full() + } +} + +impl Panel for TagView {} + +struct PanelHarness { + split: bool, + main: Entity, + split_view: Entity, +} + +impl Render for PanelHarness { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + let panel = PanelRow::new("panel-harness").main(self.main.clone()); + let panel = if self.split { + panel.split(self.split_view.clone()) + } else { + panel + }; + div().size_full().child(panel) + } +} + +fn panel_window(cx: &mut TestAppContext, split: bool) -> VisualTestContext { + let (main, split_view) = cx.update(|cx| { + Theme::init(cx); + let main = cx.new(|_| TagView::new("panel-test-main")); + let split = cx.new(|_| TagView::new("panel-test-split")); + (main, split) + }); + + let window = cx.open_window(size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), |_, _| { + PanelHarness { + split, + main, + split_view, + } + }); + let cx = VisualTestContext::from_window(window.into(), cx); + cx.run_until_parked(); + cx +} + +#[gpui::test] +fn main_fills_the_row_without_a_split(cx: &mut TestAppContext) { + let mut cx = panel_window(cx, false); + + let main = cx + .debug_bounds("panel-test-main") + .expect("main panel laid out"); + + // The row's padding and the island's inset are all main gives up. + assert!(main.size.width >= px(WINDOW_WIDTH - 40.0)); + assert!(main.size.height >= px(WINDOW_HEIGHT - 40.0)); + assert!(main.origin.x >= px(0.0)); +} + +#[gpui::test] +fn split_makes_two_half_width_panels(cx: &mut TestAppContext) { + let mut cx = panel_window(cx, true); + + let main = cx + .debug_bounds("panel-test-main") + .expect("main panel laid out"); + let split = cx + .debug_bounds("panel-test-split") + .expect("split panel laid out"); + + // Both islands share the row at half width, main first, and neither + // leaves the viewport. The divider's width lands on the remainder pane. + assert!( + (main.size.width - split.size.width).abs() <= px(10.0), + "main={:?} split={:?}", + main.size.width, + split.size.width + ); + assert!(main.size.width < px(WINDOW_WIDTH / 2.0)); + assert!(main.right() <= split.left()); + assert!(split.right() <= px(WINDOW_WIDTH)); + assert!(main.size.height >= px(WINDOW_HEIGHT - 40.0)); +} + +#[gpui::test] +fn dragging_the_divider_resizes_the_panels(cx: &mut TestAppContext) { + let mut cx = panel_window(cx, true); + + let before = cx + .debug_bounds("panel-test-main") + .expect("main panel laid out"); + + // Press the divider between the islands and drag it 100px to the right. + let handle = cx.debug_bounds("resize-handle").expect("divider laid out"); + let seam = point(handle.center().x, px(400.0)); + cx.simulate_event(MouseDownEvent { + position: seam, + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + first_mouse: false, + }); + cx.simulate_event(MouseMoveEvent { + position: point(seam.x + px(100.0), seam.y), + pressed_button: Some(MouseButton::Left), + modifiers: Modifiers::default(), + }); + cx.simulate_event(MouseUpEvent { + position: point(seam.x + px(100.0), seam.y), + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + }); + cx.run_until_parked(); + + // The main panel grew by the drag; the split panel gave up the space. + let after = cx + .debug_bounds("panel-test-main") + .expect("main panel laid out after the drag"); + assert_eq!(after.size.width, before.size.width + px(100.0)); +} diff --git a/crates/ui/tests/sizing.rs b/crates/ui/tests/sizing.rs new file mode 100644 index 0000000..8d7b440 --- /dev/null +++ b/crates/ui/tests/sizing.rs @@ -0,0 +1,59 @@ +use gpui::{ + Context, IntoElement, ParentElement as _, Render, Styled as _, TestAppContext, + VisualTestContext, Window, div, px, size, +}; +use ui::button::Button; +use ui::common::Sizable as _; +use ui::dropdown_menu::DropdownMenu; +use ui::icons::IconRole; +use ui::menu::MenuItem; +use ui::theme::Theme; + +struct Harness; + +impl Render for Harness { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + div() + .size_full() + .flex() + .flex_col() + .gap_2() + .child( + Button::new("height-probe") + .label("Probe") + .debug_selector(|| "height-probe".to_string()), + ) + .child( + Button::new("xsmall-height-probe") + .label("Probe") + .xsmall() + .debug_selector(|| "xsmall-height-probe".to_string()), + ) + .child( + DropdownMenu::new("icon-only-dropdown") + .icon(IconRole::More) + .accessibility_label("More actions") + .items(|_, _| vec![MenuItem::new("One")]), + ) + } +} + +#[gpui::test] +fn buttons_render_at_their_token_heights(cx: &mut TestAppContext) { + cx.update(Theme::init); + let window = cx.open_window(size(px(400.), px(400.)), |_, _| Harness); + let mut cx = VisualTestContext::from_window(window.into(), cx); + cx.run_until_parked(); + + let medium = cx.debug_bounds("height-probe").expect("button laid out"); + let xsmall = cx + .debug_bounds("xsmall-height-probe") + .expect("xsmall button laid out"); + let icon_only = cx + .debug_bounds("icon-only-dropdown-trigger") + .expect("icon-only dropdown laid out"); + + assert_eq!(medium.size.height, px(32.0)); + assert_eq!(xsmall.size.height, px(20.0)); + assert_eq!(icon_only.size, size(px(32.0), px(32.0))); +} diff --git a/crates/ui/tests/tabs.rs b/crates/ui/tests/tabs.rs new file mode 100644 index 0000000..c85478e --- /dev/null +++ b/crates/ui/tests/tabs.rs @@ -0,0 +1,259 @@ +//! Grouped tabs: same-kind tabs collapse into one chip that opens a popover +//! listing the members; picking one selects it by its original index. Tabs +//! also drag onto each other to reorder, and pinned tabs wear the active +//! treatment at all times. + +use std::cell::RefCell; +use std::rc::Rc; + +use gpui::{ + Context, IntoElement, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, + ParentElement as _, Render, Styled as _, TestAppContext, VisualTestContext, Window, div, point, + px, size, +}; +use ui::data::tabs::{Tab, Tabs, TabsVariant}; +use ui::theme::Theme; + +struct StripHarness { + changed: Rc>>, + reordered: Rc>>, + pinned: bool, +} + +impl Render for StripHarness { + fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { + let changed = self.changed.clone(); + let reordered = self.reordered.clone(); + div().size_full().child( + Tabs::new("strip") + .variant(TabsVariant::Pill) + .draggable(true) + .tabs({ + let pinned = self.pinned; + move |_, _| { + vec![ + Tab::new("a", "Alpha").kind("Kind"), + Tab::new("b", "Beta").kind("Kind"), + Tab::new("c", "Gamma"), + Tab::new("d", "Delta").kind("Lone").pinned(pinned), + ] + } + }) + .on_change(move |index, _, _| changed.borrow_mut().push(index)) + .on_reorder(move |from, to, _, _| reordered.borrow_mut().push((from, to))), + ) + } +} + +fn strip_window( + cx: &mut TestAppContext, + changed: Rc>>, + reordered: Rc>>, + pinned: bool, +) -> VisualTestContext { + cx.update(Theme::init); + let window = cx.open_window(size(px(800.), px(600.)), |_, _| StripHarness { + changed, + reordered, + pinned, + }); + let cx = VisualTestContext::from_window(window.into(), cx); + cx.run_until_parked(); + cx +} + +#[gpui::test] +fn same_kind_tabs_collapse_into_one_group(cx: &mut TestAppContext) { + let mut cx = strip_window( + cx, + Rc::new(RefCell::new(Vec::new())), + Rc::new(RefCell::new(Vec::new())), + false, + ); + + assert!( + cx.debug_bounds("strip-group-Kind").is_some(), + "two same-kind tabs draw one group chip" + ); + assert!( + cx.debug_bounds("strip-tab-Alpha").is_none(), + "grouped members do not draw inline" + ); + assert!(cx.debug_bounds("strip-tab-Beta").is_none()); + + // A tab outside any two-member kind group draws itself, kinded or not. + assert!(cx.debug_bounds("strip-tab-Gamma").is_some()); + assert!(cx.debug_bounds("strip-tab-Delta").is_some()); + assert!( + cx.debug_bounds("strip-group-Lone").is_none(), + "a lone kinded tab is not grouped" + ); +} + +#[gpui::test] +fn picking_a_group_member_selects_it(cx: &mut TestAppContext) { + let changed = Rc::new(RefCell::new(Vec::new())); + let mut cx = strip_window( + cx, + changed.clone(), + Rc::new(RefCell::new(Vec::new())), + false, + ); + + let chip = cx + .debug_bounds("strip-group-Kind") + .expect("group chip drawn"); + cx.simulate_click(chip.center(), Modifiers::none()); + cx.run_until_parked(); + + let beta = cx + .debug_bounds("strip-tab-Beta") + .expect("the popover lists the members"); + cx.simulate_click(beta.center(), Modifiers::none()); + cx.run_until_parked(); + + assert_eq!( + changed.borrow().as_slice(), + &[1], + "picking a member reports its original index" + ); + assert!( + cx.debug_bounds("strip-tab-Beta").is_none(), + "a selection dismisses the popover" + ); +} + +#[gpui::test] +fn dragging_a_tab_onto_another_reorders_it(cx: &mut TestAppContext) { + let reordered = Rc::new(RefCell::new(Vec::new())); + let mut cx = strip_window( + cx, + Rc::new(RefCell::new(Vec::new())), + reordered.clone(), + false, + ); + + // The strip's group chip hides Alpha and Beta; Gamma draws inline, so the + // drag runs from Gamma onto Delta: moving Gamma before Delta is a no-op + // shift — use Delta onto Gamma instead, reporting (3, 2). + let gamma = cx.debug_bounds("strip-tab-Gamma").expect("gamma drawn"); + let delta = cx.debug_bounds("strip-tab-Delta").expect("delta drawn"); + + cx.simulate_event(MouseDownEvent { + position: delta.center(), + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + first_mouse: false, + }); + cx.simulate_event(MouseMoveEvent { + position: gamma.center(), + pressed_button: Some(MouseButton::Left), + modifiers: Modifiers::default(), + }); + cx.simulate_event(MouseUpEvent { + position: gamma.center(), + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + }); + cx.run_until_parked(); + + assert_eq!( + reordered.borrow().as_slice(), + &[(3, 2)], + "dropping Delta before Gamma reports the move" + ); +} + +#[gpui::test] +fn dropping_a_tab_back_on_itself_reorders_nothing(cx: &mut TestAppContext) { + let reordered = Rc::new(RefCell::new(Vec::new())); + let mut cx = strip_window( + cx, + Rc::new(RefCell::new(Vec::new())), + reordered.clone(), + false, + ); + + let gamma = cx.debug_bounds("strip-tab-Gamma").expect("gamma drawn"); + cx.simulate_event(MouseDownEvent { + position: gamma.center(), + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + first_mouse: false, + }); + cx.simulate_event(MouseMoveEvent { + position: gamma.center() + point(px(2.0), px(0.0)), + pressed_button: Some(MouseButton::Left), + modifiers: Modifiers::default(), + }); + cx.simulate_event(MouseUpEvent { + position: gamma.center(), + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + }); + cx.run_until_parked(); + + assert!( + reordered.borrow().is_empty(), + "a self-drop is a no-op, not a reorder" + ); +} + +#[gpui::test] +fn a_vertical_drag_cancels_the_reorder(cx: &mut TestAppContext) { + let reordered = Rc::new(RefCell::new(Vec::new())); + let mut cx = strip_window( + cx, + Rc::new(RefCell::new(Vec::new())), + reordered.clone(), + false, + ); + + // Drag Delta straight down past the axis lock, then back onto Gamma: + // the gesture locked vertical, so the drop must not reorder. + let delta = cx.debug_bounds("strip-tab-Delta").expect("delta drawn"); + let gamma = cx.debug_bounds("strip-tab-Gamma").expect("gamma drawn"); + let start = delta.center(); + + cx.simulate_event(MouseDownEvent { + position: start, + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + first_mouse: false, + }); + // The drag engages a few pixels down; land the origin there. + cx.simulate_event(MouseMoveEvent { + position: start + point(px(0.0), px(3.0)), + pressed_button: Some(MouseButton::Left), + modifiers: Modifiers::default(), + }); + // Past the axis lock, vertically: dy 30 vs dx 0. + cx.simulate_event(MouseMoveEvent { + position: start + point(px(0.0), px(30.0)), + pressed_button: Some(MouseButton::Left), + modifiers: Modifiers::default(), + }); + // Back over Gamma — still canceled. + cx.simulate_event(MouseMoveEvent { + position: gamma.center(), + pressed_button: Some(MouseButton::Left), + modifiers: Modifiers::default(), + }); + cx.simulate_event(MouseUpEvent { + position: gamma.center(), + button: MouseButton::Left, + modifiers: Modifiers::default(), + click_count: 1, + }); + cx.run_until_parked(); + + assert!( + reordered.borrow().is_empty(), + "a vertical drag never reorders, even dropped on another tab" + ); +} diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml index 48ce876..5f8f541 100644 --- a/desktop/Cargo.toml +++ b/desktop/Cargo.toml @@ -27,7 +27,6 @@ icons = [ ] [dependencies] -assets = { path = "../crates/assets" } metadata = { path = "../crates/metadata" } paths = { path = "../crates/paths" } settings = { path = "../crates/settings" } @@ -36,7 +35,7 @@ signed_state = { path = "../crates/signed_state" } gpui.workspace = true gpui_platform.workspace = true -gpui-native-kit.workspace = true +ui = { path = "../crates/ui" } reqwest_client.workspace = true tracing.workspace = true tracing-subscriber.workspace = true diff --git a/desktop/src/main.rs b/desktop/src/main.rs index e5ba880..e92bcc5 100644 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -1,10 +1,10 @@ use std::sync::Arc; -use assets::Assets; use gpui::*; -use gpui_native_kit::theme::{ActiveTheme as _, Theme}; use gpui_platform::application; use settings::SettingsStore; +use ui::Assets; +use ui::theme::{ActiveTheme as _, Theme}; actions!(signed, [Quit]); @@ -15,9 +15,7 @@ fn main() { .with_assets(Assets) .with_http_client(Arc::new(reqwest_client::ReqwestClient::new())) .run(move |cx| { - gpui_native_kit::init(cx); - gpui_native_kit::editor::code::bind_code_view_keys(cx); - gpui_native_kit::editor::markdown::bind_text_view_keys(cx); + ui::init(cx); cx.bind_keys([ KeyBinding::new("cmd-q", Quit, None), diff --git a/docs/gpui-native-kit-gaps.md b/docs/ui-gaps.md similarity index 57% rename from docs/gpui-native-kit-gaps.md rename to docs/ui-gaps.md index fee3e0d..1a09cd9 100644 --- a/docs/gpui-native-kit-gaps.md +++ b/docs/ui-gaps.md @@ -1,25 +1,25 @@ -# gpui-native-kit gaps +# ui gaps -Known Signed features the kit does not currently support. Recorded instead of -modifying the kit or reimplementing a parallel mechanism. +Known Signed features `ui` does not currently support. Recorded instead of +modifying it or reimplementing a parallel mechanism. 1. **Custom themes.** `Signed Light`/`Signed Dark`, theme registry names, font - sizes, radii, focus ring, and shadows are removed. The kit derives colors, + sizes, radii, focus ring, and shadows are removed. `ui` derives colors, radii, fonts, and chrome from the OS; `AppearanceMode` is preserved through `set_mode_override`/`follow_system`. 2. **Tab bar navigation.** The previous/next tab buttons and - `tab_bar.hide_navigation_buttons` are removed; the kit tab strip has none. + `tab_bar.hide_navigation_buttons` are removed; `ui` tab strip has none. 3. **Traffic-light placement.** Custom macOS traffic-light position and the 44px - tab bar are removed. The kit uses `theme.titlebar_height` and a fixed 78px + tab bar are removed. `ui` uses `theme.titlebar_height` and a fixed 78px traffic-light pad. -4. **Virtual list.** The kit has no data-driven virtual list. Screens keep +4. **Virtual list.** `ui` has no data-driven virtual list. Screens keep `gpui::uniform_list` for fixed-height lists and `ScrollArea` for the Inbox. -5. **Editable code field.** The kit code view is read-only and supports four +5. **Editable code field.** `ui` code view is read-only and supports four grammars. Signed only previews files read-only; other extensions render as plain text. -6. **Hunk-only diffs.** Kit `DiffViewState` needs the full old and new texts; +6. **Hunk-only diffs.** The `ui` `DiffViewState` needs the full old and new texts; `CommitDiff` carries hunks only. The custom hunk rows are retained. -7. **Tree data.** The kit tree is flat with caller-managed expansion. +7. **Tree data.** `ui` tree is flat with caller-managed expansion. Folder rows use `IconRole::Folder` and file rows use `IconRole::File`. 8. **Dynamic dock panels.** `DockState` has no unregister or `open_view` API. Per-repository/per-entity panels register a builder keyed by a unique id and @@ -28,13 +28,9 @@ modifying the kit or reimplementing a parallel mechanism. 9. **Dialogs.** Dialogs are elements mounted at the window root; there is no `window.open_dialog`, dialog stack, or non-dismissible option. A single-slot `DialogHost` is used, and the passphrase dialog ignores dismiss requests. -10. **Notifications.** The kit toast shows one toast at a time; backend errors +10. **Notifications.** `ui` toast shows one toast at a time; backend errors queue but only the current toast is visible. 11. **Segmented badges.** `Segmented` has no badge slot; filter counts fold into labels. 12. **Combobox trigger.** `Combobox` has no custom trigger renderer; branch/tag selectors lose the leading git icon and custom caret. -13. **Icons.** The kit provides common platform roles plus Settings, Help, - Refresh, File, Folder, and similar glyphs. App-specific git, issue, and - pull-request glyphs remain in `assets::CustomIconName` through `IconNamed`; - kit icons are unpainted unless given a color.