diff --git a/src/vector-studio/README.md b/src/vector-studio/README.md index 83f92d60e3..bbe9f6abbd 100644 --- a/src/vector-studio/README.md +++ b/src/vector-studio/README.md @@ -24,7 +24,7 @@ npm run build # production build in dist/ (includes the collaboration worker) - **Files:** documents are saved as .ai files: PDF-compatible files whose pages any program that reads .ai or PDF can show, with the editable document inside. A .ai file saved here opens exactly as it was left; one made in another program opens from its PDF pages and saves back to the same file after asking once. Files saved before as .vstudio still open. - **Documents:** multiple artboards, layers, templates, version history, File Info, Package, Print with presets, marks, bleed, scaling and tiling, Save for Web, slices, Export for Screens, Asset Export, SVG/PDF/EPS/PNG/JPEG/WebP/TIFF/DXF export, Trace Image. - **Import:** open or place SVG, PDF (pages as artboards, or one page cropped to a page box; editable paths, colors with spot swatches, gradients, patterns, clipping, transparency, images, text kept editable or as outlines, layers), PDF-compatible .ai files from other programs, EPS/PostScript (interpreted, or its preview image), DXF (layers, units, curves, text, blocks) and PNG, JPEG, WebP, GIF, TIFF, BMP and PSD images. -- **Workflow:** History and Actions panels, File > Scripts (sandboxed automation: a Script Editor for typing and saving scripts on a tablet, a Scripting Reference, geometry such as area and label points, path operations and batch edits; built-in Color by Number and Select Smallest Object), Variables (data-driven artwork from CSV), Libraries shared across documents, customizable keyboard shortcuts and workspaces, View options (outline, pixel preview, trim view, presentation mode, proof colors, saved views, rotate view), Links, Attributes, Document Info, SVG Interactivity. +- **Workflow:** History and Actions panels, File > Scripts (sandboxed automation: a Script Editor for typing and saving scripts on a tablet, a Scripting Reference, geometry such as area and label points, path operations and batch edits; built-in Color by Number and Select Smallest Object), Variables (data-driven artwork from CSV), Libraries shared across documents, customizable keyboard shortcuts and workspaces (floating panels, a movable Tools panel, panels on either side, all by drag with mouse, touch or stylus, saved per workspace), View options (outline, pixel preview, trim view, presentation mode, proof colors, saved views, rotate view), Links, Attributes, Document Info, SVG Interactivity. - **Collaboration:** Invite to Edit (live co-editing with presence and roles), Share for Review, and comments. ## Architecture diff --git a/src/vector-studio/src/app.js b/src/vector-studio/src/app.js index a82a1f1f82..e49ddfe892 100644 --- a/src/vector-studio/src/app.js +++ b/src/vector-studio/src/app.js @@ -165,7 +165,7 @@ export class App extends Emitter { this.docArea = h('main#main.doc-area', this.tabsEl, this.isolationBar, h('div.canvas-stack', this.canvasWrap, this.taskbar, this.home), this.statusbar.el, this.canvasDesc); this.dock = createDock(this); for (const P of this.panelClasses) this.dock.register(P); - this.workspace = h('div.workspace', this.toolbar.el, this.docArea, this.dock.el); + this.workspace = h('div.workspace', this.toolbar.el, this.docArea, this.dock.el, this.dock.floatLayer); this.toastHost = h('div.toast-host', { role: 'status', 'aria-live': 'polite' }); this.root.replaceChildren(this.topbar, this.workspace, this.toastHost); this.root.classList.toggle('dock-closed', !this.dockOpen); diff --git a/src/vector-studio/src/features/workspace/styles.css b/src/vector-studio/src/features/workspace/styles.css index cf1a0872cf..a62e63fb61 100644 --- a/src/vector-studio/src/features/workspace/styles.css +++ b/src/vector-studio/src/features/workspace/styles.css @@ -230,7 +230,8 @@ .screen-full .doc-tabs, .screen-full .statusbar, .screen-full .isolation-bar, -.screen-full .pattern-bar { +.screen-full .pattern-bar, +.screen-full .float-panels { display: none !important; } @@ -346,3 +347,85 @@ dialog.presentation::backdrop { grid-template-columns: minmax(0, 1fr); } } + +/* ---- Tools panel and panel dock positions (Window > Tools Position, Panels on Left) ---- */ +@media (min-width: 761px) { + .app:is(.tools-right, .panels-left, .tools-float) .toolbar { + grid-area: tools; + width: var(--toolbar-w); + } + + .app:is(.tools-right, .panels-left, .tools-float) .doc-area { + grid-area: doc; + } + + .app:is(.tools-right, .panels-left, .tools-float) .panels-area { + grid-area: panels; + } + + .app.tools-right .workspace { + grid-template-columns: minmax(0, 1fr) auto auto; + grid-template-areas: 'doc tools panels'; + } + + .app.panels-left .workspace { + grid-template-columns: auto auto minmax(0, 1fr); + grid-template-areas: 'panels tools doc'; + } + + .app.panels-left.tools-right .workspace { + grid-template-columns: auto minmax(0, 1fr) auto; + grid-template-areas: 'panels doc tools'; + } + + .app.tools-float .workspace { + grid-template-columns: minmax(0, 1fr) auto; + grid-template-areas: 'doc panels'; + } + + .app.tools-float.panels-left .workspace { + grid-template-columns: auto minmax(0, 1fr); + grid-template-areas: 'panels doc'; + } + + .app.tools-right .toolbar { + border-right: 0; + border-left: 1px solid var(--border); + } + + .app.panels-left:not(.tools-right) .toolbar { + border-left: 0; + } + + /* A floating Tools panel: over the canvas, as tall as its tools (at most the workspace). */ + .app.tools-float .toolbar { + position: absolute; + grid-area: auto; + z-index: 45; + max-height: calc(100% - 8px); + border: 1px solid var(--border); + border-radius: var(--radius); + box-shadow: var(--shadow-float); + } + + .app.tools-float .toolbar-scroll { + flex: 0 1 auto; + } +} + +/* Where the Tools panel would dock while its grip is dragged. */ +.tools-dock-zone { + position: absolute; + top: 0; + bottom: 0; + z-index: 46; + width: 6px; + background: var(--accent); + opacity: 0.8; + pointer-events: none; +} + +.tools-dragging, +.tools-dragging * { + cursor: grabbing !important; +} diff --git a/src/vector-studio/src/features/workspace/window.js b/src/vector-studio/src/features/workspace/window.js index ba80c8600d..ffdf5c6e42 100644 --- a/src/vector-studio/src/features/workspace/window.js +++ b/src/vector-studio/src/features/workspace/window.js @@ -1,7 +1,10 @@ /** * Window menu features: workspaces (built-in arrangements, saved ones, - * New / Manage / Reset), tool sets (Basic, Advanced, an edited set from the - * All Tools drawer) and showing the Tools panel, the Control bar, New + * New / Manage / Reset, and the current arrangement kept across sessions), + * tool sets (Basic, Advanced, an edited set from the All Tools drawer), + * where the Tools panel and the panel dock sit (the Tools panel docks on + * either side or floats, dragged by its grip; the panels dock on either + * side) and showing the Tools panel, the Control bar, New * Window (a second view of a document), arranging documents (tabs, side by * side, stacked, floating) and the screen modes. */ @@ -12,6 +15,7 @@ import { openDialog } from '../../ui/dialogs/dialog.js'; import { openPopover, closePopover } from '../../ui/popover.js'; import { TOOL_LAYOUT } from '../../ui/toolbar.js'; import { createControlBar } from './control-bar.js'; +import { trackDrag } from '../../ui/drag.js'; // ---- tool sets ---- @@ -241,6 +245,10 @@ export function captureWorkspace(app, name) { dock: layout.dock, strip: layout.strip, active: layout.active, + floating: layout.floating, + toolsPosition: toolsPosition(app), + toolsFloat: app.prefs.get('toolsFloat') || null, + panelsSide: panelsSide(app), toolbar: toolSet(app), toolbarHidden: app.prefs.get('toolbarHidden') || [], controlBar: Boolean(app.prefs.get('controlBar')), @@ -255,12 +263,27 @@ export function applyWorkspace(app, ws, key) { setToolSet(app, ws.toolbar || 'advanced'); setControlBar(app, Boolean(ws.controlBar)); setToolbarVisible(app, ws.toolbarVisible !== false); + setPanelsSide(app, ws.panelsSide); + setToolsPosition(app, ws.toolsPosition, ws.toolsFloat); if (ws.dockOpen !== false && !app.dockOpen) app.setDockOpen(true); app.root.classList.remove('hide-panels', 'hide-dock'); app.prefs.set('workspace', key); + // The workspace as it was defined: changes made from here on are kept again. + app.prefs.set('workspaceLayout', null); app.refreshChrome(); } +/** Keep the panel arrangement as the user changed it, for the next session (Reset brings back the workspace's own). */ +function rememberLayout(app) { + app.prefs.set('workspaceLayout', { key: currentKey(app), ...app.dock.getLayout() }); +} + +/** The arrangement kept from the last session, when it belongs to workspace `key`. */ +function rememberedLayout(app, key) { + const v = app.prefs.get('workspaceLayout'); + return v && typeof v === 'object' && v.key === key && Array.isArray(v.dock) ? v : null; +} + /** Workspace by key: 'essentials', ..., or 'saved:'. */ export function workspaceByKey(app, key) { if (key?.startsWith('saved:')) return savedWorkspaces(app).find((w) => w.name === key.slice(6)) || null; @@ -311,6 +334,109 @@ function setToolbarVisible(app, on) { app.root.classList.toggle('hide-toolbar', !on); } +// ---- Tools panel and panel dock positions ---- + +export const TOOLS_POSITIONS = ['left', 'right', 'float']; + +/** How close (px) to the canvas edge the Tools panel grip must come to dock there. */ +const TOOLS_DOCK_EDGE = 36; + +export function toolsPosition(app) { + const v = app.prefs.get('toolsPosition'); + return TOOLS_POSITIONS.includes(v) ? v : 'left'; +} + +export function panelsSide(app) { + return app.prefs.get('panelsSide') === 'left' ? 'left' : 'right'; +} + +/** Move a floating Tools panel to (x, y) in the workspace, keeping its grip on screen. */ +function placeFloatingTools(app, at) { + const el = app.toolbar?.el; + const ws = app.workspace; + if (!el || !ws) return null; + const W = ws.clientWidth || window.innerWidth; + const H = ws.clientHeight || window.innerHeight; + // Fully on screen: pushed up when there is not room below for all of it. + const x = Math.round(Math.max(0, Math.min(W - Math.max(40, el.offsetWidth), Number(at?.x) || 12))); + const y = Math.round(Math.max(0, Math.min(H - Math.max(40, el.offsetHeight) - 4, Number(at?.y) || 12))); + el.style.left = `${x}px`; + el.style.top = `${y}px`; + return { x, y }; +} + +/** Dock the Tools panel on the left or right of the canvas, or float it (at `at`, workspace pixels). */ +export function setToolsPosition(app, pos, at = null) { + const next = TOOLS_POSITIONS.includes(pos) ? pos : 'left'; + app.prefs.set('toolsPosition', next); + if (next === 'float' && at) app.prefs.set('toolsFloat', { x: Math.round(Number(at.x) || 0), y: Math.round(Number(at.y) || 0) }); + applyToolsPosition(app); +} + +function applyToolsPosition(app) { + const pos = toolsPosition(app); + app.root.classList.toggle('tools-right', pos === 'right'); + app.root.classList.toggle('tools-float', pos === 'float'); + const el = app.toolbar?.el; + if (!el) return; + if (pos === 'float') placeFloatingTools(app, app.prefs.get('toolsFloat')); + else el.style.left = el.style.top = ''; + requestAnimationFrame(() => { + app.toolbar?.refit?.(); + // Its columns may change its height: keep it on screen. + if (toolsPosition(app) === 'float') placeFloatingTools(app, app.prefs.get('toolsFloat')); + }); +} + +/** Dock the panels (strip and tabbed dock) on the left or right edge. */ +export function setPanelsSide(app, side) { + const next = side === 'left' ? 'left' : 'right'; + app.prefs.set('panelsSide', next); + app.root.classList.toggle('panels-left', next === 'left'); + app.dock.closeFlyout?.(false); +} + +/** + * The Tools panel grip: dragging it floats the panel under the pointer; + * releasing it near the canvas's left or right edge docks it on that side. + */ +function wireToolsGrip(app) { + const grip = app.toolbar?.grip; + if (!grip) return; + const mark = h('div.tools-dock-zone', { 'aria-hidden': 'true' }); + grip.addEventListener('pointerdown', (e) => { + if (e.button !== 0) return; + e.preventDefault(); + const el = app.toolbar.el; + let grab = null; + let side = null; + trackDrag(e, { + start: (ev, origin) => { + const r = el.getBoundingClientRect(); + const wr = app.workspace.getBoundingClientRect(); + grab = { x: origin.x - r.left, y: origin.y - r.top }; + if (toolsPosition(app) !== 'float') setToolsPosition(app, 'float', { x: r.left - wr.left, y: r.top - wr.top }); + app.root.classList.add('tools-dragging'); + }, + move: (ev) => { + const wr = app.workspace.getBoundingClientRect(); + placeFloatingTools(app, { x: ev.clientX - wr.left - grab.x, y: ev.clientY - wr.top - grab.y }); + const dr = app.docArea.getBoundingClientRect(); + side = ev.clientX < dr.left + TOOLS_DOCK_EDGE ? 'left' : ev.clientX > dr.right - TOOLS_DOCK_EDGE ? 'right' : null; + if (!side) return mark.remove(); + mark.style.left = `${(side === 'left' ? dr.left : dr.right - 6) - wr.left}px`; + if (!mark.isConnected) app.workspace.append(mark); + }, + end: (ev, { cancelled }) => { + mark.remove(); + app.root.classList.remove('tools-dragging'); + if (!cancelled && side) setToolsPosition(app, side); + else app.prefs.set('toolsFloat', { x: el.offsetLeft, y: el.offsetTop }); + }, + }); + }); +} + // ---- documents: new window, arrangement ---- /** A second editor (view) on the same document, shown as its own tab. */ @@ -499,6 +625,18 @@ export function installWindow(app) { { id: 'window.toolbar.advanced', label: 'Advanced', checked: (a) => toolSet(a) === 'advanced', run: (a) => setToolSet(a, 'advanced') }, { id: 'window.toolbar.edit', label: 'Edit Toolbar...', run: (a) => openToolDrawer(a, a.toolbar?.el.querySelector('.toolbar-misc .tool-btn')) }, { id: 'window.toolbar', label: 'Tools', checked: (a) => a.prefs.get('toolbarVisible') !== false, run: (a) => setToolbarVisible(a, a.prefs.get('toolbarVisible') === false) }, + ...TOOLS_POSITIONS.map((pos) => ({ + id: `window.tools.${pos}`, + label: { left: 'Dock on Left', right: 'Dock on Right', float: 'Floating' }[pos], + checked: (a) => toolsPosition(a) === pos, + run: (a) => setToolsPosition(a, pos), + })), + ...['left', 'right'].map((side) => ({ + id: `window.panels.${side}`, + label: side === 'left' ? 'Dock on Left' : 'Dock on Right', + checked: (a) => panelsSide(a) === side, + run: (a) => setPanelsSide(a, side), + })), { id: 'window.controlBar', label: 'Control', checked: (a) => Boolean(a.prefs.get('controlBar')), run: (a) => setControlBar(a, !a.prefs.get('controlBar')) }, { id: 'window.newWindow', label: 'New Window', enabled: hasDoc, run: (a) => newWindow(a) }, { id: 'window.arrange.cascade', label: 'Cascade', enabled: (a) => a.editors.length > 0, run: (a) => cascadeWindows(a) }, @@ -537,20 +675,30 @@ export function installWindow(app) { if ('controlBar' in values) setControlBar(app, Boolean(app.prefs.get('controlBar'))); if ('toolbarSet' in values || 'toolbarHidden' in values) applyToolSet(app); if ('toolbarVisible' in values) setToolbarVisible(app, app.prefs.get('toolbarVisible') !== false); - const ws = 'workspace' in values && workspaceByKey(app, currentKey(app)); + if ('toolsPosition' in values || 'toolsFloat' in values) applyToolsPosition(app); + if ('panelsSide' in values) setPanelsSide(app, app.prefs.get('panelsSide')); + const ws = ('workspace' in values || 'workspaceLayout' in values) && (rememberedLayout(app, currentKey(app)) || workspaceByKey(app, currentKey(app))); if (ws) app.dock.setLayout(ws); }); + app.on('panel-layout', () => rememberLayout(app)); app.on('started', () => { if (app.prefs.get('controlBar')) setControlBar(app, true); applyToolSet(app); setToolbarVisible(app, app.prefs.get('toolbarVisible') !== false); + setPanelsSide(app, panelsSide(app)); + applyToolsPosition(app); const key = app.prefs.get('workspace'); - const saved = key && workspaceByKey(app, key); - // The workspace's panels, on the dock tab last used (when it is one of them). + // The panels as they were left last session, else the workspace's own, + // on the dock tab last used (when it is one of them). + const saved = rememberedLayout(app, currentKey(app)) || (key && workspaceByKey(app, key)); const tab = app.prefs.get('dockTab'); - if (saved && key !== 'essentials') app.dock.setLayout(saved.dock?.includes(tab) ? { ...saved, active: tab } : saved); + if (saved && (key !== 'essentials' || saved.key)) app.dock.setLayout(saved.dock?.includes(tab) ? { ...saved, active: tab } : saved); wireToolbarDrag(app); + wireToolsGrip(app); + window.addEventListener('resize', () => { + if (toolsPosition(app) === 'float') placeFloatingTools(app, app.prefs.get('toolsFloat')); + }); // Clicking or scrolling over a document beside the active one makes it active first. const pick = (e) => { const pane = e.target.closest?.('.view-host'); diff --git a/src/vector-studio/src/styles/panels.css b/src/vector-studio/src/styles/panels.css index acf2e4d3f6..41d216b5b8 100644 --- a/src/vector-studio/src/styles/panels.css +++ b/src/vector-studio/src/styles/panels.css @@ -952,3 +952,149 @@ min-width: 0; padding: 2px 4px; } + +/* ---- Floating panels and panel drags ---- */ +/* A finger on a dock tab drags it; on a strip icon, a swipe along the strip + still scrolls the strip, and a drag across it tears the panel off. */ +.dock-tab { + touch-action: none; +} + +.strip-btn:not(.strip-stack) { + touch-action: pan-y; +} + +@media (max-width: 760px) { + .strip-btn:not(.strip-stack) { + touch-action: pan-x; + } +} + +.float-panels { + position: absolute; + inset: 0; + z-index: 40; + pointer-events: none; +} + +.float-panels:empty, +.hide-panels .float-panels, +.hide-dock .float-panels, +.dock-closed .float-panels { + display: none; +} + +.float-panel { + position: absolute; + display: flex; + flex-direction: column; + max-height: 100%; + min-width: 200px; + min-height: 0; + pointer-events: auto; + background: var(--bg-panel); + border: 1px solid var(--border); + border-radius: var(--radius); + box-shadow: var(--shadow-float); + overflow: hidden; +} + +.float-panel.dropping { + opacity: 0.6; +} + +.float-panel-head { + display: flex; + align-items: center; + justify-content: space-between; + flex: none; + padding: 4px 4px 4px 12px; + border-bottom: 1px solid var(--border); + cursor: grab; + touch-action: none; + user-select: none; + -webkit-user-select: none; +} + +.panel-dragging, +.panel-dragging * { + cursor: grabbing !important; +} + +.float-panel-body { + flex: 1; + min-height: 0; + overflow-y: auto; + overflow-x: hidden; + scrollbar-width: thin; +} + +.float-panel-foot { + position: relative; + flex: none; + height: 12px; + border-top: 1px solid var(--border); +} + +.float-panel-resize { + position: absolute; + right: 0; + bottom: 0; + width: 16px; + height: 16px; + cursor: nwse-resize; + touch-action: none; + background: linear-gradient(135deg, transparent 50%, var(--text-3) 50%, var(--text-3) 56%, transparent 56%, transparent 68%, var(--text-3) 68%, var(--text-3) 74%, transparent 74%); + opacity: 0.7; +} + +@media (pointer: coarse) { + .float-panel-foot { + height: 20px; + } + + .float-panel-resize { + width: 28px; + height: 28px; + } +} + +/* Drop targets while a panel is dragged: the dock tabs (with an insertion mark) and the icon strip. */ +.dock-head { + position: relative; +} + +.dock-head.drop-target, +.panel-strip.drop-target { + background: color-mix(in srgb, var(--accent) 14%, var(--bg-panel)); + box-shadow: inset 0 0 0 2px var(--accent); +} + +.dock-insert-mark { + position: absolute; + top: 6px; + bottom: 6px; + width: 2px; + background: var(--accent); + border-radius: 1px; + pointer-events: none; +} + +/* Panels docked on the left edge: the dock sits at the edge, the strip beside it, flyouts open toward the canvas. */ +@media (min-width: 761px) { + .panels-left .panels-area { + flex-direction: row-reverse; + } + + .panels-left .panel-strip, + .panels-left .dock { + border-left: 0; + border-right: 1px solid var(--border); + } + + .panels-left .panel-flyout, + .panels-left.dock-closed .panel-flyout { + right: auto; + left: 100%; + } +} diff --git a/src/vector-studio/src/styles/shell.css b/src/vector-studio/src/styles/shell.css index 29958666fc..b656126b70 100644 --- a/src/vector-studio/src/styles/shell.css +++ b/src/vector-studio/src/styles/shell.css @@ -161,6 +161,7 @@ puter-user-menu::part(apps-panel) { /* ---- Workspace ---- */ .workspace { + position: relative; display: grid; grid-template-columns: var(--toolbar-w) minmax(0, 1fr) auto; grid-template-rows: minmax(0, 1fr); @@ -191,9 +192,27 @@ puter-user-menu::part(apps-panel) { .toolbar-head { display: flex; justify-content: center; + align-items: center; + gap: 2px; padding-top: 4px; } +/* Drags the Tools panel out to float, or to an edge to dock it there. */ +.toolbar-grip { + display: inline-flex; + align-items: center; + justify-content: center; + width: 14px; + height: 14px; + color: var(--text-3); + cursor: grab; + touch-action: none; +} + +.toolbar-grip:hover { + color: var(--text); +} + .toolbar-cols { width: 28px; height: 14px; diff --git a/src/vector-studio/src/ui/dock.js b/src/vector-studio/src/ui/dock.js index f3cbeb0ece..a763301075 100644 --- a/src/vector-studio/src/ui/dock.js +++ b/src/vector-studio/src/ui/dock.js @@ -3,10 +3,19 @@ * icon strip of collapsed panels that open as flyouts beside it, like a * pro editor's collapsed panel groups. On narrow screens the dock becomes * a bottom sheet (see responsive.css) toggled from the status bar. + * + * Any panel can also float in its own window over the canvas: drag a dock + * tab or a strip icon out (or pick Float Panel from its panel menu), move + * the window by its header and resize it from its corner, then drop its + * header on the dock's tabs to dock it as a tab or on the strip to collapse + * it to an icon. Dragging a dock tab along the tabs reorders them. Drags + * use pointer events, so they work the same with a mouse, a finger or a + * stylus. */ import { h } from '../lib/dom.js'; import { icon } from './icons.js'; import { formatShortcut, IS_MAC } from '../commands/registry.js'; +import { trackDrag, pointIn } from './drag.js'; /** 'Shift+Mod+F10' -> 'Shift+Meta+F10' (aria-keyshortcuts names real keys). */ function ariaShortcut(sc) { @@ -19,6 +28,11 @@ const PHONE_QUERY = '(max-width: 760px)'; /** Minimum time between panel refreshes during a live drag. */ export const LIVE_PANEL_MS = 150; +/** Floating panel window limits (px). */ +export const FLOAT_MIN_W = 200; +export const FLOAT_MIN_H = 120; +const FLOAT_DEFAULT_W = 280; + /** * Collapsed panels sit in the strip in these groups, separated by a rule. * When the strip is too short for every icon, the largest groups collapse @@ -96,13 +110,35 @@ export function createDock(app) { return p.menu() || []; } + /** Where panel `id` is: 'dock', 'strip', 'float' or null (opened from the Window menu only). */ + function placeOf(id) { + if (floats.has(id)) return 'float'; + if (dockIds.includes(id)) return 'dock'; + if (stripIds.includes(id)) return 'strip'; + return null; + } + + /** The panel menu's workspace items: float, dock or collapse the panel. */ + function layoutMenu(id) { + const at = placeOf(id); + const lastTab = at === 'dock' && dockIds.length < 2; + const items = []; + if (at !== 'float') items.push({ label: 'Float Panel', enabled: !lastTab, run: () => floatPanel(id, { focus: true, user: true }) }); + if (at !== 'dock') items.push({ label: 'Dock as Tab', run: () => dockPanel(id, { user: true }) }); + if (at !== 'strip') items.push({ label: 'Collapse to Icon', enabled: !lastTab, run: () => collapsePanel(id, { user: true }) }); + if (at === 'float') items.push({ label: 'Close Panel', run: () => closeFloat(id, { user: true }) }); + return items; + } + function openPanelMenu(id, anchor) { - const spec = panelMenu(id); - if (spec.length) app.showMenuAt(anchor, spec, `${panels.get(id).constructor.title} panel menu`); + if (!panels.has(id)) return; + const own = panelMenu(id); + const spec = [...own, ...(own.length ? ['-'] : []), ...layoutMenu(id)]; + app.showMenuAt(anchor, spec, `${panels.get(id).constructor.title} panel menu`); } function syncMenuButton(btn, id) { - const has = !!id && panelMenu(id).length > 0; + const has = !!id && panels.has(id); btn.hidden = !has; if (has) { const title = panels.get(id).constructor.title; @@ -113,6 +149,11 @@ export function createDock(app) { // One complementary landmark holds the strip, the flyout and the dock. // The hidden heading keeps the outline h1 (app) > h2 (panels) > h3 (panel sections). const el = h('aside.panels-area', { 'aria-label': 'Panels' }, h('h2.sr-only', 'Panels'), strip, flyout, dock); + // Floating panels sit over the canvas (the workspace places this layer). + const floatLayer = h('div.float-panels'); + const floats = new Map(); // panel id -> { el, x, y, w, h } (h null: as tall as its content) + const lastFloat = new Map(); // panel id -> where it floated before it was closed + const changed = () => app.emit?.('panel-layout'); let scheduled = false; let lastLive = 0; @@ -143,10 +184,11 @@ export function createDock(app) { return p; } - function addToDock(id) { + function addToDock(id, index = dockIds.length) { const p = panels.get(id); const PanelClass = p.constructor; - dockIds.push(id); + const at = Math.max(0, Math.min(dockIds.length, index)); + dockIds.splice(at, 0, id); const tab = h( 'button.dock-tab', { @@ -157,6 +199,9 @@ export function createDock(app) { 'aria-selected': 'false', tabindex: '-1', onclick: () => showTab(id), + onpointerdown: (e) => { + if (e.button === 0) beginPanelDrag(e, id); + }, onkeydown: (e) => { if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return; e.preventDefault(); @@ -168,7 +213,7 @@ export function createDock(app) { }, PanelClass.title, ); - tabs.append(tab); + tabs.insertBefore(tab, tabs.children[at] || null); p.el.id = `tabpanel-${id}`; p.el.setAttribute('role', 'tabpanel'); p.el.setAttribute('aria-labelledby', `tab-${id}`); @@ -197,6 +242,9 @@ export function createDock(app) { 'data-panel': id, tabindex: '-1', onclick: () => toggleFlyout(id), + onpointerdown: (e) => { + if (e.button === 0) beginPanelDrag(e, id); + }, }, icon(PanelClass.icon, 18), ); @@ -350,9 +398,11 @@ export function createDock(app) { const r = btn.getBoundingClientRect(); const fw = menuEl.offsetWidth; const fh = menuEl.offsetHeight; - // Beside the vertical strip; above it when the strip is a row (phones). + // Beside the vertical strip, on the canvas side; above it when the strip is a row (phones). const row = stripIsRow(); - menuEl.style.left = `${Math.max(4, row ? Math.min(window.innerWidth - fw - 4, r.left) : r.left - fw - 4)}px`; + const besideLeft = r.left - fw - 4; + const left = row ? Math.min(window.innerWidth - fw - 4, r.left) : app.root?.classList.contains('panels-left') ? Math.min(window.innerWidth - fw - 4, r.right + 4) : besideLeft; + menuEl.style.left = `${Math.max(4, left)}px`; menuEl.style.top = `${Math.max(4, row ? r.top - fh - 4 : Math.min(window.innerHeight - fh - 4, r.top))}px`; document.addEventListener('pointerdown', outsideStackMenu, true); (menuEl.querySelector('[aria-checked="true"]') || menuEl.querySelector('.flyout-item'))?.focus(); @@ -369,22 +419,27 @@ export function createDock(app) { queueFit(); } - /** The panel arrangement: { dock: [ids], strip: [ids], active } (panels in neither open from the Window menu). */ + /** + * The panel arrangement: { dock: [ids], strip: [ids], active, floating: + * [{ id, x, y, w, h }] } (panels in none of them open from the Window menu). + */ function getLayout() { - return { dock: [...dockIds], strip: [...stripIds], active: activeTab }; + return { dock: [...dockIds], strip: [...stripIds], active: activeTab, floating: [...floats].map(([id, f]) => ({ id, x: Math.round(f.x), y: Math.round(f.y), w: Math.round(f.w), h: f.h == null ? null : Math.round(f.h) })) }; } /** * Rearrange the panels (workspaces): `dock` lists the tabbed panels in - * order, `strip` the collapsed ones; unknown ids are ignored and at least - * one dock tab is kept. + * order, `strip` the collapsed ones, `floating` the panels in their own + * windows; unknown ids are ignored and at least one dock tab is kept. */ - function setLayout({ dock: dockOrder = [], strip: stripOrder = [], active = null } = {}) { + function setLayout({ dock: dockOrder = [], strip: stripOrder = [], active = null, floating = [] } = {}) { closeFlyout(false); + for (const id of [...floats.keys()]) removeFloat(id); const known = (ids) => [...new Set(ids)].filter((id) => panels.has(id)); let nextDock = known(dockOrder); if (!nextDock.length) nextDock = dockIds.length ? [dockIds[0]] : [...panels.keys()].slice(0, 1); const nextStrip = known(stripOrder).filter((id) => !nextDock.includes(id)); + const nextFloat = (Array.isArray(floating) ? floating : []).filter((f) => f && panels.has(f.id) && !nextDock.includes(f.id) && !nextStrip.includes(f.id)); for (const id of dockIds) { const p = panels.get(id); if (p.visible) p.hidden(); @@ -400,8 +455,285 @@ export function createDock(app) { renderStrip(); queueFit(); showTab(nextDock.includes(active) ? active : nextDock.includes(activeTab) ? activeTab : nextDock[0]); + const seen = new Set(); + for (const f of nextFloat) { + if (seen.has(f.id)) continue; + seen.add(f.id); + floatPanel(f.id, f); + } + } + + // ---- Floating panels ---- + + /** Take panel `id` out of the dock or the strip (not the last dock tab). */ + function detach(id) { + if (flyoutId === id) closeFlyout(false); + const i = dockIds.indexOf(id); + if (i >= 0) { + const p = panels.get(id); + dockIds.splice(i, 1); + tabs.querySelector(`#tab-${id}`)?.remove(); + if (p.visible) p.hidden(); + p.el.remove(); + p.el.hidden = false; + for (const a of ['id', 'role', 'aria-labelledby']) p.el.removeAttribute(a); + if (activeTab === id && dockIds.length) showTab(dockIds[Math.min(i, dockIds.length - 1)]); + } + const j = stripIds.indexOf(id); + if (j >= 0) { + stripIds.splice(j, 1); + renderStrip(); + queueFit(); + } + } + + const layerSize = () => { + const r = floatLayer.getBoundingClientRect(); + return { left: r.left, top: r.top, width: r.width || window.innerWidth, height: r.height || window.innerHeight }; + }; + + /** Keep a floating panel inside the workspace (its size too, as far as the workspace allows). */ + function placeFloat(f) { + const { width, height } = layerSize(); + f.w = Math.max(FLOAT_MIN_W, Math.min(Number(f.w) || FLOAT_DEFAULT_W, width)); + if (f.h != null) f.h = Math.max(FLOAT_MIN_H, Math.min(Number(f.h) || FLOAT_MIN_H, height)); + f.x = Math.max(0, Math.min(width - f.w, Number(f.x) || 0)); + f.y = Math.max(0, Math.min(height - (f.h ?? 32), Number(f.y) || 0)); + Object.assign(f.el.style, { left: `${f.x}px`, top: `${f.y}px`, width: `${f.w}px`, height: f.h == null ? '' : `${f.h}px` }); + } + + let zTop = 1; + const raise = (f) => (f.el.style.zIndex = String(++zTop)); + + /** + * Show panel `id` in its own window at { x, y } (workspace pixels), `w` + * wide and `h` tall (null: as tall as its content). The last dock tab + * stays docked. + */ + function floatPanel(id, { x, y, w, h: ht = null, focus = false, user = false } = {}) { + const p = panels.get(id); + if (!p) return null; + if (floats.has(id)) { + const f = floats.get(id); + raise(f); + if (focus) focusFloat(f); + return f; + } + if (dockIds.includes(id) && dockIds.length < 2) return null; + const prev = lastFloat.get(id); + const n = floats.size; + if (x == null || y == null) { + const { width } = layerSize(); + ({ x, y } = prev || { x: Math.max(8, width - (Number(w) || FLOAT_DEFAULT_W) - 24 - n * 24), y: 16 + n * 24 }); + } + detach(id); + const P = p.constructor; + const menuBtn = h('button.icon-btn.panel-menu-btn', { type: 'button', 'aria-haspopup': 'menu', 'aria-label': `${P.title} panel menu`, 'data-tip': `${P.title} panel menu`, onclick: (e) => openPanelMenu(id, e.currentTarget) }, icon('menu', 14)); + const collapse = h('button.icon-btn', { type: 'button', 'aria-label': `Collapse ${P.title} to icon`, 'data-tip': 'Collapse to icon', onclick: () => collapsePanel(id, { user: true }) }, icon('chevrons-right', 14)); + const close = h('button.icon-btn', { type: 'button', 'aria-label': `Close ${P.title}`, 'data-tip': 'Close', onclick: () => closeFloat(id, { user: true }) }, icon('x', 14)); + const head = h('div.float-panel-head', { 'data-tip': 'Drag to move, or onto the panel tabs to dock' }, h('h2.flyout-title', P.title), h('div.flyout-actions', menuBtn, collapse, close)); + // The resize corner sits in its own bottom edge, clear of the panel's footer buttons. + const resize = h('div.float-panel-resize', { 'aria-hidden': 'true' }); + const body = h('div.float-panel-body', p.el); + const win = h('div.float-panel', { role: 'dialog', 'aria-modal': 'false', 'aria-label': P.title, 'data-panel': id }, head, body, h('div.float-panel-foot', resize)); + const f = { el: win, x, y, w: w ?? prev?.w ?? FLOAT_DEFAULT_W, h: ht ?? prev?.h ?? null }; + floats.set(id, f); + p.el.hidden = false; + floatLayer.append(win); + placeFloat(f); + raise(f); + win.addEventListener('pointerdown', () => raise(f), true); + head.addEventListener('pointerdown', (e) => { + if (e.button !== 0 || e.target.closest('button')) return; + e.preventDefault(); + beginPanelDrag(e, id); + }); + resize.addEventListener('pointerdown', (e) => { + if (e.button !== 0) return; + e.preventDefault(); + e.stopPropagation(); + const start = { w: f.w, h: f.h ?? win.offsetHeight, x: e.clientX, y: e.clientY }; + trackDrag(e, { + threshold: 0, + move: (ev) => { + f.w = start.w + ev.clientX - start.x; + f.h = start.h + ev.clientY - start.y; + placeFloat(f); + }, + end: () => changed(), + }); + }); + win.addEventListener('keydown', (e) => { + if (e.key !== 'Escape' || e.defaultPrevented) return; + // Escape leaves the panel for the canvas; the panel stays open. + e.stopPropagation(); + app.canvasHost?.focus(); + }); + p.shown(); + if (focus) focusFloat(f); + if (user) changed(); + return f; } + function focusFloat(f) { + (f.el.querySelector('.float-panel-body button, .float-panel-body input, .float-panel-body select, .float-panel-body [tabindex="0"]') || f.el.querySelector('button'))?.focus?.(); + } + + /** Remove a floating panel's window (the panel goes nowhere: callers place it). */ + function removeFloat(id) { + const f = floats.get(id); + if (!f) return; + floats.delete(id); + lastFloat.set(id, { x: f.x, y: f.y, w: f.w, h: f.h }); + const p = panels.get(id); + if (p.visible) p.hidden(); + if (p.el.parentNode === f.el.querySelector('.float-panel-body')) p.el.remove(); + f.el.remove(); + } + + /** Close a floating panel (the Window menu opens it again where it was). */ + function closeFloat(id, { user = false } = {}) { + const f = floats.get(id); + if (!f) return; + const hadFocus = f.el.contains(document.activeElement); + removeFloat(id); + if (hadFocus) app.canvasHost?.focus(); + if (user) changed(); + } + + /** Dock panel `id` as a tab (at `index`, else last) and show it. */ + function dockPanel(id, { index = dockIds.length, user = false } = {}) { + if (!panels.has(id)) return; + if (dockIds.includes(id)) { + moveTab(id, index); + } else { + removeFloat(id); + detach(id); + addToDock(id, index); + } + app.setDockOpen?.(true); + showTab(id); + if (user) changed(); + } + + /** Collapse panel `id` to an icon in the strip (not the last dock tab). */ + function collapsePanel(id, { user = false } = {}) { + if (!panels.has(id) || stripIds.includes(id)) return; + if (dockIds.includes(id) && dockIds.length < 2) return; + const hadFocus = floats.get(id)?.el.contains(document.activeElement); + removeFloat(id); + detach(id); + stripIds.push(id); + renderStrip(); + queueFit(); + if (hadFocus) stripButtonFor(id)?.focus(); + if (user) changed(); + } + + /** Move dock tab `id` to `index` among the tabs. */ + function moveTab(id, index) { + const from = dockIds.indexOf(id); + if (from < 0) return; + const at = Math.max(0, Math.min(dockIds.length - 1, index)); + if (at === from) return; + dockIds.splice(from, 1); + dockIds.splice(at, 0, id); + const tab = tabs.querySelector(`#tab-${id}`); + tabs.insertBefore(tab, tabs.children[at + (at > from ? 1 : 0)] || null); + } + + /** The dock tab index for a drop at client x (among the tabs other than `id`). */ + function tabIndexAt(x, id) { + let i = 0; + for (const t of tabs.children) { + if (t.id === `tab-${id}`) continue; + const r = t.getBoundingClientRect(); + if (x > r.left + r.width / 2) i++; + } + return i; + } + + const dockHead = dock.querySelector('.dock-head'); + const insertMark = h('div.dock-insert-mark', { 'aria-hidden': 'true' }); + + /** What a panel dragged to (x, y) would drop on: the dock tabs, the strip, or nothing (it floats). */ + function dropZone(x, y, id) { + if (app.dockOpen !== false && pointIn(dockHead, x, y, 10)) return { kind: 'tabs', index: tabIndexAt(x, id) }; + if (pointIn(strip, x, y, 6)) return { kind: 'strip' }; + return { kind: 'float' }; + } + + function showDropZone(zone) { + dockHead.classList.toggle('drop-target', zone?.kind === 'tabs'); + strip.classList.toggle('drop-target', zone?.kind === 'strip'); + if (zone?.kind !== 'tabs') return insertMark.remove(); + const others = [...tabs.children].filter((t) => !t.classList.contains('dragging')); + const ref = others[zone.index]; + const hr = dockHead.getBoundingClientRect(); + const r = ref ? ref.getBoundingClientRect() : others.at(-1)?.getBoundingClientRect(); + const left = ref ? r.left : r ? r.right : hr.left + 8; + insertMark.style.left = `${left - hr.left - 1}px`; + if (!insertMark.isConnected) dockHead.append(insertMark); + } + + /** + * Drag panel `id` from its dock tab, strip icon or floating window header. + * Along the dock tabs it reorders; anywhere else it floats under the + * pointer, and dropping it on the tabs or the strip docks or collapses it. + */ + function beginPanelDrag(e, id) { + let grab = null; + let zone = null; + const follow = (ev) => { + const f = floats.get(id); + const { left, top } = layerSize(); + f.x = ev.clientX - left - grab.x; + f.y = ev.clientY - top - grab.y; + placeFloat(f); + }; + trackDrag(e, { + threshold: placeOf(id) === 'float' ? 2 : undefined, + start: (ev, origin) => { + if (placeOf(id) === 'float') { + const r = floats.get(id).el.getBoundingClientRect(); + grab = { x: origin.x - r.left, y: origin.y - r.top }; + } + closeStackMenu(false); + app.root?.classList.add('panel-dragging'); + }, + move: (ev) => { + zone = dropZone(ev.clientX, ev.clientY, id); + const at = placeOf(id); + if (at === 'dock' && zone.kind === 'tabs') { + moveTab(id, zone.index); + return; + } + if (at === 'strip' && zone.kind === 'strip') return; + if (at !== 'float') { + // Torn out of the dock or the strip: it floats under the pointer. + if (!floatPanel(id, { x: 0, y: 0 })) return; + grab = { x: Math.min(60, (floats.get(id).w || FLOAT_DEFAULT_W) / 2), y: 14 }; + } + floats.get(id).el.classList.toggle('dropping', zone.kind !== 'float'); + follow(ev); + showDropZone(zone); + }, + end: (ev, { cancelled }) => { + app.root?.classList.remove('panel-dragging'); + showDropZone(null); + floats.get(id)?.el.classList.remove('dropping'); + if (!cancelled && placeOf(id) === 'float' && zone?.kind === 'tabs') dockPanel(id, { index: zone.index }); + else if (!cancelled && placeOf(id) === 'float' && zone?.kind === 'strip') collapsePanel(id); + changed(); + }, + }); + } + + /** Keep floating panels inside the workspace when the window shrinks. */ + window.addEventListener('resize', () => { + for (const f of floats.values()) placeFloat(f); + }); + function showTab(id, { remember = true } = {}) { if (!dockIds.includes(id)) return; activeTab = id; @@ -430,6 +762,12 @@ export function createDock(app) { showTab(id); return; } + // A floating panel comes to the front; one closed from its window opens there again. + if (floats.has(id) || (lastFloat.has(id) && !stripIds.includes(id))) { + closeFlyout(false); + floatPanel(id, { focus }); + return; + } closeFlyout(false); const p = panels.get(id); if (!p) return; @@ -474,6 +812,7 @@ export function createDock(app) { return { el, + floatLayer, register, start, showTab, @@ -483,7 +822,12 @@ export function createDock(app) { fitStrip, getLayout, setLayout, - isOpen: (id) => flyoutId === id || (activeTab === id && dockIds.includes(id)), + floatPanel: (id, opts) => floatPanel(id, opts), + dockPanel, + collapsePanel, + closeFloat, + placeOf, + isOpen: (id) => flyoutId === id || floats.has(id) || (activeTab === id && dockIds.includes(id)), panels, update: scheduleUpdate, get flyoutId() { diff --git a/src/vector-studio/src/ui/drag.js b/src/vector-studio/src/ui/drag.js new file mode 100644 index 0000000000..fb15aa8067 --- /dev/null +++ b/src/vector-studio/src/ui/drag.js @@ -0,0 +1,70 @@ +/** + * Pointer drags for the workspace chrome (panel tabs, panel icons, floating + * panels, the Tools panel grip). One code path for mouse, touch and stylus: + * the drag starts once the pointer has moved past a small threshold, so a + * tap or click on the same control still works, and the click that follows + * a real drag is swallowed. Listeners sit on the window, so a drag survives + * its handle being moved to another part of the page mid-drag. + */ + +/** Movement (px) before a press becomes a drag: a finger wobbles more than a mouse. */ +export function dragThreshold(e) { + return e.pointerType === 'touch' ? 10 : e.pointerType === 'pen' ? 6 : 4; +} + +/** + * Track a drag from a pointerdown event `e`. + * handlers: { threshold, start(ev, origin), move(ev), end(ev, { cancelled }) } + * `start` runs once the pointer passes the threshold (return false to give + * up); `move` and `end` run only after a start. Returns a function that + * cancels the drag. + */ +export function trackDrag(e, { threshold = dragThreshold(e), start, move, end } = {}) { + const pointerId = e.pointerId ?? 1; + const origin = { x: e.clientX, y: e.clientY }; + let started = false; + let done = false; + const onMove = (ev) => { + if ((ev.pointerId ?? 1) !== pointerId || done) return; + if (!started) { + if (Math.hypot(ev.clientX - origin.x, ev.clientY - origin.y) < threshold) return; + if (start && start(ev, origin) === false) return finish(ev, true, false); + started = true; + } + ev.preventDefault?.(); + move?.(ev); + }; + const onUp = (ev) => { + if ((ev.pointerId ?? 1) !== pointerId || done) return; + finish(ev, ev.type !== 'pointerup', started); + }; + function finish(ev, cancelled, notify) { + done = true; + window.removeEventListener('pointermove', onMove, true); + window.removeEventListener('pointerup', onUp, true); + window.removeEventListener('pointercancel', onUp, true); + if (!notify) return; + end?.(ev, { cancelled }); + // The click that follows the release belongs to the drag, not to the control. + const swallow = (c) => { + c.preventDefault(); + c.stopPropagation(); + }; + window.addEventListener('click', swallow, { capture: true, once: true }); + setTimeout(() => window.removeEventListener('click', swallow, true), 0); + } + window.addEventListener('pointermove', onMove, true); + window.addEventListener('pointerup', onUp, true); + window.addEventListener('pointercancel', onUp, true); + return () => { + if (!done) finish(null, true, false); + }; +} + +/** Whether client point (x, y) is inside element `el` (grown by `pad` px); false for hidden elements. */ +export function pointIn(el, x, y, pad = 0) { + if (!el?.isConnected) return false; + const r = el.getBoundingClientRect(); + if (!r.width || !r.height) return false; + return x >= r.left - pad && x <= r.right + pad && y >= r.top - pad && y <= r.bottom + pad; +} diff --git a/src/vector-studio/src/ui/menus.js b/src/vector-studio/src/ui/menus.js index 8a1dd30955..b339d8cf6e 100644 --- a/src/vector-studio/src/ui/menus.js +++ b/src/vector-studio/src/ui/menus.js @@ -502,6 +502,8 @@ export const MENUS = [ '-', { label: 'Toolbars', source: 'toolbars' }, 'window.toolbar', + { label: 'Tools Position', submenu: ['window.tools.left', 'window.tools.right', 'window.tools.float'] }, + { label: 'Panels Position', submenu: ['window.panels.left', 'window.panels.right'] }, 'window.contextualTaskbar', 'window.controlBar', '-', diff --git a/src/vector-studio/src/ui/toolbar.js b/src/vector-studio/src/ui/toolbar.js index d50f712d8c..0f57a46743 100644 --- a/src/vector-studio/src/ui/toolbar.js +++ b/src/vector-studio/src/ui/toolbar.js @@ -175,7 +175,9 @@ export function createToolbar(app) { flyout.style.left = `${Math.max(4, Math.min(window.innerWidth - fw - 4, r.left))}px`; flyout.style.top = `${Math.max(4, r.top - fh - 4)}px`; } else { - flyout.style.left = `${Math.min(window.innerWidth - fw - 4, r.right + 4)}px`; + // Toward the canvas: to the left when the Tools panel is on the right or there is no room. + const leftward = app.root?.classList.contains('tools-right') || r.right + 4 + fw > window.innerWidth - 4; + flyout.style.left = `${Math.max(4, leftward ? r.left - fw - 4 : r.right + 4)}px`; flyout.style.top = `${Math.min(window.innerHeight - fh - 4, r.top)}px`; } document.addEventListener('pointerdown', outside, true); @@ -332,7 +334,9 @@ export function createToolbar(app) { }).observe(scroller); window.addEventListener('resize', applyColumns); requestAnimationFrame(applyColumns); - el.append(h('div.toolbar-head', colsBtn), scroller, h('div.toolbar-bottom', fs, modes, h('div.toolbar-misc', moreBtn, screenBtn))); + // The grip moves the Tools panel: drag it to float the panel, or to either edge to dock it there (features/workspace). + const grip = h('div.toolbar-grip', { 'aria-hidden': 'true', 'data-tip': 'Drag to move the Tools panel' }, icon('grip', 12)); + el.append(h('div.toolbar-head', grip, colsBtn), scroller, h('div.toolbar-bottom', fs, modes, h('div.toolbar-misc', moreBtn, screenBtn))); const refreshTool = () => { for (const btn of groupButtons) { @@ -382,5 +386,5 @@ export function createToolbar(app) { } }; - return { el, refreshTool, refreshPaint, refreshTips, closeFlyout, rebuild, list, tearOff, refit: applyColumns }; + return { el, grip, refreshTool, refreshPaint, refreshTips, closeFlyout, rebuild, list, tearOff, refit: applyColumns }; } diff --git a/src/vector-studio/src/ui/widgets.js b/src/vector-studio/src/ui/widgets.js index 6eae01d87f..5f46a5f2f1 100644 --- a/src/vector-studio/src/ui/widgets.js +++ b/src/vector-studio/src/ui/widgets.js @@ -65,6 +65,8 @@ export function installTooltips(root = document) { document.body.append(tipEl); let owner = null; const show = (target) => { + // A delayed show can outlive the page (a test environment torn down mid-delay). + if (typeof document === 'undefined' || !target.isConnected) return; const text = target.getAttribute('data-tip'); if (!text || document.documentElement.dataset.tooltips === 'off') return; tipEl.textContent = text; diff --git a/src/vector-studio/tests/panel-menus.test.js b/src/vector-studio/tests/panel-menus.test.js index 073f49919f..710409890f 100644 --- a/src/vector-studio/tests/panel-menus.test.js +++ b/src/vector-studio/tests/panel-menus.test.js @@ -19,11 +19,14 @@ class PlainPanel extends Panel { } describe('panel options menus', () => { - it('shows a menu button in the flyout header only for panels with a menu', () => { + it('shows a menu button in the flyout header for every panel (the workspace items)', () => { const app = bootApp({ install: (a) => (a.registerPanel(MenuPanel), a.registerPanel(PlainPanel)) }); const btn = () => document.querySelector('.panel-flyout .panel-menu-btn'); app.dock.openPanel('plainTest'); - expect(btn().hidden).toBe(true); + expect(btn().hidden).toBe(false); + btn().click(); + expect([...document.querySelectorAll('[role="menu"] [role^="menuitem"]')].map((i) => i.textContent.trim())).toEqual(['Float Panel', 'Dock as Tab']); + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); app.dock.openPanel('menuTest'); expect(btn().hidden).toBe(false); expect(btn().getAttribute('aria-label')).toBe('Menu Test panel menu'); @@ -34,7 +37,8 @@ describe('panel options menus', () => { app.dock.openPanel('menuTest'); document.querySelector('.panel-flyout .panel-menu-btn').click(); const items = [...document.querySelectorAll('[role="menu"] [role^="menuitem"]')]; - expect(items.map((i) => i.textContent.trim())).toEqual(['Do Thing', 'Disabled']); + // The panel's own items, then the workspace items. + expect(items.map((i) => i.textContent.trim())).toEqual(['Do Thing', 'Disabled', 'Float Panel', 'Dock as Tab']); items[0].click(); expect(app.dock.panels.get('menuTest').ran).toBe(1); }); @@ -42,7 +46,8 @@ describe('panel options menus', () => { it('tracks the active dock tab', () => { const app = bootApp(); const btn = document.querySelector('.dock-head .panel-menu-btn'); - // Built-in dock panels without a menu keep the button hidden. - expect(btn.hidden).toBe(!app.dock.panels.get(app.dock.getLayout().active).menu().length); + // Every dock tab has a menu: at least Float Panel and Collapse to Icon. + expect(btn.hidden).toBe(false); + expect(btn.getAttribute('aria-label')).toBe(`${app.dock.panels.get(app.dock.getLayout().active).constructor.title} panel menu`); }); }); diff --git a/src/vector-studio/tests/workspace-flexible.test.js b/src/vector-studio/tests/workspace-flexible.test.js new file mode 100644 index 0000000000..8edb74b980 --- /dev/null +++ b/src/vector-studio/tests/workspace-flexible.test.js @@ -0,0 +1,255 @@ +// Floating, docking and collapsing panels; moving the Tools panel and the +// panel dock; the arrangement saved in workspaces and kept across sessions. +import { describe, it, expect, beforeAll } from 'vitest'; +import { installCanvasStub } from './helpers.js'; +import { App } from '../src/app.js'; +import { Prefs } from '../src/prefs.js'; +import { captureWorkspace, applyWorkspace } from '../src/features/workspace/window.js'; + +beforeAll(() => installCanvasStub()); + +async function boot(store = new Map()) { + const { installFeatures } = await import('../src/features.js'); + document.body.innerHTML = '
'; + const storage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)) }; + const app = new App(document.getElementById('app'), { prefs: new Prefs(storage), env: 'web', onSignOut: () => {} }); + installFeatures(app); + app.start(); + return app; +} + +/** Give an element a layout box (jsdom has none). */ +function box(el, left, top, width, height) { + el.getBoundingClientRect = () => ({ left, top, width, height, right: left + width, bottom: top + height, x: left, y: top }); +} + +function pointer(target, type, x, y, pointerType = 'mouse') { + const e = new MouseEvent(type, { bubbles: true, cancelable: true, clientX: x, clientY: y, button: 0 }); + Object.defineProperty(e, 'pointerId', { value: 1 }); + Object.defineProperty(e, 'pointerType', { value: pointerType }); + target.dispatchEvent(e); + return e; +} + +/** A drag from `target` through `points`, released at the last one. */ +function drag(target, [x0, y0], ...points) { + pointer(target, 'pointerdown', x0, y0); + for (const [x, y] of points) pointer(target.isConnected ? target : document.body, 'pointermove', x, y); + const [x, y] = points.at(-1); + pointer(document.body, 'pointerup', x, y); +} + +/** Lay out the dock head, tabs and strip as on a 1280 x 800 screen. */ +function layoutChrome(app) { + const head = app.dock.el.querySelector('.dock-head'); + box(head, 976, 40, 304, 34); + [...app.dock.el.querySelectorAll('.dock-tab')].forEach((t, i) => box(t, 984 + i * 80, 40, 76, 34)); + box(app.dock.el.querySelector('.panel-strip'), 936, 40, 40, 700); + box(app.dock.floatLayer, 52, 40, 884, 740); +} + +const menuItems = () => [...document.querySelectorAll('[role="menu"] [role^="menuitem"]')]; +const runMenuItem = (label) => menuItems().find((i) => i.textContent.trim() === label).click(); + +describe('floating panels', () => { + it('floats a dock tab from its panel menu, then docks it again', async () => { + const app = await boot(); + expect(app.dock.getLayout().dock).toEqual(['properties', 'layers']); + app.dock.showTab('layers'); + document.querySelector('.dock-head .panel-menu-btn').click(); + expect(menuItems().map((i) => i.textContent.trim())).toEqual(expect.arrayContaining(['Float Panel', 'Collapse to Icon'])); + runMenuItem('Float Panel'); + const layout = app.dock.getLayout(); + expect(layout.dock).toEqual(['properties']); + expect(layout.floating.map((f) => f.id)).toEqual(['layers']); + expect(layout.active).toBe('properties'); + const win = app.dock.floatLayer.querySelector('.float-panel[data-panel="layers"]'); + expect(win.getAttribute('role')).toBe('dialog'); + expect(win.contains(app.dock.panels.get('layers').el)).toBe(true); + expect(app.dock.panels.get('layers').visible).toBe(true); + expect(app.dock.isOpen('layers')).toBe(true); + // The last dock tab cannot float or collapse (the dock keeps one tab). + document.querySelector('.dock-head .panel-menu-btn').click(); + expect(menuItems().find((i) => i.textContent.trim() === 'Float Panel').getAttribute('aria-disabled')).toBe('true'); + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); + expect(app.dock.floatPanel('properties')).toBeNull(); + // Dock as Tab from the floating window's menu. + win.querySelector('.panel-menu-btn').click(); + runMenuItem('Dock as Tab'); + expect(app.dock.getLayout()).toMatchObject({ dock: ['properties', 'layers'], active: 'layers', floating: [] }); + expect(win.isConnected).toBe(false); + }); + + it('tears a panel off the strip by dragging, moves it, and docks it on the tabs', async () => { + const app = await boot(); + layoutChrome(app); + const btn = app.dock.el.querySelector('.strip-btn[data-panel="color"]'); + box(btn, 940, 100, 32, 30); + // A short wobble is still a click. + pointer(btn, 'pointerdown', 950, 110); + pointer(btn, 'pointermove', 952, 111); + pointer(btn, 'pointerup', 952, 111); + expect(app.dock.placeOf('color')).toBe('strip'); + // Dragging out over the canvas floats it under the pointer. + drag(btn, [950, 110], [900, 120], [600, 300]); + expect(app.dock.placeOf('color')).toBe('float'); + const f = app.dock.getLayout().floating[0]; + expect(f.id).toBe('color'); + expect(f.x).toBe(600 - 52 - 60); + expect(f.y).toBe(300 - 40 - 14); + expect(app.dock.el.querySelector('.strip-btn[data-panel="color"]')).toBeNull(); + // The click that ends the drag does not toggle anything. + expect(app.dock.flyoutId).toBe(null); + // Move it by its header. + const win = app.dock.floatLayer.querySelector('.float-panel'); + const head = win.querySelector('.float-panel-head'); + box(win, 52 + f.x, 40 + f.y, f.w, 200); + drag(head, [52 + f.x + 100, 40 + f.y + 10], [52 + f.x + 150, 40 + f.y + 40]); + expect(app.dock.getLayout().floating[0]).toMatchObject({ x: f.x + 50, y: f.y + 30 }); + // Dropping the header on the tabs (between Properties and Layers) docks it there. + box(win, 52 + f.x + 50, 40 + f.y + 30, f.w, 200); + drag(head, [52 + f.x + 150, 40 + f.y + 40], [1040, 60], [1066, 56]); + expect(app.dock.getLayout()).toMatchObject({ dock: ['properties', 'color', 'layers'], active: 'color', floating: [] }); + expect(app.dock.el.querySelector('.dock-head').classList.contains('drop-target')).toBe(false); + }); + + it('highlights the drop target while dragging and collapses to the strip on drop', async () => { + const app = await boot(); + layoutChrome(app); + app.dock.floatPanel('swatches', { x: 100, y: 100 }); + const win = app.dock.floatLayer.querySelector('.float-panel'); + const head = win.querySelector('.float-panel-head'); + box(win, 152, 140, 280, 200); + pointer(head, 'pointerdown', 200, 150); + pointer(head, 'pointermove', 950, 300); + expect(app.dock.el.querySelector('.panel-strip').classList.contains('drop-target')).toBe(true); + expect(win.classList.contains('dropping')).toBe(true); + pointer(document.body, 'pointerup', 950, 300); + expect(app.dock.placeOf('swatches')).toBe('strip'); + expect(app.dock.el.querySelector('.panel-strip').classList.contains('drop-target')).toBe(false); + expect(app.dock.el.querySelector('.strip-btn[data-panel="swatches"]')).toBeTruthy(); + }); + + it('reorders dock tabs by dragging along them, with a touch drag', async () => { + const app = await boot(); + app.dock.dockPanel('color'); + layoutChrome(app); + expect(app.dock.getLayout().dock).toEqual(['properties', 'layers', 'color']); + const tab = app.dock.el.querySelector('#tab-color'); + pointer(tab, 'pointerdown', 1190, 56, 'touch'); + pointer(tab, 'pointermove', 1185, 56, 'touch'); // under the touch threshold + expect(app.dock.getLayout().dock).toEqual(['properties', 'layers', 'color']); + pointer(tab, 'pointermove', 1000, 56, 'touch'); + pointer(document.body, 'pointerup', 1000, 56, 'touch'); + expect(app.dock.getLayout().dock).toEqual(['color', 'properties', 'layers']); + expect([...app.dock.el.querySelectorAll('.dock-tab')].map((t) => t.textContent)).toEqual(['Color', 'Properties', 'Layers']); + }); + + it('resizes a floating panel from its corner and closes it; the Window menu opens it where it was', async () => { + const app = await boot(); + layoutChrome(app); + app.dock.floatPanel('stroke', { x: 40, y: 50, w: 260 }); + const win = app.dock.floatLayer.querySelector('.float-panel'); + Object.defineProperty(win, 'offsetHeight', { value: 180, configurable: true }); + drag(win.querySelector('.float-panel-resize'), [400, 300], [460, 380]); + expect(app.dock.getLayout().floating[0]).toMatchObject({ x: 40, y: 50, w: 320, h: 260 }); + await new Promise((r) => setTimeout(r, 0)); // past the click that ends a drag + win.querySelector('[aria-label="Close Stroke"]').click(); + expect(app.dock.placeOf('stroke')).toBe(null); + expect(app.dock.isOpen('stroke')).toBe(false); + await app.commands.run('panel.stroke'); + expect(app.dock.getLayout().floating[0]).toMatchObject({ id: 'stroke', x: 40, y: 50, w: 320, h: 260 }); + }); + + it('keeps a floating panel header on screen', async () => { + const app = await boot(); + layoutChrome(app); + app.dock.floatPanel('align', { x: 5000, y: -300, w: 99999 }); + const f = app.dock.getLayout().floating[0]; + expect(f.w).toBe(884); + expect(f.x).toBeLessThanOrEqual(884 - 48); + expect(f.y).toBe(0); + }); +}); + +describe('Tools panel and panel dock positions', () => { + it('docks the Tools panel right, floats it and docks the panels left from the Window menu', async () => { + const app = await boot(); + expect(app.root.classList.contains('tools-right')).toBe(false); + await app.commands.run('window.tools.right'); + expect(app.root.classList.contains('tools-right')).toBe(true); + expect(app.commands.isChecked('window.tools.right')).toBe(true); + await app.commands.run('window.tools.float'); + expect(app.root.classList.contains('tools-float')).toBe(true); + expect(app.root.classList.contains('tools-right')).toBe(false); + await app.commands.run('window.panels.left'); + expect(app.root.classList.contains('panels-left')).toBe(true); + expect(app.commands.isChecked('window.panels.left')).toBe(true); + await app.commands.run('window.panels.right'); + expect(app.root.classList.contains('panels-left')).toBe(false); + }); + + it('drags the Tools panel by its grip to float it, then to the right edge to dock it there', async () => { + const app = await boot(); + box(app.workspace, 0, 40, 1280, 760); + box(app.docArea, 52, 40, 884, 760); + box(app.toolbar.el, 0, 40, 52, 600); + const grip = app.toolbar.el.querySelector('.toolbar-grip'); + expect(grip).toBeTruthy(); + drag(grip, [20, 46], [200, 200], [400, 300]); + expect(app.root.classList.contains('tools-float')).toBe(true); + expect(app.prefs.get('toolsPosition')).toBe('float'); + expect(app.toolbar.el.style.left).toBe('380px'); + // Near the canvas's right edge: a dock mark shows, and releasing docks it. + box(app.toolbar.el, 380, 294, 52, 600); + pointer(grip, 'pointerdown', 400, 300); + pointer(grip, 'pointermove', 920, 300); + expect(app.workspace.querySelector('.tools-dock-zone')).toBeTruthy(); + pointer(document.body, 'pointerup', 920, 300); + expect(app.workspace.querySelector('.tools-dock-zone')).toBeNull(); + expect(app.prefs.get('toolsPosition')).toBe('right'); + expect(app.root.classList.contains('tools-right')).toBe(true); + expect(app.root.classList.contains('tools-float')).toBe(false); + expect(app.toolbar.el.style.left).toBe(''); + }); +}); + +describe('saving the arrangement', () => { + it('saves floating panels and positions in a workspace and applies them back', async () => { + const app = await boot(); + layoutChrome(app); + app.dock.floatPanel('color', { x: 30, y: 60, w: 250 }); + await app.commands.run('window.tools.right'); + await app.commands.run('window.panels.left'); + const ws = captureWorkspace(app, 'Tablet'); + expect(ws).toMatchObject({ toolsPosition: 'right', panelsSide: 'left', floating: [{ id: 'color', x: 30, y: 60, w: 250, h: null }] }); + await app.commands.run('window.workspace.essentials'); + expect(app.dock.getLayout().floating).toEqual([]); + expect(app.root.classList.contains('tools-right')).toBe(false); + expect(app.root.classList.contains('panels-left')).toBe(false); + applyWorkspace(app, ws, 'saved:Tablet'); + expect(app.dock.getLayout().floating).toEqual([{ id: 'color', x: 30, y: 60, w: 250, h: null }]); + expect(app.root.classList.contains('tools-right')).toBe(true); + expect(app.root.classList.contains('panels-left')).toBe(true); + }); + + it('keeps the arrangement for the next session until the workspace is reset', async () => { + const store = new Map(); + let app = await boot(store); + layoutChrome(app); + app.dock.floatPanel('layers', { x: 20, y: 30, user: true }); + app.dock.collapsePanel('align', { user: true }); + await app.commands.run('window.tools.float'); + app = await boot(store); + expect(app.dock.getLayout().dock).toEqual(['properties']); + expect(app.dock.getLayout().floating.map((f) => f.id)).toEqual(['layers']); + expect(app.root.classList.contains('tools-float')).toBe(true); + await app.commands.run('window.resetWorkspace'); + expect(app.dock.getLayout().dock).toEqual(['properties', 'layers']); + expect(app.dock.getLayout().floating).toEqual([]); + expect(app.root.classList.contains('tools-float')).toBe(false); + app = await boot(store); + expect(app.dock.getLayout().dock).toEqual(['properties', 'layers']); + expect(app.dock.getLayout().floating).toEqual([]); + }); +});