AI-native design editor. Open-source Figma alternative.
feat(toolbar): customize the toolbar in Settings (#1058)
Danila Poyarkovf5ae3097c917
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2782277c5..9bbe24573 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,12 +4,12 @@### Breaking changes+- `useFlatReorderDrag` from `@open-pencil/vue` takes `operations`, which drops each target accepts, and `onCombine`, for dropping onto an item, and `FlatReorderInstruction` is now any list-item `Instruction`, so it can be `'combine'` when a list opts in; code that switches on its `operation` needs that case.- The editor `Tool` type from `@open-pencil/core` and `@open-pencil/vue` includes `'COMMENT'`, and `EDITOR_TOOLS` and `TOOL_SHORTCUTS` list the Comment tool on <kbd>C</kbd>, so a `Record<Tool, …>` needs a `COMMENT` entry and toolbars built on `ToolbarRoot` show it. The canvas places nothing while it is active; the app's comments layer does.- A paint's `gradientTransform` follows Figma's convention everywhere: it maps the layer's unit square onto gradient space, where a linear gradient runs from (0, 0.5) to (1, 0.5). Gradients made in OpenPencil before this release, which used the inverse, draw differently; code that builds gradients by hand should use `linearGradientTransform` and `ellipticalGradientTransform` from the new `@open-pencil/scene-graph/gradient`, which also has Figma's default transform and stops. `isGradientFill` and `GradientFillType` moved there from `@open-pencil/core/geometry`, and `linearGradientEndpoints` is removed from the canvas module.- `useStrokeControls` from `@open-pencil/vue` acts on the whole selection: `updateAlign`, `selectSide`, and `updateBorderWeight` no longer take a node, and `currentAlign()` and `borderWeight(side)` read the selection and return `MIXED` when it differs. `useEffectsControls().scrubEffect` and `commitEffect` no longer take a node. `useTypography` edits every selected text layer and adds `nodes`, `merged`, and `fontFeature`. The `panels.layersCount` message is now `panels.selectedCount`.- The app renders `render` JSX itself and no longer accepts the pre-rendered tree that earlier versions of `openpencil-mcp` send, so an older `openpencil-mcp` fails to render into this app version; update it with the app.- `VectorizedPath` from `@open-pencil/core/vector` replaces `clipNetworks` with `clips`, each the clip path's `id` and one network per clip shape, and adds `elements`, the groups and shape a path was drawn from. `SVGVectorizeResult` adds `texts`, the SVG's text placed in the target space, and `SVGImportData` from `@open-pencil/core/io` adds the root `name` and whether the SVG is `sized`.-- `VectorizedPath` from `@open-pencil/core/vector` replaces `clipNetworks` with `clips`, each the clip path's `id` and one network per clip shape, and adds `elements`, the groups and shape a path was drawn from. `SVGImportData` from `@open-pencil/core/io` adds the root `name` and whether the SVG is `sized`.- `@open-pencil/scene-graph/layout-guides` is now `@open-pencil/scene-graph/layout`, which also exports the per-axis sizing helpers and the auto layout keyword parsers; `layoutGuideLines` and `layoutGuideSections` are unchanged.- `SceneNode` from `@open-pencil/scene-graph` has `isExposedInstance`, whether an instance inside a component shows its properties on instances of that component, so code that builds `SceneNode` objects itself must include it. In the plugin API, `isExposedInstance` and `exposedInstances` follow that flag and Figma's rules instead of treating an instance whose swap is bound to a property as exposed: only an instance in a component's own layers whose component has properties can be exposed, and its copies in instances report it but cannot change it.- `usePosition` from `@open-pencil/vue` reports and edits `x`, `y`, and `rotation` as Figma's properties panel does: the turned layer's box on the canvas, measured from its frame or page, and its counterclockwise angle. `getDefaultCanvasBgColor` and `CANVAS_BG_COLOR_DARK` are removed from `@open-pencil/core/constants`; new pages use `PAGE_DEFAULT_BACKGROUNDS`, keyed by interface theme.@@ -113,6 +113,7 @@- Join a shared room right away under a generated name such as *Teal Fox*, and set the one name every room shows in Settings or the share panel.- Choose an accent color in **Settings → General → Appearance**: one of eight presets or any custom color. Buttons, toggles, selected layers, focus rings, the active tool, and the canvas selection, handles, size labels, and ruler badges follow it in both themes, and text on accent surfaces turns dark when the color is too light for white. The CLI and MCP `settings` commands read and set it as `appearance.accent`.+- Customize the toolbar in **Settings → Toolbar**, also opened from **Customize toolbar…** when you right-click it: hide tools, reorder them, and choose which share a flyout, on desktop and mobile alike. Hidden tools keep their shortcuts, **Move** always stays, and tools added in later versions join their default flyout in a customized toolbar.### Changed- Bound variables show as a neutral chip in the properties panel instead of purple text, so they no longer read as components.diff --git a/packages/docs/user-guide/drawing-shapes.md b/packages/docs/user-guide/drawing-shapes.mdindex 6c56a5df1..2ac62b3b9 100644--- a/packages/docs/user-guide/drawing-shapes.md+++ b/packages/docs/user-guide/drawing-shapes.md@@ -25,6 +25,17 @@ The shapes flyout (accessible from the toolbar) includes additional shapes:Polygon and Star have no keyboard shortcut — access them from the shapes flyout in the toolbar.+## Customizing the Toolbar++Right-click the toolbar and choose **Customize toolbar…**, or open **Settings → Toolbar**, to change it:++- Turn a tool's switch off to hide it. Hidden tools keep their keyboard shortcuts. **Move** is always shown.+- Drag a tool to reorder it. Dropped inside a box it joins that flyout; dropped in the gap between boxes it becomes a button of its own; dropped onto another tool, the two share a flyout.+- A tool's **⋯** menu moves it up or down, groups it with the tool above, or ungroups it from its flyout. Its grip also moves it with <kbd>↑</kbd> and <kbd>↓</kbd>.+- **Insert icon** runs a command rather than picking a tool, so it can move and hide but not join a flyout.++**Reset to default** restores the original layout. Tools added in later versions join their default flyout, so a customized toolbar still gets them.+## Constrained DrawingHold <kbd>Shift</kbd> while dragging to constrain the shape:diff --git a/packages/vue/src/i18n/locales/de/settings.json b/packages/vue/src/i18n/locales/de/settings.jsonindex 02c7fc840..2a6e34684 100644--- a/packages/vue/src/i18n/locales/de/settings.json+++ b/packages/vue/src/i18n/locales/de/settings.json@@ -35,6 +35,17 @@"accentGreen": "Grün","accentGraphite": "Graphit","accentCustom": "Eigene Farbe",+ "toolbar": "Werkzeugleiste",+ "toolbarDescription": "Ziehe Werkzeuge, um sie neu anzuordnen, und lege eines auf ein anderes, um beide in ein Menü zu legen. Ausgeblendete Werkzeuge behalten ihre Tastenkürzel.",+ "toolbarShow": "{tool} anzeigen",+ "toolbarReorder": "{tool} verschieben",+ "toolbarOptions": "Optionen für {tool}",+ "toolbarMoveUp": "Nach oben",+ "toolbarMoveDown": "Nach unten",+ "toolbarGroupWith": "Mit {tool} gruppieren",+ "toolbarUngroup": "Gruppierung aufheben",+ "toolbarReset": "Auf Standard zurücksetzen",+ "customizeToolbar": "Werkzeugleiste anpassen…","discardChanges": "Änderungen verwerfen?","discardChangesDescription": "Deine ungespeicherten Änderungen gehen verloren.","keepEditing": "Weiter bearbeiten",diff --git a/packages/vue/src/i18n/locales/es/settings.json b/packages/vue/src/i18n/locales/es/settings.jsonindex ee4e03ea6..5fe62d028 100644--- a/packages/vue/src/i18n/locales/es/settings.json+++ b/packages/vue/src/i18n/locales/es/settings.json@@ -35,6 +35,17 @@"accentGreen": "Verde","accentGraphite": "Grafito","accentCustom": "Color personalizado",+ "toolbar": "Barra de herramientas",+ "toolbarDescription": "Arrastra las herramientas para reordenarlas y suelta una sobre otra para ponerlas en un menú. Las herramientas ocultas conservan sus atajos.",+ "toolbarShow": "Mostrar {tool}",+ "toolbarReorder": "Reordenar {tool}",+ "toolbarOptions": "Opciones de {tool}",+ "toolbarMoveUp": "Subir",+ "toolbarMoveDown": "Bajar",+ "toolbarGroupWith": "Agrupar con {tool}",+ "toolbarUngroup": "Desagrupar",+ "toolbarReset": "Restablecer valores predeterminados",+ "customizeToolbar": "Personalizar barra de herramientas…","discardChanges": "¿Descartar los cambios?","discardChangesDescription": "Se perderán los cambios sin guardar.","keepEditing": "Seguir editando",diff --git a/packages/vue/src/i18n/locales/fr/settings.json b/packages/vue/src/i18n/locales/fr/settings.jsonindex 444be070a..3f5a86abe 100644--- a/packages/vue/src/i18n/locales/fr/settings.json+++ b/packages/vue/src/i18n/locales/fr/settings.json@@ -35,6 +35,17 @@"accentGreen": "Vert","accentGraphite": "Graphite","accentCustom": "Couleur personnalisée",+ "toolbar": "Barre d’outils",+ "toolbarDescription": "Faites glisser les outils pour les réordonner, et déposez-en un sur un autre pour les réunir dans un menu. Les outils masqués gardent leurs raccourcis.",+ "toolbarShow": "Afficher {tool}",+ "toolbarReorder": "Réordonner {tool}",+ "toolbarOptions": "Options de {tool}",+ "toolbarMoveUp": "Monter",+ "toolbarMoveDown": "Descendre",+ "toolbarGroupWith": "Grouper avec {tool}",+ "toolbarUngroup": "Dégrouper",+ "toolbarReset": "Rétablir les valeurs par défaut",+ "customizeToolbar": "Personnaliser la barre d’outils…","discardChanges": "Abandonner les modifications ?","discardChangesDescription": "Vos modifications non enregistrées seront perdues.","keepEditing": "Continuer à modifier",diff --git a/packages/vue/src/i18n/locales/it/settings.json b/packages/vue/src/i18n/locales/it/settings.jsonindex 4ca6e58ca..76c2fd6eb 100644--- a/packages/vue/src/i18n/locales/it/settings.json+++ b/packages/vue/src/i18n/locales/it/settings.json@@ -35,6 +35,17 @@"accentGreen": "Verde","accentGraphite": "Grafite","accentCustom": "Colore personalizzato",+ "toolbar": "Barra degli strumenti",+ "toolbarDescription": "Trascina gli strumenti per riordinarli e rilasciane uno su un altro per metterli in un menu. Gli strumenti nascosti mantengono le loro scorciatoie.",+ "toolbarShow": "Mostra {tool}",+ "toolbarReorder": "Riordina {tool}",+ "toolbarOptions": "Opzioni di {tool}",+ "toolbarMoveUp": "Sposta su",+ "toolbarMoveDown": "Sposta giù",+ "toolbarGroupWith": "Raggruppa con {tool}",+ "toolbarUngroup": "Separa",+ "toolbarReset": "Ripristina predefiniti",+ "customizeToolbar": "Personalizza barra degli strumenti…","discardChanges": "Scartare le modifiche?","discardChangesDescription": "Le modifiche non salvate andranno perse.","keepEditing": "Continua a modificare",diff --git a/packages/vue/src/i18n/locales/ja/settings.json b/packages/vue/src/i18n/locales/ja/settings.jsonindex 96a50412b..f55563868 100644--- a/packages/vue/src/i18n/locales/ja/settings.json+++ b/packages/vue/src/i18n/locales/ja/settings.json@@ -35,6 +35,17 @@"accentGreen": "グリーン","accentGraphite": "グラファイト","accentCustom": "カスタムカラー",+ "toolbar": "ツールバー",+ "toolbarDescription": "ツールをドラッグして並べ替え、別のツールの上にドロップすると同じメニューにまとめられます。非表示のツールもショートカットで使えます。",+ "toolbarShow": "{tool}を表示",+ "toolbarReorder": "{tool}を並べ替え",+ "toolbarOptions": "{tool}のオプション",+ "toolbarMoveUp": "上へ移動",+ "toolbarMoveDown": "下へ移動",+ "toolbarGroupWith": "{tool}とまとめる",+ "toolbarUngroup": "グループ解除",+ "toolbarReset": "デフォルトに戻す",+ "customizeToolbar": "ツールバーをカスタマイズ…","discardChanges": "変更を破棄しますか?","discardChangesDescription": "保存されていない変更は失われます。","keepEditing": "編集を続ける",diff --git a/packages/vue/src/i18n/locales/pl/settings.json b/packages/vue/src/i18n/locales/pl/settings.jsonindex 56a1fc9df..e59794e5c 100644--- a/packages/vue/src/i18n/locales/pl/settings.json+++ b/packages/vue/src/i18n/locales/pl/settings.json@@ -35,6 +35,17 @@"accentGreen": "Zielony","accentGraphite": "Grafitowy","accentCustom": "Własny kolor",+ "toolbar": "Pasek narzędzi",+ "toolbarDescription": "Przeciągaj narzędzia, aby zmienić ich kolejność, i upuść jedno na drugie, aby umieścić je w jednym menu. Ukryte narzędzia zachowują skróty.",+ "toolbarShow": "Pokaż {tool}",+ "toolbarReorder": "Zmień kolejność: {tool}",+ "toolbarOptions": "Opcje: {tool}",+ "toolbarMoveUp": "Przesuń w górę",+ "toolbarMoveDown": "Przesuń w dół",+ "toolbarGroupWith": "Grupuj z: {tool}",+ "toolbarUngroup": "Rozgrupuj",+ "toolbarReset": "Przywróć domyślne",+ "customizeToolbar": "Dostosuj pasek narzędzi…","discardChanges": "Odrzucić zmiany?","discardChangesDescription": "Niezapisane zmiany zostaną utracone.","keepEditing": "Kontynuuj edycję",diff --git a/packages/vue/src/i18n/locales/ru/settings.json b/packages/vue/src/i18n/locales/ru/settings.jsonindex d5d95f508..7b349ff86 100644--- a/packages/vue/src/i18n/locales/ru/settings.json+++ b/packages/vue/src/i18n/locales/ru/settings.json@@ -35,6 +35,17 @@"accentGreen": "Зелёный","accentGraphite": "Графит","accentCustom": "Свой цвет",+ "toolbar": "Панель инструментов",+ "toolbarDescription": "Перетаскивайте инструменты, чтобы изменить порядок, и бросьте один на другой, чтобы объединить их в меню. Скрытые инструменты сохраняют сочетания клавиш.",+ "toolbarShow": "Показывать {tool}",+ "toolbarReorder": "Переместить {tool}",+ "toolbarOptions": "Параметры: {tool}",+ "toolbarMoveUp": "Переместить вверх",+ "toolbarMoveDown": "Переместить вниз",+ "toolbarGroupWith": "Объединить с: {tool}",+ "toolbarUngroup": "Разгруппировать",+ "toolbarReset": "Сбросить по умолчанию",+ "customizeToolbar": "Настроить панель инструментов…","discardChanges": "Отменить изменения?","discardChangesDescription": "Несохранённые изменения будут потеряны.","keepEditing": "Продолжить редактирование",diff --git a/packages/vue/src/i18n/locales/zh-cn/settings.json b/packages/vue/src/i18n/locales/zh-cn/settings.jsonindex 134d9d21d..a2c1cc0cd 100644--- a/packages/vue/src/i18n/locales/zh-cn/settings.json+++ b/packages/vue/src/i18n/locales/zh-cn/settings.json@@ -35,6 +35,17 @@"accentGreen": "绿色","accentGraphite": "石墨色","accentCustom": "自定义颜色",+ "toolbar": "工具栏",+ "toolbarDescription": "拖动工具以重新排序,将一个工具拖到另一个上即可放入同一菜单。隐藏的工具仍保留快捷键。",+ "toolbarShow": "显示{tool}",+ "toolbarReorder": "重新排序{tool}",+ "toolbarOptions": "{tool}选项",+ "toolbarMoveUp": "上移",+ "toolbarMoveDown": "下移",+ "toolbarGroupWith": "与{tool}组合",+ "toolbarUngroup": "取消组合",+ "toolbarReset": "恢复默认",+ "customizeToolbar": "自定义工具栏…","discardChanges": "放弃更改?","discardChangesDescription": "未保存的更改将丢失。","keepEditing": "继续编辑",diff --git a/packages/vue/src/i18n/messages/settings.ts b/packages/vue/src/i18n/messages/settings.tsindex 2925389db..e22fab7d3 100644--- a/packages/vue/src/i18n/messages/settings.ts+++ b/packages/vue/src/i18n/messages/settings.ts@@ -1,3 +1,5 @@+import { params } from '@nanostores/i18n'+import { i18n } from '#vue/i18n/create'export const settingsMessageDefaults = {@@ -15,6 +17,18 @@ export const settingsMessageDefaults = {accentGreen: 'Green',accentGraphite: 'Graphite',accentCustom: 'Custom color',+ toolbar: 'Toolbar',+ toolbarDescription:+ 'Drag tools to reorder them, and drop one onto another to put both in a menu. Hidden tools keep their shortcuts.',+ toolbarShow: params('Show {tool}'),+ toolbarReorder: params('Reorder {tool}'),+ toolbarOptions: params('{tool} options'),+ toolbarMoveUp: 'Move up',+ toolbarMoveDown: 'Move down',+ toolbarGroupWith: params('Group with {tool}'),+ toolbarUngroup: 'Ungroup',+ toolbarReset: 'Reset to default',+ customizeToolbar: 'Customize toolbar…',title: 'Settings',description: 'Manage integrations and app preferences.',general: 'General',diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.tsindex a6b647678..28bd331ab 100644--- a/packages/vue/src/index.ts+++ b/packages/vue/src/index.ts@@ -75,6 +75,7 @@ export type {FlatReorderAxis,FlatReorderInstruction,FlatReorderItem,+ FlatReorderOperations,UseFlatReorderDragOptions} from '#vue/shared/drag/useFlatReorderDrag'export { useInlineRename } from '#vue/editor/inline-rename/use'diff --git a/packages/vue/src/shared/drag/useFlatReorderDrag.ts b/packages/vue/src/shared/drag/useFlatReorderDrag.tsindex 5e128a58e..31d5473f8 100644--- a/packages/vue/src/shared/drag/useFlatReorderDrag.ts+++ b/packages/vue/src/shared/drag/useFlatReorderDrag.ts@@ -1,7 +1,9 @@import {attachInstruction,extractInstruction,- type Instruction+ type Availability,+ type Instruction,+ type Operation} from '@atlaskit/pragmatic-drag-and-drop-hitbox/list-item'import { getReorderDestinationIndex } from '@atlaskit/pragmatic-drag-and-drop-hitbox/util/get-reorder-destination-index'import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine'@@ -13,10 +15,9 @@ import {import { onScopeDispose, ref } from 'vue'export type FlatReorderAxis = 'vertical' | 'horizontal'-export type FlatReorderInstruction = Extract<- Instruction,- { operation: 'reorder-before' | 'reorder-after' }->+export type FlatReorderInstruction = Instruction+/** Which drops a target takes from a source: before it, after it, or onto it. */+export type FlatReorderOperations = Partial<Record<Operation, boolean>>export interface FlatReorderItem {id: string@@ -25,10 +26,24 @@ export interface FlatReorderItem {export interface UseFlatReorderDragOptions<TItem extends FlatReorderItem> {items: () => readonly TItem[]onMove: (sourceId: string, targetIndex: number) => void+ /** Dropping onto the middle of an item, for lists where items can merge. */+ onCombine?: (sourceId: string, targetId: string) => void+ /** Which drops each target takes; by default before and after, never onto. */+ operations?: (sourceId: string, targetId: string) => FlatReorderOperationsaxis?: FlatReorderAxisgetId?: (item: TItem) => string}+const REORDER_ONLY: FlatReorderOperations = { 'reorder-before': true, 'reorder-after': true }++function availability(operations: FlatReorderOperations) {+ const result: { [TKey in Operation]?: Availability } = {}+ for (const operation of ['reorder-before', 'reorder-after', 'combine'] as const) {+ result[operation] = operations[operation] ? 'available' : 'not-available'+ }+ return result+}+interface RegisteredItem {element: HTMLElementcleanup: () => void@@ -37,14 +52,13 @@ interface RegisteredItem {function isFlatReorderInstruction(instruction: Instruction | null): instruction is FlatReorderInstruction {- return (- !!instruction &&- !instruction.blocked &&- (instruction.operation === 'reorder-before' || instruction.operation === 'reorder-after')- )+ return !!instruction && !instruction.blocked}-function edgeForInstruction(instruction: FlatReorderInstruction, axis: FlatReorderAxis) {+function edgeForInstruction(+ instruction: Extract<Instruction, { operation: 'reorder-before' | 'reorder-after' }>,+ axis: FlatReorderAxis+) {if (axis === 'vertical') {return instruction.operation === 'reorder-before' ? 'top' : 'bottom'}@@ -54,6 +68,8 @@ function edgeForInstruction(instruction: FlatReorderInstruction, axis: FlatReordexport function useFlatReorderDrag<TItem extends FlatReorderItem>({items,onMove,+ onCombine,+ operations = () => REORDER_ONLY,axis = 'vertical',getId = (item) => item.id}: UseFlatReorderDragOptions<TItem>) {@@ -93,17 +109,16 @@ export function useFlatReorderDrag<TItem extends FlatReorderItem>({}),dropTargetForElements({element,- getData: ({ input, element: target }) =>+ getData: ({ input, element: target, source }) =>attachInstruction({ id },{input,element: target,axis,- operations: {- 'reorder-before': 'available',- 'reorder-after': 'available'- }+ operations: availability(+ typeof source.data.id === 'string' ? operations(source.data.id, id) : {}+ )}),canDrop: ({ source }) => source.data.id !== id,@@ -136,6 +151,12 @@ export function useFlatReorderDrag<TItem extends FlatReorderItem>({const dropInstruction = extractInstruction(target.data)if (!isFlatReorderInstruction(dropInstruction)) return+ draggingId.value = null+ clearInstruction()+ if (dropInstruction.operation === 'combine') {+ onCombine?.(sourceId, targetId)+ return+ }const currentItems = items()const startIndex = currentItems.findIndex((item) => getId(item) === sourceId)@@ -148,8 +169,6 @@ export function useFlatReorderDrag<TItem extends FlatReorderItem>({})if (targetIndex !== startIndex) onMove(sourceId, targetIndex)- draggingId.value = null- clearInstruction()}})diff --git a/src/app/editor/toolbar/layout.ts b/src/app/editor/toolbar/layout.tsnew file mode 100644index 000000000..ebe3042f6--- /dev/null+++ b/src/app/editor/toolbar/layout.ts@@ -0,0 +1,287 @@+import { uniq } from 'es-toolkit'++import { EDITOR_TOOLS, type EditorToolDef, type Tool } from '@open-pencil/core/editor'++/** Toolbar buttons that run a command instead of switching the tool. */+export const TOOLBAR_ACTIONS = ['insert-icon'] as const+export type ToolbarAction = (typeof TOOLBAR_ACTIONS)[number]+export type ToolbarEntry = Tool | ToolbarAction++/**+ * What the toolbar shows, in order. A group of one is a button and a larger group is a flyout+ * keyed by its first shown member. Hidden entries keep their place so showing them restores it.+ */+export interface ToolbarLayout {+ groups: ToolbarEntry[][]+ hidden: ToolbarEntry[]+}++/** The one entry the toolbar always shows, so it is never empty. */+export const PINNED_TOOLBAR_ENTRY: ToolbarEntry = 'SELECT'++export const DEFAULT_TOOLBAR_LAYOUT: Readonly<ToolbarLayout> = {+ groups: [+ ...EDITOR_TOOLS.map((tool) => [...(tool.flyout ?? [tool.key])]),+ ...TOOLBAR_ACTIONS.map((action) => [action])+ ],+ hidden: []+}++const ENTRIES = DEFAULT_TOOLBAR_LAYOUT.groups.flat()++export function isToolbarEntry(value: unknown): value is ToolbarEntry {+ return ENTRIES.some((entry) => entry === value)+}++export function isToolbarAction(entry: ToolbarEntry): entry is ToolbarAction {+ return TOOLBAR_ACTIONS.some((action) => action === entry)+}++function groupOf(groups: ToolbarEntry[][], entry: ToolbarEntry) {+ return groups.find((group) => group.includes(entry))+}++/**+ * Places an entry the stored layout lacks, such as a tool added in a later release: into its+ * default flyout when another member of it is placed, otherwise after the entry before it.+ */+function placeMissing(groups: ToolbarEntry[][], entry: ToolbarEntry) {+ const home = groupOf(DEFAULT_TOOLBAR_LAYOUT.groups, entry) ?? [entry]+ const sibling = home.find((member) => member !== entry && groupOf(groups, member))+ const siblingGroup = sibling && groupOf(groups, sibling)+ if (siblingGroup) {+ const before = home+ .slice(0, home.indexOf(entry))+ .findLast((member) => siblingGroup.includes(member))+ siblingGroup.splice(before ? siblingGroup.indexOf(before) + 1 : 0, 0, entry)+ return+ }+ const anchor = ENTRIES.slice(0, ENTRIES.indexOf(entry)).findLast((other) =>+ groupOf(groups, other)+ )+ const at = anchor ? groups.findIndex((group) => group.includes(anchor)) + 1 : 0+ groups.splice(at, 0, [entry])+}++/**+ * Reads a stored layout: unknown entries and repeats are dropped, actions stand alone, empty+ * groups go, and entries it does not mention are placed as `placeMissing` describes.+ */+export function normalizeToolbarLayout(+ storedGroups: readonly (readonly unknown[])[],+ storedHidden: readonly unknown[]+): ToolbarLayout {+ const groups: ToolbarEntry[][] = []+ const placed = new Set<ToolbarEntry>()+ for (const stored of storedGroups) {+ let group: ToolbarEntry[] = []+ for (const value of stored) {+ if (!isToolbarEntry(value) || placed.has(value)) continue+ placed.add(value)+ if (!isToolbarAction(value)) {+ group.push(value)+ continue+ }+ if (group.length > 0) groups.push(group)+ groups.push([value])+ group = []+ }+ if (group.length > 0) groups.push(group)+ }+ for (const entry of ENTRIES) if (!placed.has(entry)) placeMissing(groups, entry)+ const hidden = uniq(storedHidden.filter(isToolbarEntry)).filter(+ (entry) => entry !== PINNED_TOOLBAR_ENTRY+ )+ return { groups, hidden }+}++export type ToolbarItem =+ | { kind: 'tool'; tool: EditorToolDef }+ | { kind: 'action'; action: ToolbarAction }++/** The toolbar's buttons and flyouts for a layout, without its hidden entries. */+export function toolbarItems(+ layout: ToolbarLayout,+ labels: Readonly<Record<Tool, string>>,+ shortcuts: Readonly<Record<Tool, string>>+): ToolbarItem[] {+ return layout.groups.flatMap((group): ToolbarItem[] => {+ const shown = group.filter((entry) => !layout.hidden.includes(entry))+ const first = shown.at(0)+ if (first === undefined) return []+ if (isToolbarAction(first)) return [{ kind: 'action', action: first }]+ const tools = shown.filter((entry): entry is Tool => !isToolbarAction(entry))+ const tool: EditorToolDef = { key: first, label: labels[first], shortcut: shortcuts[first] }+ if (tools.length > 1) tool.flyout = tools+ return [{ kind: 'tool', tool }]+ })+}++/** One entry as Settings lists it, with how it relates to the row above. */+export interface ToolbarRow {+ entry: ToolbarEntry+ hidden: boolean+ /** In the same flyout as the row above. */+ joined: boolean+ /** In a flyout with other entries. */+ inFlyout: boolean+ /** The entry above, which this row's group can join when `canJoin`. */+ above?: ToolbarEntry+ /** Can share a flyout with the row above: both are tools in different groups. */+ canJoin: boolean+ canMoveUp: boolean+ canMoveDown: boolean+}++/** Whether a group can merge into the one above it: both exist and neither is a command. */+function canJoinAbove(groups: ToolbarEntry[][], groupIndex: number) {+ if (groupIndex < 1 || groupIndex >= groups.length) return false+ const [first] = groups[groupIndex]+ const [above] = groups[groupIndex - 1]+ return !isToolbarAction(first) && !isToolbarAction(above)+}++export function toolbarRows(layout: ToolbarLayout): ToolbarRow[] {+ const { groups } = layout+ const flat = groups.flat()+ return groups.flatMap((group, groupIndex) =>+ group.map((entry, index) => {+ const alone = group.length === 1+ const position = flat.indexOf(entry)+ return {+ entry,+ hidden: layout.hidden.includes(entry),+ joined: index > 0,+ inFlyout: !alone,+ above: position > 0 ? flat[position - 1] : undefined,+ canJoin: index === 0 && canJoinAbove(groups, groupIndex),+ canMoveUp: !alone || groupIndex > 0,+ canMoveDown: !alone || groupIndex < groups.length - 1+ }+ })+ )+}++function locate(layout: ToolbarLayout, entry: ToolbarEntry) {+ const groups = layout.groups.map((group) => [...group])+ const groupIndex = groups.findIndex((group) => group.includes(entry))+ const group = groupIndex === -1 ? undefined : groups[groupIndex]+ return { groups, groupIndex, group, index: group ? group.indexOf(entry) : -1 }+}++export function setToolbarEntryHidden(+ layout: ToolbarLayout,+ entry: ToolbarEntry,+ hidden: boolean+): ToolbarLayout {+ if (entry === PINNED_TOOLBAR_ENTRY) return layout+ const others = layout.hidden.filter((other) => other !== entry)+ return { groups: layout.groups, hidden: hidden ? [...others, entry] : others }+}++/**+ * Moves an entry one step. Inside a flyout it moves among the flyout's members and past either+ * end becomes a button of its own; a button swaps places with the button or flyout next to it.+ */+export function moveToolbarEntry(+ layout: ToolbarLayout,+ entry: ToolbarEntry,+ step: -1 | 1+): ToolbarLayout {+ const { groups, groupIndex, group, index } = locate(layout, entry)+ if (!group) return layout+ if (group.length === 1) {+ const target = groupIndex + step+ if (target < 0 || target >= groups.length) return layout+ groups[groupIndex] = groups[target]+ groups[target] = group+ return { ...layout, groups }+ }+ const target = index + step+ if (target < 0 || target >= group.length) {+ group.splice(index, 1)+ groups.splice(step < 0 ? groupIndex : groupIndex + 1, 0, [entry])+ return { ...layout, groups }+ }+ group.splice(index, 1)+ group.splice(target, 0, entry)+ return { ...layout, groups }+}++/** Merges the entry's group into the group above it, making one flyout. */+export function joinToolbarEntry(layout: ToolbarLayout, entry: ToolbarEntry): ToolbarLayout {+ const { groups, groupIndex, group, index } = locate(layout, entry)+ if (!group || index !== 0 || !canJoinAbove(groups, groupIndex)) return layout+ groups.splice(groupIndex - 1, 2, [...groups[groupIndex - 1], ...group])+ return { ...layout, groups }+}++/** Takes an entry out of its flyout, leaving it a button right after the flyout. */+export function detachToolbarEntry(layout: ToolbarLayout, entry: ToolbarEntry): ToolbarLayout {+ const { groups, groupIndex, group, index } = locate(layout, entry)+ if (!group || group.length < 2) return layout+ group.splice(index, 1)+ groups.splice(groupIndex + 1, 0, [entry])+ return { ...layout, groups }+}++function withoutEntry(layout: ToolbarLayout, entry: ToolbarEntry) {+ return layout.groups+ .map((group) => group.filter((member) => member !== entry))+ .filter((group) => group.length > 0)+}++/**+ * Drops an entry at `index` of the list without it. Between two members of a flyout it joins+ * that flyout; anywhere else it becomes a button of its own, as does a command.+ */+export function placeToolbarEntry(+ layout: ToolbarLayout,+ entry: ToolbarEntry,+ index: number+): ToolbarLayout {+ const groups = withoutEntry(layout, entry)+ const flat = groups.flat()+ const before = index > 0 ? flat[index - 1] : undefined+ const after = index < flat.length ? flat[index] : undefined+ const host = before && groupOf(groups, before)+ if (host && after && host.includes(after) && !isToolbarAction(entry)) {+ host.splice(host.indexOf(before) + 1, 0, entry)+ return { ...layout, groups }+ }+ const at = before ? groups.findIndex((group) => group.includes(before)) + 1 : 0+ groups.splice(at, 0, [entry])+ return { ...layout, groups }+}++/** Drops an entry onto a tool: both share that tool's flyout, the entry right after it. */+export function combineToolbarEntry(+ layout: ToolbarLayout,+ entry: ToolbarEntry,+ target: ToolbarEntry+): ToolbarLayout {+ if (!toolbarDropOperations(layout, entry, target).combine) return layout+ const groups = withoutEntry(layout, entry)+ const host = groupOf(groups, target)+ if (!host) return layout+ host.splice(host.indexOf(target) + 1, 0, entry)+ return { ...layout, groups }+}++/**+ * Where an entry can be dropped on a row: onto another group's tool to share its flyout, and+ * before or after any row, except that a command only lands between groups.+ */+export function toolbarDropOperations(+ layout: ToolbarLayout,+ entry: ToolbarEntry,+ target: ToolbarEntry+) {+ const group = groupOf(layout.groups, target) ?? [target]+ const action = isToolbarAction(entry)+ return {+ 'reorder-before': !action || group[0] === target,+ 'reorder-after': !action || group.at(-1) === target,+ combine: !action && !isToolbarAction(target) && !group.includes(entry)+ }+}diff --git a/src/app/editor/toolbar/shortcuts.ts b/src/app/editor/toolbar/shortcuts.tsnew file mode 100644index 000000000..cf3d49865--- /dev/null+++ b/src/app/editor/toolbar/shortcuts.ts@@ -0,0 +1,22 @@+import type { Tool } from '@open-pencil/core/editor'++/** Each tool's key as the toolbar and Settings print it; empty for tools without one. */+export const TOOL_SHORTCUT_LABELS: Readonly<Record<Tool, string>> = {+ SELECT: 'V',+ FRAME: 'F',+ SECTION: 'S',+ RECTANGLE: 'R',+ ELLIPSE: 'O',+ LINE: 'L',+ POLYGON: '',+ STAR: '',+ PEN: 'P',+ TEXT: 'T',+ HAND: 'H',+ COMMENT: 'C'+}++/** A tool's tooltip: its name, then its key when it has one. */+export function toolTip(label: string, shortcut: string): string {+ return shortcut ? `${label} (${shortcut})` : label+}diff --git a/src/app/settings/dialog.ts b/src/app/settings/dialog.tsindex 36c1bbcf2..72bcc0aac 100644--- a/src/app/settings/dialog.ts+++ b/src/app/settings/dialog.ts@@ -2,6 +2,7 @@ import { ref } from 'vue'export type SettingsSection =| 'general'+ | 'toolbar'| 'ai'| 'usage'| 'diagnostics'diff --git a/src/app/settings/preferences/store.ts b/src/app/settings/preferences/store.tsindex e5ddf1c3c..f08e4ac7b 100644--- a/src/app/settings/preferences/store.ts+++ b/src/app/settings/preferences/store.ts@@ -6,6 +6,11 @@ import { DEFAULT_SNAPPING_PREFERENCES, type SnappingPreferences } from '@open-peimport { COMMENT_SORTS, type CommentSort } from '@open-pencil/scene-graph'import { DEFAULT_AGENT_STEPS, resolveAgentStepLimit } from '@/app/ai/chat/step-limit'+import {+ DEFAULT_TOOLBAR_LAYOUT,+ normalizeToolbarLayout,+ type ToolbarLayout+} from '@/app/editor/toolbar/layout'import {accentPreferenceSchema,DEFAULT_ACCENT,@@ -73,6 +78,7 @@ export interface AppPreferences {}designCheck: DesignCheckPreferencescomments: CommentPreferences+ toolbar: ToolbarLayoutonboarding: {aiSetup: AISetupState}@@ -100,6 +106,7 @@ export const DEFAULT_APP_PREFERENCES: Readonly<AppPreferences> = {onlyMine: false,sort: 'newest'},+ toolbar: structuredClone(DEFAULT_TOOLBAR_LAYOUT),onboarding: { aiSetup: 'pending' }}@@ -162,6 +169,18 @@ const appPreferencesSchema = section({onlyMine: v.fallback(v.boolean(), defaults.comments.onlyMine),sort: v.fallback(v.picklist(COMMENT_SORTS), defaults.comments.sort)}),+ toolbar: v.fallback(+ v.pipe(+ v.object({+ groups: v.fallback(v.array(v.array(v.unknown())), () =>+ structuredClone(DEFAULT_TOOLBAR_LAYOUT.groups)+ ),+ hidden: v.fallback(v.array(v.unknown()), () => [])+ }),+ v.transform(({ groups, hidden }) => normalizeToolbarLayout(groups, hidden))+ ),+ () => structuredClone(DEFAULT_TOOLBAR_LAYOUT)+ ),onboarding: section({aiSetup: v.fallback(v.picklist(AI_SETUP_STATES), defaults.onboarding.aiSetup)})@@ -235,3 +254,7 @@ export function updateCommentPreferences(changes: Partial<CommentPreferences>):comments: { ...appPreferences.value.comments, ...changes }}}++export function updateToolbarLayout(toolbar: ToolbarLayout): void {+ appPreferences.value = { ...appPreferences.value, toolbar }+}diff --git a/src/components/MobileHud/context.ts b/src/components/MobileHud/context.tsindex 7211e5637..2e0cc0d09 100644--- a/src/components/MobileHud/context.ts+++ b/src/components/MobileHud/context.ts@@ -19,7 +19,7 @@ import { openFileDialog } from '@/app/shell/menu/use'import { toast } from '@/app/shell/ui'import { roomStatusText } from '@/components/collab-room/statusText'import { presenceRows } from '@/components/presence/rows'-import type { ToolbarActionItem } from '@/components/Toolbar/types'+import type { ToolbarActionItem } from '@/components/toolbar/types'import { getShareURL } from '@/constants'type MenuAction = ToolbarActionItemdiff --git a/src/components/Toolbar/DesktopToolbar.vue b/src/components/Toolbar/DesktopToolbar.vuedeleted file mode 100644index 0dc133a65..000000000--- a/src/components/Toolbar/DesktopToolbar.vue+++ /dev/null@@ -1,77 +0,0 @@-<script setup lang="ts">-import { ToolbarRoot } from 'reka-ui'--import type { EditorToolDef } from '@open-pencil/core/editor'-import {- getToolbarToolSelection,- isToolbarToolActive,- toolbarToolTestId,- ToolbarItem-} from '@open-pencil/vue'-import type { Tool } from '@open-pencil/vue'--import ToolButton from '@/components/Toolbar/ToolButton.vue'-import ToolFlyout from '@/components/Toolbar/ToolFlyout.vue'-import type { ToolbarUI, ToolIconMap, ToolLabels } from '@/components/Toolbar/types'-import Tip from '@/components/ui/overlay/Tip.vue'--const { tools, activeTool, flyoutSelections, toolIcons, toolLabels, toolShortcuts, ui } =- defineProps<{- tools: EditorToolDef[]- activeTool: Tool- flyoutSelections: ReadonlyMap<Tool, Tool>- toolIcons: ToolIconMap- toolLabels: ToolLabels- toolShortcuts: Record<Tool, string>- ui?: ToolbarUI- }>()--const emit = defineEmits<{- setTool: [tool: Tool]-}>()-</script>--<template>- <div- data-canvas-obstacle- class="absolute bottom-4 left-1/2 z-10 flex -translate-x-1/2 items-center"- >- <ToolbarRoot- data-test-id="toolbar"- class="flex gap-0.5 rounded-xl bg-panel p-1 shadow-[0_8px_30px_rgb(0_0_0/0.4)]"- >- <template v-for="tool in tools" :key="tool.key">- <Tip- v-if="tool.flyout && tool.flyout.length > 1"- :label="`${toolLabels[getToolbarToolSelection(tool, activeTool, flyoutSelections)]} (${tool.shortcut})`"- >- <ToolFlyout- :tool="tool"- :active-tool="activeTool"- :selected-tool="getToolbarToolSelection(tool, activeTool, flyoutSelections)"- :tool-icons="toolIcons"- :tool-labels="toolLabels"- :tool-shortcuts="toolShortcuts"- :ui="ui"- @select="emit('setTool', $event)"- />- </Tip>-- <ToolbarItem v-else v-slot="{ active, actions }" :tool="tool.key">- <Tip :label="`${toolLabels[tool.key]} (${tool.shortcut})`">- <ToolButton- :data-test-id="toolbarToolTestId(tool.key)"- :icon="toolIcons[tool.key]"- :label="toolLabels[tool.key]"- :active="active || isToolbarToolActive(tool, activeTool)"- :ui="ui"- @click="actions.select"- />- </Tip>- </ToolbarItem>- </template>- <!-- Inserting rather than drawing: commands such as placing an icon. -->- <slot name="end" />- </ToolbarRoot>- </div>-</template>diff --git a/src/components/Toolbar/Toolbar.vue b/src/components/Toolbar/Toolbar.vuedeleted file mode 100644index 0b8a31951..000000000--- a/src/components/Toolbar/Toolbar.vue+++ /dev/null@@ -1,114 +0,0 @@-<script setup lang="ts">-import { computed } from 'vue'--import {- ToolbarRoot,- useEditorCommands,- useI18n,- useToolbarState,- useViewportKind-} from '@open-pencil/vue'-import type { Tool } from '@open-pencil/vue'--import { useEditorStore } from '@/app/editor/active-store'-import { toolIcons } from '@/app/editor/icons'-import { useActionToast } from '@/app/shell/toast/action'-import InsertIconButton from '@/components/icon-picker/InsertIconButton.vue'-import { useToolbarActions } from '@/components/Toolbar/actions'-import DesktopToolbar from '@/components/Toolbar/DesktopToolbar.vue'-import MobileToolbar from '@/components/Toolbar/MobileToolbar.vue'-import type { ToolbarActionItem } from '@/components/Toolbar/types'-import { useMenuUI } from '@/components/ui/menu/menu'--const store = useEditorStore()-const { isMobile } = useViewportKind()-const { getCommand } = useEditorCommands()-const { showActionToast } = useActionToast()-const { menu, tools: toolTexts } = useI18n()--const toolLabels = computed<Record<Tool, string>>(() => ({- SELECT: toolTexts.value.move,- FRAME: toolTexts.value.frame,- SECTION: toolTexts.value.section,- RECTANGLE: toolTexts.value.rectangle,- ELLIPSE: toolTexts.value.ellipse,- LINE: toolTexts.value.line,- POLYGON: toolTexts.value.polygon,- STAR: toolTexts.value.star,- PEN: toolTexts.value.pen,- TEXT: toolTexts.value.text,- HAND: toolTexts.value.hand,- COMMENT: toolTexts.value.comment-}))--const toolShortcuts: Record<Tool, string> = {- SELECT: 'V',- FRAME: 'F',- SECTION: 'S',- RECTANGLE: 'R',- ELLIPSE: 'O',- LINE: 'L',- POLYGON: '',- STAR: '',- PEN: 'P',- TEXT: 'T',- HAND: 'H',- COMMENT: 'C'-}--const flyoutMenuCls = useMenuUI({ content: 'min-w-32' })-const toolbarUI = { flyoutContent: flyoutMenuCls.content }-const { editActions, arrangeActions } = useToolbarActions({ store, getCommand, menu })--const { mobileCategory, slideDirection, hasPrev, hasNext, goPrev, goNext } = useToolbarState()--function onActionTap(item: ToolbarActionItem) {- item.action()- showActionToast(item.label)-}-</script>--<template>- <ToolbarRoot v-slot="{ tools, activeTool, flyoutSelections, actions }">- <DesktopToolbar- v-if="!isMobile"- :tools="tools"- :active-tool="activeTool"- :flyout-selections="flyoutSelections"- :tool-icons="toolIcons"- :tool-labels="toolLabels"- :tool-shortcuts="toolShortcuts"- :ui="toolbarUI"- @set-tool="actions.setTool"- >- <template #end>- <InsertIconButton :ui="toolbarUI" />- </template>- </DesktopToolbar>-- <MobileToolbar- v-else- :tools="tools"- :active-tool="activeTool"- :flyout-selections="flyoutSelections"- :tool-icons="toolIcons"- :tool-labels="toolLabels"- :tool-shortcuts="toolShortcuts"- :ui="toolbarUI"- :mobile-category="mobileCategory"- :slide-direction="slideDirection"- :has-prev="hasPrev"- :has-next="hasNext"- :edit-actions="editActions"- :arrange-actions="arrangeActions"- @set-tool="actions.setTool"- @prev="goPrev"- @next="goNext"- @action="onActionTap"- >- <template #end>- <InsertIconButton mobile :ui="toolbarUI" />- </template>- </MobileToolbar>- </ToolbarRoot>-</template>diff --git a/src/components/editor/EditorWorkspace.vue b/src/components/editor/EditorWorkspace.vueindex 99227b1b2..ae37ca064 100644--- a/src/components/editor/EditorWorkspace.vue+++ b/src/components/editor/EditorWorkspace.vue@@ -20,7 +20,7 @@ import LayersPanel from '@/components/LayersPanel.vue'import MobileDrawer from '@/components/MobileDrawer.vue'import MobileHud from '@/components/MobileHud/MobileHud.vue'import PropertiesPanel from '@/components/PropertiesPanel.vue'-import Toolbar from '@/components/Toolbar/Toolbar.vue'+import Toolbar from '@/components/toolbar/Toolbar.vue'import IconButton from '@/components/ui/button/IconButton.vue'import VariablesDialog from '@/components/variables/VariablesDialog.vue'import splitterTheme from '@/theme/splitter'diff --git a/src/components/icon-picker/InsertIconButton.vue b/src/components/icon-picker/InsertIconButton.vueindex acf248f0b..09731e7e1 100644--- a/src/components/icon-picker/InsertIconButton.vue+++ b/src/components/icon-picker/InsertIconButton.vue@@ -5,8 +5,8 @@ import { usePanelMessages } from '@open-pencil/vue'import { useEditorStore } from '@/app/editor/active-store'import { toast } from '@/app/shell/ui'-import ToolButton from '@/components/Toolbar/ToolButton.vue'-import type { ToolbarUI } from '@/components/Toolbar/types'+import ToolButton from '@/components/toolbar/ToolButton.vue'+import type { ToolbarUI } from '@/components/toolbar/types'import IconPicker from './IconPicker.vue'diff --git a/src/components/settings/SettingsDialog.vue b/src/components/settings/SettingsDialog.vueindex 5bffb4f63..d8cb54841 100644--- a/src/components/settings/SettingsDialog.vue+++ b/src/components/settings/SettingsDialog.vue@@ -21,6 +21,7 @@ import MediaSettingsPanel from '@/components/settings/media/MediaSettingsPanel.vimport ModelsPanel from '@/components/settings/models/ModelsPanel.vue'import StorageSettingsPanel from '@/components/settings/storage/StorageSettingsPanel.vue'import ToolAccessSettingsPanel from '@/components/settings/tool-access/ToolAccessSettingsPanel.vue'+import ToolbarSettingsPanel from '@/components/settings/toolbar/ToolbarSettingsPanel.vue'import UsageSettingsPanel from '@/components/settings/usage/UsageSettingsPanel.vue'import AppButton from '@/components/ui/button/AppButton.vue'import {@@ -44,6 +45,7 @@ const sections = computed(() =>[{ value: 'general', label: settings.value.general },+ { value: 'toolbar', label: settings.value.toolbar },{ value: 'ai', label: settings.value.aiAndAgents },{ value: 'usage', label: settings.value.usage },{ value: 'diagnostics', label: settings.value.diagnostics },@@ -103,6 +105,10 @@ function onOpenChange(open: boolean): void {<template #leading><icon-lucide-settings class="size-3.5" /></template>{{ settings.general }}</AppTabsTrigger>+ <AppTabsTrigger value="toolbar" data-test-id="settings-section-toolbar">+ <template #leading><icon-lucide-panel-bottom class="size-3.5" /></template>+ {{ settings.toolbar }}+ </AppTabsTrigger><AppTabsTrigger value="ai" data-test-id="settings-section-ai"><template #leading><icon-lucide-sparkles class="size-3.5" /></template>{{ settings.aiAndAgents }}@@ -136,6 +142,9 @@ function onOpenChange(open: boolean): void {<AppTabsContent value="general" as-child><SettingsPage><GeneralSettingsPanel /></SettingsPage></AppTabsContent>+ <AppTabsContent value="toolbar" as-child>+ <SettingsPage><ToolbarSettingsPanel /></SettingsPage>+ </AppTabsContent><AppTabsContent value="ai" as-child><section class="flex min-h-0 min-w-0 flex-1 flex-col" data-test-id="settings-ai-panel"><ModelsPanel>diff --git a/src/components/settings/toolbar/ToolbarLayoutEditor.stories.ts b/src/components/settings/toolbar/ToolbarLayoutEditor.stories.tsnew file mode 100644index 000000000..afa4b008b--- /dev/null+++ b/src/components/settings/toolbar/ToolbarLayoutEditor.stories.ts@@ -0,0 +1,61 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, userEvent, within } from 'storybook/test'+import { ref } from 'vue'++import {+ DEFAULT_TOOLBAR_LAYOUT,+ normalizeToolbarLayout,+ type ToolbarLayout+} from '@/app/editor/toolbar/layout'++import ToolbarLayoutEditor from './ToolbarLayoutEditor.vue'++type Args = { layout: ToolbarLayout }++const meta = {+ title: 'App/Settings/Toolbar Layout',+ args: { layout: structuredClone(DEFAULT_TOOLBAR_LAYOUT) },+ render: (args) => ({+ components: { ToolbarLayoutEditor },+ // Args arrive as reactive proxies, so the editor gets its own copy to change.+ setup: () => ({ layout: ref(normalizeToolbarLayout(args.layout.groups, args.layout.hidden)) }),+ template: '<div class="max-w-xl bg-panel p-4"><ToolbarLayoutEditor v-model="layout" /></div>'+ })+} satisfies Meta<Args>+export default meta+type Story = StoryObj<typeof meta>++export const Default: Story = {}++export const Customized: Story = {+ args: {+ layout: normalizeToolbarLayout(+ [['SELECT', 'HAND'], ['FRAME'], ['SECTION'], ['TEXT', 'COMMENT'], ['insert-icon']],+ ['PEN', 'STAR']+ )+ }+}++export const Regrouping: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await userEvent.click(canvas.getByRole('switch', { name: 'Show Pen' }))+ await expect(canvas.getByRole('switch', { name: 'Show Pen' })).not.toBeChecked()++ // Grouping moves the row into the box above, so each check finds it again.+ const options = () => canvas.getByRole('button', { name: 'Comment options' })+ const menu = within(canvasElement.ownerDocument.body)+ await userEvent.click(options())+ await userEvent.click(await menu.findByRole('menuitem', { name: 'Group with Hand' }))+ await expect(options()).toHaveFocus()+ await userEvent.click(options())+ await expect(await menu.findByRole('menuitem', { name: 'Ungroup' })).toBeVisible()+ await userEvent.keyboard('{Escape}')++ const grip = () => canvas.getByRole('button', { name: 'Reorder Comment' })+ grip().focus()+ await userEvent.keyboard('{ArrowUp}')+ await expect(grip()).toHaveFocus()+ await expect(canvas.getByRole('switch', { name: 'Show Move' })).toBeDisabled()+ }+}diff --git a/src/components/settings/toolbar/ToolbarLayoutEditor.vue b/src/components/settings/toolbar/ToolbarLayoutEditor.vuenew file mode 100644index 000000000..61edb0646--- /dev/null+++ b/src/components/settings/toolbar/ToolbarLayoutEditor.vue@@ -0,0 +1,159 @@+<script setup lang="ts">+import { computed, ref, type ComponentPublicInstance } from 'vue'++import { useFlatReorderDrag } from '@open-pencil/vue'++import {+ combineToolbarEntry,+ detachToolbarEntry,+ isToolbarAction,+ isToolbarEntry,+ joinToolbarEntry,+ moveToolbarEntry,+ PINNED_TOOLBAR_ENTRY,+ placeToolbarEntry,+ setToolbarEntryHidden,+ toolbarDropOperations,+ toolbarRows,+ type ToolbarEntry,+ type ToolbarLayout,+ type ToolbarRow+} from '@/app/editor/toolbar/layout'+import { TOOL_SHORTCUT_LABELS } from '@/app/editor/toolbar/shortcuts'+import ToolbarLayoutJoint from '@/components/settings/toolbar/ToolbarLayoutJoint.vue'+import ToolbarLayoutRow, {+ type ToolbarRowControl+} from '@/components/settings/toolbar/ToolbarLayoutRow.vue'+import { toolbarEntryIcons, useToolbarEntryLabels } from '@/components/toolbar/labels'++/**+ * Lists every toolbar entry with its visibility, order and flyout, one box per flyout. A dragged+ * row lands on a joint: inside a box it joins that flyout, between boxes it becomes a button.+ * Dropped onto another row, the two share a flyout. Each row's grip and options do the same from+ * the keyboard.+ */+const layout = defineModel<ToolbarLayout>({ required: true })+const labels = useToolbarEntryLabels()++/** A row and its place in the whole list, which is also the joint above it. */+interface PlacedRow {+ row: ToolbarRow+ index: number+}++const rows = computed(() => toolbarRows(layout.value))+/** One box per flyout or button; the head is its first row, whose joint sits above the box. */+interface Box {+ head: PlacedRow+ rows: PlacedRow[]+}++const boxes = computed(() => {+ const result: Box[] = []+ for (const [index, row] of rows.value.entries()) {+ const placed = { row, index }+ const last = result.at(-1)+ if (row.joined && last) last.rows.push(placed)+ else result.push({ head: placed, rows: [placed] })+ }+ return result+})++const drag = useFlatReorderDrag({+ items: () => rows.value.map((row) => ({ id: row.entry })),+ operations: (source, target) =>+ isToolbarEntry(source) && isToolbarEntry(target)+ ? toolbarDropOperations(layout.value, source, target)+ : {},+ onMove: (source, index) => {+ if (isToolbarEntry(source)) layout.value = placeToolbarEntry(layout.value, source, index)+ },+ onCombine: (source, target) => {+ if (isToolbarEntry(source) && isToolbarEntry(target))+ layout.value = combineToolbarEntry(layout.value, source, target)+ }+})++/** The joint a dragged row would land on: above the target row, or below it. */+const dropJoint = computed(() => {+ const operation = drag.instruction.value?.operation+ const target = rows.value.findIndex((row) => row.entry === drag.instructionTargetId.value)+ if (target === -1 || !operation || operation === 'combine') return null+ return operation === 'reorder-before' ? target : target + 1+})++function isCombineTarget(entry: ToolbarEntry) {+ return drag.instruction.value?.operation === 'combine' && drag.instructionTargetId.value === entry+}++function setupRow(element: Element | ComponentPublicInstance | null, entry: ToolbarEntry) {+ drag.setupItem(element instanceof HTMLElement ? element : null, () => ({ id: entry }))+}++/** Editing can move a row to another box, so the control used takes focus where it lands. */+const focusRequest = ref<{ entry: ToolbarEntry; control: ToolbarRowControl } | null>(null)++function focusFor(entry: ToolbarEntry) {+ return focusRequest.value?.entry === entry ? focusRequest.value.control : null+}++function edit(+ entry: ToolbarEntry,+ control: ToolbarRowControl,+ change: (current: ToolbarLayout) => ToolbarLayout+) {+ layout.value = change(layout.value)+ focusRequest.value = { entry, control }+}++function setShown(entry: ToolbarEntry, shown: boolean) {+ layout.value = setToolbarEntryHidden(layout.value, entry, !shown)+}+</script>++<template>+ <div class="group/list flex flex-col" data-test-id="toolbar-layout">+ <template v-for="(box, boxIndex) in boxes" :key="box.head.row.entry">+ <ToolbarLayoutJoint+ :kind="boxIndex === 0 ? 'end' : 'between'"+ :dropping="dropJoint === box.head.index"+ />+ <div class="flex flex-col rounded border border-border">+ <template v-for="{ row, index } in box.rows" :key="row.entry">+ <ToolbarLayoutJoint v-if="row.joined" kind="inside" :dropping="dropJoint === index" />+ <div+ :ref="(element) => setupRow(element, row.entry)"+ class="data-[dragging]:opacity-40"+ :data-entry="row.entry"+ :data-dragging="drag.draggingId.value === row.entry || undefined"+ >+ <ToolbarLayoutRow+ :label="labels[row.entry]"+ :icon="toolbarEntryIcons[row.entry]"+ :shortcut="isToolbarAction(row.entry) ? '' : TOOL_SHORTCUT_LABELS[row.entry]"+ :hidden="row.hidden"+ :pinned="row.entry === PINNED_TOOLBAR_ENTRY"+ :can-move-up="row.canMoveUp"+ :can-move-down="row.canMoveDown"+ :group-with="row.canJoin && row.above ? labels[row.above] : undefined"+ :in-flyout="row.inFlyout"+ :drop-target="isCombineTarget(row.entry)"+ :focus="focusFor(row.entry)"+ @move="+ (step, control) =>+ edit(row.entry, control, (current) => moveToolbarEntry(current, row.entry, step))+ "+ @group="edit(row.entry, 'options', (current) => joinToolbarEntry(current, row.entry))"+ @ungroup="+ edit(row.entry, 'options', (current) => detachToolbarEntry(current, row.entry))+ "+ @update:shown="setShown(row.entry, $event)"+ @focused="focusRequest = null"+ />+ </div>+ </template>+ </div>+ </template>+ <ToolbarLayoutJoint kind="end" :dropping="dropJoint === rows.length" />+ </div>+</template>diff --git a/src/components/settings/toolbar/ToolbarLayoutJoint.vue b/src/components/settings/toolbar/ToolbarLayoutJoint.vuenew file mode 100644index 000000000..345fe9c16--- /dev/null+++ b/src/components/settings/toolbar/ToolbarLayoutJoint.vue@@ -0,0 +1,19 @@+<script setup lang="ts">+import { tv } from 'tailwind-variants'++import theme from '@/theme/settings/toolbar/joint'++/** Where two rows meet, showing the line where a dragged row would land. */+const { kind, dropping } = defineProps<{+ kind: 'inside' | 'between' | 'end'+ dropping: boolean+}>()++const styles = tv(theme)+</script>++<template>+ <div :class="styles({ kind }).root()">+ <span v-if="dropping" :class="styles().line()" />+ </div>+</template>diff --git a/src/components/settings/toolbar/ToolbarLayoutRow.vue b/src/components/settings/toolbar/ToolbarLayoutRow.vuenew file mode 100644index 000000000..745f58032--- /dev/null+++ b/src/components/settings/toolbar/ToolbarLayoutRow.vue@@ -0,0 +1,160 @@+<script setup lang="ts">+import {+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuPortal,+ DropdownMenuRoot,+ DropdownMenuSeparator,+ DropdownMenuTrigger+} from 'reka-ui'+import { tv } from 'tailwind-variants'+import { useTemplateRef, watchPostEffect, type Component } from 'vue'++import { useI18n } from '@open-pencil/vue'++import IconButton from '@/components/ui/button/IconButton.vue'+import AppShortcutText from '@/components/ui/menu/AppShortcutText.vue'+import { useMenuUI } from '@/components/ui/menu/menu'+import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'+import theme from '@/theme/settings/toolbar/row'++export type ToolbarRowControl = 'grip' | 'options'++/**+ * One toolbar entry. Drag it anywhere; its grip moves it with the arrow keys, and its options+ * move it or put it in or out of a flyout without a pointer.+ */+const {+ label,+ icon,+ shortcut,+ hidden,+ pinned,+ canMoveUp,+ canMoveDown,+ groupWith,+ inFlyout,+ dropTarget,+ focus+} = defineProps<{+ label: string+ icon: Component+ shortcut: string+ hidden: boolean+ /** Always shown, so its switch stays on. */+ pinned: boolean+ canMoveUp: boolean+ canMoveDown: boolean+ /** The tool above that this row can share a flyout with. */+ groupWith?: string+ inFlyout: boolean+ /** Another row is about to be dropped onto this one. */+ dropTarget: boolean+ /** The control to focus, as after an edit put the row in another box. */+ focus: ToolbarRowControl | null+}>()++const emit = defineEmits<{+ /** `control` is the one used, which keeps focus once the row has moved. */+ move: [step: -1 | 1, control: ToolbarRowControl]+ group: []+ ungroup: []+ 'update:shown': [shown: boolean]+ focused: []+}>()++const { settings } = useI18n()+const styles = tv(theme)+const menu = useMenuUI({ content: 'min-w-44', item: 'justify-start gap-2' })+const controls = {+ grip: useTemplateRef('grip'),+ options: useTemplateRef('options')+}++// Runs after render, so a control that just mounted, as when its row moved boxes, takes focus.+watchPostEffect(() => {+ const control = focus && controls[focus].value+ if (!control) return+ control.focus()+ emit('focused')+})++function onGripKey(event: KeyboardEvent) {+ if (event.key === 'ArrowUp' && canMoveUp) emit('move', -1, 'grip')+ else if (event.key === 'ArrowDown' && canMoveDown) emit('move', 1, 'grip')+ else return+ event.preventDefault()+}+</script>++<template>+ <div :class="styles().root()">+ <span v-if="dropTarget" :class="styles().target()" />+ <IconButton+ ref="grip"+ :class="styles().grip()"+ :label="settings.toolbarReorder({ tool: label })"+ aria-keyshortcuts="ArrowUp ArrowDown"+ @keydown="onGripKey"+ >+ <icon-lucide-grip-vertical class="size-3.5" />+ </IconButton>+ <component :is="icon" :class="styles({ hidden }).icon()" aria-hidden="true" />+ <span :class="styles({ hidden }).label()">{{ label }}</span>+ <AppShortcutText :ui="{ base: styles().shortcut() }">{{ shortcut }}</AppShortcutText>+ <DropdownMenuRoot :modal="false">+ <DropdownMenuTrigger as-child>+ <IconButton+ ref="options"+ :class="styles().options()"+ :label="settings.toolbarOptions({ tool: label })"+ >+ <icon-lucide-ellipsis class="size-3.5" />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuPortal>+ <!-- The editor puts focus back on this row's options once the edit has rendered. -->+ <DropdownMenuContent+ :class="menu.content"+ align="end"+ :side-offset="4"+ @close-auto-focus.prevent+ >+ <DropdownMenuItem+ :class="menu.item"+ :disabled="!canMoveUp"+ @select="emit('move', -1, 'options')"+ >+ <icon-lucide-arrow-up :class="menu.icon" />+ {{ settings.toolbarMoveUp }}+ </DropdownMenuItem>+ <DropdownMenuItem+ :class="menu.item"+ :disabled="!canMoveDown"+ @select="emit('move', 1, 'options')"+ >+ <icon-lucide-arrow-down :class="menu.icon" />+ {{ settings.toolbarMoveDown }}+ </DropdownMenuItem>+ <template v-if="groupWith || inFlyout">+ <DropdownMenuSeparator :class="menu.separator" />+ <DropdownMenuItem v-if="groupWith" :class="menu.item" @select="emit('group')">+ <icon-lucide-link-2 :class="menu.icon" />+ {{ settings.toolbarGroupWith({ tool: groupWith }) }}+ </DropdownMenuItem>+ <DropdownMenuItem v-if="inFlyout" :class="menu.item" @select="emit('ungroup')">+ <icon-lucide-unlink-2 :class="menu.icon" />+ {{ settings.toolbarUngroup }}+ </DropdownMenuItem>+ </template>+ </DropdownMenuContent>+ </DropdownMenuPortal>+ </DropdownMenuRoot>+ <AppSwitch+ :model-value="!hidden"+ :disabled="pinned"+ :label="settings.toolbarShow({ tool: label })"+ @update:model-value="emit('update:shown', $event)"+ />+ </div>+</template>diff --git a/src/components/settings/toolbar/ToolbarSettingsPanel.vue b/src/components/settings/toolbar/ToolbarSettingsPanel.vuenew file mode 100644index 000000000..9d283ab41--- /dev/null+++ b/src/components/settings/toolbar/ToolbarSettingsPanel.vue@@ -0,0 +1,37 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useI18n } from '@open-pencil/vue'++import { DEFAULT_TOOLBAR_LAYOUT } from '@/app/editor/toolbar/layout'+import { appPreferences, updateToolbarLayout } from '@/app/settings/preferences/store'+import SettingsSection from '@/components/settings/layout/SettingsSection.vue'+import ToolbarLayoutEditor from '@/components/settings/toolbar/ToolbarLayoutEditor.vue'+import AppButton from '@/components/ui/button/AppButton.vue'++const { settings } = useI18n()++const layout = computed({+ get: () => appPreferences.value.toolbar,+ set: updateToolbarLayout+})++function reset() {+ updateToolbarLayout(structuredClone(DEFAULT_TOOLBAR_LAYOUT))+}+</script>++<template>+ <section class="flex flex-col gap-6" data-test-id="settings-toolbar-panel">+ <SettingsSection>+ <template #title>{{ settings.toolbar }}</template>+ <template #description>{{ settings.toolbarDescription }}</template>+ <template #actions>+ <AppButton @click="reset">+ {{ settings.toolbarReset }}+ </AppButton>+ </template>+ <ToolbarLayoutEditor v-model="layout" />+ </SettingsSection>+ </section>+</template>diff --git a/src/components/toolbar/DesktopToolbar.vue b/src/components/toolbar/DesktopToolbar.vuenew file mode 100644index 000000000..6b861937b--- /dev/null+++ b/src/components/toolbar/DesktopToolbar.vue@@ -0,0 +1,91 @@+<script setup lang="ts">+import { ToolbarRoot } from 'reka-ui'++import type { EditorToolDef } from '@open-pencil/core/editor'+import {+ getToolbarToolSelection,+ isToolbarToolActive,+ toolbarToolTestId,+ ToolbarItem+} from '@open-pencil/vue'+import type { Tool } from '@open-pencil/vue'++import type { ToolbarAction, ToolbarItem as ToolbarLayoutItem } from '@/app/editor/toolbar/layout'+import { toolTip } from '@/app/editor/toolbar/shortcuts'+import ToolButton from '@/components/toolbar/ToolButton.vue'+import ToolFlyout from '@/components/toolbar/ToolFlyout.vue'+import type { ToolbarUI, ToolIconMap, ToolLabels } from '@/components/toolbar/types'+import Tip from '@/components/ui/overlay/Tip.vue'++const { items, activeTool, flyoutSelections, toolIcons, toolLabels, toolShortcuts, ui } =+ defineProps<{+ items: ToolbarLayoutItem[]+ activeTool: Tool+ flyoutSelections: ReadonlyMap<Tool, Tool>+ toolIcons: ToolIconMap+ toolLabels: ToolLabels+ toolShortcuts: Readonly<Record<Tool, string>>+ ui?: ToolbarUI+ }>()++const emit = defineEmits<{+ setTool: [tool: Tool]+}>()++/** The tool a flyout's button shows: the active one if it is in the flyout, else the last used. */+function selectedTool(tool: EditorToolDef) {+ return getToolbarToolSelection(tool, activeTool, flyoutSelections)+}++defineSlots<{+ /** A button that runs a command, such as placing an icon, rather than picking a tool. */+ action(props: { action: ToolbarAction }): unknown+}>()+</script>++<template>+ <div+ data-canvas-obstacle+ class="absolute bottom-4 left-1/2 z-10 flex -translate-x-1/2 items-center"+ >+ <ToolbarRoot+ data-test-id="toolbar"+ class="flex gap-0.5 rounded-xl bg-panel p-1 shadow-[0_8px_30px_rgb(0_0_0/0.4)]"+ >+ <template v-for="item in items" :key="item.kind === 'tool' ? item.tool.key : item.action">+ <slot v-if="item.kind === 'action'" name="action" :action="item.action" />++ <Tip+ v-else-if="item.tool.flyout"+ :label="+ toolTip(toolLabels[selectedTool(item.tool)], toolShortcuts[selectedTool(item.tool)])+ "+ >+ <ToolFlyout+ :tool="item.tool"+ :active-tool="activeTool"+ :selected-tool="selectedTool(item.tool)"+ :tool-icons="toolIcons"+ :tool-labels="toolLabels"+ :tool-shortcuts="toolShortcuts"+ :ui="ui"+ @select="emit('setTool', $event)"+ />+ </Tip>++ <ToolbarItem v-else v-slot="{ active, actions }" :tool="item.tool.key">+ <Tip :label="toolTip(toolLabels[item.tool.key], toolShortcuts[item.tool.key])">+ <ToolButton+ :data-test-id="toolbarToolTestId(item.tool.key)"+ :icon="toolIcons[item.tool.key]"+ :label="toolLabels[item.tool.key]"+ :active="active || isToolbarToolActive(item.tool, activeTool)"+ :ui="ui"+ @click="actions.select"+ />+ </Tip>+ </ToolbarItem>+ </template>+ </ToolbarRoot>+ </div>+</template>diff --git a/src/components/Toolbar/MobileToolbar.vue b/src/components/toolbar/MobileToolbar.vuesimilarity index 95%rename from src/components/Toolbar/MobileToolbar.vuerename to src/components/toolbar/MobileToolbar.vueindex 5eb2f0021..a32086ee5 100644--- a/src/components/Toolbar/MobileToolbar.vue+++ b/src/components/toolbar/MobileToolbar.vue@@ -11,15 +11,15 @@ import type { Tool } from '@open-pencil/vue'import { animationsEnabled } from '@/app/shell/motion'import { useMotionTransitions } from '@/app/shell/motion/transitions'-import ToolbarActionGroup from '@/components/Toolbar/ToolbarActionGroup.vue'-import ToolButton from '@/components/Toolbar/ToolButton.vue'-import ToolFlyout from '@/components/Toolbar/ToolFlyout.vue'+import ToolbarActionGroup from '@/components/toolbar/ToolbarActionGroup.vue'+import ToolButton from '@/components/toolbar/ToolButton.vue'+import ToolFlyout from '@/components/toolbar/ToolFlyout.vue'import type {ToolbarActionItem,ToolbarUI,ToolIconMap,ToolLabels-} from '@/components/Toolbar/types'+} from '@/components/toolbar/types'import toolbarTheme from '@/theme/toolbar'const {@@ -42,7 +42,7 @@ const {flyoutSelections: ReadonlyMap<Tool, Tool>toolIcons: ToolIconMaptoolLabels: ToolLabels- toolShortcuts: Record<Tool, string>+ toolShortcuts: Readonly<Record<Tool, string>>ui?: ToolbarUImobileCategory: numberslideDirection: number@@ -118,7 +118,7 @@ function navigationClass(disabled: boolean) {><template v-for="tool in tools" :key="tool.key"><ToolFlyout- v-if="tool.flyout && tool.flyout.length > 1"+ v-if="tool.flyout"mobile:tool="tool":active-tool="activeTool"diff --git a/src/components/Toolbar/ToolButton.vue b/src/components/toolbar/ToolButton.vuesimilarity index 93%rename from src/components/Toolbar/ToolButton.vuerename to src/components/toolbar/ToolButton.vueindex fa3c9927f..dfc9e2e19 100644--- a/src/components/Toolbar/ToolButton.vue+++ b/src/components/toolbar/ToolButton.vue@@ -4,7 +4,7 @@ import { tv } from 'tailwind-variants'import { computed } from 'vue'import type { Component } from 'vue'-import type { ToolbarUI } from '@/components/Toolbar/types'+import type { ToolbarUI } from '@/components/toolbar/types'import toolbarTheme from '@/theme/toolbar'interface ToolButtonProps {diff --git a/src/components/Toolbar/ToolFlyout.vue b/src/components/toolbar/ToolFlyout.vuesimilarity index 93%rename from src/components/Toolbar/ToolFlyout.vuerename to src/components/toolbar/ToolFlyout.vueindex 894a0b388..d44e51102 100644--- a/src/components/Toolbar/ToolFlyout.vue+++ b/src/components/toolbar/ToolFlyout.vue@@ -24,8 +24,9 @@ import {} from '@open-pencil/vue'import type { Tool } from '@open-pencil/vue'-import ToolButton from '@/components/Toolbar/ToolButton.vue'-import type { ToolbarUI, ToolIconMap, ToolLabels } from '@/components/Toolbar/types'+import { toolTip } from '@/app/editor/toolbar/shortcuts'+import ToolButton from '@/components/toolbar/ToolButton.vue'+import type { ToolbarUI, ToolIconMap, ToolLabels } from '@/components/toolbar/types'import AppShortcutText from '@/components/ui/menu/AppShortcutText.vue'import { menu } from '@/components/ui/menu/menu'import toolbarTheme from '@/theme/toolbar'@@ -45,7 +46,7 @@ const {selectedTool: TooltoolIcons: ToolIconMaptoolLabels: ToolLabels- toolShortcuts: Record<Tool, string>+ toolShortcuts: Readonly<Record<Tool, string>>ui?: ToolbarUImobile?: boolean}>()@@ -72,7 +73,7 @@ function flyoutItemClass() {<template><div :class="styles.flyoutGroup({ class: ui?.flyoutGroup })">- <slot :label="`${toolLabels[selectedTool]} (${tool.shortcut})`">+ <slot :label="toolTip(toolLabels[selectedTool], toolShortcuts[selectedTool])"><ToolButton:data-test-id="toolbarToolTestId(selectedTool, mobile)":icon="toolIcons[selectedTool]"diff --git a/src/components/Toolbar/Toolbar.stories.ts b/src/components/toolbar/Toolbar.stories.tssimilarity index 100%rename from src/components/Toolbar/Toolbar.stories.tsrename to src/components/toolbar/Toolbar.stories.tsdiff --git a/src/components/toolbar/Toolbar.vue b/src/components/toolbar/Toolbar.vuenew file mode 100644index 000000000..85d9f0909--- /dev/null+++ b/src/components/toolbar/Toolbar.vue@@ -0,0 +1,104 @@+<script setup lang="ts">+import { computed } from 'vue'++import {+ ToolbarRoot,+ useEditorCommands,+ useI18n,+ useToolbarState,+ useViewportKind+} from '@open-pencil/vue'++import { useEditorStore } from '@/app/editor/active-store'+import { toolIcons } from '@/app/editor/icons'+import { toolbarItems } from '@/app/editor/toolbar/layout'+import { TOOL_SHORTCUT_LABELS } from '@/app/editor/toolbar/shortcuts'+import { appPreferences } from '@/app/settings/preferences/store'+import { useActionToast } from '@/app/shell/toast/action'+import InsertIconButton from '@/components/icon-picker/InsertIconButton.vue'+import { useToolbarActions } from '@/components/toolbar/actions'+import DesktopToolbar from '@/components/toolbar/DesktopToolbar.vue'+import { useToolLabels } from '@/components/toolbar/labels'+import MobileToolbar from '@/components/toolbar/MobileToolbar.vue'+import ToolbarContextMenu from '@/components/toolbar/ToolbarContextMenu.vue'+import type { ToolbarActionItem } from '@/components/toolbar/types'+import { useMenuUI } from '@/components/ui/menu/menu'++const store = useEditorStore()+const { isMobile } = useViewportKind()+const { getCommand } = useEditorCommands()+const { showActionToast } = useActionToast()+const { menu } = useI18n()++const toolLabels = useToolLabels()++const items = computed(() =>+ toolbarItems(appPreferences.value.toolbar, toolLabels.value, TOOL_SHORTCUT_LABELS)+)+const tools = computed(() =>+ items.value.flatMap((item) => (item.kind === 'tool' ? [item.tool] : []))+)+const actionItems = computed(() =>+ items.value.flatMap((item) => (item.kind === 'action' ? [item.action] : []))+)++const flyoutMenuCls = useMenuUI({ content: 'min-w-32' })+const toolbarUI = { flyoutContent: flyoutMenuCls.content }+const { editActions, arrangeActions } = useToolbarActions({ store, getCommand, menu })++const { mobileCategory, slideDirection, hasPrev, hasNext, goPrev, goNext } = useToolbarState()++function onActionTap(item: ToolbarActionItem) {+ item.action()+ showActionToast(item.label)+}+</script>++<template>+ <ToolbarRoot v-slot="{ activeTool, flyoutSelections, actions }" :tools="tools">+ <ToolbarContextMenu>+ <DesktopToolbar+ v-if="!isMobile"+ :items="items"+ :active-tool="activeTool"+ :flyout-selections="flyoutSelections"+ :tool-icons="toolIcons"+ :tool-labels="toolLabels"+ :tool-shortcuts="TOOL_SHORTCUT_LABELS"+ :ui="toolbarUI"+ @set-tool="actions.setTool"+ >+ <template #action="{ action }">+ <InsertIconButton v-if="action === 'insert-icon'" :ui="toolbarUI" />+ </template>+ </DesktopToolbar>++ <MobileToolbar+ v-else+ :tools="tools"+ :active-tool="activeTool"+ :flyout-selections="flyoutSelections"+ :tool-icons="toolIcons"+ :tool-labels="toolLabels"+ :tool-shortcuts="TOOL_SHORTCUT_LABELS"+ :ui="toolbarUI"+ :mobile-category="mobileCategory"+ :slide-direction="slideDirection"+ :has-prev="hasPrev"+ :has-next="hasNext"+ :edit-actions="editActions"+ :arrange-actions="arrangeActions"+ @set-tool="actions.setTool"+ @prev="goPrev"+ @next="goNext"+ @action="onActionTap"+ >+ <template #end>+ <template v-for="action in actionItems" :key="action">+ <InsertIconButton v-if="action === 'insert-icon'" mobile :ui="toolbarUI" />+ </template>+ </template>+ </MobileToolbar>+ </ToolbarContextMenu>+ </ToolbarRoot>+</template>diff --git a/src/components/Toolbar/ToolbarActionGroup.vue b/src/components/toolbar/ToolbarActionGroup.vuesimilarity index 98%rename from src/components/Toolbar/ToolbarActionGroup.vuerename to src/components/toolbar/ToolbarActionGroup.vueindex 5212fd473..8c5c28f07 100644--- a/src/components/Toolbar/ToolbarActionGroup.vue+++ b/src/components/toolbar/ToolbarActionGroup.vue@@ -4,7 +4,7 @@ import { tv } from 'tailwind-variants'import { vTestId } from '@open-pencil/vue'-import type { ToolbarActionItem, ToolbarUI } from '@/components/Toolbar/types'+import type { ToolbarActionItem, ToolbarUI } from '@/components/toolbar/types'import toolbarTheme from '@/theme/toolbar'const { actions, testPrefix, ui } = defineProps<{diff --git a/src/components/toolbar/ToolbarContextMenu.vue b/src/components/toolbar/ToolbarContextMenu.vuenew file mode 100644index 000000000..6abdb14d0--- /dev/null+++ b/src/components/toolbar/ToolbarContextMenu.vue@@ -0,0 +1,34 @@+<script setup lang="ts">+import {+ ContextMenuContent,+ ContextMenuItem,+ ContextMenuPortal,+ ContextMenuRoot,+ ContextMenuTrigger+} from 'reka-ui'++import { useI18n } from '@open-pencil/vue'++import { openSettingsDialog } from '@/app/settings/dialog'+import { useMenuUI } from '@/components/ui/menu/menu'++/** Right-clicking the toolbar offers its Settings page. */+const { settings } = useI18n()+const menu = useMenuUI({ content: 'w-48', item: 'justify-start gap-2' })+</script>++<template>+ <ContextMenuRoot>+ <ContextMenuTrigger as-child>+ <slot />+ </ContextMenuTrigger>+ <ContextMenuPortal>+ <ContextMenuContent :class="menu.content">+ <ContextMenuItem :class="menu.item" @select="openSettingsDialog('toolbar')">+ <icon-lucide-sliders-horizontal :class="menu.icon" />+ {{ settings.customizeToolbar }}+ </ContextMenuItem>+ </ContextMenuContent>+ </ContextMenuPortal>+ </ContextMenuRoot>+</template>diff --git a/src/components/Toolbar/actions.ts b/src/components/toolbar/actions.tssimilarity index 97%rename from src/components/Toolbar/actions.tsrename to src/components/toolbar/actions.tsindex 30d7f87bf..f587d4f91 100644--- a/src/components/Toolbar/actions.ts+++ b/src/components/toolbar/actions.ts@@ -14,7 +14,7 @@ import IconUngroup from '~icons/lucide/ungroup'import type { useEditorCommands } from '@open-pencil/vue'import type { EditorStore } from '@/app/editor/active-store'-import type { ToolbarActionItem } from '@/components/Toolbar/types'+import type { ToolbarActionItem } from '@/components/toolbar/types'type ToolbarActionOptions = {store: EditorStorediff --git a/src/components/toolbar/labels.ts b/src/components/toolbar/labels.tsnew file mode 100644index 000000000..6ee54caf0--- /dev/null+++ b/src/components/toolbar/labels.ts@@ -0,0 +1,41 @@+import { computed, type Component } from 'vue'+import IconSmilePlus from '~icons/lucide/smile-plus'++import { useI18n, usePanelMessages } from '@open-pencil/vue'+import type { Tool } from '@open-pencil/vue'++import { toolIcons } from '@/app/editor/icons'+import type { ToolbarEntry } from '@/app/editor/toolbar/layout'++export function useToolLabels() {+ const { tools } = useI18n()+ return computed<Record<Tool, string>>(() => ({+ SELECT: tools.value.move,+ FRAME: tools.value.frame,+ SECTION: tools.value.section,+ RECTANGLE: tools.value.rectangle,+ ELLIPSE: tools.value.ellipse,+ LINE: tools.value.line,+ POLYGON: tools.value.polygon,+ STAR: tools.value.star,+ PEN: tools.value.pen,+ TEXT: tools.value.text,+ HAND: tools.value.hand,+ COMMENT: tools.value.comment+ }))+}++/** Names for everything the toolbar can show, tools and commands alike. */+export function useToolbarEntryLabels() {+ const toolLabels = useToolLabels()+ const panels = usePanelMessages()+ return computed<Record<ToolbarEntry, string>>(() => ({+ ...toolLabels.value,+ 'insert-icon': panels.value.insertIcon+ }))+}++export const toolbarEntryIcons: Readonly<Record<ToolbarEntry, Component>> = {+ ...toolIcons,+ 'insert-icon': IconSmilePlus+}diff --git a/src/components/Toolbar/types.ts b/src/components/toolbar/types.tssimilarity index 100%rename from src/components/Toolbar/types.tsrename to src/components/toolbar/types.tsdiff --git a/src/components/ui/button/IconButton.vue b/src/components/ui/button/IconButton.vueindex 26bf524bd..2a920969d 100644--- a/src/components/ui/button/IconButton.vue+++ b/src/components/ui/button/IconButton.vue@@ -1,6 +1,6 @@<script setup lang="ts">import { tv } from 'tailwind-variants'-import { computed, normalizeClass, useAttrs } from 'vue'+import { computed, normalizeClass, useAttrs, useTemplateRef } from 'vue'import Tip from '@/components/ui/overlay/Tip.vue'import theme from '@/theme/button/icon-button'@@ -12,6 +12,7 @@ const {label,side = 'top',size = 'xs',+ toggle = false,type = 'button'} = defineProps<{active?: boolean@@ -20,10 +21,14 @@ const {label: stringside?: 'top' | 'bottom' | 'left' | 'right'size?: ControlSize+ /** A toggle button: `aria-pressed` says whether it is on, off included. */+ toggle?: booleantype?: 'button' | 'submit' | 'reset'}>()const attrs = useAttrs()+const button = useTemplateRef<HTMLButtonElement>('button')+defineExpose({ focus: (options?: FocusOptions) => button.value?.focus(options) })defineOptions({ inheritAttrs: false })@@ -40,12 +45,13 @@ const cls = computed(() =><template><Tip as-child :label="label" :side="side" :disabled="disabled"><button+ ref="button"v-bind="buttonAttrs"data-slot="icon-button":type="type":disabled="disabled":aria-label="label"- :aria-pressed="active ? 'true' : undefined"+ :aria-pressed="active ? 'true' : toggle ? 'false' : undefined":data-state="active ? 'on' : 'off'":class="cls">diff --git a/src/theme/settings/toolbar/joint.ts b/src/theme/settings/toolbar/joint.tsnew file mode 100644index 000000000..960822706--- /dev/null+++ b/src/theme/settings/toolbar/joint.ts@@ -0,0 +1,17 @@+/**+ * Where two rows meet in Settings › Toolbar, and where a dragged row lands: a box's divider+ * between rows that share a flyout, the gap between boxes, or nothing at the ends.+ */+export default {+ slots: {+ root: 'relative',+ line: 'pointer-events-none absolute inset-x-1 top-1/2 h-0.5 -translate-y-1/2 rounded-full bg-accent'+ },+ variants: {+ kind: {+ inside: { root: 'h-px bg-border' },+ between: { root: 'h-2' },+ end: { root: 'h-0' }+ }+ }+}diff --git a/src/theme/settings/toolbar/row.ts b/src/theme/settings/toolbar/row.tsnew file mode 100644index 000000000..e8b5c6ace--- /dev/null+++ b/src/theme/settings/toolbar/row.ts@@ -0,0 +1,19 @@+/** One tool or command in Settings › Toolbar. */+export default {+ slots: {+ root: 'group/row relative flex cursor-grab items-center gap-2 px-2 py-1.5',+ grip: 'cursor-grab text-muted',+ icon: 'size-4 shrink-0 text-surface',+ label: 'min-w-0 flex-1 truncate text-xs text-surface',+ shortcut: 'w-4 shrink-0 text-center',+ /** Shown while the row is hovered or in use, and always where there is no hover. */+ options:+ 'opacity-0 group-hover/row:opacity-100 group-focus-within/row:opacity-100 data-[state=open]:opacity-100 [@media(hover:none)]:opacity-100',+ target: 'pointer-events-none absolute inset-0 rounded-sm ring-2 ring-inset ring-accent'+ },+ variants: {+ hidden: {+ true: { icon: 'text-muted', label: 'text-muted' }+ }+ }+}diff --git a/src/theme/toggle/switch.ts b/src/theme/toggle/switch.tsindex 3dc407241..86a2ffa18 100644--- a/src/theme/toggle/switch.ts+++ b/src/theme/toggle/switch.ts@@ -1,6 +1,6 @@const switchTheme = {slots: {- root: 'relative inline-flex shrink-0 cursor-pointer items-center rounded-full border border-border bg-panel-field outline-none transition-colors hover:border-border-strong focus-visible:ring-1 focus-visible:ring-panel-focus data-[state=checked]:border-accent data-[state=checked]:bg-accent',+ root: 'relative inline-flex shrink-0 cursor-pointer items-center rounded-full border border-border bg-panel-field outline-none transition-colors hover:border-border-strong focus-visible:ring-1 focus-visible:ring-panel-focus data-[state=checked]:border-accent data-[state=checked]:bg-accent data-[disabled]:cursor-default data-[disabled]:opacity-50',thumb:'pointer-events-none block rounded-full bg-muted shadow-sm transition-transform data-[state=checked]:bg-white'},diff --git a/tests/app/editor/toolbar/layout.test.ts b/tests/app/editor/toolbar/layout.test.tsnew file mode 100644index 000000000..14d0736dd--- /dev/null+++ b/tests/app/editor/toolbar/layout.test.ts@@ -0,0 +1,216 @@+import { describe, expect, test } from 'bun:test'++import {+ combineToolbarEntry,+ DEFAULT_TOOLBAR_LAYOUT,+ detachToolbarEntry,+ joinToolbarEntry,+ moveToolbarEntry,+ normalizeToolbarLayout,+ placeToolbarEntry,+ setToolbarEntryHidden,+ toolbarDropOperations,+ toolbarItems,+ toolbarRows,+ type ToolbarEntry,+ type ToolbarLayout+} from '@/app/editor/toolbar/layout'+import { TOOL_SHORTCUT_LABELS } from '@/app/editor/toolbar/shortcuts'++const SHAPES: ToolbarEntry[] = ['RECTANGLE', 'LINE', 'ELLIPSE', 'POLYGON', 'STAR']+const LABELS = { ...TOOL_SHORTCUT_LABELS }++function layout(groups: ToolbarEntry[][], hidden: ToolbarEntry[] = []): ToolbarLayout {+ return normalizeToolbarLayout(groups, hidden)+}++describe('normalizeToolbarLayout', () => {+ test('keeps the default layout as it is', () => {+ expect(layout(DEFAULT_TOOLBAR_LAYOUT.groups)).toEqual(DEFAULT_TOOLBAR_LAYOUT)+ })++ test('drops unknown entries, repeats and empty groups', () => {+ const groups = [['SELECT', 'LASSO', 'SELECT'], [], ['FRAME', 'SECTION', 'FRAME']]+ const result = normalizeToolbarLayout(groups, ['HAND', 'HAND', 'GHOST'])+ expect(result.groups.slice(0, 2)).toEqual([['SELECT'], ['FRAME', 'SECTION']])+ expect(result.hidden).toEqual(['HAND'])+ })++ test('never hides Move', () => {+ expect(layout(DEFAULT_TOOLBAR_LAYOUT.groups, ['SELECT', 'PEN']).hidden).toEqual(['PEN'])+ })++ test('keeps commands out of flyouts', () => {+ const result = layout([['SELECT', 'insert-icon', 'HAND'], ['COMMENT']])+ expect(result.groups.slice(-4)).toEqual([['TEXT'], ['insert-icon'], ['HAND'], ['COMMENT']])+ })++ test('puts a tool the stored layout lacks into its default flyout', () => {+ const result = layout([['SELECT'], ['STAR', 'RECTANGLE', 'ELLIPSE'], ['LINE']])+ expect(result.groups[2]).toEqual(['STAR', 'RECTANGLE', 'ELLIPSE', 'POLYGON'])+ expect(result.groups.at(-1)).toEqual(['LINE'])+ })++ test('places a tool whose flyout is gone after the entry before it by default', () => {+ const stored: ToolbarEntry[][] = [['TEXT'], ['SELECT'], SHAPES, ['HAND']]+ expect(layout(stored).groups).toEqual([+ ['TEXT'],+ ['SELECT'],+ ['FRAME', 'SECTION'],+ SHAPES,+ ['PEN'],+ ['HAND'],+ ['COMMENT'],+ ['insert-icon']+ ])+ })+})++describe('toolbarItems', () => {+ test('makes a button of a single shown tool and a flyout keyed by the first shown member', () => {+ const items = toolbarItems(+ layout(DEFAULT_TOOLBAR_LAYOUT.groups, ['SECTION', 'RECTANGLE']),+ LABELS,+ TOOL_SHORTCUT_LABELS+ )+ expect(items[1]).toEqual({+ kind: 'tool',+ tool: { key: 'FRAME', label: 'F', shortcut: 'F' }+ })+ expect(items[2]).toEqual({+ kind: 'tool',+ tool: {+ key: 'LINE',+ label: 'L',+ shortcut: 'L',+ flyout: ['LINE', 'ELLIPSE', 'POLYGON', 'STAR']+ }+ })+ expect(items.at(-1)).toEqual({ kind: 'action', action: 'insert-icon' })+ })++ test('leaves out a flyout whose members are all hidden', () => {+ const items = toolbarItems(+ layout(DEFAULT_TOOLBAR_LAYOUT.groups, ['FRAME', 'SECTION']),+ LABELS,+ TOOL_SHORTCUT_LABELS+ )+ expect(items.map((item) => (item.kind === 'tool' ? item.tool.key : item.action))).not.toContain(+ 'FRAME'+ )+ })+})++describe('editing', () => {+ const base = layout(DEFAULT_TOOLBAR_LAYOUT.groups)++ test('hiding and showing keeps the entry in place', () => {+ const hidden = setToolbarEntryHidden(base, 'PEN', true)+ expect(hidden.hidden).toEqual(['PEN'])+ expect(hidden.groups).toEqual(base.groups)+ expect(setToolbarEntryHidden(hidden, 'PEN', false).hidden).toEqual([])+ expect(setToolbarEntryHidden(base, 'SELECT', true)).toBe(base)+ })++ test('a button swaps with the button or flyout next to it', () => {+ const moved = moveToolbarEntry(base, 'PEN', -1)+ expect(moved.groups.slice(2, 4)).toEqual([['PEN'], SHAPES])+ expect(moveToolbarEntry(base, 'SELECT', -1)).toBe(base)+ })++ test('a flyout member moves inside the flyout and past its end becomes a button', () => {+ const inside = moveToolbarEntry(base, 'SECTION', -1)+ expect(inside.groups[1]).toEqual(['SECTION', 'FRAME'])+ const out = moveToolbarEntry(inside, 'SECTION', -1)+ expect(out.groups.slice(0, 3)).toEqual([['SELECT'], ['SECTION'], ['FRAME']])+ const below = moveToolbarEntry(base, 'SECTION', 1)+ expect(below.groups.slice(1, 3)).toEqual([['FRAME'], ['SECTION']])+ })++ test('joining merges a group into the one above', () => {+ const joined = joinToolbarEntry(base, 'TEXT')+ expect(joined.groups[3]).toEqual(['PEN', 'TEXT'])+ expect(joinToolbarEntry(base, 'insert-icon')).toBe(base)+ expect(joinToolbarEntry(base, 'SELECT')).toBe(base)+ expect(joinToolbarEntry(base, 'LINE')).toBe(base)+ })++ test('removing a tool from its flyout leaves only it a button, after the flyout', () => {+ expect(detachToolbarEntry(base, 'ELLIPSE').groups.slice(2, 4)).toEqual([+ ['RECTANGLE', 'LINE', 'POLYGON', 'STAR'],+ ['ELLIPSE']+ ])+ expect(detachToolbarEntry(base, 'PEN')).toBe(base)+ })++ test('rows say how each entry relates to the one above', () => {+ const rows = toolbarRows(base)+ const row = (entry: ToolbarEntry) => rows.find((candidate) => candidate.entry === entry)+ expect(row('SELECT')).toMatchObject({+ joined: false,+ canJoin: false,+ canMoveUp: false+ })+ expect(row('SECTION')).toMatchObject({+ joined: true,+ canJoin: false,+ canMoveUp: true+ })+ expect(row('PEN')).toMatchObject({ joined: false, canJoin: true })+ expect(row('insert-icon')).toMatchObject({+ canJoin: false,+ canMoveDown: false+ })+ })+})++describe('dragging', () => {+ const base = layout(DEFAULT_TOOLBAR_LAYOUT.groups)+ /** Where an entry sits in the list the dragged Pen is lifted out of. */+ const indexOf = (entry: ToolbarEntry) => {+ const flat: ToolbarEntry[] = base.groups.flat().filter((other) => other !== 'PEN')+ return flat.indexOf(entry)+ }++ test('a tool dropped between two flyout members joins the flyout', () => {+ const dropped = placeToolbarEntry(base, 'PEN', indexOf('LINE'))+ expect(dropped.groups[2]).toEqual(['RECTANGLE', 'PEN', 'LINE', 'ELLIPSE', 'POLYGON', 'STAR'])+ })++ test('a tool dropped between groups becomes a button there', () => {+ const dropped = placeToolbarEntry(base, 'PEN', indexOf('RECTANGLE'))+ expect(dropped.groups.slice(1, 4)).toEqual([['FRAME', 'SECTION'], ['PEN'], SHAPES])+ })++ test('a flyout member dragged to the gap leaves its flyout', () => {+ const flat = base.groups.flat().filter((entry) => entry !== 'SECTION')+ const dropped = placeToolbarEntry(base, 'SECTION', flat.indexOf('PEN'))+ expect(dropped.groups.slice(1, 5)).toEqual([['FRAME'], SHAPES, ['SECTION'], ['PEN']])+ })++ test('a command never lands inside a flyout', () => {+ const flat = base.groups.flat().filter((entry) => entry !== 'insert-icon')+ const dropped = placeToolbarEntry(base, 'insert-icon', flat.indexOf('LINE'))+ expect(dropped.groups.slice(2, 4)).toEqual([SHAPES, ['insert-icon']])+ expect(toolbarDropOperations(base, 'insert-icon', 'LINE')).toEqual({+ 'reorder-before': false,+ 'reorder-after': false,+ combine: false+ })+ expect(toolbarDropOperations(base, 'insert-icon', 'RECTANGLE')['reorder-before']).toBe(true)+ })++ test('a tool dropped onto another shares its flyout, right after it', () => {+ expect(combineToolbarEntry(base, 'COMMENT', 'TEXT').groups).toContainEqual(['TEXT', 'COMMENT'])+ expect(combineToolbarEntry(base, 'PEN', 'LINE').groups[2]).toEqual([+ 'RECTANGLE',+ 'LINE',+ 'PEN',+ 'ELLIPSE',+ 'POLYGON',+ 'STAR'+ ])+ expect(combineToolbarEntry(base, 'LINE', 'STAR')).toBe(base)+ expect(combineToolbarEntry(base, 'PEN', 'insert-icon')).toBe(base)+ })+})diff --git a/tests/e2e/settings/tabs.spec.ts b/tests/e2e/settings/tabs.spec.tsindex c2e4b922f..680efe27a 100644--- a/tests/e2e/settings/tabs.spec.ts+++ b/tests/e2e/settings/tabs.spec.ts@@ -17,6 +17,10 @@ test('settings tabs associate panels and support vertical keyboard navigation',await expect(dialog).toHaveScreenshot('settings-tabs-general.png')await general.focus()await general.press('ArrowDown')+ const toolbar = page.getByTestId('settings-section-toolbar')+ await expect(toolbar).toBeFocused()+ await expect(page.getByTestId('settings-toolbar-panel')).toBeVisible()+ await toolbar.press('ArrowDown')const ai = page.getByTestId('settings-section-ai')await expect(ai).toBeFocused()await expect(ai).toHaveAttribute('aria-selected', 'true')diff --git a/tests/e2e/settings/tabs.spec.ts-snapshots/settings-tabs-general-openpencil-darwin.png b/tests/e2e/settings/tabs.spec.ts-snapshots/settings-tabs-general-openpencil-darwin.pngindex c834756d0..3ac1d028b 100644Binary files a/tests/e2e/settings/tabs.spec.ts-snapshots/settings-tabs-general-openpencil-darwin.png and b/tests/e2e/settings/tabs.spec.ts-snapshots/settings-tabs-general-openpencil-darwin.png differdiff --git a/tests/e2e/toolbar/customize.spec.ts b/tests/e2e/toolbar/customize.spec.tsnew file mode 100644index 000000000..c6c05e21d--- /dev/null+++ b/tests/e2e/toolbar/customize.spec.ts@@ -0,0 +1,70 @@+import { expect, test, type Page } from '@playwright/test'++import { CanvasHelper } from '#tests/helpers/canvas'+import {+ toolbarFlyoutItemTestId,+ toolbarFlyoutTestId,+ toolbarToolTestId+} from '#tests/helpers/test-ids'++/** The tools the toolbar shows, in order: a flyout counts as the tool its button shows. */+function toolbarOrder(page: Page) {+ return page+ .getByTestId('toolbar')+ .locator('button[aria-pressed]')+ .evaluateAll((buttons) =>+ buttons.flatMap((button) => button.getAttribute('data-test-id') ?? [])+ )+}++test('the toolbar hides, reorders and regroups tools from Settings and keeps the layout', async ({+ page+}) => {+ await page.goto('/?test')+ const canvas = new CanvasHelper(page)+ await canvas.waitForInit()++ await page.getByTestId('toolbar').click({ button: 'right' })+ await page.getByRole('menuitem', { name: 'Customize toolbar…' }).click()+ const settings = page.getByTestId('settings-toolbar-panel')+ await expect(settings).toBeVisible()++ await settings.getByRole('switch', { name: 'Show Pen' }).click()+ // Dropping Comment onto Hand puts both in one menu; Text's grip moves it with the keyboard.+ await settings+ .getByRole('button', { name: 'Reorder Comment' })+ .dragTo(settings.locator('[data-entry="HAND"]'))+ await settings.getByRole('button', { name: 'Reorder Text' }).press('ArrowUp')+ await page.getByTestId('app-settings-done').click()+ await expect(page.getByTestId('app-settings-dialog')).toBeHidden()++ const expectCustomized = async () => {+ await expect(page.getByTestId(toolbarToolTestId('PEN'))).toHaveCount(0)+ expect(await toolbarOrder(page)).toEqual(+ (['SELECT', 'FRAME', 'RECTANGLE', 'TEXT', 'HAND'] as const).map((tool) =>+ toolbarToolTestId(tool)+ )+ )+ await page.getByTestId(toolbarFlyoutTestId('HAND')).click()+ await page.getByTestId(toolbarFlyoutItemTestId('COMMENT')).click()+ await expect(page.getByTestId(toolbarToolTestId('COMMENT'))).toHaveAttribute(+ 'aria-pressed',+ 'true'+ )+ }+ await expectCustomized()++ await page.reload()+ await canvas.waitForInit()+ await expectCustomized()++ await canvas.pressKey('p')+ expect(await page.evaluate(() => window.openPencil?.getStore?.().state.activeTool)).toBe('PEN')++ await page.getByTestId('toolbar').click({ button: 'right' })+ await page.getByRole('menuitem', { name: 'Customize toolbar…' }).click()+ await page.getByRole('button', { name: 'Reset to default' }).click()+ await page.getByTestId('app-settings-done').click()+ await expect(page.getByTestId(toolbarToolTestId('PEN'))).toBeVisible()+ canvas.assertNoErrors()+})