Skip to content

AI-native design editor. Open-source Figma alternative.

feat(updater): show download progress while installing an update

Danila Poyarkova029e267c20f
diff --git a/.storybook/preview.ts b/.storybook/preview.ts
index 5526701d5..93c8fc29c 100644
--- a/.storybook/preview.ts
+++ b/.storybook/preview.ts
@@ -50,7 +50,7 @@ const preview: Preview = {
'Overlays',
['Dialog'],
'Feedback',
- ['Placeholder'],
+ ['Placeholder', 'Toast'],
'Layout',
['Panel Foundation']
],
diff --git a/AGENTS.md b/AGENTS.md
index fff9dcd10..5aed249b6 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -83,6 +83,8 @@ App dialogs compose the Reka-backed components under `src/components/ui/dialog/`
Prefer `dev:portless`, especially in worktrees. It assigns branch-specific app and `mcp.open-pencil` sibling URLs with isolated runtime discovery. Use fixed-port `dev` only for Playwright, Tauri, and Dev Container flows.
+A fresh worktree needs `bun install` and `bun run build:packages` before docs, Storybook, or any workflow that resolves workspace subpath exports; without the package builds those resolve to missing `packages/*/dist` targets.
+
Browser tests use the canonical `playwright.config.ts`; do not create task-specific config copies or server runners. Managed runs must start the intended checkout, with server reuse explicitly opted into only for local development, never baseline comparisons or CI. Isolate the app URL and MCP endpoint, CORS origin, socket, and discovery path together. Playwright owns Vite; the existing Vite automation plugin owns MCP startup and cleanup; browser fixtures own interactions, not server processes. See `packages/docs/development/testing.md` for configuration and commands.
## Releases & CI
@@ -282,14 +284,14 @@ Keep responsibilities distinct: engine tests cover state contracts, Playwright b
### Component structure
- Generic UI is grouped by component family under `src/components/ui/{button,input,select,toggle,dialog,panel,binding,feedback,overlay,menu,paint}/`; do not create a folder named after a single component. Theme families mirror these under `src/theme/`; feature themes remain separate. Use explicit imports without old-path forwarding shims.
-- Colocate `ComponentName.stories.ts` with `ComponentName.vue`. Multipart composition stories may use a descriptive family name. Preserve explicit Storybook titles and exported story names during file moves; keep default playgrounds static and give interaction flows named stories. Use deterministic fixtures and colocated Vue demos for substantial markup.
+- Colocate `ComponentName.stories.ts` with `ComponentName.vue`. Multipart composition stories may use a descriptive family name. Preserve explicit Storybook titles and exported story names during file moves; keep default playgrounds static and give interaction flows named stories. Prefer inline story fixtures for small app-local states. Use colocated `examples/<Variant>.vue` SFCs for substantial templates or fixtures that need SFC template/slot typing, including app-only fixtures; shared SDK examples use the same convention (see below). Story templates compile at runtime, so they must be plain JavaScript — no type assertions or other TypeScript syntax — and `icon-lucide-*` tags do not resolve there; import icons from `~icons/...` and register them.
- `src/components/ui/**` is store-free app design-system code; feature controls stay in their domain.
- SDK property primitives remain controlled/editor-agnostic. Compose property rows from `PanelGrid`, `PanelFieldGroup`, `PanelItemRow`, and `PropertyItemRow`; use `BindableValue`, `FillRoot`, and `FillSwatch` rather than rebuilding binding/picker infrastructure.
- Do not add automated tests or snapshot baselines for simple CSS-only UI changes, including spacing, sizing, colors, and responsive breakpoints. Verify these visually instead. Keep automated coverage focused on behavior and contracts; the separate canvas-renderer visual coverage requirement still applies.
- Prefer accessible role/name, label, then text in tests. Use scoped `data-slot` anatomy or semantic attributes (`data-property`, `data-command`, `data-node-id`) when needed; reserve `data-test-id` for integration boundaries and never add test-hook props.
- Use Reka UI primitives and typed Tailwind Variants themes under `src/theme/**`; merge per-instance `ui` slot overrides, expose `class` for single-root components, and do not add one-off class props. Use `UI` casing in type names.
- Bind visual state through semantic `data-*` attributes; Steiger rejects template-time `use*UI()`, visual-state utility branches, and raw SVG app icons.
-- Storybook is the internal state workshop; VitePress is canonical public SDK documentation. Reuse colocated demos, derive API tables from source/JSDoc, and keep examples valid against public exports.
+- Storybook is the internal state workshop; VitePress is canonical public SDK documentation. Derive API tables from source/JSDoc and keep examples valid against public exports. An example shared by Storybook and a docs page lives in `packages/vue/src/primitives/<Primitive>/examples/<Variant>.vue` (PascalCase variant name, e.g. `States.vue`); the story renders it and the docs page imports it with `#vue/primitives/...`. Do not render Storybook stories inside VitePress pages: `@storybook/vue3` assigns `window.STORYBOOK_ENV` on import so it cannot be server-rendered, the docs bundle ships runtime-only Vue so runtime templates silently fail, and a client-only embed drops examples from the prerendered HTML while adding the Storybook preview runtime and `storybook/test` to the published docs.
- Prefer models/events/props over imperative slot actions except for explicitly renderless action primitives. Use VueUse for DOM refs/focus.
- App wrappers around SDK primitives use shared UI helpers rather than scattered raw classes.
- Commands use `packages/vue/src/editor/commands/registry.ts` for shortcuts, bindings, and menu IDs. Store portable tokens (`MOD+D`) and format them at render time; labels/translations never contain shortcuts.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4a75e2cb5..c30e3b142 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,10 @@
- Choose PPTX in the Export panel's format list, alongside PNG, JPG, WEBP, SVG, and PDF.
+### Changed
+
+- Show download progress with a percentage and transferred size while installing a desktop update, instead of an indeterminate message that lasted until the restart.
+
### Fixed
- Show what to update instead of a blank window when the browser or system WebView is too old, naming the detected macOS, Safari, Chrome, Edge, Firefox, WebKitGTK, or WebView2 version and linking a prefilled bug report, and explain a failed start the same way (#744).
diff --git a/packages/docs/programmable/sdk/api/components/bindable-value.md b/packages/docs/programmable/sdk/api/components/bindable-value.md
index bd256fd9f..c5e47ee38 100644
--- a/packages/docs/programmable/sdk/api/components/bindable-value.md
+++ b/packages/docs/programmable/sdk/api/components/bindable-value.md
@@ -4,7 +4,7 @@ description: Provider-driven value binding primitives for custom editor controls
---
<script setup lang="ts">
-import BindableValueDemo from '#vue/primitives/BindableValue/demo/BindableValueDemo.vue'
+import BindableValueStates from '#vue/primitives/BindableValue/examples/States.vue'
import { data } from './bindable-value.data'
</script>
@@ -14,7 +14,7 @@ BindableValue composes variable or token binding with fields without coupling th
specific editor store. Applications supply a `BindingProvider`; NumberField consumes the context
automatically when nested beneath `BindableValueRoot`.
-<BindableValueDemo />
+<BindableValueStates />
## Anatomy
diff --git a/packages/docs/programmable/sdk/api/components/channel-slider.md b/packages/docs/programmable/sdk/api/components/channel-slider.md
index dc8acbe2f..778879e06 100644
--- a/packages/docs/programmable/sdk/api/components/channel-slider.md
+++ b/packages/docs/programmable/sdk/api/components/channel-slider.md
@@ -4,7 +4,7 @@ description: Accessible scalar channel slider for OkHCL controls.
---
<script setup lang="ts">
-import ColorFillDemo from '#vue/primitives/Fill/demo/ColorFillDemo.vue'
+import FillStates from '#vue/primitives/Fill/examples/States.vue'
import { data } from './channel-slider.data'
</script>
@@ -14,7 +14,7 @@ import { data } from './channel-slider.data'
Slider while accepting an arbitrary scalar channel. OpenPencil uses it only for OkHCL channels;
standard RGB, HSL, and HSB controls should use Reka `ColorSlider` directly.
-<ColorFillDemo />
+<FillStates />
## Anatomy
diff --git a/packages/docs/programmable/sdk/api/components/fill-root.md b/packages/docs/programmable/sdk/api/components/fill-root.md
index aed1db37b..41a4b882c 100644
--- a/packages/docs/programmable/sdk/api/components/fill-root.md
+++ b/packages/docs/programmable/sdk/api/components/fill-root.md
@@ -4,7 +4,7 @@ description: Headless fill category state and conversion actions.
---
<script setup lang="ts">
-import ColorFillDemo from '#vue/primitives/Fill/demo/ColorFillDemo.vue'
+import FillStates from '#vue/primitives/Fill/examples/States.vue'
import { data } from './fill-root.data'
</script>
@@ -13,7 +13,7 @@ import { data } from './fill-root.data'
`FillRoot` owns solid, gradient, and image category state without owning a popover or visual swatch.
Compose it around the picker surface appropriate for your application.
-<ColorFillDemo />
+<FillStates />
Its default slot exposes the current fill, category, transparency, swatch background, and grouped
conversion actions. Category changes emit immutable `Fill` values and are no-ops when the requested
diff --git a/packages/docs/programmable/sdk/api/components/fill-swatch.md b/packages/docs/programmable/sdk/api/components/fill-swatch.md
index a891d4bc2..0fc7bd2ab 100644
--- a/packages/docs/programmable/sdk/api/components/fill-swatch.md
+++ b/packages/docs/programmable/sdk/api/components/fill-swatch.md
@@ -4,7 +4,6 @@ description: Binding-aware semantic preview for solid, gradient, and image fills
---
<script setup lang="ts">
-import ColorFillDemo from '#vue/primitives/Fill/demo/ColorFillDemo.vue'
import { data } from './fill-swatch.data'
</script>
diff --git a/packages/docs/programmable/sdk/api/components/number-field.md b/packages/docs/programmable/sdk/api/components/number-field.md
index 23901af72..c10257532 100644
--- a/packages/docs/programmable/sdk/api/components/number-field.md
+++ b/packages/docs/programmable/sdk/api/components/number-field.md
@@ -4,7 +4,7 @@ description: Headless numeric field primitives with scrubbing, expressions, and
---
<script setup lang="ts">
-import NumberFieldDemo from '#vue/primitives/NumberField/demo/NumberFieldDemo.vue'
+import NumberFieldStates from '#vue/primitives/NumberField/examples/States.vue'
import { data } from './number-field.data'
</script>
@@ -13,7 +13,7 @@ import { data } from './number-field.data'
The NumberField family provides a headless numeric control with pointer scrubbing, mixed values,
keyboard stepping, safe arithmetic expressions, units, trailing actions, and binding-aware state.
-<NumberFieldDemo />
+<NumberFieldStates />
## Anatomy
diff --git a/packages/docs/programmable/sdk/api/components/property-section.md b/packages/docs/programmable/sdk/api/components/property-section.md
index 0a7c99123..59c609dcf 100644
--- a/packages/docs/programmable/sdk/api/components/property-section.md
+++ b/packages/docs/programmable/sdk/api/components/property-section.md
@@ -4,7 +4,7 @@ description: Headless collapsible anatomy for property-panel sections.
---
<script setup lang="ts">
-import PropertyPrimitivesDemo from '#vue/primitives/PropertySection/demo/PropertyPrimitivesDemo.vue'
+import PropertySectionStates from '#vue/primitives/PropertySection/examples/States.vue'
import { data } from './property-section.data'
</script>
@@ -13,7 +13,7 @@ import { data } from './property-section.data'
PropertySection supplies collapsible section anatomy and canonical open, empty, and disabled state
attributes without imposing presentation.
-<PropertyPrimitivesDemo />
+<PropertySectionStates />
## Anatomy
diff --git a/packages/vue/src/i18n/locales/de/updates.json b/packages/vue/src/i18n/locales/de/updates.json
index a116473b7..982fdea23 100644
--- a/packages/vue/src/i18n/locales/de/updates.json
+++ b/packages/vue/src/i18n/locales/de/updates.json
@@ -4,6 +4,8 @@
"available": "OpenPencil {version} ist verfügbar.",
"installPrompt": "Jetzt herunterladen und installieren? Die App wird nach der Installation neu gestartet.",
"downloading": "OpenPencil {version} wird heruntergeladen",
+ "downloadProgress": "{percent} % · {downloaded} von {total}",
+ "downloadProgressUnknown": "{downloaded} heruntergeladen",
"installedTitle": "Update installiert",
"installed": "OpenPencil {version} wurde installiert{size}. Neustart jetzt.",
"unavailable": "Updates sind noch nicht verfügbar. Veröffentliche zuerst ein signiertes Release mit latest.json.",
diff --git a/packages/vue/src/i18n/locales/es/updates.json b/packages/vue/src/i18n/locales/es/updates.json
index dbf6bd005..afd9711eb 100644
--- a/packages/vue/src/i18n/locales/es/updates.json
+++ b/packages/vue/src/i18n/locales/es/updates.json
@@ -4,6 +4,8 @@
"available": "Está disponible la versión {version} de OpenPencil.",
"installPrompt": "¿Descargar e instalar ahora? La app se reiniciará después de instalar la actualización.",
"downloading": "Descargando OpenPencil {version}",
+ "downloadProgress": "{percent} % · {downloaded} de {total}",
+ "downloadProgressUnknown": "{downloaded} descargados",
"installedTitle": "Actualización instalada",
"installed": "Se ha instalado la versión {version} de OpenPencil{size}. Reiniciando ahora...",
"unavailable": "Las actualizaciones aún no están disponibles. Publica primero una versión firmada con latest.json.",
diff --git a/packages/vue/src/i18n/locales/fr/updates.json b/packages/vue/src/i18n/locales/fr/updates.json
index 3a3364ccb..a145984c3 100644
--- a/packages/vue/src/i18n/locales/fr/updates.json
+++ b/packages/vue/src/i18n/locales/fr/updates.json
@@ -4,6 +4,8 @@
"available": "OpenPencil {version} est disponible.",
"installPrompt": "Télécharger et installer maintenant ? L’app redémarrera après l’installation de la mise à jour.",
"downloading": "Téléchargement d’OpenPencil {version}",
+ "downloadProgress": "{percent} % · {downloaded} sur {total}",
+ "downloadProgressUnknown": "{downloaded} téléchargés",
"installedTitle": "Mise à jour installée",
"installed": "OpenPencil {version} a été installé{size}. Redémarrage maintenant.",
"unavailable": "Les mises à jour ne sont pas encore disponibles. Publiez d’abord une version signée avec latest.json.",
diff --git a/packages/vue/src/i18n/locales/it/updates.json b/packages/vue/src/i18n/locales/it/updates.json
index a1cae2ce0..31a6b7966 100644
--- a/packages/vue/src/i18n/locales/it/updates.json
+++ b/packages/vue/src/i18n/locales/it/updates.json
@@ -4,6 +4,8 @@
"available": "OpenPencil {version} è disponibile.",
"installPrompt": "Scaricare e installare ora? L’app verrà riavviata dopo l’installazione dell’aggiornamento.",
"downloading": "Download di OpenPencil {version}",
+ "downloadProgress": "{percent}% · {downloaded} di {total}",
+ "downloadProgressUnknown": "{downloaded} scaricati",
"installedTitle": "Aggiornamento installato",
"installed": "OpenPencil {version} è stato installato{size}. Riavvio in corso.",
"unavailable": "Gli aggiornamenti non sono ancora disponibili. Pubblica prima una release firmata con latest.json.",
diff --git a/packages/vue/src/i18n/locales/ja/updates.json b/packages/vue/src/i18n/locales/ja/updates.json
index 7899a8921..ae8e5f747 100644
--- a/packages/vue/src/i18n/locales/ja/updates.json
+++ b/packages/vue/src/i18n/locales/ja/updates.json
@@ -4,6 +4,8 @@
"available": "OpenPencil のバージョン {version} が利用可能です。",
"installPrompt": "今すぐダウンロードしてインストールしますか?インストール後、アプリが再起動します。",
"downloading": "OpenPencil {version} をダウンロード中",
+ "downloadProgress": "{percent}% · {downloaded} / {total}",
+ "downloadProgressUnknown": "{downloaded} をダウンロード済み",
"installedTitle": "アップデート完了",
"installed": "OpenPencil のバージョン {version} がインストールされました{size}。再起動しています...",
"unavailable": "アップデートはまだ利用できません。まず、latest.json を含む署名付きバージョンを公開してください。",
diff --git a/packages/vue/src/i18n/locales/pl/updates.json b/packages/vue/src/i18n/locales/pl/updates.json
index 13ae459b7..2f3ad3c2c 100644
--- a/packages/vue/src/i18n/locales/pl/updates.json
+++ b/packages/vue/src/i18n/locales/pl/updates.json
@@ -4,6 +4,8 @@
"available": "OpenPencil {version} jest dostępny.",
"installPrompt": "Pobrać i zainstalować teraz? Aplikacja uruchomi się ponownie po zainstalowaniu aktualizacji.",
"downloading": "Pobieranie OpenPencil {version}",
+ "downloadProgress": "{percent}% · {downloaded} z {total}",
+ "downloadProgressUnknown": "Pobrano {downloaded}",
"installedTitle": "Aktualizacja zainstalowana",
"installed": "OpenPencil {version} został zainstalowany{size}. Ponowne uruchamianie.",
"unavailable": "Aktualizacje nie są jeszcze dostępne. Najpierw opublikuj podpisane wydanie z latest.json.",
diff --git a/packages/vue/src/i18n/locales/ru/updates.json b/packages/vue/src/i18n/locales/ru/updates.json
index 730789223..03c4117ee 100644
--- a/packages/vue/src/i18n/locales/ru/updates.json
+++ b/packages/vue/src/i18n/locales/ru/updates.json
@@ -4,6 +4,8 @@
"available": "Доступен OpenPencil {version}.",
"installPrompt": "Скачать и установить сейчас? После установки обновления приложение перезапустится.",
"downloading": "Загрузка OpenPencil {version}",
+ "downloadProgress": "{percent}% · {downloaded} из {total}",
+ "downloadProgressUnknown": "Загружено {downloaded}",
"installedTitle": "Обновление установлено",
"installed": "OpenPencil {version} установлен{size}. Перезапуск.",
"unavailable": "Обновления пока недоступны. Сначала опубликуйте подписанный релиз с latest.json.",
diff --git a/packages/vue/src/i18n/locales/zh-cn/updates.json b/packages/vue/src/i18n/locales/zh-cn/updates.json
index 7e32fc3bb..7c2a7d28a 100644
--- a/packages/vue/src/i18n/locales/zh-cn/updates.json
+++ b/packages/vue/src/i18n/locales/zh-cn/updates.json
@@ -4,6 +4,8 @@
"available": "OpenPencil {version} 可用。",
"installPrompt": "现在下载并安装吗?安装更新后应用将重新启动。",
"downloading": "正在下载 OpenPencil {version}",
+ "downloadProgress": "{percent}% · {downloaded} / {total}",
+ "downloadProgressUnknown": "已下载 {downloaded}",
"installedTitle": "更新已安装",
"installed": "OpenPencil {version} 已安装{size}。正在重新启动。",
"unavailable": "更新暂不可用。请先发布包含 latest.json 的已签名版本。",
diff --git a/packages/vue/src/i18n/messages/updates.ts b/packages/vue/src/i18n/messages/updates.ts
index de0609391..d948919f5 100644
--- a/packages/vue/src/i18n/messages/updates.ts
+++ b/packages/vue/src/i18n/messages/updates.ts
@@ -8,6 +8,8 @@ export const updatesMessageDefaults = {
available: params('OpenPencil {version} is available.'),
installPrompt: 'Download and install it now? The app will restart after the update is installed.',
downloading: params('Downloading OpenPencil {version}'),
+ downloadProgress: params('{percent}% · {downloaded} of {total}'),
+ downloadProgressUnknown: params('{downloaded} downloaded'),
installedTitle: 'Update installed',
installed: params('OpenPencil {version} was installed{size}. Restarting now.'),
unavailable: 'Updates are not available yet. Publish a signed release with latest.json first.',
diff --git a/packages/vue/src/primitives/BindableValue/BindableValue.stories.ts b/packages/vue/src/primitives/BindableValue/BindableValue.stories.ts
index 94c8d4970..c20ac9e43 100644
--- a/packages/vue/src/primitives/BindableValue/BindableValue.stories.ts
+++ b/packages/vue/src/primitives/BindableValue/BindableValue.stories.ts
@@ -1,12 +1,11 @@
import type { Meta, StoryObj } from '@storybook/vue3-vite'
import { expect, userEvent, within } from 'storybook/test'
-import BindableValueDemo from './demo/BindableValueDemo.vue'
-import ModeEditDemo from './demo/ModeEditDemo.vue'
+import BindableValueStates from './examples/States.vue'
const meta = {
title: 'Vue SDK/Primitives/BindableValue',
- component: BindableValueDemo,
+ component: BindableValueStates,
tags: ['autodocs'],
parameters: {
docs: {
@@ -16,15 +15,11 @@ const meta = {
}
}
}
-} satisfies Meta<typeof BindableValueDemo>
+} satisfies Meta<typeof BindableValueStates>
export default meta
type Story = StoryObj<typeof meta>
-export const ModeEditing: Story = {
- render: () => ({ components: { ModeEditDemo }, template: '<ModeEditDemo />' })
-}
-
export const StateMatrix: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement)
diff --git a/packages/vue/src/primitives/BindableValue/BindableValueModeEdit.stories.ts b/packages/vue/src/primitives/BindableValue/BindableValueModeEdit.stories.ts
new file mode 100644
index 000000000..b9ad2d704
--- /dev/null
+++ b/packages/vue/src/primitives/BindableValue/BindableValueModeEdit.stories.ts
@@ -0,0 +1,16 @@
+import type { Meta, StoryObj } from '@storybook/vue3-vite'
+
+import ModeEdit from './examples/ModeEdit.vue'
+
+// Kept apart from BindableValue.stories.ts: this example builds a real editor, and the
+// docs pages render the lighter state matrix, so the engine must not share its module.
+const meta = {
+ title: 'Vue SDK/Primitives/BindableValue'
+} satisfies Meta
+
+export default meta
+type Story = StoryObj<typeof meta>
+
+export const ModeEditing: Story = {
+ render: () => ({ components: { ModeEdit }, template: '<ModeEdit />' })
+}
diff --git a/packages/vue/src/primitives/BindableValue/demo/ModeEditDemo.vue b/packages/vue/src/primitives/BindableValue/examples/ModeEdit.vue
similarity index 98%
rename from packages/vue/src/primitives/BindableValue/demo/ModeEditDemo.vue
rename to packages/vue/src/primitives/BindableValue/examples/ModeEdit.vue
index d4e5e8e7e..cd54e5253 100644
--- a/packages/vue/src/primitives/BindableValue/demo/ModeEditDemo.vue
+++ b/packages/vue/src/primitives/BindableValue/examples/ModeEdit.vue
@@ -9,7 +9,7 @@ import BindableValueRoot from '#vue/primitives/BindableValue/BindableValueRoot.v
const editor = createEditor()
const page = editor.graph.getPages()[0]
-if (!page) throw new Error('Missing demo page')
+if (!page) throw new Error('Missing example page')
const collection = editor.graph.createCollection('Spacing')
editor.graph.addMode(collection.id, 'large', 'Large')
editor.graph.addMode(collection.id, 'untouched', 'Untouched')
diff --git a/packages/vue/src/primitives/BindableValue/demo/BindableValueDemo.vue b/packages/vue/src/primitives/BindableValue/examples/States.vue
similarity index 96%
rename from packages/vue/src/primitives/BindableValue/demo/BindableValueDemo.vue
rename to packages/vue/src/primitives/BindableValue/examples/States.vue
index c094b9e58..6f53854eb 100644
--- a/packages/vue/src/primitives/BindableValue/demo/BindableValueDemo.vue
+++ b/packages/vue/src/primitives/BindableValue/examples/States.vue
@@ -20,7 +20,7 @@ const variables: Variable[] = [
id: 'space/md',
name: 'Space/md',
type: 'FLOAT',
- collectionId: 'demo',
+ collectionId: 'example',
valuesByMode: { default: 16 },
description: '',
hiddenFromPublishing: false
@@ -29,7 +29,7 @@ const variables: Variable[] = [
id: 'space/lg',
name: 'Space/lg',
type: 'FLOAT',
- collectionId: 'demo',
+ collectionId: 'example',
valuesByMode: { default: 24 },
description: '',
hiddenFromPublishing: false
@@ -65,10 +65,10 @@ const provider: BindingProvider<number> = {
if (ids.size > 1) return 'mixed'
return ids.has(undefined) ? 'unbound' : 'bound'
},
- resolve: (variableId) =>
- variables.find((variable) => variable.id === variableId)?.valuesByMode.default as
- | number
- | undefined,
+ resolve: (variableId) => {
+ const value = variables.find((variable) => variable.id === variableId)?.valuesByMode.default
+ return typeof value === 'number' ? value : undefined
+ },
bind(target, variableId) {
bindings.value[key(target)] = variableId
revision.value++
@@ -100,7 +100,7 @@ const provider: BindingProvider<number> = {
id,
name,
type: 'FLOAT',
- collectionId: 'demo',
+ collectionId: 'example',
valuesByMode: { default: value },
description: '',
hiddenFromPublishing: false
diff --git a/packages/vue/src/primitives/CommandPalette/CommandPalette.stories.ts b/packages/vue/src/primitives/CommandPalette/CommandPalette.stories.ts
index df31353d1..505d7cd6d 100644
--- a/packages/vue/src/primitives/CommandPalette/CommandPalette.stories.ts
+++ b/packages/vue/src/primitives/CommandPalette/CommandPalette.stories.ts
@@ -1,11 +1,11 @@
import type { Meta, StoryObj } from '@storybook/vue3-vite'
import { expect, userEvent, within } from 'storybook/test'
-import CommandPaletteDemo from './CommandPaletteDemo.vue'
+import CommandPaletteStates from './examples/States.vue'
const meta = {
title: 'Vue SDK/Primitives/Command Palette',
- component: CommandPaletteDemo,
+ component: CommandPaletteStates,
tags: ['autodocs'],
parameters: {
docs: {
@@ -14,7 +14,7 @@ const meta = {
}
}
}
-} satisfies Meta<typeof CommandPaletteDemo>
+} satisfies Meta<typeof CommandPaletteStates>
export default meta
type Story = StoryObj<typeof meta>
diff --git a/packages/vue/src/primitives/CommandPalette/CommandPaletteDemo.vue b/packages/vue/src/primitives/CommandPalette/examples/States.vue
similarity index 92%
rename from packages/vue/src/primitives/CommandPalette/CommandPaletteDemo.vue
rename to packages/vue/src/primitives/CommandPalette/examples/States.vue
index 419eb0323..6f195953b 100644
--- a/packages/vue/src/primitives/CommandPalette/CommandPaletteDemo.vue
+++ b/packages/vue/src/primitives/CommandPalette/examples/States.vue
@@ -1,8 +1,8 @@
<script setup lang="ts">
import { ref } from 'vue'
-import CommandPaletteRoot from './CommandPaletteRoot.vue'
-import type { CommandPaletteGroup } from './types'
+import CommandPaletteRoot from '#vue/primitives/CommandPalette/CommandPaletteRoot.vue'
+import type { CommandPaletteGroup } from '#vue/primitives/CommandPalette/types'
const selected = ref('')
const selectedLabels = ref<string[]>([])
diff --git a/packages/vue/src/primitives/Fill/ColorFill.stories.ts b/packages/vue/src/primitives/Fill/ColorFill.stories.ts
index 14109432d..bd8cba1be 100644
--- a/packages/vue/src/primitives/Fill/ColorFill.stories.ts
+++ b/packages/vue/src/primitives/Fill/ColorFill.stories.ts
@@ -1,11 +1,11 @@
import type { Meta, StoryObj } from '@storybook/vue3-vite'
import { expect, userEvent, within } from 'storybook/test'
-import ColorFillDemo from '#vue/primitives/Fill/demo/ColorFillDemo.vue'
+import ColorFillStates from './examples/States.vue'
const meta = {
title: 'Vue SDK/Primitives/Color and Fill',
- component: ColorFillDemo,
+ component: ColorFillStates,
tags: ['autodocs'],
parameters: {
docs: {
@@ -15,7 +15,7 @@ const meta = {
}
}
}
-} satisfies Meta<typeof ColorFillDemo>
+} satisfies Meta<typeof ColorFillStates>
export default meta
type Story = StoryObj<typeof meta>
diff --git a/packages/vue/src/primitives/Fill/demo/ColorFillDemo.vue b/packages/vue/src/primitives/Fill/examples/States.vue
similarity index 97%
rename from packages/vue/src/primitives/Fill/demo/ColorFillDemo.vue
rename to packages/vue/src/primitives/Fill/examples/States.vue
index e1e33d832..24a2c5bc5 100644
--- a/packages/vue/src/primitives/Fill/demo/ColorFillDemo.vue
+++ b/packages/vue/src/primitives/Fill/examples/States.vue
@@ -32,12 +32,12 @@ const gradient: Fill = {
}
const editableFill = ref<Fill>(structuredClone(solid))
const chroma = ref(0.16)
-const target: BindingTarget[] = [{ nodeId: 'demo', path: 'fills/0/color' }]
+const target: BindingTarget[] = [{ nodeId: 'example', path: 'fills/0/color' }]
const variable: Variable = {
id: 'color/brand',
name: 'Color/Brand',
type: 'COLOR',
- collectionId: 'demo',
+ collectionId: 'example',
valuesByMode: { default: { r: 0.65, g: 0.3, b: 0.95, a: 1 } },
description: '',
hiddenFromPublishing: false
diff --git a/packages/vue/src/primitives/NumberField/NumberField.stories.ts b/packages/vue/src/primitives/NumberField/NumberField.stories.ts
index 9b613b886..347fad969 100644
--- a/packages/vue/src/primitives/NumberField/NumberField.stories.ts
+++ b/packages/vue/src/primitives/NumberField/NumberField.stories.ts
@@ -1,11 +1,11 @@
import type { Meta, StoryObj } from '@storybook/vue3-vite'
import { expect, userEvent, within } from 'storybook/test'
-import NumberFieldDemo from './demo/NumberFieldDemo.vue'
+import NumberFieldStates from './examples/States.vue'
const meta = {
title: 'Vue SDK/Primitives/NumberField',
- component: NumberFieldDemo,
+ component: NumberFieldStates,
tags: ['autodocs'],
parameters: {
docs: {
@@ -15,7 +15,7 @@ const meta = {
}
}
}
-} satisfies Meta<typeof NumberFieldDemo>
+} satisfies Meta<typeof NumberFieldStates>
export default meta
type Story = StoryObj<typeof meta>
@@ -27,9 +27,7 @@ export const StateMatrix: Story = {
await expect(root).toHaveStyle({ height: '26px' })
await userEvent.click(root)
- const input = canvasElement.querySelector<HTMLInputElement>(
- '[data-test-id="interactive-number-input"]'
- )
+ const input = root.querySelector('input')
if (!input) throw new Error('Expected the editing NumberField input')
await userEvent.clear(input)
await userEvent.type(input, '12*8+4{Enter}')
@@ -44,9 +42,8 @@ export const StateMatrix: Story = {
export const Editing: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement)
- await userEvent.click(canvas.getByLabelText('Interactive number field'))
- await expect(
- canvasElement.querySelector('[data-test-id="interactive-number-input"]')
- ).toBeVisible()
+ const root = canvas.getByLabelText('Interactive number field')
+ await userEvent.click(root)
+ await expect(root.querySelector('input')).toBeVisible()
}
}
diff --git a/packages/vue/src/primitives/NumberField/demo/NumberFieldDemo.vue b/packages/vue/src/primitives/NumberField/examples/States.vue
similarity index 95%
rename from packages/vue/src/primitives/NumberField/demo/NumberFieldDemo.vue
rename to packages/vue/src/primitives/NumberField/examples/States.vue
index 6b7913314..17e89c5ec 100644
--- a/packages/vue/src/primitives/NumberField/demo/NumberFieldDemo.vue
+++ b/packages/vue/src/primitives/NumberField/examples/States.vue
@@ -35,15 +35,11 @@ const bound = ref<number | symbol>(8)
>
<div
v-bind="attrs"
- data-story-control
class="flex h-[26px] w-56 items-center overflow-hidden rounded border border-transparent bg-[var(--vp-c-bg-alt)] text-xs outline-none focus-within:border-[var(--vp-c-brand-1)]"
@pointerdown="!editing && actions.startScrub($event)"
>
<NumberFieldLeading class="px-2 text-[var(--vp-c-text-2)]">W</NumberFieldLeading>
- <NumberFieldInput
- data-test-id="interactive-number-input"
- class="min-w-0 flex-1 border-0 bg-transparent outline-none"
- />
+ <NumberFieldInput class="min-w-0 flex-1 border-0 bg-transparent outline-none" />
<NumberFieldValue class="min-w-0 flex-1 truncate" />
<NumberFieldUnit class="pr-1 text-[var(--vp-c-text-2)]">px</NumberFieldUnit>
<NumberFieldTrailing
diff --git a/packages/vue/src/primitives/PropertySection/PropertyPrimitives.stories.ts b/packages/vue/src/primitives/PropertySection/PropertyPrimitives.stories.ts
index fa9c3dafc..f7adf3939 100644
--- a/packages/vue/src/primitives/PropertySection/PropertyPrimitives.stories.ts
+++ b/packages/vue/src/primitives/PropertySection/PropertyPrimitives.stories.ts
@@ -1,11 +1,11 @@
import type { Meta, StoryObj } from '@storybook/vue3-vite'
import { expect, userEvent, within } from 'storybook/test'
-import PropertyPrimitivesDemo from './demo/PropertyPrimitivesDemo.vue'
+import PropertyPrimitivesStates from './examples/States.vue'
const meta = {
title: 'Vue SDK/Primitives/Property Primitives',
- component: PropertyPrimitivesDemo,
+ component: PropertyPrimitivesStates,
tags: ['autodocs'],
parameters: {
docs: {
@@ -15,7 +15,7 @@ const meta = {
}
}
}
-} satisfies Meta<typeof PropertyPrimitivesDemo>
+} satisfies Meta<typeof PropertyPrimitivesStates>
export default meta
type Story = StoryObj<typeof meta>
diff --git a/packages/vue/src/primitives/PropertySection/demo/PropertyPrimitivesDemo.vue b/packages/vue/src/primitives/PropertySection/examples/States.vue
similarity index 99%
rename from packages/vue/src/primitives/PropertySection/demo/PropertyPrimitivesDemo.vue
rename to packages/vue/src/primitives/PropertySection/examples/States.vue
index b0237466b..2614dea50 100644
--- a/packages/vue/src/primitives/PropertySection/demo/PropertyPrimitivesDemo.vue
+++ b/packages/vue/src/primitives/PropertySection/examples/States.vue
@@ -42,7 +42,7 @@ function removeFill(index: number) {
function toggleFill(index: number) {
const fill = fills.value[index]
- if (fill) fill.visible = !fill.visible
+ fill.visible = !fill.visible
}
</script>
diff --git a/src/App.vue b/src/App.vue
index eb7f3a815..7b87b582b 100644
--- a/src/App.vue
+++ b/src/App.vue
@@ -21,7 +21,7 @@ import LibraryUpdateReviewDialog from '@/components/libraries/review/LibraryUpda
import RecoveryDialog from '@/components/recovery/RecoveryDialog.vue'
import SettingsDialog from '@/components/settings/SettingsDialog.vue'
import AppShell from '@/components/shell/AppShell.vue'
-import AppToast from '@/components/shell/AppToast.vue'
+import Toaster from '@/components/shell/Toaster.vue'
const store = useEditorStore()
const { updates, locale } = useI18n()
@@ -59,7 +59,7 @@ onMounted(() => {
<UnsavedChangesDialog />
<PublishLibraryDialog />
<LibraryUpdateReviewDialog />
- <AppToast />
+ <Toaster />
</TooltipProvider>
</MotionConfig>
</template>
diff --git a/src/app/shell/ui.ts b/src/app/shell/ui.ts
index e1ed66f37..1ffc634f4 100644
--- a/src/app/shell/ui.ts
+++ b/src/app/shell/ui.ts
@@ -2,9 +2,9 @@ import { useEventListener } from '@vueuse/core'
import { ref } from 'vue'
import { isTauri } from '@/app/tauri/env'
-import type { ToastVariant } from '@/components/ui/feedback/toast'
+import type { ToastProgress, ToastVariant } from '@/components/ui/feedback/toast'
-export type { ToastVariant } from '@/components/ui/feedback/toast'
+export type { ToastProgress, ToastVariant } from '@/components/ui/feedback/toast'
export interface ToastAction {
label: string
@@ -18,6 +18,24 @@ export interface Toast {
/** Number of times this message has been raised since it appeared. */
count: number
action?: ToastAction
+ /** Present while a long-running operation behind this toast reports progress. */
+ progress?: ToastProgress
+ /** Measurement text beside the progress bar, formatted by the producing domain. */
+ progressLabel?: string
+}
+
+export interface ToastPatch {
+ message?: string
+ /** `null` clears the bar, which resumes the toast's normal auto-dismissal. */
+ progress?: ToastProgress | null
+ /** `null` removes the measurement line. */
+ progressLabel?: string | null
+}
+
+/** Handle for a toast that a long-running operation updates until it finishes. */
+export interface ToastHandle {
+ update(patch: ToastPatch): void
+ dismiss(): void
}
const TOAST_DURATION = 3000
@@ -36,19 +54,62 @@ function push(message: string, variant: ToastVariant, action?: ToastAction) {
// Dedupe: if the same message+variant is already visible, increment
// its repeat count instead of stacking a duplicate. Prevents the
// cascade-on-every-frame failure mode where a single unhealthy
- // event source floods the viewport.
- const existing = toasts.value.find((t) => t.message === message && t.variant === variant)
+ // event source floods the viewport. Toasts driven by a progress handle
+ // are addressed by that handle and must never absorb or merge messages.
+ const existing = toasts.value.find(
+ (t) => t.message === message && t.variant === variant && !t.progress
+ )
if (existing) {
existing.count += 1
existing.action = action
return
}
toasts.value.push({ id: ++nextId, message, variant, count: 1, action })
+ trim()
+}
+
+function trim() {
if (toasts.value.length > TOAST_STACK_LIMIT) {
toasts.value.splice(0, toasts.value.length - TOAST_STACK_LIMIT)
}
}
+/** Toast-driven work keeps its toast open until progress clears or the work ends. */
+export function toastDuration(entry: Toast): number {
+ if (entry.progress) return 0
+ return entry.variant === 'error' ? ERROR_TOAST_DURATION : TOAST_DURATION
+}
+
+function startProgress(
+ message: string,
+ options: { variant?: ToastVariant; progress?: ToastProgress; progressLabel?: string } = {}
+): ToastHandle {
+ const id = ++nextId
+ toasts.value.push({
+ id,
+ message,
+ variant: options.variant ?? 'default',
+ count: 1,
+ progress: options.progress ?? {},
+ progressLabel: options.progressLabel
+ })
+ trim()
+ return {
+ update(patch) {
+ // Resolve through the array so mutations land on the reactive proxy and
+ // a toast that was trimmed or dismissed in the meantime is left alone.
+ const entry = toasts.value.find((t) => t.id === id)
+ if (!entry) return
+ if (patch.message !== undefined) entry.message = patch.message
+ if (patch.progress !== undefined) entry.progress = patch.progress ?? undefined
+ if (patch.progressLabel !== undefined) entry.progressLabel = patch.progressLabel ?? undefined
+ },
+ dismiss() {
+ remove(id)
+ }
+ }
+}
+
function info(message: string) {
push(message, 'default')
}
@@ -82,6 +143,7 @@ export const toast = {
info,
warning,
error,
+ startProgress,
remove,
toasts,
setupGlobalErrorHandler,
diff --git a/src/app/shell/updater.ts b/src/app/shell/updater.ts
index 04c6d6301..434d651ec 100644
--- a/src/app/shell/updater.ts
+++ b/src/app/shell/updater.ts
@@ -12,6 +12,8 @@ interface UpdaterMessages {
available: (params: { version: string }) => string
installPrompt: string
downloading: (params: { version: string }) => string
+ downloadProgress: (params: { percent: number; downloaded: string; total: string }) => string
+ downloadProgressUnknown: (params: { downloaded: string }) => string
installedTitle: string
installed: (params: { version: string; size: string }) => string
unavailable: string
@@ -76,15 +78,37 @@ async function runUpdateCheck(silent: boolean, messages: Ref<UpdaterMessages>) {
let downloaded = 0
let contentLength: number | undefined
- toast.info(t.downloading({ version: update.version }))
-
- await update.downloadAndInstall((event) => {
- if (event.event === 'Started') {
- contentLength = event.data.contentLength
- return
- }
- if (event.event === 'Progress') downloaded += event.data.chunkLength
- })
+ const progressToast = toast.startProgress(t.downloading({ version: update.version }))
+ let reportedLabel = ''
+
+ // Skip chunks that leave the displayed percentage and rounded byte counts
+ // unchanged. This deduplicates labels; it is not a fixed-rate throttle.
+ const reportProgress = () => {
+ const label = downloadProgressLabel(t, downloaded, contentLength)
+ if (label === reportedLabel) return
+ reportedLabel = label
+ progressToast.update({
+ progressLabel: label,
+ progress: contentLength ? { value: downloaded, max: contentLength } : { value: downloaded }
+ })
+ }
+
+ try {
+ await update.downloadAndInstall((event) => {
+ if (event.event === 'Started') {
+ contentLength = event.data.contentLength
+ reportProgress()
+ return
+ }
+ if (event.event === 'Progress') {
+ downloaded += event.data.chunkLength
+ reportProgress()
+ }
+ })
+ } finally {
+ // Dismissed on failure too: a toast with a progress bar never expires on its own.
+ progressToast.dismiss()
+ }
const sizeLabel = contentLength
? ` (${formatBytes(downloaded)} of ${formatBytes(contentLength)})`
@@ -110,6 +134,21 @@ function isMissingUpdateManifestError(message: string) {
return message.toLowerCase().includes('valid release json')
}
+function downloadProgressLabel(
+ messages: UpdaterMessages,
+ downloaded: number,
+ contentLength?: number
+) {
+ if (!contentLength)
+ return messages.downloadProgressUnknown({ downloaded: formatBytes(downloaded) })
+ const percent = Math.min(100, Math.max(0, Math.round((downloaded / contentLength) * 100)))
+ return messages.downloadProgress({
+ percent,
+ downloaded: formatBytes(downloaded),
+ total: formatBytes(contentLength)
+ })
+}
+
function formatBytes(bytes: number) {
if (bytes < 1024) return `${bytes} B`
const kib = bytes / 1024
diff --git a/src/components/FileApiBanner.vue b/src/components/FileApiBanner.vue
index 2ac537d41..bd8694453 100644
--- a/src/components/FileApiBanner.vue
+++ b/src/components/FileApiBanner.vue
@@ -14,7 +14,7 @@ const show = !IS_TAURI && !supportsFileSystemAccess()
</script>
<template>
- <AppBanner v-if="show" test-id="safari-banner" storage-key="safari-banner-dismissed">
+ <AppBanner v-if="show" storage-key="safari-banner-dismissed">
{{ files.browserFileAPINotSupported }}
<ExternalLink :href="supportURL" class="ml-1">{{ common.browserSupport }}</ExternalLink>
<template #dismiss>{{ common.dismiss }}</template>
diff --git a/src/components/LayerTree/LayerTree.stories.ts b/src/components/LayerTree/LayerTree.stories.ts
index ff07dfa1f..65fbd5b88 100644
--- a/src/components/LayerTree/LayerTree.stories.ts
+++ b/src/components/LayerTree/LayerTree.stories.ts
@@ -1,12 +1,12 @@
import type { Meta, StoryObj } from '@storybook/vue3-vite'
import { expect, within } from 'storybook/test'
-import LayerTreeThemeDemo from './demo/LayerTreeThemeDemo.vue'
-import LayerTreeVirtualizedDemo from './demo/LayerTreeVirtualizedDemo.vue'
+import LayerTreeStateMatrix from './examples/States.vue'
+import LayerTreeVirtualized from './examples/Virtualized.vue'
const meta = {
title: 'Editor/Layer Tree',
- component: LayerTreeThemeDemo,
+ component: LayerTreeStateMatrix,
tags: ['autodocs'],
parameters: {
docs: {
@@ -23,8 +23,8 @@ type Story = StoryObj<{ adjacent?: boolean }>
export const Virtualized: Story = {
render: () => ({
- components: { LayerTreeVirtualizedDemo },
- template: '<LayerTreeVirtualizedDemo />'
+ components: { LayerTreeVirtualized },
+ template: '<LayerTreeVirtualized />'
})
}
diff --git a/src/components/LayerTree/demo/LayerTreeThemeDemo.vue b/src/components/LayerTree/examples/States.vue
similarity index 91%
rename from src/components/LayerTree/demo/LayerTreeThemeDemo.vue
rename to src/components/LayerTree/examples/States.vue
index 4cbab97d9..2ba379e62 100644
--- a/src/components/LayerTree/demo/LayerTreeThemeDemo.vue
+++ b/src/components/LayerTree/examples/States.vue
@@ -1,11 +1,16 @@
<script setup lang="ts">
-const { adjacent = false } = defineProps<{ adjacent?: boolean }>()
import type { LayerNode } from '@open-pencil/vue'
-import LayerTreeNodeRow from '../LayerTreeNodeRow.vue'
-import LayerTreeRenameRow from '../LayerTreeRenameRow.vue'
-import type { LayerRenameControls, LayerTreeChrome, LayerTreeItemActions } from '../types'
-import { provideLayerTreeUI } from '../ui'
+import LayerTreeNodeRow from '@/components/LayerTree/LayerTreeNodeRow.vue'
+import LayerTreeRenameRow from '@/components/LayerTree/LayerTreeRenameRow.vue'
+import type {
+ LayerRenameControls,
+ LayerTreeChrome,
+ LayerTreeItemActions
+} from '@/components/LayerTree/types'
+import { provideLayerTreeUI } from '@/components/LayerTree/ui'
+
+const { adjacent = false } = defineProps<{ adjacent?: boolean }>()
provideLayerTreeUI(() => undefined)
diff --git a/src/components/LayerTree/demo/LayerTreeVirtualizedDemo.vue b/src/components/LayerTree/examples/Virtualized.vue
similarity index 91%
rename from src/components/LayerTree/demo/LayerTreeVirtualizedDemo.vue
rename to src/components/LayerTree/examples/Virtualized.vue
index 22510fbab..30d22e29b 100644
--- a/src/components/LayerTree/demo/LayerTreeVirtualizedDemo.vue
+++ b/src/components/LayerTree/examples/Virtualized.vue
@@ -5,13 +5,12 @@ import { reactive, ref } from 'vue'
import { useInlineRename } from '@open-pencil/vue'
import type { LayerNode } from '@open-pencil/vue'
+import { LAYER_TREE_ROW_HEIGHT } from '@/components/LayerTree/geometry'
+import LayerTreeNodeRow from '@/components/LayerTree/LayerTreeNodeRow.vue'
+import LayerTreeRenameRow from '@/components/LayerTree/LayerTreeRenameRow.vue'
+import { provideLayerTreeUI } from '@/components/LayerTree/ui'
import AppButton from '@/components/ui/button/AppButton.vue'
-import { LAYER_TREE_ROW_HEIGHT } from '../geometry'
-import LayerTreeNodeRow from '../LayerTreeNodeRow.vue'
-import LayerTreeRenameRow from '../LayerTreeRenameRow.vue'
-import { provideLayerTreeUI } from '../ui'
-
interface DemoNode extends LayerNode {
children?: DemoNode[]
}
@@ -39,7 +38,7 @@ function resolveNode(id: unknown): DemoNode {
const node = items
.flatMap((item) => [item, ...(item.children ?? [])])
.find((item) => item.id === id)
- if (!node) throw new Error('Unknown demo node')
+ if (!node) throw new Error('Unknown tree node')
return node
}
diff --git a/src/components/canvas/ColorSpaceBanner.vue b/src/components/canvas/ColorSpaceBanner.vue
index 96af3db49..6a7b3413c 100644
--- a/src/components/canvas/ColorSpaceBanner.vue
+++ b/src/components/canvas/ColorSpaceBanner.vue
@@ -26,7 +26,7 @@ const message = computed(() => rendering.value.wideGamutUnavailable)
</script>
<template>
- <AppBanner v-if="show" test-id="wide-gamut-banner" storage-key="wide-gamut-banner-dismissed">
+ <AppBanner v-if="show" storage-key="wide-gamut-banner-dismissed">
{{ message }}
<ExternalLink :href="supportURL" class="ml-1">{{ common.browserSupport }}</ExternalLink>
<template #dismiss>{{ common.dismiss }}</template>
diff --git a/src/components/navigation/NavigationTheme.stories.ts b/src/components/navigation/NavigationTheme.stories.ts
index 09b371381..32d6f7f44 100644
--- a/src/components/navigation/NavigationTheme.stories.ts
+++ b/src/components/navigation/NavigationTheme.stories.ts
@@ -1,11 +1,10 @@
import type { Meta, StoryObj } from '@storybook/vue3-vite'
import { expect, within } from 'storybook/test'
-import NavigationThemeDemo from './demo/NavigationThemeDemo.vue'
+import NavigationStates from './examples/States.vue'
const meta = {
title: 'Design System/Editor/Navigation',
- component: NavigationThemeDemo,
tags: ['autodocs'],
parameters: {
docs: {
@@ -13,8 +12,9 @@ const meta = {
component: 'Page list, Layers/Assets segmented tabs, and document TabBar theme states.'
}
}
- }
-} satisfies Meta<typeof NavigationThemeDemo>
+ },
+ component: NavigationStates
+} satisfies Meta<typeof NavigationStates>
export default meta
type Story = StoryObj<typeof meta>
diff --git a/src/components/navigation/demo/NavigationThemeDemo.vue b/src/components/navigation/examples/States.vue
similarity index 100%
rename from src/components/navigation/demo/NavigationThemeDemo.vue
rename to src/components/navigation/examples/States.vue
diff --git a/src/components/properties/binding/BindingField.stories.ts b/src/components/properties/binding/BindingField.stories.ts
index 3d688e857..0c7c4689c 100644
--- a/src/components/properties/binding/BindingField.stories.ts
+++ b/src/components/properties/binding/BindingField.stories.ts
@@ -1,11 +1,11 @@
import type { Meta, StoryObj } from '@storybook/vue3-vite'
import { expect, userEvent, within } from 'storybook/test'
-import BindingFieldDemo from './demo/BindingFieldDemo.vue'
+import BindingFieldStates from './examples/States.vue'
const meta = {
title: 'Editor/Properties/Binding Field',
- component: BindingFieldDemo,
+ component: BindingFieldStates,
tags: ['autodocs'],
parameters: {
docs: {
@@ -15,7 +15,7 @@ const meta = {
}
}
}
-} satisfies Meta<typeof BindingFieldDemo>
+} satisfies Meta<typeof BindingFieldStates>
export default meta
type Story = StoryObj<typeof meta>
@@ -26,10 +26,6 @@ export const StateMatrix: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement)
const page = within(canvasElement.ownerDocument.body)
- const controls = Array.from(canvasElement.querySelectorAll<HTMLElement>('[data-story-control]'))
-
- for (const control of controls) await expect(control).toHaveStyle({ height: '26px' })
-
const detachField = canvas.getByLabelText('Detach bound field')
await expect(detachField).toHaveAttribute('data-bound')
diff --git a/src/components/properties/binding/demo/BindingFieldDemoItem.vue b/src/components/properties/binding/examples/Field.vue
similarity index 99%
rename from src/components/properties/binding/demo/BindingFieldDemoItem.vue
rename to src/components/properties/binding/examples/Field.vue
index fd49dbfcf..3b47edeb1 100644
--- a/src/components/properties/binding/demo/BindingFieldDemoItem.vue
+++ b/src/components/properties/binding/examples/Field.vue
@@ -49,7 +49,6 @@ function tooltip(variableName: string, resolvedValue: unknown) {
>
<div
v-bind="{ ...attrs, ...binding.stateAttrs }"
- data-story-control
class="group/binding flex h-6 min-w-0 items-center rounded border border-transparent bg-panel-field text-xs text-surface outline-none hover:bg-panel-field-hover focus-within:border-panel-focus data-[derived]:text-muted"
:data-derived="derived ? '' : undefined"
@pointerdown="
diff --git a/src/components/properties/binding/demo/BindingFieldDemo.vue b/src/components/properties/binding/examples/States.vue
similarity index 95%
rename from src/components/properties/binding/demo/BindingFieldDemo.vue
rename to src/components/properties/binding/examples/States.vue
index 057d3aae6..dd9aa7ddc 100644
--- a/src/components/properties/binding/demo/BindingFieldDemo.vue
+++ b/src/components/properties/binding/examples/States.vue
@@ -4,7 +4,7 @@ import { ref } from 'vue'
import type { Variable } from '@open-pencil/scene-graph'
import type { BindingProvider, BindingState, BindingTarget } from '@open-pencil/vue'
-import BindingFieldDemoItem from './BindingFieldDemoItem.vue'
+import Field from './Field.vue'
const variables: Variable[] = [
{
@@ -134,7 +134,7 @@ const mixedTargets: BindingTarget[] = [
<div class="grid grid-cols-2 gap-1.5 px-3">
<label class="space-y-1">
<span class="text-[11px] text-muted">Unbound</span>
- <BindingFieldDemoItem
+ <Field
v-model="values.unbound"
label="Unbound field"
:provider="provider"
@@ -143,7 +143,7 @@ const mixedTargets: BindingTarget[] = [
</label>
<label class="space-y-1">
<span class="text-[11px] text-muted">Detach on edit</span>
- <BindingFieldDemoItem
+ <Field
v-model="values.detach"
label="Detach bound field"
:provider="provider"
@@ -152,7 +152,7 @@ const mixedTargets: BindingTarget[] = [
</label>
<label class="space-y-1">
<span class="text-[11px] text-muted">Read only</span>
- <BindingFieldDemoItem
+ <Field
v-model="values.readonly"
label="Readonly bound field"
:provider="provider"
@@ -162,7 +162,7 @@ const mixedTargets: BindingTarget[] = [
</label>
<label class="space-y-1">
<span class="text-[11px] text-muted">Edit variable</span>
- <BindingFieldDemoItem
+ <Field
v-model="values.editVariable"
label="Edit variable field"
:provider="provider"
@@ -172,7 +172,7 @@ const mixedTargets: BindingTarget[] = [
</label>
<label class="space-y-1">
<span class="text-[11px] text-muted">Mixed</span>
- <BindingFieldDemoItem
+ <Field
v-model="values.mixed"
label="Mixed binding field"
:provider="provider"
@@ -181,7 +181,7 @@ const mixedTargets: BindingTarget[] = [
</label>
<label class="space-y-1">
<span class="text-[11px] text-muted">Disabled</span>
- <BindingFieldDemoItem
+ <Field
v-model="values.disabled"
label="Disabled bound field"
:provider="provider"
@@ -191,7 +191,7 @@ const mixedTargets: BindingTarget[] = [
</label>
<label class="col-span-2 space-y-1">
<span class="text-[11px] text-muted">Derived by auto layout</span>
- <BindingFieldDemoItem
+ <Field
v-model="values.derived"
label="Derived bound field"
:provider="provider"
diff --git a/src/components/shell/AppToast.vue b/src/components/shell/AppToast.vue
deleted file mode 100644
index 7e9bb0bef..000000000
--- a/src/components/shell/AppToast.vue
+++ /dev/null
@@ -1,79 +0,0 @@
-<script setup lang="ts">
-import { useClipboard } from '@vueuse/core'
-import { ToastProvider, ToastRoot, ToastDescription, ToastViewport, ToastClose } from 'reka-ui'
-
-import { useI18n } from '@open-pencil/vue'
-
-import { toast } from '@/app/shell/ui'
-import { useToastUI } from '@/components/ui/feedback/toast'
-import type { ToastVariant } from '@/components/ui/feedback/toast'
-import Tip from '@/components/ui/overlay/Tip.vue'
-
-const { copy, copied } = useClipboard({ copiedDuring: 1500 })
-const { common, settings } = useI18n()
-const defaultToastClass = useToastUI({ tone: 'default' }).base
-const warningToastClass = useToastUI({ tone: 'warning' }).base
-const errorToastClass = useToastUI({ tone: 'error' }).base
-
-function toastClass(tone: ToastVariant) {
- if (tone === 'error') return errorToastClass
- if (tone === 'warning') return warningToastClass
- return defaultToastClass
-}
-</script>
-
-<template>
- <ToastProvider swipe-direction="up">
- <ToastRoot
- v-for="t in toast.toasts.value"
- :key="t.id"
- data-test-id="toast-item"
- :duration="t.variant === 'error' ? toast.ERROR_TOAST_DURATION : toast.TOAST_DURATION"
- :class="toastClass(t.variant)"
- @update:open="
- (open) => {
- if (!open) toast.remove(t.id)
- }
- "
- >
- <icon-lucide-check v-if="t.variant === 'default'" class="mt-0.5 size-3 shrink-0" />
- <icon-lucide-triangle-alert v-else class="mt-0.5 size-3 shrink-0" />
- <ToastDescription class="min-w-0 flex-1 select-text">
- {{ t.message }}<span v-if="t.count > 1" class="ml-1.5 opacity-70">×{{ t.count }}</span>
- </ToastDescription>
- <button
- v-if="t.action"
- type="button"
- class="shrink-0 cursor-pointer rounded px-1.5 py-0.5 text-[10px] font-medium underline-offset-2 hover:underline"
- @click="t.action.run()"
- >
- {{ t.action.label }}
- </button>
- <Tip
- v-if="t.variant !== 'default'"
- :label="copied ? common.copiedExclamation : common.copyMessage"
- >
- <button
- data-test-id="toast-copy-message"
- class="mt-0.5 shrink-0 cursor-pointer rounded p-0.5 opacity-70 hover:opacity-100"
- @click="copy(t.message)"
- >
- <icon-lucide-check v-if="copied" class="size-3" />
- <icon-lucide-copy v-else class="size-3" />
- </button>
- </Tip>
- <ToastClose
- v-if="t.variant !== 'default'"
- data-test-id="toast-close"
- class="mt-0.5 shrink-0 cursor-pointer rounded p-0.5 opacity-70 hover:opacity-100"
- >
- <icon-lucide-x class="size-3" />
- </ToastClose>
- </ToastRoot>
-
- <ToastViewport
- :label="`${settings.notifications} (F8)`"
- class="fixed top-2 left-1/2 z-[9999] flex -translate-x-1/2 flex-col items-center gap-1.5"
- />
- </ToastProvider>
-</template>
diff --git a/src/components/shell/Toaster.vue b/src/components/shell/Toaster.vue
new file mode 100644
index 000000000..59442c34c
--- /dev/null
+++ b/src/components/shell/Toaster.vue
@@ -0,0 +1,36 @@
+<script setup lang="ts">
+import { ToastProvider, ToastViewport } from 'reka-ui'
+
+import { useI18n } from '@open-pencil/vue'
+
+import { toast, toastDuration } from '@/app/shell/ui'
+import AppToast from '@/components/ui/feedback/AppToast.vue'
+
+const { common, settings } = useI18n()
+</script>
+
+<template>
+ <ToastProvider swipe-direction="up">
+ <AppToast
+ v-for="t in toast.toasts.value"
+ :key="t.id"
+ :message="t.message"
+ :variant="t.variant"
+ :count="t.count"
+ :progress="t.progress"
+ :progress-label="t.progressLabel"
+ :action-label="t.action?.label"
+ :duration="toastDuration(t)"
+ :copyable="t.variant !== 'default'"
+ :copy-label="common.copyMessage"
+ :copied-label="common.copiedExclamation"
+ :close-label="common.close"
+ @close="toast.remove(t.id)"
+ @action="t.action?.run()"
+ />
+ <ToastViewport
+ :label="`${settings.notifications} (F8)`"
+ class="fixed top-2 left-1/2 z-[9999] flex -translate-x-1/2 flex-col items-center gap-1.5"
+ />
+ </ToastProvider>
+</template>
diff --git a/src/components/ui/feedback/AppBanner.stories.ts b/src/components/ui/feedback/AppBanner.stories.ts
index 4e892ee0c..5c9f056ec 100644
--- a/src/components/ui/feedback/AppBanner.stories.ts
+++ b/src/components/ui/feedback/AppBanner.stories.ts
@@ -15,7 +15,7 @@ export const Dismissible: Story = {
render: () => ({
components: { AppBanner },
template: `
- <AppBanner storage-key="storybook-banner-dismissed" test-id="app-banner">
+ <AppBanner storage-key="storybook-banner-dismissed">
This display or browser cannot show Display-P3 colors, so the canvas previews them in sRGB.
<template #dismiss>Dismiss</template>
</AppBanner>
diff --git a/src/components/ui/feedback/AppBanner.vue b/src/components/ui/feedback/AppBanner.vue
index 924afb7a9..1e68bf5fc 100644
--- a/src/components/ui/feedback/AppBanner.vue
+++ b/src/components/ui/feedback/AppBanner.vue
@@ -4,7 +4,7 @@ import { computed } from 'vue'
import { banner, type BannerProps } from './banner'
-const { storageKey, testId, ui } = defineProps<BannerProps>()
+const { storageKey, ui } = defineProps<BannerProps>()
const dismissed = storageKey ? useLocalStorage(storageKey, false) : null
const styles = computed(() => {
@@ -18,11 +18,11 @@ const styles = computed(() => {
</script>
<template>
- <div v-if="!dismissed" :data-test-id="testId" :class="styles.root">
+ <div v-if="!dismissed" :class="styles.root" data-slot="banner" role="status">
<span :class="styles.content"><slot /></span>
<button
v-if="storageKey"
- :data-test-id="testId ? `${testId}-dismiss` : undefined"
+ data-slot="banner-dismiss"
:class="styles.dismiss"
@click="dismissed = true"
>
diff --git a/src/components/ui/feedback/AppToast.stories.ts b/src/components/ui/feedback/AppToast.stories.ts
new file mode 100644
index 000000000..9a12a3ee4
--- /dev/null
+++ b/src/components/ui/feedback/AppToast.stories.ts
@@ -0,0 +1,160 @@
+import type { Meta, StoryObj } from '@storybook/vue3-vite'
+import { ToastProvider, ToastViewport } from 'reka-ui'
+import { computed, ref } from 'vue'
+
+import AppButton from '@/components/ui/button/AppButton.vue'
+
+import AppToast from './AppToast.vue'
+import { toastProgressPercent, type ToastProps, type ToastProgress } from './toast'
+
+const meta = {
+ title: 'Design System/Toast',
+ component: AppToast,
+ // A toast only renders inside a provider, and the viewport is where it lands.
+ decorators: [
+ () => ({
+ components: { ToastProvider, ToastViewport },
+ template: `
+ <ToastProvider swipe-direction="up">
+ <story />
+ <ToastViewport class="fixed top-2 left-1/2 z-50 flex -translate-x-1/2 flex-col items-center gap-1.5" />
+ </ToastProvider>
+ `
+ })
+ ],
+ args: {
+ message: 'Document exported to Downloads',
+ // Static stories must not expire while a reviewer is reading them.
+ duration: 0
+ },
+ render: (args) => ({
+ components: { AppToast },
+ setup: () => ({ args }),
+ template: '<AppToast v-bind="args" />'
+ })
+} satisfies Meta<ToastProps>
+
+export default meta
+type Story = StoryObj<typeof meta>
+
+export const Default: Story = {}
+
+export const Warning: Story = {
+ args: {
+ message: 'Storage workspace is offline. Changes are queued locally.',
+ variant: 'warning',
+ copyable: true,
+ copyLabel: 'Copy message',
+ copiedLabel: 'Copied',
+ closeLabel: 'Close'
+ }
+}
+
+export const Error: Story = {
+ args: {
+ message: 'Could not save “shadow Figma kit (Community).fig”.',
+ variant: 'error',
+ copyable: true,
+ copyLabel: 'Copy message',
+ copiedLabel: 'Copied',
+ closeLabel: 'Close'
+ }
+}
+
+export const WithAction: Story = {
+ args: { message: 'Design file moved to Trash.', actionLabel: 'Undo' }
+}
+
+export const RepeatedMessage: Story = {
+ args: {
+ message: 'Lost connection to the collaboration room',
+ variant: 'warning',
+ count: 4,
+ copyable: true,
+ copyLabel: 'Copy message',
+ copiedLabel: 'Copied',
+ closeLabel: 'Close'
+ }
+}
+
+export const DownloadProgress: Story = {
+ args: {
+ message: 'Downloading OpenPencil 0.15.2',
+ progress: { value: 10_100_000, max: 24_000_000 },
+ progressLabel: '42% · 9.6 MiB of 22.9 MiB'
+ }
+}
+
+export const DownloadProgressUnknownTotal: Story = {
+ args: {
+ message: 'Downloading OpenPencil 0.15.2',
+ progress: { value: 4_400_000 },
+ progressLabel: '4.2 MiB downloaded'
+ }
+}
+
+export const ProgressLifecycle: Story = {
+ render: () => ({
+ components: { AppButton, AppToast },
+ setup() {
+ const TOTAL_BYTES = 24_000_000
+ const STEP_BYTES = TOTAL_BYTES / 8
+ const AUTO_DISMISS_MS = 3000
+
+ const downloaded = ref(0)
+ const totalBytes = ref<number | null>(TOTAL_BYTES)
+ const reporting = ref(true)
+
+ const progress = computed<ToastProgress | null>(() => {
+ if (!reporting.value) return null
+ return totalBytes.value === null
+ ? { value: downloaded.value }
+ : { value: downloaded.value, max: totalBytes.value }
+ })
+ const progressLabel = computed(() => {
+ const percent = toastProgressPercent(progress.value)
+ if (percent === null) return `${formatMiB(downloaded.value)} downloaded`
+ return `${percent}% · ${formatMiB(downloaded.value)} of ${formatMiB(totalBytes.value ?? 0)}`
+ })
+ const duration = computed(() => (progress.value ? 0 : AUTO_DISMISS_MS))
+
+ function formatMiB(bytes: number) {
+ return `${(bytes / 1024 / 1024).toFixed(1)} MiB`
+ }
+
+ return {
+ progress,
+ progressLabel,
+ duration,
+ advance: () => {
+ downloaded.value = Math.min(TOTAL_BYTES, downloaded.value + STEP_BYTES)
+ },
+ reset: () => {
+ downloaded.value = 0
+ totalBytes.value = TOTAL_BYTES
+ reporting.value = true
+ },
+ useUnknownTotal: () => {
+ totalBytes.value = null
+ },
+ stopReporting: () => {
+ reporting.value = false
+ }
+ }
+ },
+ template: `
+ <div class="mt-24 flex flex-wrap items-center gap-2">
+ <AppButton @click="advance">Advance download</AppButton>
+ <AppButton @click="reset">Reset</AppButton>
+ <AppButton @click="useUnknownTotal">Unknown total</AppButton>
+ <AppButton @click="stopReporting">Clear progress</AppButton>
+ </div>
+ <AppToast
+ message="Downloading OpenPencil 0.15.2"
+ :progress="progress"
+ :progress-label="progressLabel"
+ :duration="duration"
+ />
+ `
+ })
+}
diff --git a/src/components/ui/feedback/AppToast.vue b/src/components/ui/feedback/AppToast.vue
new file mode 100644
index 000000000..e283715c0
--- /dev/null
+++ b/src/components/ui/feedback/AppToast.vue
@@ -0,0 +1,118 @@
+<script setup lang="ts">
+import { useClipboard } from '@vueuse/core'
+import { ToastClose, ToastDescription, ToastRoot } from 'reka-ui'
+import { computed } from 'vue'
+
+import Tip from '@/components/ui/overlay/Tip.vue'
+
+import {
+ toast as toastTheme,
+ toastProgressPercent,
+ toastProgressState,
+ type ToastProps
+} from './toast'
+
+const {
+ message,
+ variant = 'default',
+ count = 1,
+ progress = null,
+ progressLabel,
+ actionLabel,
+ duration,
+ copyable = false,
+ copyLabel,
+ copiedLabel,
+ closeLabel,
+ ui
+} = defineProps<ToastProps>()
+
+const emit = defineEmits<{ close: []; action: [] }>()
+
+const { copy, copied } = useClipboard({ copiedDuring: 1500 })
+const state = computed(() => toastProgressState(progress))
+const percent = computed(() => toastProgressPercent(progress))
+const styles = computed(() => {
+ const theme = toastTheme({ tone: variant, progress: state.value })
+ return {
+ root: theme.root({ class: ui?.root }),
+ icon: theme.icon({ class: ui?.icon }),
+ content: theme.content({ class: ui?.content }),
+ message: theme.message({ class: ui?.message }),
+ count: theme.count({ class: ui?.count }),
+ progress: theme.progress({ class: ui?.progress }),
+ progressTrack: theme.progressTrack({ class: ui?.progressTrack }),
+ progressFill: theme.progressFill({ class: ui?.progressFill }),
+ progressLabel: theme.progressLabel({ class: ui?.progressLabel }),
+ action: theme.action({ class: ui?.action }),
+ control: theme.control({ class: ui?.control })
+ }
+})
+</script>
+
+<template>
+ <!-- Reka does not cancel an existing dismissal timer when duration becomes 0.
+ Remount when switching lifetime policy so resumed work cannot expire. -->
+ <ToastRoot
+ :key="duration === 0 ? 'persistent' : 'timed'"
+ data-slot="toast"
+ :duration="duration"
+ :class="styles.root"
+ :data-tone="variant"
+ :data-progress="state"
+ @update:open="
+ (open) => {
+ if (!open) emit('close')
+ }
+ "
+ >
+ <icon-lucide-loader-2 v-if="state !== 'none'" :class="styles.icon" aria-hidden="true" />
+ <icon-lucide-check v-else-if="variant === 'default'" :class="styles.icon" aria-hidden="true" />
+ <icon-lucide-triangle-alert v-else :class="styles.icon" aria-hidden="true" />
+ <div :class="styles.content" data-slot="toast-content">
+ <ToastDescription :class="styles.message">
+ {{ message }}<span v-if="count > 1" :class="styles.count">×{{ count }}</span>
+ </ToastDescription>
+ <div v-if="state !== 'none'" :class="styles.progress" data-slot="toast-progress">
+ <div
+ role="progressbar"
+ :class="styles.progressTrack"
+ :aria-label="progressLabel ?? message"
+ :aria-valuenow="percent ?? undefined"
+ :aria-valuemin="percent === null ? undefined : 0"
+ :aria-valuemax="percent === null ? undefined : 100"
+ >
+ <div
+ :class="styles.progressFill"
+ :style="percent === null ? undefined : { width: `${percent}%` }"
+ data-slot="toast-progress-fill"
+ />
+ </div>
+ <p v-if="progressLabel" :class="styles.progressLabel" data-slot="toast-progress-label">
+ {{ progressLabel }}
+ </p>
+ </div>
+ <slot />
+ </div>
+ <button v-if="actionLabel" type="button" :class="styles.action" @click="emit('action')">
+ {{ actionLabel }}
+ </button>
+ <template v-if="copyable">
+ <Tip :label="copied ? copiedLabel : copyLabel">
+ <button
+ type="button"
+ data-slot="toast-copy"
+ :class="styles.control"
+ :aria-label="copied ? copiedLabel : copyLabel"
+ @click="copy(message)"
+ >
+ <icon-lucide-check v-if="copied" class="size-3" aria-hidden="true" />
+ <icon-lucide-copy v-else class="size-3" aria-hidden="true" />
+ </button>
+ </Tip>
+ <ToastClose data-slot="toast-close" :class="styles.control" :aria-label="closeLabel">
+ <icon-lucide-x class="size-3" aria-hidden="true" />
+ </ToastClose>
+ </template>
+ </ToastRoot>
+</template>
diff --git a/src/components/ui/feedback/banner.ts b/src/components/ui/feedback/banner.ts
index f79d5664f..9271a67a4 100644
--- a/src/components/ui/feedback/banner.ts
+++ b/src/components/ui/feedback/banner.ts
@@ -9,6 +9,5 @@ export type BannerUI = ComponentUI<typeof bannerTheme>
export interface BannerProps {
/** Persist dismissal under this key; omit to keep the banner permanently visible. */
storageKey?: string
- testId?: string
ui?: BannerUI
}
diff --git a/src/components/ui/feedback/toast.ts b/src/components/ui/feedback/toast.ts
index dce3a8bf3..eb7c0f1ca 100644
--- a/src/components/ui/feedback/toast.ts
+++ b/src/components/ui/feedback/toast.ts
@@ -1,23 +1,50 @@
-import { twMerge } from 'tailwind-merge'
-import { tv } from 'tailwind-variants'
+import { tv, type VariantProps } from 'tailwind-variants'
+import type { ComponentUI } from '@/components/ui/types'
+import toastTheme from '@/theme/feedback/toast'
+
+export const toast = tv(toastTheme)
+export type ToastUI = ComponentUI<typeof toastTheme>
+export type ToastProgressState = VariantProps<typeof toast>['progress']
+
+/** Selects the toast treatment; non-default tones are dismissible and copyable. */
export type ToastVariant = 'default' | 'warning' | 'error'
-const toast = tv({
- base: 'motion-reduce:data-[state=open]:animate-none motion-reduce:data-[state=closed]:animate-none flex max-w-sm items-start gap-1.5 rounded-md px-2.5 py-1.5 text-xs shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out data-[state=closed]:slide-out-to-top-1 data-[state=open]:animate-in data-[state=open]:fade-in data-[state=open]:slide-in-from-top-1 data-[swipe=cancel]:translate-y-0 data-[swipe=cancel]:transition-transform data-[swipe=move]:translate-y-[var(--reka-toast-swipe-move-y)]',
- variants: {
- tone: {
- default: 'bg-accent text-white',
- warning:
- 'border border-[var(--color-warning-border)] bg-[var(--color-warning-bg)] text-[var(--color-warning-text)]',
- error: 'bg-red-600 text-white'
- }
- },
- defaultVariants: { tone: 'default' }
-})
+/** Progress reported by a long-running operation behind a toast. */
+export interface ToastProgress {
+ /** Completed units. */
+ value?: number
+ /** Total units; omit alongside `value` when the producer cannot measure the work. */
+ max?: number
+}
+
+export function toastProgressPercent(progress?: ToastProgress | null): number | null {
+ if (progress?.value === undefined || progress.max === undefined) return null
+ if (progress.max <= 0) return null
+ return Math.min(100, Math.max(0, Math.round((progress.value / progress.max) * 100)))
+}
+
+export function toastProgressState(progress?: ToastProgress | null): ToastProgressState {
+ if (!progress) return 'none'
+ return toastProgressPercent(progress) === null ? 'indeterminate' : 'determinate'
+}
-export function useToastUI(options?: { tone?: ToastVariant; ui?: { base?: string } }) {
- return {
- base: twMerge(toast(options), options?.ui?.base)
- }
+export interface ToastProps {
+ message: string
+ variant?: ToastVariant
+ /** Number of times this message repeated while it stayed visible. */
+ count?: number
+ /** Present while a long-running operation reports progress. */
+ progress?: ToastProgress | null
+ /** Measurement text beside the bar, formatted by the producing domain. */
+ progressLabel?: string
+ /** Renders an inline action that emits `action` when pressed. */
+ actionLabel?: string
+ /** Milliseconds before auto-dismissal; 0 keeps a reported-progress toast open. */
+ duration?: number
+ copyable?: boolean
+ copyLabel?: string
+ copiedLabel?: string
+ closeLabel?: string
+ ui?: ToastUI
}
diff --git a/src/components/ui/panel/PanelFoundation.stories.ts b/src/components/ui/panel/PanelFoundation.stories.ts
index 76e908968..69c7d963f 100644
--- a/src/components/ui/panel/PanelFoundation.stories.ts
+++ b/src/components/ui/panel/PanelFoundation.stories.ts
@@ -4,16 +4,17 @@ import { expect, userEvent, within } from 'storybook/test'
import { ref } from 'vue'
import MoreIcon from '~icons/lucide/ellipsis'
import EyeIcon from '~icons/lucide/eye'
+import LayoutPanelTopIcon from '~icons/lucide/layout-panel-top'
import LinkIcon from '~icons/lucide/link'
import RotateIcon from '~icons/lucide/rotate-ccw'
import SquareIcon from '~icons/lucide/square'
+import AppButton from '@/components/ui/button/AppButton.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
import AppInput from '@/components/ui/input/AppInput.vue'
import AppSelect from '@/components/ui/select/AppSelect.vue'
import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'
-import PanelSelectionDemo from './demo/PanelSelectionDemo.vue'
import PanelFieldGroup from './PanelFieldGroup.vue'
import PanelGrid from './PanelGrid.vue'
import PanelHeader from './PanelHeader.vue'
@@ -36,7 +37,28 @@ export default meta
type Story = StoryObj<typeof meta>
export const SelectionTransition: Story = {
- render: () => ({ components: { PanelSelectionDemo }, template: '<PanelSelectionDemo />' })
+ render: () => ({
+ components: { AppButton, IconButton, LayoutPanelTopIcon, PanelSection },
+ setup() {
+ const container = ref(false)
+ return { container }
+ },
+ template: `
+ <div class="w-72 bg-panel text-surface">
+ <AppButton @click="container = !container">Switch selection</AppButton>
+ <PanelSection :label="container ? 'Auto layout' : 'Layout'">
+ <template v-if="container" #actions>
+ <IconButton label="Remove auto layout" active>
+ <LayoutPanelTopIcon class="size-3.5" />
+ </IconButton>
+ </template>
+ <p class="text-xs text-muted">
+ {{ container ? 'Frame selection' : 'Rectangle selection' }}
+ </p>
+ </PanelSection>
+ </div>
+ `
+ })
}
export const StateMatrix: Story = {
diff --git a/src/components/ui/panel/demo/PanelSelectionDemo.vue b/src/components/ui/panel/demo/PanelSelectionDemo.vue
deleted file mode 100644
index d0fe2cc22..000000000
--- a/src/components/ui/panel/demo/PanelSelectionDemo.vue
+++ /dev/null
@@ -1,24 +0,0 @@
-<script setup lang="ts">
-import { ref } from 'vue'
-
-import AppButton from '@/components/ui/button/AppButton.vue'
-import IconButton from '@/components/ui/button/IconButton.vue'
-
-import PanelSection from '../PanelSection.vue'
-
-const container = ref(false)
-</script>
-
-<template>
- <div class="w-72 bg-panel text-surface">
- <AppButton @click="container = !container">Switch selection</AppButton>
- <PanelSection :label="container ? 'Auto layout' : 'Layout'">
- <template v-if="container" #actions>
- <IconButton label="Remove auto layout" active
- ><icon-lucide-layout-panel-top class="size-3.5"
- /></IconButton>
- </template>
- <p class="text-xs text-muted">{{ container ? 'Frame selection' : 'Rectangle selection' }}</p>
- </PanelSection>
- </div>
-</template>
diff --git a/src/theme/feedback/toast.ts b/src/theme/feedback/toast.ts
new file mode 100644
index 000000000..eb35fed6a
--- /dev/null
+++ b/src/theme/feedback/toast.ts
@@ -0,0 +1,41 @@
+import { motionStyles } from '@/theme/motion/styles'
+
+const toastTheme = {
+ slots: {
+ root: 'motion-reduce:data-[state=open]:animate-none motion-reduce:data-[state=closed]:animate-none flex max-w-sm items-start gap-1.5 rounded-md px-2.5 py-1.5 text-xs shadow-md data-[state=closed]:animate-out data-[state=closed]:fade-out data-[state=closed]:slide-out-to-top-1 data-[state=open]:animate-in data-[state=open]:fade-in data-[state=open]:slide-in-from-top-1 data-[swipe=cancel]:translate-y-0 data-[swipe=cancel]:transition-transform data-[swipe=move]:translate-y-[var(--reka-toast-swipe-move-y)]',
+ icon: 'mt-0.5 size-3 shrink-0',
+ content: 'min-w-0 flex-1',
+ message: 'select-text',
+ count: 'ml-1.5 opacity-70',
+ progress: 'mt-1.5 flex flex-col gap-1',
+ progressTrack: 'h-1 w-full overflow-hidden rounded-full bg-current/25',
+ progressFill:
+ 'h-full rounded-full bg-current transition-[width] duration-150 ease-out motion-reduce:transition-none',
+ progressLabel: 'text-[10px] leading-none tabular-nums opacity-80',
+ action:
+ 'shrink-0 cursor-pointer rounded px-1.5 py-0.5 text-[10px] font-medium underline-offset-2 hover:underline',
+ control: 'mt-0.5 shrink-0 cursor-pointer rounded p-0.5 opacity-70 hover:opacity-100'
+ },
+ variants: {
+ tone: {
+ default: { root: 'bg-accent text-white' },
+ warning: {
+ root: 'border border-[var(--color-warning-border)] bg-[var(--color-warning-bg)] text-[var(--color-warning-text)]'
+ },
+ error: { root: 'bg-red-600 text-white' }
+ },
+ // A determinate bar takes its width from the consumer; an indeterminate one
+ // pulses in place so the toast still reads as work in progress.
+ progress: {
+ none: {},
+ determinate: { icon: motionStyles.spinner },
+ indeterminate: {
+ icon: motionStyles.spinner,
+ progressFill: 'motion-reduce:animate-none w-1/3 animate-pulse'
+ }
+ }
+ },
+ defaultVariants: { tone: 'default' as const, progress: 'none' as const }
+} as const
+
+export default toastTheme
diff --git a/steiger.config.ts b/steiger.config.ts
index 5b2ead48b..d278fa632 100644
--- a/steiger.config.ts
+++ b/steiger.config.ts
@@ -38,6 +38,7 @@ export default defineConfig([
'open-pencil/no-non-ui-imports-in-shared-ui': 'error',
'open-pencil/no-app-imports-in-shared-ui': 'error',
'open-pencil/no-property-panel-internals-outside-panel': 'error',
+ 'open-pencil/no-production-test-ids-in-shared-layers': 'error',
'open-pencil/no-native-title-attributes-in-vue': 'error',
'open-pencil/no-ui-imports-in-core': 'error',
'open-pencil/scripts-are-entrypoint-shims': 'error',
diff --git a/tests/e2e/canvas/color-space.webkit.spec.ts b/tests/e2e/canvas/color-space.webkit.spec.ts
index df5d1878f..be3195ad6 100644
--- a/tests/e2e/canvas/color-space.webkit.spec.ts
+++ b/tests/e2e/canvas/color-space.webkit.spec.ts
@@ -6,7 +6,8 @@ import {
emulateWideGamutDisplay,
focusPaintEffects,
sceneBufferState,
- waitForSettledScene
+ waitForSettledScene,
+ wideGamutBanner
} from '#tests/helpers/canvas/color-space'
test.use({ viewport: { width: 1200, height: 900 } })
@@ -56,7 +57,7 @@ test('warns when a Display-P3 document cannot be presented in wide gamut', async
await canvas.waitForInit()
// New documents are sRGB, so this notice only applies once a document declares Display P3.
- const banner = page.getByTestId('wide-gamut-banner')
+ const banner = wideGamutBanner(page)
await expect(banner).toBeHidden()
expect(await sceneBufferState(page)).toMatchObject({
colorSpace: 'srgb',
diff --git a/tests/e2e/chat/responses.spec.ts b/tests/e2e/chat/responses.spec.ts
index 710a599bb..01335acbc 100644
--- a/tests/e2e/chat/responses.spec.ts
+++ b/tests/e2e/chat/responses.spec.ts
@@ -38,11 +38,11 @@ test('authentication errors explain the cause and link to Settings', async ({
}) => {
await chat.submit('Trigger expired key error')
- const toast = chat.page.getByTestId('toast-item').filter({
+ const toast = chat.page.locator('[data-slot="toast"]').filter({
hasText: 'Your provider API key is invalid or expired. Replace it in Settings.'
})
await expect(toast).toBeVisible()
- await expect(chat.page.getByTestId('toast-item')).toHaveCount(1)
+ await expect(chat.page.locator('[data-slot="toast"]')).toHaveCount(1)
await toast.getByRole('button', { name: 'Open settings' }).click()
await expect(chat.page.getByTestId('app-settings-dialog')).toBeVisible()
})
@@ -50,7 +50,7 @@ test('authentication errors explain the cause and link to Settings', async ({
test('transport errors show a safe localized toast', async ({ configuredChat: chat }) => {
await chat.submit('Trigger missing agent error')
await expect(
- chat.page.getByTestId('toast-item').filter({
+ chat.page.locator('[data-slot="toast"]').filter({
hasText: 'The model request failed. Check the provider settings and try again.'
})
).toBeVisible()
diff --git a/tests/e2e/storybook/toast.spec.ts b/tests/e2e/storybook/toast.spec.ts
new file mode 100644
index 000000000..6b1ffb681
--- /dev/null
+++ b/tests/e2e/storybook/toast.spec.ts
@@ -0,0 +1,88 @@
+import { expect, test } from '@playwright/test'
+
+test('determinate progress exposes its value and bar width', async ({ page }) => {
+ await page.goto('/iframe.html?id=design-system-toast--download-progress&viewMode=story')
+
+ const toast = page.locator('[data-slot="toast"]')
+ await expect(toast).toHaveAttribute('data-progress', 'determinate')
+ await expect(toast.locator('[data-slot="toast-progress-label"]')).toHaveText(
+ '42% · 9.6 MiB of 22.9 MiB'
+ )
+
+ const bar = toast.getByRole('progressbar')
+ await expect(bar).toHaveAttribute('aria-valuenow', '42')
+ await expect(bar).toHaveAttribute('aria-valuemin', '0')
+ await expect(bar).toHaveAttribute('aria-valuemax', '100')
+ await expect(toast.locator('[data-slot="toast-progress-fill"]')).toHaveAttribute(
+ 'style',
+ /width: 42%/
+ )
+})
+
+test('progress without a known total stays indeterminate', async ({ page }) => {
+ await page.goto(
+ '/iframe.html?id=design-system-toast--download-progress-unknown-total&viewMode=story'
+ )
+
+ const toast = page.locator('[data-slot="toast"]')
+ await expect(toast).toHaveAttribute('data-progress', 'indeterminate')
+ await expect(toast.getByRole('progressbar')).not.toHaveAttribute('aria-valuenow', /\d/)
+ await expect(toast.locator('[data-slot="toast-progress-label"]')).toHaveText('4.2 MiB downloaded')
+})
+
+test('a reported total flips between determinate, indeterminate, and cleared', async ({ page }) => {
+ await page.clock.install()
+ await page.goto('/iframe.html?id=design-system-toast--progress-lifecycle&viewMode=story')
+
+ const toast = page.locator('[data-slot="toast"]')
+ const bar = toast.getByRole('progressbar')
+ await expect(toast).toHaveAttribute('data-progress', 'determinate')
+ await expect(bar).toHaveAttribute('aria-valuenow', '0')
+
+ // The bar follows the reported work and keeps the toast open instead of expiring.
+ await page.getByRole('button', { name: 'Advance download' }).click()
+ await expect(bar).toHaveAttribute('aria-valuenow', '13')
+ await expect(toast.locator('[data-slot="toast-progress-label"]')).toHaveText(
+ '13% · 2.9 MiB of 22.9 MiB'
+ )
+ await page.clock.fastForward(3_500)
+ await expect(toast).toBeVisible()
+
+ // Losing the total must drop the value rather than pinning the bar at 13%.
+ await page.getByRole('button', { name: 'Unknown total' }).click()
+ await expect(toast).toHaveAttribute('data-progress', 'indeterminate')
+ await expect(bar).not.toHaveAttribute('aria-valuenow', /\d/)
+
+ // Clearing progress removes the bar and returns the toast to auto-dismissal.
+ await page.getByRole('button', { name: 'Clear progress' }).click()
+ await expect(toast).toHaveAttribute('data-progress', 'none')
+ await expect(toast.getByRole('progressbar')).toHaveCount(0)
+ await page.clock.fastForward(3_500)
+ await expect(toast).toBeHidden()
+})
+
+test('resuming progress cancels the pending auto-dismissal', async ({ page }) => {
+ await page.clock.install()
+ await page.goto('/iframe.html?id=design-system-toast--progress-lifecycle&viewMode=story')
+
+ const toast = page.locator('[data-slot="toast"]')
+ await expect(toast).toHaveAttribute('data-progress', 'determinate')
+ await page.getByRole('button', { name: 'Clear progress' }).click()
+ await expect(toast).toHaveAttribute('data-progress', 'none')
+ await page.getByRole('button', { name: 'Reset', exact: true }).click()
+ await expect(toast).toHaveAttribute('data-progress', 'determinate')
+
+ // Advance beyond the timer installed before progress resumed.
+ await page.clock.fastForward(3_500)
+ await expect(toast).toBeVisible()
+ await page.getByRole('button', { name: 'Advance download' }).click()
+ await expect(toast.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '13')
+})
+
+test('an action toast renders its action', async ({ page }) => {
+ await page.goto('/iframe.html?id=design-system-toast--with-action&viewMode=story')
+
+ const toast = page.locator('[data-slot="toast"]')
+ await expect(toast).toContainText('Design file moved to Trash.')
+ await expect(toast.getByRole('button', { name: 'Undo' })).toBeVisible()
+})
diff --git a/tests/engine/app/shell/toast.test.ts b/tests/engine/app/shell/toast.test.ts
new file mode 100644
index 000000000..ea595107e
--- /dev/null
+++ b/tests/engine/app/shell/toast.test.ts
@@ -0,0 +1,71 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { toast, toastDuration } from '@/app/shell/ui'
+
+function entryAt(index = 0) {
+ const entry = toast.toasts.value[index]
+ if (!entry) throw new Error(`Missing toast at index ${index}`)
+ return entry
+}
+
+afterEach(() => {
+ for (const entry of toast.toasts.value) toast.remove(entry.id)
+})
+
+describe('toast progress', () => {
+ test('keeps a reported-progress toast open until progress clears', () => {
+ const handle = toast.startProgress('Downloading OpenPencil 0.15.1')
+
+ expect(entryAt().progress).toEqual({})
+ expect(toastDuration(entryAt())).toBe(0)
+
+ handle.update({ progress: { value: 5, max: 10 }, progressLabel: '50%' })
+ expect(entryAt().progressLabel).toBe('50%')
+ expect(toastDuration(entryAt())).toBe(0)
+
+ handle.update({ progress: null, progressLabel: null })
+ expect(entryAt().progress).toBeUndefined()
+ expect(entryAt().progressLabel).toBeUndefined()
+ expect(toastDuration(entryAt())).toBe(toast.TOAST_DURATION)
+ })
+
+ test('updates one toast in place instead of stacking every chunk', () => {
+ const handle = toast.startProgress('Downloading OpenPencil 0.15.1')
+
+ handle.update({ message: 'Downloading OpenPencil 0.15.1' })
+ handle.update({ progressLabel: '42% · 9.6 MiB of 22.9 MiB' })
+
+ expect(toast.toasts.value).toHaveLength(1)
+ expect(entryAt().progressLabel).toBe('42% · 9.6 MiB of 22.9 MiB')
+ })
+
+ test('does not merge a repeated message into a progress toast', () => {
+ const handle = toast.startProgress('Downloading OpenPencil 0.15.1')
+
+ toast.info('Downloading OpenPencil 0.15.1')
+
+ expect(toast.toasts.value).toHaveLength(2)
+ expect(entryAt().progress).toEqual({})
+ handle.dismiss()
+ expect(toast.toasts.value).toHaveLength(1)
+ })
+
+ test('errors keep their longer duration only without reported progress', () => {
+ toast.warning('Storage workspace is offline')
+ expect(toastDuration(entryAt())).toBe(toast.TOAST_DURATION)
+
+ toast.error('Could not save the document')
+ expect(toastDuration(entryAt(1))).toBe(toast.ERROR_TOAST_DURATION)
+ })
+
+ test('ignores updates to a toast that was trimmed away', () => {
+ const dropped = toast.startProgress('First download')
+ for (let index = 0; index < 5; index += 1) toast.info(`Message ${index}`)
+
+ expect(toast.toasts.value.map((entry) => entry.message)).not.toContain('First download')
+
+ dropped.update({ progressLabel: 'ignored' })
+
+ expect(toast.toasts.value.map((entry) => entry.progressLabel)).not.toContain('ignored')
+ })
+})
diff --git a/tests/engine/tauri/processes.test.ts b/tests/engine/tauri/processes.test.ts
index 2c7f52fe2..925e058eb 100644
--- a/tests/engine/tauri/processes.test.ts
+++ b/tests/engine/tauri/processes.test.ts
@@ -3,6 +3,7 @@ import { afterEach, describe, expect, test, vi } from 'bun:test'
import { ref } from 'vue'
import { spawnACPProcess } from '@/app/ai/acp/process'
+import { toast } from '@/app/shell/ui'
import { checkForAppUpdate } from '@/app/shell/updater'
import { clearTauriMocks, mockTauriIPC } from '#tests/helpers/tauri/mocks'
@@ -10,6 +11,7 @@ import { clearTauriMocks, mockTauriIPC } from '#tests/helpers/tauri/mocks'
afterEach(async () => {
await clearTauriMocks()
vi.restoreAllMocks()
+ for (const entry of toast.toasts.value) toast.remove(entry.id)
Reflect.deleteProperty(globalThis, 'window')
Reflect.deleteProperty(globalThis, 'navigator')
})
@@ -118,6 +120,16 @@ describe('Tauri updater helper', () => {
available: ({ version }: { version: string }) => `Version ${version}`,
installPrompt: 'Install now?',
downloading: ({ version }: { version: string }) => `Downloading ${version}`,
+ downloadProgress: ({
+ percent,
+ downloaded,
+ total
+ }: {
+ percent: number
+ downloaded: string
+ total: string
+ }) => `${percent}% of ${total} (${downloaded})`,
+ downloadProgressUnknown: ({ downloaded }: { downloaded: string }) => `${downloaded} downloaded`,
installedTitle: 'Installed',
installed: ({ version, size }: { version: string; size: string }) =>
`Installed ${version}${size}`,
@@ -180,4 +192,40 @@ describe('Tauri updater helper', () => {
})
expect(calls[2]?.args).toMatchObject({ rid: 9 })
})
+
+ test('reports download progress once and clears the toast on failure', async () => {
+ await mockTauriIPC((cmd, args) => {
+ if (cmd === 'plugin:updater|check') {
+ return {
+ rid: 9,
+ currentVersion: '0.11.8',
+ version: '0.11.9',
+ date: null,
+ body: 'Release notes',
+ rawJson: '{}'
+ }
+ }
+ if (cmd === 'plugin:dialog|message') {
+ const options = args as { buttons?: string }
+ if (options.buttons === 'OkCancel') return 'Ok'
+ }
+ if (cmd === 'plugin:updater|download_and_install') {
+ const onEvent = (args as { onEvent: { onmessage: (event: unknown) => void } }).onEvent
+ onEvent.onmessage({ event: 'Started', data: { contentLength: 4 } })
+ onEvent.onmessage({ event: 'Progress', data: { chunkLength: 2 } })
+ expect(toast.toasts.value).toHaveLength(1)
+ expect(toast.toasts.value[0]?.progress).toEqual({ value: 2, max: 4 })
+ expect(toast.toasts.value[0]?.progressLabel).toBe('50% of 4 B (2 B)')
+ throw new Error('download interrupted')
+ }
+ return null
+ })
+
+ await checkForAppUpdate({ messages })
+
+ // The failed progress toast must not linger: it never expires on its own.
+ expect(toast.toasts.value.map((entry) => entry.message)).toEqual([
+ 'Failed: download interrupted'
+ ])
+ })
})
diff --git a/tests/helpers/canvas/color-space.ts b/tests/helpers/canvas/color-space.ts
index b1c79374d..36e1c55ab 100644
--- a/tests/helpers/canvas/color-space.ts
+++ b/tests/helpers/canvas/color-space.ts
@@ -12,11 +12,16 @@ export async function emulateWideGamutDisplay(page: Page) {
})
}
+/** The wide-gamut notice is the only capability banner whose content names Display-P3. */
+export function wideGamutBanner(page: Page) {
+ return page.getByRole('status').filter({ hasText: 'Display-P3' })
+}
+
/** Keep the wide-gamut notice from resizing the canvas in rendering-fidelity tests. */
export async function dismissWideGamutBanner(page: Page) {
- const banner = page.getByTestId('wide-gamut-banner')
+ const banner = wideGamutBanner(page)
await banner.waitFor({ state: 'visible', timeout: 5_000 }).catch(() => undefined)
- if (await banner.isVisible()) await page.getByTestId('wide-gamut-banner-dismiss').click()
+ if (await banner.isVisible()) await banner.locator('[data-slot="banner-dismiss"]').click()
}
/** Focus the demo's paint and effects page, where blends and masks live. */