From 78cedb36a5886856ae90068f0ddbdfbf78e46c5f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 04:18:56 -0500 Subject: [PATCH 01/17] feat(canvas): the canvas can draw temporary styles in two named layers over the stored ones, play and trial, without an engine command and without rebuilding any node, and an empty value shows what the element inherits at the picked breakpoint --- frontend/src/features/try/types.ts | 70 ++++++++++++++++++++++++++++ frontend/src/ui/canvas.ts | 73 ++++++++++++++++++++++-------- 2 files changed, 125 insertions(+), 18 deletions(-) create mode 100644 frontend/src/features/try/types.ts diff --git a/frontend/src/features/try/types.ts b/frontend/src/features/try/types.ts new file mode 100644 index 00000000..ec46680d --- /dev/null +++ b/frontend/src/features/try/types.ts @@ -0,0 +1,70 @@ +export type LayerName = 'play' | 'trial'; + +export type LayerFrame = Record>; + +export interface TryCanvas { + setLayer(name: LayerName, frame: LayerFrame | null): void; +} + +export type TrialEnd = 'kept' | 'reverted' | 'dropped' | 'refused'; + +export interface TrialOwner { + readonly key: string; + readonly label: string; + readonly anchor: HTMLElement; + inside?(): readonly HTMLElement[]; + ended(how: TrialEnd): void; +} + +export interface Trial { + readonly key: string; + readonly pending: boolean; + readonly over: boolean; + value(): string; + put(value: string, name: string): void; + keep(): Promise; + revert(): void; +} + +export interface TryBar { + readonly element: HTMLElement; + show(owner: TrialOwner, name: string): void; + pending(on: boolean): void; + hide(): void; + focusKeep(): void; +} + +export interface TryBarActions { + keep(): void; + revert(): void; + leave(forward: boolean): void; +} + +export interface TryKit { + enabled(): boolean; + setEnabled(on: boolean): void; + begin(owner: TrialOwner): Trial; + active(): Trial | null; + busy(): boolean; + live(key: string, value: string | null): void; + settled(key: string): void; + drop(): void; + intercept(command: string): boolean; + sync(): void; +} + +export interface TryOptions { + canvas: TryCanvas; + overlay: HTMLElement; + fields: ReadonlyMap; + segments: ReadonlyMap; + scope(): string; + node(): string; + exists?(id: string): boolean; + stored(key: string): string; + inherited(key: string): string; + editing(): boolean; + setStyle(key: string, value: string): Promise; + status(message: string, error?: boolean): void; + changed?(): void; +} diff --git a/frontend/src/ui/canvas.ts b/frontend/src/ui/canvas.ts index adef3683..9a909fae 100644 --- a/frontend/src/ui/canvas.ts +++ b/frontend/src/ui/canvas.ts @@ -1,5 +1,6 @@ import type { Collection, Page, Site } from '../types'; import { t } from '../i18n'; +import type { LayerFrame, LayerName } from '../features/try/types'; type ItemContext = { collection: string; item: Collection['items'][number]; ids: Record; suffix: string }; @@ -78,6 +79,7 @@ export class Canvas { private faceCss = ''; private faceStyle?: HTMLStyleElement; private motionFrame: Record> | null = null; + private layers: Record = { play: null, trial: null }; private posters: Record = {}; private posterLights: Record = {}; private posterNodes = new Map(); @@ -94,6 +96,26 @@ export class Canvas { if (this.last) this.render(this.last.site, this.last.page, this.last.selected, this.last.width, this.last.locale, this.last.scope); } + setLayer(name: LayerName, frame: LayerFrame | null): void { + const next = frame && Object.keys(frame).length ? frame : null; + const before = this.layers[name]; + if (JSON.stringify(next) === JSON.stringify(before)) return; + this.layers[name] = next ? JSON.parse(JSON.stringify(next)) as LayerFrame : null; + if (!this.last || !this.doc) return; + const touched = new Map>(); + for (const id of new Set([...Object.keys(before || {}), ...Object.keys(next || {})])) { + if (JSON.stringify(before?.[id]) === JSON.stringify(next?.[id])) continue; + touched.set(id, new Set([...Object.keys(before?.[id] || {}), ...Object.keys(next?.[id] || {})].map(cssName))); + } + const { site, scope } = this.last; + for (const [key, node] of this.nodes) { + if (key.endsWith(':list')) continue; + const id = node.dataset.fwId!; + const only = touched.get(id); + if (only && site.nodes[id]) this.restyle(node, key, site, id, scope, only); + } + } + setPosters(posters: Record, lights: Record = {}): void { if (JSON.stringify(Object.entries(posters)) === JSON.stringify(Object.entries(this.posters)) && JSON.stringify(Object.entries(lights)) === JSON.stringify(Object.entries(this.posterLights))) return; this.posters = { ...posters }; @@ -392,24 +414,7 @@ export class Canvas { if (previous === 'src') this.imageSources.delete(key); } this.attrs.set(key, nextAttrs); - const effective = { ...data.styles }; - const picked = site.breakpoints.find(breakpoint => breakpoint.id === scope); - const matching = [...site.breakpoints].filter(breakpoint => breakpoint.maxWidth === 100000 || (picked !== undefined && breakpoint.maxWidth >= picked.maxWidth)).sort((a, b) => b.maxWidth - a.maxWidth); - matching.forEach(breakpoint => Object.assign(effective, data.breakpoints?.[breakpoint.id])); - const framed = this.motionFrame?.[id]; - if (framed) for (const [name, content] of Object.entries(framed)) { - for (const own of Object.keys(effective)) if (cssName(own) === cssName(name)) delete effective[own]; - effective[name] = content; - } - const nextStyles = new Set(); - for (const [name, content] of Object.entries(effective)) { - const property = cssName(name); - if (!safeStyle(property, content)) continue; - nextStyles.add(property); - if (node.style.getPropertyValue(property) !== content) node.style.setProperty(property, content); - } - for (const previous of this.styles.get(key) || []) if (!nextStyles.has(previous)) node.style.removeProperty(previous); - this.styles.set(key, nextStyles); + this.restyle(node, key, site, id, scope); if (!voidTags.has(tag)) { if (['textarea', 'option'].includes(tag)) { if (this.doc.activeElement !== node && node.textContent !== displayedText) node.textContent = displayedText; @@ -442,6 +447,38 @@ export class Canvas { return node; } + private restyle(node: HTMLElement, key: string, site: Site, id: string, scope: string, only?: Set): void { + const data = site.nodes[id]; + const effective: Record = { ...data.styles }; + const picked = site.breakpoints.find(breakpoint => breakpoint.id === scope); + const matching = [...site.breakpoints].filter(breakpoint => breakpoint.maxWidth === 100000 || (picked !== undefined && breakpoint.maxWidth >= picked.maxWidth)).sort((a, b) => b.maxWidth - a.maxWidth); + matching.forEach(breakpoint => Object.assign(effective, data.breakpoints?.[breakpoint.id])); + const base = !picked || picked.maxWidth === 100000; + const over = (frame: Record | undefined): void => { + if (frame) for (const [name, content] of Object.entries(frame)) { + for (const own of Object.keys(effective)) if (cssName(own) === cssName(name)) delete effective[own]; + if (content !== null) { effective[name] = content; continue; } + if (base) continue; + const wider: Record = { ...data.styles }; + matching.forEach(breakpoint => { if (breakpoint.id !== scope) Object.assign(wider, data.breakpoints?.[breakpoint.id]); }); + const found = Object.keys(wider).filter(own => cssName(own) === cssName(name)).pop(); + if (found !== undefined) effective[found] = wider[found]; + } + }; + over(this.motionFrame?.[id]); + over(this.layers.play?.[id]); + over(this.layers.trial?.[id]); + const nextStyles = new Set(); + for (const [name, content] of Object.entries(effective)) { + const property = cssName(name); + if (!safeStyle(property, content)) continue; + nextStyles.add(property); + if ((!only || only.has(property)) && node.style.getPropertyValue(property) !== content) node.style.setProperty(property, content); + } + for (const previous of this.styles.get(key) || []) if (!nextStyles.has(previous) && (!only || only.has(previous))) node.style.removeProperty(previous); + this.styles.set(key, nextStyles); + } + private bindEvents(doc: Document): void { (doc.defaultView as (Window & { navigation?: EventTarget }) | null)?.navigation?.addEventListener('navigate', event => { if (event.cancelable) event.preventDefault(); }); doc.addEventListener('click', event => { From e1c364571b126d6c9f77f46ec5e363cbaf597077 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 04:18:58 -0500 Subject: [PATCH 02/17] feat(inspector): a Design field control can hand its pending value to the page while a thumb, the color square or a gradient stop is dragged, and a drag in the color picker is dropped when the brand restriction comes on --- .../inspector/controls/color-picker.ts | 1 + .../src/features/inspector/controls/index.ts | 25 ++++++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/frontend/src/features/inspector/controls/color-picker.ts b/frontend/src/features/inspector/controls/color-picker.ts index 3b5bf697..a487a719 100644 --- a/frontend/src/features/inspector/controls/color-picker.ts +++ b/frontend/src/features/inspector/controls/color-picker.ts @@ -300,6 +300,7 @@ export class Picker { refresh(target: PickerTarget, value: string): void { if (!this.isOpen(target)) return; this.guard(); + if (this.restricted()) for (const area of [this.area, ...this.mounted.flatMap(item => item.areas)]) if (area.dragging()) area.cancel(); this.paintSets(value); this.paintTabs(); if (value === this.seen) return; diff --git a/frontend/src/features/inspector/controls/index.ts b/frontend/src/features/inspector/controls/index.ts index bd7ec8ae..dea27c82 100644 --- a/frontend/src/features/inspector/controls/index.ts +++ b/frontend/src/features/inspector/controls/index.ts @@ -29,6 +29,7 @@ export interface ControlOptions { changed?(): void; setStyles?(styles: Record): Promise; scope(key: string): string; + trial?: { live(key: string, value: string | null): void; settled(key: string): void }; } export interface InstalledKit extends ControlKit { @@ -65,7 +66,7 @@ function englishLabel(head: HTMLElement | null, key: string): string { } interface Gesture { scope: string; held: string; values: Set; dead: boolean; released: boolean } -interface Upgraded { field: StyleField; control: Control; toggle: HTMLButtonElement; shown: boolean; gesture: Gesture | null; stale: Set } +interface Upgraded { field: StyleField; control: Control; toggle: HTMLButtonElement; shown: boolean; gesture: Gesture | null; stale: Set; live: string | null } let installed = false; @@ -110,11 +111,23 @@ export function installControls(options: ControlOptions): InstalledKit { }; const committed = (key: string, stored: string): string => inflight.get(options.scope(key))?.at(-1)?.value ?? stored; const shown = (key: string, stored: string): string => held(key) ?? committed(key, stored); + function live(entry: Upgraded, value: string | null): void { + if (value === null) { + if (entry.live === null) return; + entry.live = null; + } else entry.live = options.scope(entry.field.key); + options.trial?.live(entry.field.key, value); + } function settle(key: string, scope: string): void { const list = inflight.get(scope); if (!list || list.length) return; inflight.delete(scope); const entry = upgraded.get(key); + const open = entry?.gesture; + if (entry && entry.live === scope && !(open && !open.dead && open.scope === scope)) { + entry.live = null; + options.trial?.settled(key); + } if (entry && entry.gesture) { later(entry); return; } if (!entry || options.scope(key) !== scope || document.activeElement === entry.field.input) return; entry.field.restore(); @@ -163,6 +176,7 @@ export function installControls(options: ControlOptions): InstalledKit { const gesture = entry.gesture; if (gesture) gesture.dead = true; if (cancel) { try { cancel.call(entry.control); } catch { } } + live(entry, null); entry.stale = new Set(); if (!gesture) return; if (cancel) { entry.stale = gesture.values; entry.gesture = null; } else gesture.dead = true; @@ -260,21 +274,24 @@ export function installControls(options: ControlOptions): InstalledKit { const value = next.trim(); const scope = options.scope(key); const gesture = entry.gesture; - if (gesture && (gesture.dead || gesture.scope !== scope)) { gesture.dead = true; gesture.values.add(value); return; } + if (gesture && (gesture.dead || gesture.scope !== scope)) { gesture.dead = true; gesture.values.add(value); live(entry, null); return; } if (gesture) { gesture.held = value; gesture.values.add(value); gesture.released = false; } else { entry.gesture = { scope, held: value, values: new Set([value]), dead: false, released: false }; entry.stale = new Set(); } if (input.value !== next) input.value = next; + live(entry, value); }, restore() { entry.gesture = null; const stored = committed(key, values().value); if (input.value !== stored) input.value = stored; + const flying = inflight.get(options.scope(key))?.at(-1); + live(entry, flying && entry.live === options.scope(key) ? flying.value : null); settle(key, options.scope(key)); }, async commit(next: string) { const entered = next.trim(); const gesture = entry.gesture; - if (gesture && (gesture.dead || gesture.scope !== options.scope(key))) { entry.stale = gesture.values; entry.gesture = null; return; } + if (gesture && (gesture.dead || gesture.scope !== options.scope(key))) { entry.stale = gesture.values; entry.gesture = null; live(entry, null); return; } if (!gesture && entry.stale.size) { const stray = entry.stale.has(entered); entry.stale = new Set(); @@ -297,7 +314,7 @@ export function installControls(options: ControlOptions): InstalledKit { }; let control: Control; try { control = factory(field, host); } catch (error) { console.error(error); continue; } - entry = { field, control, toggle, shown: false, gesture: null, stale: new Set() }; + entry = { field, control, toggle, shown: false, gesture: null, stale: new Set(), live: null }; upgraded.set(key, entry); toggle.addEventListener('click', event => { event.preventDefault(); From 003eff3c557f66aa75f51c6d5d7b9bf32d775ca4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 04:19:01 -0500 Subject: [PATCH 03/17] feat(inspector): a try bar that names the choice being tried with Keep and Revert, and segment groups that try a clicked or arrowed choice instead of writing it --- frontend/src/features/try/bar.ts | 226 ++++++++++++++++++++++++++ frontend/src/features/try/segments.ts | 135 +++++++++++++++ frontend/src/styles/try-bar.css | 19 +++ 3 files changed, 380 insertions(+) create mode 100644 frontend/src/features/try/bar.ts create mode 100644 frontend/src/features/try/segments.ts create mode 100644 frontend/src/styles/try-bar.css diff --git a/frontend/src/features/try/bar.ts b/frontend/src/features/try/bar.ts new file mode 100644 index 00000000..0909bd93 --- /dev/null +++ b/frontend/src/features/try/bar.ts @@ -0,0 +1,226 @@ +import { element } from '../../ui/dom'; +import { label, labelAttr } from '../../i18n'; +import { formatKeys } from '../../commands/registry'; +import type { TrialOwner, TryBar, TryBarActions } from './types'; +import '../../styles/try-bar.css'; + +const GAP = 6; +const MARGIN = 8; +const WAIT_MS = 300; +const FOCUSABLE = 'button:not(:disabled), select:not(:disabled), input:not(:disabled), [tabindex]:not([tabindex="-1"])'; + +type Box = { top: number; right: number; bottom: number; left: number }; + +function button(name: string, keys: string, className: string): HTMLButtonElement { + const node = element('button', 'fw-try-btn ' + className); + node.type = 'button'; + const text = element('span', 'fw-try-btn-name'); + label(text, name); + const key = element('span', 'fw-try-key', formatKeys(keys)); + key.dataset.noI18n = ''; + node.append(text, key); + return node; +} + +function spinner(): SVGSVGElement { + const ns = 'http://www.w3.org/2000/svg'; + const svg = document.createElementNS(ns, 'svg'); + svg.setAttribute('viewBox', '0 0 24 24'); + svg.setAttribute('class', 'fw-try-wait'); + svg.setAttribute('aria-hidden', 'true'); + const ring = document.createElementNS(ns, 'circle'); + ring.setAttribute('cx', '12'); + ring.setAttribute('cy', '12'); + ring.setAttribute('r', '8'); + ring.setAttribute('fill', 'none'); + ring.setAttribute('stroke', 'currentColor'); + ring.setAttribute('stroke-width', '2'); + ring.setAttribute('stroke-linecap', 'round'); + ring.setAttribute('stroke-dasharray', '14 40'); + svg.append(ring); + return svg; +} + +function scroller(node: HTMLElement): HTMLElement | null { + for (let at = node.parentElement; at && at !== document.body; at = at.parentElement) { + const overflow = getComputedStyle(at).overflowY; + if (overflow === 'auto' || overflow === 'scroll') return at; + } + return null; +} + +function visible(node: HTMLElement): boolean { + return node.isConnected && node.getClientRects().length > 0; +} + +export function mountBar(overlay: HTMLElement, actions: TryBarActions): TryBar { + const root = element('div', 'fw-try-bar'); + root.hidden = true; + root.tabIndex = -1; + root.dataset.tryBar = ''; + root.dataset.ownKeys = ''; + root.setAttribute('role', 'group'); + labelAttr(root, 'aria-label', 'Trial'); + const text = element('span', 'fw-try-text'); + text.setAttribute('aria-live', 'polite'); + const keep = button('Keep', 'Enter', 'fw-try-keep'); + const revert = button('Revert', 'Escape', 'fw-try-revert'); + keep.querySelector('.fw-try-key')!.append(spinner()); + root.append(text, keep, revert); + overlay.append(root); + + let owner: TrialOwner | null = null; + let clip: HTMLElement | null = null; + let shownName = ''; + let last: Box | null = null; + let width = 0; + let frame = 0; + let waiting = 0; + let busy = false; + + const boxOf = (node: HTMLElement): Box => { + const box = node.getBoundingClientRect(); + return { top: box.top, right: box.right, bottom: box.bottom, left: box.left }; + }; + const same = (a: Box | null, b: Box): boolean => !!a && a.top === b.top && a.left === b.left && a.bottom === b.bottom && a.right === b.right; + + const place = (force: boolean): void => { + if (!owner) return; + const anchor = boxOf(owner.anchor); + const size = root.offsetWidth; + if (!force && same(last, anchor) && size === width) return; + last = anchor; + width = size; + const height = root.offsetHeight; + const keepClear = { ...anchor }; + for (const node of owner.inside?.() ?? []) { + if (!visible(node)) continue; + const box = node.getBoundingClientRect(); + keepClear.top = Math.min(keepClear.top, box.top); + keepClear.bottom = Math.max(keepClear.bottom, box.bottom); + keepClear.left = Math.min(keepClear.left, box.left); + keepClear.right = Math.max(keepClear.right, box.right); + } + const below = window.innerHeight - keepClear.bottom - GAP - MARGIN; + const above = keepClear.top - GAP - MARGIN; + let top = below >= height || below >= above ? keepClear.bottom + GAP : keepClear.top - GAP - height; + top = Math.max(MARGIN, Math.min(top, window.innerHeight - height - MARGIN)); + if (clip) { + const view = clip.getBoundingClientRect(); + if (anchor.bottom <= view.top) top = Math.max(top, view.top + GAP); + else if (anchor.top >= view.bottom) top = Math.min(top, view.bottom - height - GAP); + } + const left = Math.max(MARGIN, Math.min(anchor.left, window.innerWidth - size - MARGIN)); + const x = `${Math.round(left)}px`; + const y = `${Math.round(top)}px`; + if (root.style.left !== x) root.style.left = x; + if (root.style.top !== y) root.style.top = y; + }; + + const follow = (): void => { + if (frame) return; + frame = requestAnimationFrame(() => { frame = 0; place(false); }); + }; + const listen = (on: boolean): void => { + const method = on ? 'addEventListener' : 'removeEventListener'; + window[method]('scroll', follow, { capture: true, passive: true } as AddEventListenerOptions); + window[method]('resize', follow, { passive: true } as AddEventListenerOptions); + }; + + const rescue = (): void => { + if (!root.contains(document.activeElement)) return; + const anchor = owner?.anchor; + const target = !anchor || !visible(anchor) ? null + : anchor.matches(FOCUSABLE) ? anchor + : anchor.querySelector('[data-trying]:not(:disabled)') ?? anchor.querySelector('[aria-pressed="true"]:not(:disabled)') ?? anchor.querySelector(FOCUSABLE); + if (target) { target.focus({ preventScroll: true }); return; } + for (let at = anchor?.parentElement; at && at !== document.body; at = at.parentElement) { + if (!visible(at)) continue; + const next = Array.from(at.querySelectorAll(FOCUSABLE)).find(visible); + if (next) { next.focus({ preventScroll: true }); return; } + } + }; + + const pending = (on: boolean): void => { + if (busy === on) return; + busy = on; + clearTimeout(waiting); + if (on) { + if (keep === document.activeElement || revert === document.activeElement) root.focus({ preventScroll: true }); + root.setAttribute('aria-busy', 'true'); + waiting = window.setTimeout(() => root.classList.add('is-waiting'), WAIT_MS); + } else { + root.removeAttribute('aria-busy'); + root.classList.remove('is-waiting'); + } + keep.disabled = on; + revert.disabled = on; + }; + + const hide = (): void => { + if (root.hidden) return; + rescue(); + pending(false); + root.hidden = true; + owner = null; + clip = null; + last = null; + shownName = ''; + listen(false); + cancelAnimationFrame(frame); + frame = 0; + }; + + keep.addEventListener('click', () => { if (!busy) actions.keep(); }); + revert.addEventListener('click', () => { if (!busy) actions.revert(); }); + root.addEventListener('keydown', event => { + if (event.isComposing) return; + const mods = event.ctrlKey || event.metaKey || event.altKey; + if (event.key === 'Escape' && !mods) { + event.preventDefault(); + event.stopPropagation(); + if (!busy) actions.revert(); + } else if (event.key === 'Enter' && !mods) { + if (event.target !== keep) return; + event.preventDefault(); + event.stopPropagation(); + if (!busy) actions.keep(); + } else if (event.key === 'Tab' && !mods) { + const forward = !event.shiftKey; + const at = event.target; + if (at === root || (forward && at === revert) || (!forward && at === keep)) { + event.preventDefault(); + event.stopPropagation(); + actions.leave(forward); + } + } + }); + + return { + element: root, + show(next, name) { + const again = owner === next && !root.hidden; + if (shownName !== name || !again) { + label(text, 'Trying: {0}', [name]); + shownName = name; + } + if (again) { place(false); return; } + owner = next; + last = null; + clip = scroller(next.anchor); + if (root.hidden) { + root.style.left = '0px'; + root.style.top = '0px'; + root.hidden = false; + listen(true); + } + place(true); + }, + pending, + hide, + focusKeep() { + if (root.hidden) return; + (keep.disabled ? root : keep).focus({ preventScroll: true }); + } + }; +} diff --git a/frontend/src/features/try/segments.ts b/frontend/src/features/try/segments.ts new file mode 100644 index 00000000..80f289eb --- /dev/null +++ b/frontend/src/features/try/segments.ts @@ -0,0 +1,135 @@ +import { t } from '../../i18n'; +import type { Trial, TrialOwner, TryKit, TryOptions } from './types'; +import '../../styles/try-bar.css'; + +const STEPS: Record = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }; +const FOCUSABLE = 'button:not(:disabled), select:not(:disabled), input:not(:disabled), [tabindex]:not([tabindex="-1"])'; + +const shown = (node: HTMLElement): boolean => node.isConnected && node.getClientRects().length > 0; + +function shelter(group: HTMLElement): void { + let at = group.parentElement; + while (at && at !== document.body) { + if (shown(at)) { + const next = Array.from(at.querySelectorAll(FOCUSABLE)).find(node => !group.contains(node) && shown(node)); + if (next) { next.focus({ preventScroll: true }); return; } + } + at = at.parentElement; + } +} + +function installGroup(kit: TryKit, options: TryOptions, key: string, buttons: HTMLButtonElement[]): void { + const group = buttons[0]?.parentElement; + if (!group) return; + group.dataset.ownKeys = ''; + if (!group.hasAttribute('tabindex')) group.tabIndex = -1; + let trial: Trial | null = null; + let tried: HTMLButtonElement | null = null; + + const live = (): Trial | null => (trial && !trial.over ? trial : null); + const mark = (button: HTMLButtonElement | null): void => { + if (tried && tried !== button) delete tried.dataset.trying; + tried = button; + if (button && button.dataset.trying === undefined) button.dataset.trying = ''; + const state = button ? '' : 'unset'; + if (group.dataset.trying !== state) group.dataset.trying = state; + }; + const unmark = (): void => { + if (tried) delete tried.dataset.trying; + tried = null; + delete group.dataset.trying; + }; + + const start = (): Trial => { + const owner: TrialOwner = { + key, + get label() { return group.getAttribute('aria-label') || key; }, + anchor: group, + ended() { + if (trial !== mine) return; + trial = null; + unmark(); + if (group.contains(document.activeElement) && !shown(document.activeElement as HTMLElement)) shelter(group); + } + }; + const mine = kit.begin(owner); + trial = mine; + return mine; + }; + + const put = (button: HTMLButtonElement | null): void => { + const current = live() ?? start(); + mark(button); + current.put(button ? button.dataset.value || '' : '', button ? (button.textContent || '').trim() : t('None')); + }; + + const usable = (): HTMLButtonElement[] => buttons.filter(button => !button.disabled && shown(button)); + + group.addEventListener('focus', () => { + const list = usable(); + const next = (tried && list.includes(tried) ? tried : null) ?? list.find(button => button.getAttribute('aria-pressed') === 'true') ?? list[0]; + next?.focus({ preventScroll: true }); + }); + + group.addEventListener('click', event => { + if (!kit.enabled()) return; + const button = (event.target as Element | null)?.closest?.('button'); + if (!button || !buttons.includes(button as HTMLButtonElement)) return; + event.stopPropagation(); + event.preventDefault(); + if (live()?.pending || button.disabled) return; + const value = button.dataset.value || ''; + put(value === options.stored(key) ? null : button as HTMLButtonElement); + }, true); + + group.addEventListener('keydown', event => { + if (!kit.enabled() || event.isComposing || event.ctrlKey || event.metaKey || event.altKey) return; + const current = live(); + const step = STEPS[event.key]; + const ends = event.key === 'Home' || event.key === 'End'; + if (event.key === 'Delete' || event.key === 'Backspace') { event.preventDefault(); return; } + if (current?.pending) { + if (step || ends || event.key === 'Enter' || event.key === 'Escape' || event.key === ' ' || event.key === 'Tab') { + event.preventDefault(); + event.stopPropagation(); + } + return; + } + if (step || ends) { + if (event.shiftKey) return; + event.preventDefault(); + const list = usable(); + if (!list.length) return; + const stored = options.stored(key); + const from = current && tried && list.includes(tried) ? list.indexOf(tried) : list.findIndex(button => button.dataset.value === stored); + const next = event.key === 'Home' ? 0 : event.key === 'End' ? list.length - 1 + : from < 0 ? (step > 0 ? 0 : list.length - 1) + : Math.max(0, Math.min(list.length - 1, from + step)); + const target = list[next]; + if (!current && target.dataset.value === stored) return; + if (current && target === tried) return; + put(target); + if (document.activeElement !== target) target.focus(); + return; + } + if (!current) return; + if (event.key === 'Enter' && !event.shiftKey) { + event.preventDefault(); + event.stopPropagation(); + void current.keep().catch(() => undefined); + } else if (event.key === 'Escape') { + event.preventDefault(); + event.stopPropagation(); + current.revert(); + } else if (event.key === 'Tab' && !event.shiftKey) { + const keep = document.querySelector('[data-try-bar]:not([hidden])')?.querySelector('button:not(:disabled)'); + if (!keep) return; + event.preventDefault(); + keep.focus({ preventScroll: true }); + } + }); +} + +export function installSegments(kit: TryKit, options: TryOptions): void { + options.segments.forEach((buttons, key) => installGroup(kit, options, key, buttons)); +} diff --git a/frontend/src/styles/try-bar.css b/frontend/src/styles/try-bar.css new file mode 100644 index 00000000..7cc5f691 --- /dev/null +++ b/frontend/src/styles/try-bar.css @@ -0,0 +1,19 @@ +.fw-try-bar { position: fixed; top: 0; left: 0; z-index: var(--z-popover); box-sizing: border-box; display: flex; align-items: center; gap: var(--space-1); width: max-content; max-width: calc(100vw - var(--space-4)); padding: var(--space-1) var(--space-1) var(--space-1) var(--space-3); pointer-events: auto; border: 1px solid var(--line-2); border-radius: var(--radius-lg); background: color-mix(in srgb, var(--surface-2) 94%, transparent); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); box-shadow: var(--shadow-lg); color: var(--text-primary); font-size: var(--fs-12); white-space: nowrap; } +.fw-try-bar[hidden] { display: none; } +.fw-try-bar:focus { outline: none; } +.fw-try-text { flex: 0 1 auto; min-width: 0; max-width: 18em; margin-right: var(--space-1); overflow: hidden; text-overflow: ellipsis; color: var(--text-secondary); } +.fw-try-btn { flex: none; min-height: 0; height: var(--ctl-sm); padding: 0 var(--space-2); gap: var(--space-2); border-radius: var(--radius); font-size: var(--fs-12); } +.fw-try-keep { border-color: var(--accent-line); background: var(--accent-soft); color: var(--accent-ink); font-weight: 600; } +.fw-try-keep:hover:not(:disabled) { background: color-mix(in srgb, var(--accent-color) 26%, var(--surface-2)); } +.fw-try-revert { border-color: var(--line-2); background: transparent; color: var(--text-primary); } +.fw-try-key { position: relative; color: var(--text-muted); font-size: var(--fs-11); font-weight: 400; letter-spacing: 0.04em; font-variant-numeric: tabular-nums; } +.fw-try-btn:disabled { opacity: 0.55; } +.fw-try-wait { position: absolute; top: 50%; left: 50%; width: 14px; height: 14px; margin: -7px 0 0 -7px; color: var(--accent-ink); visibility: hidden; } +.fw-try-bar.is-waiting .fw-try-keep .fw-try-key { color: transparent; } +.fw-try-bar.is-waiting .fw-try-wait { visibility: visible; animation: fw-try-turn 1.2s linear infinite; } +@keyframes fw-try-turn { to { transform: rotate(360deg); } } +@media (prefers-reduced-motion: reduce) { .fw-try-bar.is-waiting .fw-try-wait { animation: none; } } +.fw-seg-btn[data-trying] { outline: 2px solid var(--accent-color); outline-offset: -2px; background: var(--accent-wash); color: var(--text-primary); } +.fw-seg-btn[data-trying].is-on { color: var(--accent-ink); } +.fw-seg[data-trying] { outline: 1px dashed var(--accent-line); outline-offset: 1px; } +.fw-seg[data-trying='unset'] .fw-seg-btn.is-on { background: transparent; text-decoration: line-through; } From 734e82b579abca6cd007da3997ffd07202b601d6 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 04:19:03 -0500 Subject: [PATCH 04/17] feat(inspector): the Design fields that are lists open the editor's own list, where a clicked or arrowed item is tried on the page while the list stays open --- frontend/src/features/try/choice-list.ts | 370 +++++++++++++++++++++++ frontend/src/styles/try-list.css | 14 + 2 files changed, 384 insertions(+) create mode 100644 frontend/src/features/try/choice-list.ts create mode 100644 frontend/src/styles/try-list.css diff --git a/frontend/src/features/try/choice-list.ts b/frontend/src/features/try/choice-list.ts new file mode 100644 index 00000000..549ca243 --- /dev/null +++ b/frontend/src/features/try/choice-list.ts @@ -0,0 +1,370 @@ +import { englishOf, label, labelAttr } from '../../i18n'; +import { element, keyed, text } from '../../ui/dom'; +import { icon } from '../../ui/icons'; +import type { Trial, TrialOwner, TryKit, TryOptions } from './types'; +import '../../styles/try-list.css'; + +interface Field { select: HTMLSelectElement; key: string; label: string } +interface Row { value: string; english: string | null; shown: string } + +const MARGIN = 8; +const GAP = 4; +const MIN_ROOM = 96; +const OPENERS = new Set([' ', 'Enter', 'ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'PageDown', 'PageUp']); + +function englishLabel(select: HTMLSelectElement, key: string): string { + const head = select.closest('.field')?.querySelector(':scope > .field-label'); + const own = head ? Array.from(head.childNodes).filter(node => node.nodeType === 3).map(node => node.textContent).join('').trim() : ''; + return own || key; +} + +function rendered(node: Element | null | undefined): boolean { + return !!node && node.isConnected && node.getClientRects().length > 0 && !node.closest('[inert]'); +} + +function typed(event: KeyboardEvent): string { + return event.key.length === 1 && event.key !== ' ' && !event.altKey ? event.key.toLowerCase() : ''; +} + +export function installChoiceLists(kit: TryKit, options: TryOptions): void { + const fields: Field[] = []; + options.fields.forEach((control, key) => { + if (control instanceof HTMLSelectElement) fields.push({ select: control, key, label: englishLabel(control, key) }); + }); + if (!fields.length) return; + + const pop = element('div', 'fw-tlist'); + pop.id = 'fw-tlist'; + pop.hidden = true; + pop.tabIndex = -1; + pop.dataset.ownKeys = ''; + pop.setAttribute('role', 'listbox'); + options.overlay.append(pop); + + let field: Field | null = null; + let rows: Row[] = []; + let nodes: HTMLElement[] = []; + let active = -1; + let tried: string | null = null; + let trial: Trial | null = null; + let owner: TrialOwner | null = null; + let shownStored = ''; + let frame = 0; + let placedAt = ''; + let made = 0; + + const bar = (): HTMLElement | null => document.querySelector('[data-try-bar]'); + const inBar = (node: Node | null): boolean => !!node && !!bar()?.contains(node); + const live = (): boolean => !!trial && !trial.over; + + function aria(select: HTMLSelectElement): void { + if (kit.enabled()) { + if (select.getAttribute('aria-haspopup') !== 'listbox') select.setAttribute('aria-haspopup', 'listbox'); + if (select.getAttribute('aria-controls') !== pop.id) select.setAttribute('aria-controls', pop.id); + const open = String(field?.select === select); + if (select.getAttribute('aria-expanded') !== open) select.setAttribute('aria-expanded', open); + } else for (const name of ['aria-haspopup', 'aria-controls', 'aria-expanded']) select.removeAttribute(name); + } + + function safe(target: Field): void { + if (rendered(target.select)) { target.select.focus({ preventScroll: true }); return; } + const head = target.select.closest('.inspector-section')?.querySelector(':scope > .section-title'); + if (head && rendered(head)) { head.focus({ preventScroll: true }); return; } + const tab = document.querySelector('.inspector-tabs button.active'); + if (tab && rendered(tab)) tab.focus({ preventScroll: true }); + } + + function guard(target: Field): void { + const check = (): void => { + const now = document.activeElement; + if (!now || now === document.body || (pop.contains(now) && pop.hidden)) safe(target); + }; + window.setTimeout(check, 0); + requestAnimationFrame(() => requestAnimationFrame(check)); + } + + function mark(): void { + if (!field) return; + const stored = options.stored(field.key); + shownStored = stored; + nodes.forEach((node, index) => { + const row = rows[index]; + const isStored = row.value === stored; + if (node.hasAttribute('data-stored') !== isStored) node.toggleAttribute('data-stored', isStored); + const trying = tried !== null && row.value === tried; + if (node.hasAttribute('data-trying') !== trying) node.toggleAttribute('data-trying', trying); + const selected = String(tried !== null ? trying : isStored); + if (node.getAttribute('aria-selected') !== selected) node.setAttribute('aria-selected', selected); + const on = index === active; + if (node.classList.contains('is-active') !== on) node.classList.toggle('is-active', on); + }); + const id = nodes[active]?.id || ''; + if (id) { if (pop.getAttribute('aria-activedescendant') !== id) pop.setAttribute('aria-activedescendant', id); } + else pop.removeAttribute('aria-activedescendant'); + const busy = String(!!trial && trial.pending); + if (pop.getAttribute('aria-busy') !== busy) pop.setAttribute('aria-busy', busy); + } + + function reveal(): void { + const node = nodes[active]; + if (!node) return; + const top = node.offsetTop - pop.clientTop; + const pad = parseFloat(getComputedStyle(pop).paddingTop) || 0; + if (top - pad < pop.scrollTop) pop.scrollTop = top - pad; + else if (top + node.offsetHeight + pad > pop.scrollTop + pop.clientHeight) pop.scrollTop = top + node.offsetHeight + pad - pop.clientHeight; + } + + function place(): void { + if (!field) return; + const box = field.select.getBoundingClientRect(); + const key = `${box.left}|${box.top}|${box.width}|${box.height}|${window.innerWidth}|${window.innerHeight}`; + if (key === placedAt) return; + placedAt = key; + pop.style.minWidth = `${Math.round(box.width)}px`; + pop.style.maxHeight = ''; + pop.style.left = '0px'; + pop.style.top = '0px'; + const width = pop.offsetWidth; + const height = pop.offsetHeight; + const below = window.innerHeight - box.bottom - GAP - MARGIN; + const above = box.top - GAP - MARGIN; + const under = below >= height || below >= above; + const room = Math.max(MIN_ROOM, under ? below : above); + if (height > room) pop.style.maxHeight = `${Math.floor(room)}px`; + const shown = Math.min(height, room); + let top = under ? box.bottom + GAP : box.top - GAP - shown; + top = Math.max(MARGIN, Math.min(top, window.innerHeight - shown - MARGIN)); + const left = Math.max(MARGIN, Math.min(box.left, window.innerWidth - width - MARGIN)); + pop.style.left = `${Math.round(left)}px`; + pop.style.top = `${Math.round(top)}px`; + } + + function watch(): void { + frame = 0; + if (!field) return; + if (!kit.enabled()) { close(); return; } + if (!rendered(field.select)) { lost(); return; } + if (options.stored(field.key) !== shownStored) mark(); + place(); + frame = requestAnimationFrame(watch); + } + + function hide(): Field | null { + const was = field; + if (!was) return null; + if (pop.contains(document.activeElement)) safe(was); + pop.hidden = true; + field = null; + active = -1; + tried = null; + placedAt = ''; + pop.removeAttribute('aria-activedescendant'); + pop.setAttribute('aria-busy', 'false'); + aria(was.select); + if (frame) cancelAnimationFrame(frame); + frame = 0; + document.removeEventListener('pointerdown', outside, true); + document.removeEventListener('focusin', moved, true); + document.removeEventListener('scroll', place, true); + window.removeEventListener('resize', place); + window.removeEventListener('blur', blurred); + return was; + } + + function close(): void { + const was = field; + if (live()) { if (!trial!.pending) trial!.revert(); return; } + hide(); + if (was) guard(was); + } + + function lost(): void { + const was = field; + if (was && pop.contains(document.activeElement)) safe(was); + if (live() && !trial!.pending) trial!.revert(); + hide(); + if (was) guard(was); + } + + function ended(mine: TrialOwner): void { + if (owner !== mine) return; + owner = null; + trial = null; + tried = null; + const was = field; + if (!was) return; + const now = document.activeElement; + const back = !now || now === document.body || pop.contains(now) || inBar(now) || now === was.select; + hide(); + if (back) safe(was); + guard(was); + } + + function rowsOf(select: HTMLSelectElement): Row[] { + return Array.from(select.options).map(option => ({ value: option.value, english: englishOf(option), shown: option.text })); + } + + function open(target: Field): void { + if (field && field !== target) close(); + if (field) return; + rows = rowsOf(target.select); + keyed(pop, rows, row => `v:${row.value}`, () => { + const node = element('div', 'fw-tlist-row'); + node.id = `fw-tlist-row-${++made}`; + node.setAttribute('role', 'option'); + const tick = element('span', 'fw-tlist-tick'); + tick.append(icon('check')); + node.append(tick, element('span', 'fw-tlist-name')); + return node; + }, (node, row) => { + const name = node.lastElementChild as HTMLElement; + if (row.english !== null) { name.removeAttribute('data-no-i18n'); label(name, row.english); } + else { name.dataset.noI18n = ''; text(name, row.shown); } + }); + nodes = Array.from(pop.children) as HTMLElement[]; + labelAttr(pop, 'aria-label', target.label); + field = target; + tried = null; + active = Math.max(0, rows.findIndex(row => row.value === options.stored(target.key))); + mark(); + pop.hidden = false; + aria(target.select); + place(); + reveal(); + pop.focus({ preventScroll: true }); + document.addEventListener('pointerdown', outside, true); + document.addEventListener('focusin', moved, true); + document.addEventListener('scroll', place, true); + window.addEventListener('resize', place); + window.addEventListener('blur', blurred); + frame = requestAnimationFrame(watch); + } + + function nameAt(index: number): string { + return nodes[index]?.lastElementChild?.textContent || rows[index]?.shown || ''; + } + + function tryAt(index: number): void { + if (!field || !kit.enabled()) return; + if (trial?.pending) return; + if (index < 0 || index >= rows.length) return; + active = index; + if (!live()) { + const target = field; + const mine: TrialOwner = { + key: target.key, + label: target.label, + anchor: pop, + inside: () => [target.select], + ended: () => ended(mine) + }; + owner = mine; + trial = kit.begin(mine); + } + tried = rows[index].value; + trial!.put(rows[index].value, nameAt(index)); + mark(); + reveal(); + } + + function seek(letter: string): void { + if (!rows.length) return; + for (let step = 1; step <= rows.length; step++) { + const index = (active + step) % rows.length; + if (nameAt(index).trim().toLowerCase().startsWith(letter)) { tryAt(index); return; } + } + } + + function keep(): void { + if (!live()) { const was = hide(); if (was) { safe(was); guard(was); } return; } + if (trial!.pending) return; + const kept = trial!; + void kept.keep().catch(() => undefined).finally(() => { if (trial === kept) mark(); }); + mark(); + } + + function outside(event: Event): void { + const target = event.target as Node; + if (!field || pop.contains(target) || field.select.contains(target) || inBar(target)) return; + close(); + } + + function moved(event: FocusEvent): void { + const target = event.target as Node; + if (!field || pop.contains(target) || target === field.select || inBar(target)) return; + if (live()) { if (!trial!.pending) trial!.revert(); return; } + hide(); + } + + function blurred(): void { + window.setTimeout(() => { + if (field && !live() && document.activeElement instanceof HTMLIFrameElement) close(); + }, 0); + } + + function key(event: KeyboardEvent): void { + if (!field) return; + if (!kit.enabled()) { close(); return; } + const busy = !!trial?.pending; + const letter = typed(event); + if (event.key === 'Tab') { + if (live()) { + const keepButton = bar()?.querySelector('button:not(:disabled)'); + if (keepButton && rendered(keepButton)) { event.preventDefault(); keepButton.focus({ preventScroll: true }); } + return; + } + hide(); + return; + } + if (event.key === 'Escape') { if (!busy) { if (live()) trial!.revert(); else { const was = hide(); if (was) { safe(was); guard(was); } } } } + else if (event.key === 'Enter') keep(); + else if (event.key === 'ArrowDown' && !event.altKey) { if (!busy && active < rows.length - 1) tryAt(active + 1); } + else if (event.key === 'ArrowUp' && !event.altKey) { if (!busy && active > 0) tryAt(active - 1); } + else if (event.key === 'Home') { if (!busy) tryAt(0); } + else if (event.key === 'End') { if (!busy) tryAt(rows.length - 1); } + else if (letter) { if (!busy) seek(letter); } + else if (!['Delete', 'Backspace', ' ', 'ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'PageDown', 'PageUp'].includes(event.key)) return; + event.preventDefault(); + event.stopPropagation(); + } + + pop.addEventListener('keydown', event => { + if (event.isComposing || event.ctrlKey || event.metaKey) return; + key(event); + }); + pop.addEventListener('mousedown', event => event.preventDefault()); + pop.addEventListener('click', event => { + const node = (event.target as Element).closest('.fw-tlist-row'); + if (!node || !field || trial?.pending) return; + const index = nodes.indexOf(node); + if (index < 0) return; + if (document.activeElement !== pop) pop.focus({ preventScroll: true }); + tryAt(index); + }); + + for (const target of fields) { + const { select } = target; + aria(select); + select.addEventListener('focus', () => aria(select)); + select.addEventListener('mousedown', event => { + aria(select); + if (!kit.enabled() || select.disabled || event.button !== 0) return; + event.preventDefault(); + if (field === target) { close(); return; } + select.focus({ preventScroll: true }); + open(target); + }); + select.addEventListener('keydown', event => { + if (event.isComposing || event.ctrlKey || event.metaKey || !kit.enabled() || select.disabled) return; + if (field === target) { pop.focus({ preventScroll: true }); key(event); return; } + const letter = typed(event); + const home = event.key === 'Home' || event.key === 'End'; + if (!letter && !home && !OPENERS.has(event.key)) return; + event.preventDefault(); + open(target); + if (event.key === 'Home') tryAt(0); + else if (event.key === 'End') tryAt(rows.length - 1); + else if (letter) seek(letter); + }); + } +} diff --git a/frontend/src/styles/try-list.css b/frontend/src/styles/try-list.css new file mode 100644 index 00000000..cfdfdcfb --- /dev/null +++ b/frontend/src/styles/try-list.css @@ -0,0 +1,14 @@ +.fw-tlist { position: fixed; top: 0; left: 0; z-index: var(--z-popover); box-sizing: border-box; display: flex; flex-direction: column; gap: 1px; min-width: 120px; max-width: calc(100vw - var(--space-4)); max-height: calc(100vh - var(--space-4)); overflow-y: auto; overscroll-behavior: contain; scrollbar-width: none; padding: var(--space-1); pointer-events: auto; border: 1px solid var(--line-2); border-radius: var(--radius-xl); background: color-mix(in srgb, var(--surface-2) 94%, transparent); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); box-shadow: var(--shadow-lg); color: var(--text-primary); font-size: var(--fs-12); outline: none; } +.fw-tlist::-webkit-scrollbar { display: none; } +.fw-tlist[hidden] { display: none; } + +.fw-tlist-row { display: grid; flex: none; grid-template-columns: 16px minmax(0, 1fr); align-items: center; column-gap: var(--space-2); height: var(--ctl-md); padding: 0 var(--space-3) 0 var(--space-1); border-radius: var(--radius); color: var(--text-secondary); white-space: nowrap; cursor: default; user-select: none; } +.fw-tlist-row:hover { background: var(--bg-hover); color: var(--text-primary); } +.fw-tlist-row[aria-selected='true'] { background: var(--accent-wash); color: var(--text-primary); } +.fw-tlist-row[data-trying] { background: var(--accent-soft); outline: 1px solid var(--accent-line); outline-offset: -1px; } +.fw-tlist:focus-visible .fw-tlist-row.is-active { outline: 2px solid var(--accent-color); outline-offset: -2px; } +.fw-tlist-tick { display: inline-flex; align-items: center; justify-content: center; width: 16px; height: 16px; color: var(--accent-color); visibility: hidden; } +.fw-tlist-row[data-stored] .fw-tlist-tick { visibility: visible; } +.fw-tlist-name { overflow: hidden; text-overflow: ellipsis; } +.fw-tlist[aria-busy='true'] .fw-tlist-row { cursor: progress; } +.fw-tlist[aria-busy='true'] .fw-tlist-row:not([data-trying]) { opacity: 0.55; } From 71d469bc5ffc6de82177140e08e9223f490dee32 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 04:19:06 -0500 Subject: [PATCH 05/17] feat(editor): a clicked choice in Display, Direction, Align, Justify, Wrap, Text alignment and the list fields shows on the page as a trial until Keep or Enter writes it as one undo step, Revert, Escape, Undo, another selection, breakpoint or page put the page back, sliders and the color picker show their value on the page while dragged, and Preferences and the View menu can turn trying off --- frontend/src/commands/catalogue.ts | 1 + frontend/src/commands/keymap.ts | 2 +- frontend/src/commands/registry.ts | 3 + frontend/src/features/inspector/context.ts | 2 + frontend/src/features/try/index.ts | 233 +++++++++++++++++++++ frontend/src/main.ts | 31 ++- 6 files changed, 268 insertions(+), 4 deletions(-) create mode 100644 frontend/src/features/try/index.ts diff --git a/frontend/src/commands/catalogue.ts b/frontend/src/commands/catalogue.ts index 6d40cf4f..8d5cf0b5 100644 --- a/frontend/src/commands/catalogue.ts +++ b/frontend/src/commands/catalogue.ts @@ -81,6 +81,7 @@ const META: Record = { 'view.refresh': { description: 'Refresh the live responsive preview.' }, 'view.preview-full': { description: 'Open or close the full-window preview of the compiled site as visitors will see it, with a page picker, device widths from the site breakpoints, locale, refresh and open in browser. While it is open every other window command is disabled.', when: 'Use when the person wants to see the finished site; it changes nothing.' }, 'view.theme': { description: 'Switch between the light and dark editor theme.' }, + 'view.try-choices': { description: 'Turn trying on or off for the Design inspector\'s choices (the segment buttons and the lists). With it on, a clicked choice shows on the canvas only and a small bar offers Keep and Revert; nothing is written until Keep, which is one undo step. With it off, a clicked choice is written at once. It only changes the editor, is remembered in this browser (Preferences > Interface > Design fields), and is never saved with the site.', when: 'Use when the person wants choices written at once, or wants to see a choice on the page before it is kept.' }, 'view.design-controls': { description: 'Show or hide the controls (sliders, color swatches, choosers) beside the Design inspector\'s CSS fields for every field that has no choice of its own; with them off the fields are plain CSS text. The typed value stays the stored value either way. It only changes the editor, is remembered in this browser (Preferences > Interface > Design fields), and is never saved with the site.', when: 'Use when the person prefers typing CSS values, or wants the sliders and pickers back.' }, 'view.layout-outlines': { description: 'Show or hide layout outlines on the design canvas: the container of the selected element and the containers around it are outlined, and a CSS grid container shows its tracks. It only changes the view, is remembered in this browser, is never saved with the site or exported, and is hidden in Preview.', when: 'Use when the person wants to see how the page is structured before moving elements.' }, 'view.hover-outline': { description: 'Turn hover outlines on or off (on by default): while the mouse rests on a row in Layers, its element gets a light outline on the canvas, and while it rests on an element on the canvas, that element is outlined and its layer row is tinted. Nothing scrolls or is selected. It only changes the view, is remembered in this browser, is never saved with the site, and shows nothing during drags, text editing, menus or Preview.', when: 'Use when the person wants, or no longer wants, a quick preview of where an element is without selecting it.' }, diff --git a/frontend/src/commands/keymap.ts b/frontend/src/commands/keymap.ts index 1d2ec252..48bb8283 100644 --- a/frontend/src/commands/keymap.ts +++ b/frontend/src/commands/keymap.ts @@ -12,7 +12,7 @@ export function installKeymap(registry: Commands, ready: () => boolean): void { const mod = comboOf(event).includes('Mod+'); const target = event.target as Element | null; const typing = !!target?.closest?.(TYPING); - if (typing && !(command.global && mod)) return; + if (typing && !(mod && (command.global || target?.matches?.('select[data-style]')))) return; if (!mod && target?.closest?.(OWN_KEYS)) return; if (command.native?.()) return; if (event.repeat && !command.repeat) { if (mod) event.preventDefault(); return; } diff --git a/frontend/src/commands/registry.ts b/frontend/src/commands/registry.ts index 50147e8e..d77d966b 100644 --- a/frontend/src/commands/registry.ts +++ b/frontend/src/commands/registry.ts @@ -81,6 +81,7 @@ export class Commands { onRun: ((command: Command, label: string) => void) | null = null; onChange: (() => void) | null = null; gate: ((command: Command) => boolean) | null = null; + intercept: ((id: string) => boolean) | null = null; execute: (action: () => unknown) => unknown = action => action(); private readonly map = new Map(); private readonly bound = new Map(); @@ -164,6 +165,7 @@ export class Commands { run(id: string, params?: Record): boolean { const command = this.map.get(id); if (!command || !this.enabled(command)) return false; + if (this.intercept?.(id)) return true; const label = this.label(command); void this.execute(() => command.run(params)); this.onRun?.(command, label); @@ -173,6 +175,7 @@ export class Commands { async call(id: string, params?: Record): Promise<{ ran: boolean; result?: unknown }> { const command = this.map.get(id); if (!command || !this.enabled(command)) return { ran: false }; + if (this.intercept?.(id)) return { ran: true }; const label = this.label(command); const result = await command.run(params); this.onRun?.(command, label); diff --git a/frontend/src/features/inspector/context.ts b/frontend/src/features/inspector/context.ts index a5d4ec25..6a83b747 100644 --- a/frontend/src/features/inspector/context.ts +++ b/frontend/src/features/inspector/context.ts @@ -21,6 +21,8 @@ export interface InspectorContext { selectNode(id: string): void; showLayers(): void; canvas: Canvas; + breakpoint?(): string; + editing?(): boolean; panes: { design: HTMLElement; content: HTMLElement; tokens: HTMLElement; motion: HTMLElement }; anchors: { afterAttributes: HTMLElement; stageBefore: HTMLElement }; } diff --git a/frontend/src/features/try/index.ts b/frontend/src/features/try/index.ts new file mode 100644 index 00000000..92ea8250 --- /dev/null +++ b/frontend/src/features/try/index.ts @@ -0,0 +1,233 @@ +import { t } from '../../i18n'; +import { mountBar } from './bar'; +import { installSegments } from './segments'; +import { installChoiceLists } from './choice-list'; +import type { LayerFrame, Trial, TrialEnd, TrialOwner, TryKit, TryOptions } from './types'; + +const STORE = 'formweb.try-choices'; +const PASS = new Set(['edit.copy', 'view.try-choices']); + +type Live = { trial: Trial; owner: TrialOwner; node: string; scope: string; base: string; value: string | null; pending: boolean; over: boolean; end(how: TrialEnd, message?: string): void }; + +function readOn(): boolean { + try { return localStorage.getItem(STORE) !== '0'; } catch { return true; } +} + +function tabbable(root: Document): HTMLElement[] { + return Array.from(root.querySelectorAll('a[href], button, input, select, textarea, [tabindex]')) + .filter(node => node.tabIndex >= 0 && !(node as HTMLButtonElement).disabled && !node.closest('[hidden], [inert]') && node.getClientRects().length > 0); +} + +export function installTry(options: TryOptions): TryKit { + let on = readOn(); + let current: Live | null = null; + const landing = new Set(); + const lives = new Map(); + let liveNode = ''; + let liveScope = ''; + let watching = 0; + + const draw = (): void => { + const frame: LayerFrame = {}; + const add = (node: string, key: string, value: string): void => { (frame[node] ||= {})[key] = value === '' ? null : value; }; + for (const [key, value] of lives) add(liveNode, key, value); + for (const entry of landing) if (entry.value !== null) add(entry.node, entry.trial.key, entry.value); + if (current && !current.over && current.value !== null) add(current.node, current.trial.key, current.value); + options.canvas.setLayer('trial', Object.keys(frame).length ? frame : null); + }; + + const hidden = (entry: Live): boolean => !entry.owner.anchor.isConnected || entry.owner.anchor.getClientRects().length === 0; + + const check = (fromSync: boolean): void => { + const scope = options.scope(); + const editing = options.editing(); + if (lives.size && (scope !== liveScope || !editing)) lives.clear(); + const entry = current; + if (entry && !entry.over && !entry.pending) { + if (fromSync && options.exists && !options.exists(entry.node)) entry.end('dropped', t('The element was changed elsewhere, so the trial was dropped.')); + else if (scope !== entry.scope || !editing) entry.end('dropped'); + else if (fromSync && options.stored(entry.trial.key) !== entry.base) entry.end('dropped', t('The element was changed elsewhere, so the trial was dropped.')); + else if (!fromSync && hidden(entry)) entry.trial.revert(); + } + draw(); + }; + + const watch = (): void => { + if (watching) return; + const tick = (): void => { + watching = 0; + if (!current && !lives.size) return; + check(false); + if (current || lives.size) watching = requestAnimationFrame(tick); + }; + watching = requestAnimationFrame(tick); + }; + + const bar = mountBar(options.overlay, { + keep: () => { if (current && !current.pending) void current.trial.keep(); }, + revert: () => { if (current && !current.pending) current.trial.revert(); }, + leave: forward => { + const entry = current; + if (!entry) return; + const anchor = entry.owner.anchor; + if (!forward) { anchor.focus({ preventScroll: true }); return; } + const inside = [anchor, ...(entry.owner.inside?.() ?? [])]; + const next = tabbable(document).find(node => !bar.element.contains(node) && !inside.some(part => part.contains(node)) && !!(anchor.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING)); + if (next) next.focus(); + else { anchor.focus({ preventScroll: true }); if (!entry.pending) entry.trial.revert(); } + } + }); + + const shelter = (entry: Live): void => { + const active = document.activeElement; + if (active && bar.element.contains(active)) entry.owner.anchor.focus({ preventScroll: true }); + }; + + const create = (owner: TrialOwner): Live => { + const entry: Live = { + owner, + node: options.node(), + scope: options.scope(), + base: options.stored(owner.key), + value: null, + pending: false, + over: false, + trial: undefined as unknown as Trial, + end(how, message) { + if (entry.over) return; + entry.over = true; + entry.pending = false; + landing.delete(entry); + const shown = entry.value !== null; + if (current === entry) { + current = null; + shelter(entry); + bar.pending(false); + bar.hide(); + } + draw(); + if (message) options.status(message, how === 'refused'); + else if (how === 'reverted' && shown) options.status(t('Not kept: {0} is unchanged.', [owner.label])); + owner.ended(how); + } + }; + entry.trial = { + key: owner.key, + get pending() { return entry.pending; }, + get over() { return entry.over; }, + value: () => entry.value ?? options.stored(owner.key), + put(value: string, name: string) { + if (entry.over || entry.pending || current !== entry) return; + entry.value = value; + draw(); + bar.show(owner, name); + watch(); + }, + async keep() { + if (entry.over || entry.pending) return; + if (entry.value === null) { entry.end('reverted'); return; } + if (options.scope() !== entry.scope || options.node() !== entry.node || !options.editing()) { entry.end('dropped'); return; } + const value = entry.value; + if (value.trim() === options.stored(owner.key).trim()) { entry.end('reverted'); return; } + entry.pending = true; + shelter(entry); + bar.pending(true); + let failure: unknown = null; + try { await options.setStyle(owner.key, value); } catch (error) { failure = error ?? new Error(t('The change was refused.')); } + if (entry.over) return; + if (failure) entry.end('refused', failure instanceof Error ? failure.message : String(failure)); + else entry.end('kept'); + }, + revert() { + if (entry.over || entry.pending) return; + entry.end('reverted'); + } + }; + return entry; + }; + + const retire = (): void => { + const entry = current; + if (!entry) return; + if (entry.pending) { + landing.add(entry); + current = null; + bar.pending(false); + bar.hide(); + return; + } + entry.trial.revert(); + }; + + document.addEventListener('focusin', event => { + const entry = current; + if (!entry || entry.over || entry.pending) return; + const target = event.target as Node | null; + if (!target || target === document.body) return; + if (bar.element.contains(target) || entry.owner.anchor.contains(target) || (entry.owner.inside?.() ?? []).some(part => part.contains(target))) return; + entry.trial.revert(); + }, true); + + document.addEventListener('focusout', event => { + const entry = current; + const left = event.target as HTMLElement | null; + if (!entry || event.relatedTarget || !left) return; + if (!bar.element.contains(left) && !entry.owner.anchor.contains(left) && !(entry.owner.inside?.() ?? []).some(part => part.contains(left))) return; + setTimeout(() => { + if (current !== entry || !document.hasFocus() || (document.activeElement && document.activeElement !== document.body)) return; + (left.isConnected && left.getClientRects().length && !(left as HTMLButtonElement).disabled ? left : entry.owner.anchor).focus({ preventScroll: true }); + }); + }, true); + + const kit: TryKit = { + enabled: () => on, + setEnabled(next: boolean) { + on = next; + try { localStorage.setItem(STORE, next ? '1' : '0'); } catch {} + if (!next && current) { if (current.pending) retire(); else current.end('dropped'); } + }, + begin(owner: TrialOwner): Trial { + retire(); + const entry = create(owner); + current = entry; + return entry.trial; + }, + active: () => current?.trial ?? null, + busy: () => lives.size > 0 || landing.size > 0 || (!!current && current.value !== null), + live(key: string, value: string | null) { + if (value === null) { + if (lives.delete(key)) draw(); + return; + } + if (current) retire(); + const scope = options.scope(); + if (scope !== liveScope) lives.clear(); + liveScope = scope; + liveNode = options.node(); + lives.set(key, value); + draw(); + watch(); + }, + settled(key: string) { + if (lives.delete(key)) draw(); + }, + drop() { + lives.clear(); + if (current?.pending) retire(); + else current?.end('dropped'); + draw(); + }, + intercept(command: string): boolean { + const entry = current; + if (!entry || entry.over || entry.pending || PASS.has(command)) return false; + const shown = entry.value !== null; + entry.trial.revert(); + return shown && command === 'edit.undo'; + }, + sync() { check(true); } + }; + + installSegments(kit, options); + installChoiceLists(kit, options); + return kit; +} diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 56a6a306..146e02f5 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -41,6 +41,7 @@ import { installPageBackground, startChoices, startCommands } from './features/i import { installCanvasMenu } from './features/canvas-menu'; import { installInspectorSearch, sectionId } from './features/inspector/search'; import { installControls } from './features/inspector/controls'; +import { installTry } from './features/try'; import { installLibrary } from './features/library'; import { convertSections, installConvert } from './features/convert'; import { installInsertFlyout } from './features/panel/insert-flyout'; @@ -1230,15 +1231,29 @@ tokensPane.append(element('p', 'empty-note', 'Site tokens are exported as CSS cu const inspectorExt = installInspector({ section, field, select, input, button, addStyle, addSegments, setStyle, nodePatch, run, status, insertionParent, makeNode, selectNode, canvas, showLayers: () => setSidebar('pages'), + breakpoint: () => breakpoint, + editing: () => !preview && !fullPreview.isOpen, panes: { design: designPane, content: contentPane, tokens: tokensPane, motion: motionPane }, anchors: { afterAttributes: attributesSection, stageBefore: viewportReadout } }); +const tryKit = installTry({ + canvas, overlay, fields: styleFields, segments: segmentFields, + scope: () => `${currentNode().id}|${breakpoint}|${pageId}`, + node: () => currentNode().id, + exists: id => !!lastState?.site.nodes[id], + stored: key => { const node = currentNode(); return (breakpoint === 'desktop' ? node.styles : node.breakpoints[breakpoint] || {})[key] || ''; }, + inherited: key => breakpoint === 'desktop' ? '' : currentNode().styles[key] || '', + editing: () => !preview && !fullPreview.isOpen && !!scrim.hidden && !demoPreview.isOpen && !featureStudio.opened && !!home.root.hidden, + setStyle, + status: (message, error) => status(message, error) +}); const controlKit = installControls({ fields: styleFields, overlay, state: () => lastState, setStyle, scope: key => `${currentNode().id}|${breakpoint}|${key}`, setStyles: styles => { const next = Object.fromEntries(Object.entries(styles).map(([name, content]) => [name, content.trim() || null])); return nodePatch(breakpoint === 'desktop' ? { styles: next } : { breakpoints: { [breakpoint]: next } }); }, status: (message, error) => status(message, error), values: key => { const node = currentNode(); return { value: (breakpoint === 'desktop' ? node.styles : node.breakpoints[breakpoint] || {})[key] || '', inherited: node.styles[key] || '' }; }, - changed: () => { value(designFieldsSelect, controlKit.defaultRaw() ? 'css' : 'controls'); designFieldsAll.disabled = !controlKit.own(); } + changed: () => { value(designFieldsSelect, controlKit.defaultRaw() ? 'css' : 'controls'); designFieldsAll.disabled = !controlKit.own(); }, + trial: { live: (key, value) => tryKit.live(key, value), settled: key => tryKit.settled(key) } }); const settingsPane = dialogPane('settings'); applyTheme(); @@ -1265,6 +1280,13 @@ designFieldsSelect.addEventListener('change', () => controlKit.setDefaultRaw(des const designFieldsAll = button('Use for all fields', undefined, () => { controlKit.clearRaw(); status('Every Design field now follows this setting.'); }); designFieldsAll.disabled = !controlKit.own(); const designFieldsNote = element('p', 'micro', 'Controls puts sliders, color swatches and choosers next to the Design fields; CSS text shows the typed value only. The switch in a field\'s label changes that field alone.'); +const tryChoices = element('input'); +tryChoices.type = 'checkbox'; +tryChoices.checked = tryKit.enabled(); +tryChoices.addEventListener('change', () => tryKit.setEnabled(tryChoices.checked)); +const tryChoicesLabel = element('label', 'checkbox-field'); +tryChoicesLabel.append(tryChoices, element('span', '', 'Try choices on the page before keeping them')); +const tryChoicesNote = element('p', 'micro', 'A clicked choice shows on the page and is written when you press Keep. With this off, choices are written at once.'); const prefsIcons: Record = { General: 'pfGeneral', Interface: 'pfInterface', Plugins: 'pfPlugins' }; const prefsPages = element('div', 'fw-prefs-pages'); const prefsNav = element('div', 'fw-prefs-nav'); @@ -1433,7 +1455,7 @@ resetPrefs.addEventListener('click', () => { resetPrefs.hidden = true; resetRow. const tokenNote = element('p', 'micro', 'For a server launched with FORMWEB_AUTH_TOKEN, enter its token below. It is stored only for this browser tab.'); const endpointNote = element('p', 'micro', `API endpoint: ${apiBase || 'same origin'} /api. The API and MCP use the same authoritative Rust document.`); prefsAdd('General', prefsGroup('Startup', autoShowHomeLabel), prefsGroup('Reset', resetPrefs, resetRow)); -prefsAdd('Interface', prefsGroup('Theme', field('Editor theme', themeSelect)), prefsGroup('Language', field('Editor language', languageSelect)), prefsGroup('Design fields', field('Show in Design fields', designFieldsSelect), designFieldsNote, designFieldsAll)); +prefsAdd('Interface', prefsGroup('Theme', field('Editor theme', themeSelect)), prefsGroup('Language', field('Editor language', languageSelect)), prefsGroup('Design fields', field('Show in Design fields', designFieldsSelect), designFieldsNote, designFieldsAll, tryChoicesLabel, tryChoicesNote)); prefsAdd('Plugins', prefsGroup('Server access', tokenNote, field('Server access token', authToken), endpointNote)); settingsPane.append(prefsPages); prefsMark('General'); @@ -1581,6 +1603,7 @@ function update(next: EditorState): void { if (control instanceof HTMLInputElement) control.placeholder = node.styles[name] || 'Auto / inherit'; }); controlKit.sync(); + tryKit.sync(); segmentFields.forEach((buttons, name) => { const own = override[name] || ''; const inherited = breakpoint === 'desktop' ? '' : node.styles[name] || ''; @@ -2308,6 +2331,7 @@ registerCommands([ { id: 'view.preview-full', label: 'Preview as published', menu: 'View', keys: ['Mod+Shift+P'], group: 1, run: () => fullPreview.toggle(), enabled: ready }, { id: 'view.theme', label: 'Light theme', menu: 'View', group: 2, run: () => setTheme(readChoice().theme === 'light' ? 'studio' : 'light'), checked: () => readChoice().theme === 'light' }, { id: 'view.design-controls', label: 'Show controls in Design fields', menu: 'View', group: 2, run: () => { controlKit.setDefaultRaw(!controlKit.defaultRaw()); status(controlKit.defaultRaw() ? 'Design fields show the CSS text only.' : 'Design fields show their controls.'); }, checked: () => !controlKit.defaultRaw() }, + { id: 'view.try-choices', label: 'Try choices before keeping them', menu: 'View', group: 2, run: () => { tryKit.setEnabled(!tryKit.enabled()); tryChoices.checked = tryKit.enabled(); status(tryKit.enabled() ? 'A clicked choice now shows on the page until you press Keep.' : 'Clicked choices are now written at once.'); }, checked: () => tryKit.enabled() }, { id: 'view.search', label: 'Search commands', menu: 'View', keys: ['Mod+K'], global: true, group: 2, run: () => commandSearch.show() }, { id: 'view.menus-in-window', label: 'Menus in Window', menu: 'View', group: 2, enabled: desktopMac, checked: menusInWindow, run: () => { const on = !menusInWindow(); setMenusInWindow(on); status(on ? 'The menus stay in the window from the next start.' : 'The menus go to the menu bar from the next start.'); } }, { id: 'window.layers', label: 'Pages and layers', menu: 'Window', run: () => toggleLeft('pages'), checked: () => activeSidebar === 'pages' && layout.state.left === 'open' }, @@ -2345,7 +2369,7 @@ installSelection({ ready, site: () => state().site, primary: () => selectedId, s installSelectionActions({ idle: () => !!scrim.hidden, pageRoot: () => currentPage().root, status, copyNote }); registerCommands(installSelectMode({ heads: [{ head: pagesHead, kind: 'pages' }, { head: layersHead, kind: 'layers' }], lists: [pagesList, layersList], frame: canvas.frame, loaded: canvas.loaded(), ready, status: message => status(message) })); registerCommands(installCanvasDrag({ frame: canvas.frame, stage, overlay, loaded: () => canvas.loaded(), state, ready, editing: () => !preview, root: () => currentPage().root, selectionIds: selectedIds, select: selectNode, commands, run, status }).commands); -registerCommands(installHoverOutline({ frame: canvas.frame, loaded: () => canvas.loaded(), list: layersList, ready, editing: () => !preview && !fullPreview.isOpen, busy: () => insertFlyout.isOpen() || !scrim.hidden, root: () => currentPage().root, selectionIds: selectedIds, status: message => status(message) })); +registerCommands(installHoverOutline({ frame: canvas.frame, loaded: () => canvas.loaded(), list: layersList, ready, editing: () => !preview && !fullPreview.isOpen, busy: () => insertFlyout.isOpen() || !scrim.hidden || tryKit.busy(), root: () => currentPage().root, selectionIds: selectedIds, status: message => status(message) })); const vector = installVector({ canvas, getSelected: () => selectedId, select: selectNode, pageRoot: () => currentPage().root, notify: message => status(message, true), panelHost: document.body }); registerCommands(vector.commands); const wishlist = installWishlist({ state, commands: batch => commands(batch), selected: () => selectedId, select: selectNode, notify: status, audit: () => request<{ issues: AuditIssue[] }>('/api/audit') }); @@ -2359,6 +2383,7 @@ const mayReplace = async (): Promise => !(await unsavedWork()) || home. const demoHooks: DemoHooks = { mayReplace: () => { demoPreview.close(); return mayReplace(); }, load: loadProjectFile, opened: () => home.dismiss(), notify: message => status(message), failed: message => { status(message, true); home.notice(message); } }; const demoPreview = new DemoPreview(id => void openDemo(demoHooks, id)); registerCommands(demoCommands(demoHooks, ready, { show: id => demoPreview.show(id), close: () => demoPreview.close(), isOpen: () => demoPreview.isOpen })); +commandRegistry.intercept = id => tryKit.intercept(id); commandRegistry.gate = item => (!demoPreview.isOpen || item.id.startsWith('demo.')) && (!fullPreview.isOpen || item.id === 'view.preview-full'); menubar.build(); menubar.blocked = () => !scrim.hidden || featureStudio.opened || demoPreview.isOpen || fullPreview.isOpen; From 10117128224a685d11f2d89c07ff97d919e728de Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 04:19:08 -0500 Subject: [PATCH 06/17] feat(motion): a click on a motion preset sets it and plays it once on the canvas with no script, Play again replays it, nothing plays under reduced motion, effects that only run in Preview say so, and Blur in shows as active --- frontend/src/features/motion/play.ts | 163 ++++++++++++++++++++++++ frontend/src/features/motion/presets.ts | 103 ++++++++++++++- frontend/src/styles/motion-play.css | 3 + 3 files changed, 263 insertions(+), 6 deletions(-) create mode 100644 frontend/src/features/motion/play.ts create mode 100644 frontend/src/styles/motion-play.css diff --git a/frontend/src/features/motion/play.ts b/frontend/src/features/motion/play.ts new file mode 100644 index 00000000..d80d6627 --- /dev/null +++ b/frontend/src/features/motion/play.ts @@ -0,0 +1,163 @@ +import type { Canvas } from '../../ui/canvas'; +import type { SiteNode } from '../../types'; +import { MOTION_SAFE, type MotionGroup, type MotionKind } from './context'; +import { clamp, easing, interpolate, type Ease } from './interpolate'; + +export type PlayKind = 'reveals' | 'loops'; + +interface Track { id: string; key: string; from: string; via: string; end: string; start: number; length: number; ease: Ease; shape?: (p: number) => string } + +export interface Player { + play(id: string, kind: PlayKind, entry: unknown, children: readonly string[]): boolean; + stop(): void; + playing(): string; +} + +const SAFE = new Set(MOTION_SAFE); +const NAMED = new Set(['linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out']); +const LOOP_MAX = 2000; +const kebab = (key: string): string => key.replace(/[A-Z]/g, c => '-' + c.toLowerCase()); + +export function playableKind(group: MotionGroup, node: SiteNode, first?: MotionKind): PlayKind | '' { + const reveal = group.reveals[node.id] as { from?: Record } | undefined; + const loop = group.loops[node.id] as { type?: string } | undefined; + const reveals = !!reveal && typeof reveal === 'object' && Object.keys(reveal.from || {}).some(key => SAFE.has(kebab(key))); + const loops = !!loop && typeof loop === 'object' && (loop.type === 'spin' || loop.type === 'float'); + if (first === 'loops' && loops) return 'loops'; + return reveals ? 'reveals' : loops ? 'loops' : ''; +} + +function revealEase(name: unknown): Ease { + const key = String(name || 'ease-out').trim(); + return easing(NAMED.has(key) || key.startsWith('cubic-bezier(') || key.startsWith('spring(') ? key : 'ease-out'); +} + +function identity(key: string, from: string): string { + const zero = (text: string): string => text.replace(/-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/gi, '0'); + const one = (text: string): string => text.replace(/-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/gi, '1'); + if (key === 'opacity') return '1'; + if (key === 'scale') return one(from); + if (key === 'translate' || key === 'rotate') return zero(from); + if (key === 'filter' || key === 'backdrop-filter' || key === 'transform') { + let whole = true; + const out = from.replace(/([a-z-]+)\(([^()]*)\)/gi, (_all, name: string, args: string) => { + const fn = name.toLowerCase(); + if (/^(blur|hue-rotate|grayscale|sepia|invert|translate[xyz3d]*|rotate[xyz3d]*|skew[xy]?)$/.test(fn)) return `${name}(${zero(args)})`; + if (/^(brightness|contrast|saturate|opacity|scale[xyz3d]*)$/.test(fn)) return `${name}(${one(args)})`; + whole = false; + return _all; + }); + return whole ? out : ''; + } + return ''; +} + +const fits = (a: string, b: string): boolean => a === b || interpolate(a, b, 0.25) !== a; + +export function createPlayer(canvas: Canvas, live: () => boolean): Player { + let tracks: Track[] = []; + let frame = 0; + let begun = 0; + let total = 0; + let current = ''; + let ending = false; + + const doc = (): Document | null => { try { return canvas.frame.contentDocument; } catch { return null; } }; + const nodeOf = (id: string): HTMLElement | null => doc()?.querySelector(`[data-fw-id="${CSS.escape(id)}"]`) ?? null; + const ownValue = (el: HTMLElement, key: string): string => { + const own = el.style.getPropertyValue(key).trim(); + if (own) return own; + return (el.ownerDocument.defaultView?.getComputedStyle(el).getPropertyValue(key) || '').trim(); + }; + + function stop(): void { + if (frame) cancelAnimationFrame(frame); + frame = 0; + const was = current || tracks.length; + tracks = []; + current = ''; + ending = false; + if (was) canvas.setLayer('play', null); + } + + function draw(elapsed: number, last: boolean): void { + const out: Record> = {}; + for (const track of tracks) { + const local = track.length > 0 ? clamp((elapsed - track.start) / track.length, 0, 1) : elapsed >= track.start ? 1 : 0; + const shown = last || local >= 1 ? track.end : track.shape ? track.shape(local) : local <= 0 ? track.from : interpolate(track.from, track.via, track.ease(local)); + (out[track.id] ||= {})[track.key] = shown; + } + canvas.setLayer('play', out); + } + + function tick(now: number): void { + frame = 0; + if (!current) return; + if (!live()) { stop(); return; } + if (ending) { stop(); return; } + const elapsed = Math.max(0, now - begun); + if (elapsed >= total) { draw(total, true); ending = true; } + else draw(elapsed, false); + frame = requestAnimationFrame(tick); + } + + function revealTracks(id: string, entry: Record, children: readonly string[]): Track[] { + const from = (entry.from && typeof entry.from === 'object' ? entry.from : {}) as Record; + const keys = Object.keys(from).map(key => [kebab(key), String(from[key])] as const).filter(([key]) => SAFE.has(key)); + const duration = Math.max(0, Number(entry.duration ?? 600) || 0); + const delay = Math.max(0, Number(entry.delay || 0) || 0); + const stagger = Math.max(0, Number(entry.stagger || 0) || 0); + const ease = revealEase(entry.easing); + const targets = entry.children ? children : [id]; + const out: Track[] = []; + targets.forEach((target, index) => { + const el = nodeOf(target); + if (!el) return; + for (const [key, start] of keys) { + const end = ownValue(el, key); + const neutral = !el.style.getPropertyValue(key).trim() ? identity(key, start) : ''; + const via = fits(start, end) ? end : neutral && fits(start, neutral) ? neutral : end; + out.push({ id: target, key, from: start, via, end, start: delay + index * stagger, length: duration, ease }); + } + }); + return out; + } + + function loopTracks(id: string, entry: Record): Track[] { + const el = nodeOf(id); + if (!el) return []; + const amount = Number(entry.amount ?? (entry.type === 'spin' ? 360 : 12)) || 0; + const period = clamp(Number(entry.duration) || (entry.type === 'spin' ? 8000 : 4000), 100, 120000); + const there = (p: number): number => 1 - Math.abs(2 * p - 1); + if (entry.type === 'spin') { + const end = ownValue(el, 'rotate'); + const base = Number(/^(-?(?:\d+\.?\d*|\.\d+))deg$/.exec(el.style.getPropertyValue('rotate').trim())?.[1] || 0); + const whole = amount % 360 === 0; + return [{ id, key: 'rotate', from: `${base}deg`, via: end, end, start: 0, length: Math.min(LOOP_MAX, period), ease: easing('linear'), shape: p => `${Math.round((base + amount * (whole ? p : there(p))) * 1000) / 1000}deg` }]; + } + const end = ownValue(el, 'translate'); + const parts = el.style.getPropertyValue('translate').trim().split(/\s+/); + const px = (part: string | undefined): number => Number(/^(-?(?:\d+\.?\d*|\.\d+))(px)?$/.exec(part || '0')?.[1] || 0); + const x = px(parts[0]), y = px(parts[1]); + const ease = easing('ease-in-out'); + return [{ id, key: 'translate', from: `${x}px ${y}px`, via: end, end, start: 0, length: Math.min(LOOP_MAX, period * 2), ease, shape: p => `${x}px ${Math.round((y - amount * ease(there(p))) * 1000) / 1000}px` }]; + } + + return { + play(id, kind, entry, children) { + stop(); + if (!entry || typeof entry !== 'object' || !live()) return false; + const next = kind === 'reveals' ? revealTracks(id, entry as Record, children) : loopTracks(id, entry as Record); + if (!next.length) return false; + tracks = next; + total = Math.max(...next.map(track => track.start + track.length)); + current = id; + begun = performance.now(); + draw(0, false); + frame = requestAnimationFrame(tick); + return true; + }, + stop, + playing: () => current + }; +} diff --git a/frontend/src/features/motion/presets.ts b/frontend/src/features/motion/presets.ts index 24d35a1f..4bfee451 100644 --- a/frontend/src/features/motion/presets.ts +++ b/frontend/src/features/motion/presets.ts @@ -1,7 +1,13 @@ import { element } from '../../ui/dom'; import { label, labelAttr } from '../../i18n'; import type { MotionContext, MotionEditor, MotionKind } from './context'; -import type { SiteNode } from '../../types'; +import type { EditorState, SiteNode } from '../../types'; +import { createPlayer, playableKind } from './play'; +import '../../styles/motion-play.css'; + +const PLAY_ICON = ''; +const SHOWN_LATER = 'This effect plays in Preview and on the published site.'; +const REDUCED = 'Your system asks for reduced motion, so nothing is played here.'; interface MotionPreset { id: string; @@ -61,12 +67,34 @@ function matches(preset: MotionPreset, node: SiteNode, entry: unknown): boolean const stored = entry as Record; const keys = ACTIVE_KEYS[preset.kind] || []; if (preset.kind === 'counters') return true; - return keys.every(key => target[key] === undefined ? stored[key] === undefined || stored[key] === false || stored[key] === 0 : JSON.stringify(target[key]) === JSON.stringify(stored[key])); + const sorted = (value: unknown): string => JSON.stringify(value && typeof value === 'object' && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : value); + return keys.every(key => target[key] === undefined ? stored[key] === undefined || stored[key] === false || stored[key] === 0 : sorted(target[key]) === sorted(stored[key])); } export function installPresets(ctx: MotionContext, container: HTMLElement): MotionEditor { let current: SiteNode | undefined; let parent = ''; + let latest: EditorState | undefined; + let laterFor = ''; + let playedAt = -1; + let playedIn = ''; + const reduced = window.matchMedia('(prefers-reduced-motion: reduce)'); + const viewOf = (): string => ctx.breakpoint?.() ?? 'desktop'; + let calm = reduced.matches; + const still = (): boolean => { + if (reduced.matches !== calm) { calm = reduced.matches; queueMicrotask(refresh); } + return calm; + }; + const live = (): boolean => !still() && (ctx.editing?.() ?? true) && !ctx.canvas.outer.hidden && !ctx.canvas.frame.closest('[inert]') && ctx.canvas.frame.getClientRects().length > 0; + const player = createPlayer(ctx.canvas, live); + const start = (node: SiteNode, first?: MotionKind): void => { + if (!latest) return; + const group = ctx.motion(latest); + const kind = playableKind(group, node, first); + if (!kind || !player.play(node.id, kind, group[kind][node.id], node.children)) return; + playedAt = latest.revision; + playedIn = viewOf(); + }; const block = ctx.section(container, 'Presets'); const help = element('p', 'micro'); label(help, 'One click sets the effect for the selected element. Click an active preset again to remove it.'); @@ -86,8 +114,21 @@ export function installPresets(ctx: MotionContext, container: HTMLElement): Moti choice.addEventListener('click', () => { if (!current) return; const node = current; - if (choice.classList.contains('is-on')) void ctx.remove(preset.kind, node.id); - else void ctx.set(preset.kind, node.id, preset.make(node, parent)); + player.stop(); + if (choice.classList.contains('is-on')) { void ctx.remove(preset.kind, node.id); return; } + const entry = preset.make(node, parent); + const shows = preset.kind === 'reveals' || (preset.kind === 'loops' && (entry.type === 'spin' || entry.type === 'float')); + void ctx.set(preset.kind, node.id, entry).then(() => { + if (!current || current.id !== node.id || !latest) return; + if (!matches(preset, current, ctx.motion(latest)[preset.kind][node.id])) return; + laterFor = shows ? '' : node.id; + refresh(); + if (!shows || still()) return; + const at = latest.revision; + requestAnimationFrame(() => setTimeout(() => { + if (current && current.id === node.id && latest && latest.revision === at && !player.playing()) start(current, preset.kind); + })); + }); }); motionGroup.append(choice); return { preset, choice }; @@ -103,14 +144,59 @@ export function installPresets(ctx: MotionContext, container: HTMLElement): Moti const on = node.attrs['data-fw-effect'] === preset.effect; const attrs: Record = { ...node.attrs, 'data-fw-effect': on ? null : preset.effect }; if (on) attrs['data-fw-effect-speed'] = null; - void ctx.run(() => ctx.nodePatch({ attrs })); + player.stop(); + void ctx.run(() => ctx.nodePatch({ attrs })).then(() => { + if (on || !current || current.id !== node.id || current.attrs['data-fw-effect'] !== preset.effect) return; + laterFor = node.id; + refresh(); + }); }); effectGroup.append(choice); return { preset, choice }; }); const effectLabel = element('span', 'field-label'); label(effectLabel, 'Classic effects'); - block.append(motionGroup, effectLabel, effectGroup); + const row = element('div', 'fw-play-row'); + const again = element('button', 'fw-play-again'); + again.type = 'button'; + again.disabled = true; + const glyph = element('span', 'icon'); + glyph.innerHTML = PLAY_ICON; + const caption = element('span'); + label(caption, 'Play again'); + again.append(glyph, caption); + const note = element('p', 'fw-play-note'); + note.setAttribute('aria-live', 'polite'); + row.append(again, note); + block.append(motionGroup, effectLabel, effectGroup, row); + + again.addEventListener('click', () => { + player.stop(); + if (current && !still()) start(current); + }); + + function refresh(): void { + if (!current || !latest) return; + const group = ctx.motion(latest); + const playable = !!playableKind(group, current); + const loop = group.loops[current.id] as { type?: string } | undefined; + const id = current.id; + const elsewhere = !!current.attrs['data-fw-effect'] || (['text', 'counters', 'pointer'] as const).some(kind => !!group[kind][id]) || (!!loop && loop.type !== 'spin' && loop.type !== 'float'); + const quiet = still(); + const said = quiet ? REDUCED : elsewhere && (!playable || laterFor === current.id) ? SHOWN_LATER : ''; + if (said) label(note, said); + else if (note.textContent) note.textContent = ''; + const off = quiet || !playable; + if (again.disabled !== off) { + if (off && document.activeElement === again) motionButtons[0].choice.focus(); + again.disabled = off; + } + } + + reduced.addEventListener('change', () => { + if (still()) player.stop(); + refresh(); + }); const mark = (choice: HTMLButtonElement, on: boolean): void => { if (choice.classList.contains('is-on') !== on) choice.classList.toggle('is-on', on); @@ -119,12 +205,17 @@ export function installPresets(ctx: MotionContext, container: HTMLElement): Moti return { update(next, node) { + const playing = player.playing(); + if (playing && (playing !== node.id || next.revision !== playedAt || viewOf() !== playedIn || !live())) player.stop(); + if (current?.id !== node.id) laterFor = ''; + latest = next; current = node; const owner = Object.values(next.site.nodes).find(candidate => candidate.children.includes(node.id)); parent = owner ? owner.id : ''; const group = ctx.motion(next); for (const { preset, choice } of motionButtons) mark(choice, matches(preset, node, group[preset.kind][node.id])); for (const { preset, choice } of effectButtons) mark(choice, node.attrs['data-fw-effect'] === preset.effect); + refresh(); } }; } diff --git a/frontend/src/styles/motion-play.css b/frontend/src/styles/motion-play.css new file mode 100644 index 00000000..37cd1823 --- /dev/null +++ b/frontend/src/styles/motion-play.css @@ -0,0 +1,3 @@ +.fw-play-row { display: grid; justify-items: start; gap: var(--space-2); margin-top: var(--space-3); } +.fw-play-again { height: var(--ctl-sm); min-height: var(--ctl-sm); } +.fw-play-note { margin: 0; width: 100%; height: 4.8em; color: var(--text-muted); font-size: var(--fs-10); line-height: 1.6; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; } From 9f97a21cc90f8e5095a1261c9dbd6ebded98ec01 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 05:03:32 -0500 Subject: [PATCH 07/17] i18n: the 15 new strings of 0.34.0 (the try bar, the switch in Preferences and the View menu, the sentences when a trial is not kept, dropped or refused, and the motion presets row) in all 23 languages --- frontend/src/i18n/keys.ts | 15 +++++++++++++++ frontend/src/i18n/locales/cs.ts | 15 +++++++++++++++ frontend/src/i18n/locales/da.ts | 15 +++++++++++++++ frontend/src/i18n/locales/de.ts | 15 +++++++++++++++ frontend/src/i18n/locales/es-MX.ts | 2 ++ frontend/src/i18n/locales/es.ts | 15 +++++++++++++++ frontend/src/i18n/locales/fi.ts | 15 +++++++++++++++ frontend/src/i18n/locales/fr.ts | 15 +++++++++++++++ frontend/src/i18n/locales/hu.ts | 15 +++++++++++++++ frontend/src/i18n/locales/id.ts | 15 +++++++++++++++ frontend/src/i18n/locales/it.ts | 15 +++++++++++++++ frontend/src/i18n/locales/ja.ts | 15 +++++++++++++++ frontend/src/i18n/locales/ko.ts | 15 +++++++++++++++ frontend/src/i18n/locales/nb.ts | 15 +++++++++++++++ frontend/src/i18n/locales/nl.ts | 15 +++++++++++++++ frontend/src/i18n/locales/pl.ts | 15 +++++++++++++++ frontend/src/i18n/locales/pt-BR.ts | 15 +++++++++++++++ frontend/src/i18n/locales/ru.ts | 15 +++++++++++++++ frontend/src/i18n/locales/sv.ts | 15 +++++++++++++++ frontend/src/i18n/locales/th.ts | 15 +++++++++++++++ frontend/src/i18n/locales/tr.ts | 15 +++++++++++++++ frontend/src/i18n/locales/uk.ts | 15 +++++++++++++++ frontend/src/i18n/locales/vi.ts | 15 +++++++++++++++ frontend/src/i18n/locales/zh-CN.ts | 15 +++++++++++++++ frontend/src/i18n/locales/zh-TW.ts | 15 +++++++++++++++ 25 files changed, 362 insertions(+) diff --git a/frontend/src/i18n/keys.ts b/frontend/src/i18n/keys.ts index 870687f9..ce0062e0 100644 --- a/frontend/src/i18n/keys.ts +++ b/frontend/src/i18n/keys.ts @@ -3013,4 +3013,19 @@ export const KEYS: readonly string[] = [ "Use gradient", "Gradient stop {0}", "Stop {0} of {1}, {2} percent", + "Trial", + "Trying: {0}", + "Keep", + "Revert", + "Play again", + "This effect plays in Preview and on the published site.", + "Your system asks for reduced motion, so nothing is played here.", + "Try choices on the page before keeping them", + "A clicked choice shows on the page and is written when you press Keep. With this off, choices are written at once.", + "Try choices before keeping them", + "A clicked choice now shows on the page until you press Keep.", + "Clicked choices are now written at once.", + "Not kept: {0} is unchanged.", + "The element was changed elsewhere, so the trial was dropped.", + "The change was refused.", ]; diff --git a/frontend/src/i18n/locales/cs.ts b/frontend/src/i18n/locales/cs.ts index 75c3a3d0..9a21ab4d 100644 --- a/frontend/src/i18n/locales/cs.ts +++ b/frontend/src/i18n/locales/cs.ts @@ -3013,4 +3013,19 @@ export default [ "Použít přechod", "Zarážka přechodu {0}", "Zarážka {0} z {1}, {2} %", + "Zkouška", + "Zkouší se: {0}", + "Ponechat", + "Vrátit", + "Přehrát znovu", + "Tento efekt se přehraje v náhledu a na publikovaném webu.", + "Váš systém žádá omezený pohyb, proto se zde nic nepřehrává.", + "Zkoušet volby na stránce, než je ponecháte", + "Kliknutá volba se ukáže na stránce a uloží se, až stisknete Ponechat. Když je to vypnuté, volby se uloží hned.", + "Zkoušet volby, než je ponecháte", + "Kliknutá volba se teď ukáže na stránce, dokud nestisknete Ponechat.", + "Kliknuté volby se teď ukládají hned.", + "Neponecháno: {0} zůstává beze změny.", + "Prvek byl změněn jinde, proto byla zkouška zrušena.", + "Změna byla odmítnuta.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/da.ts b/frontend/src/i18n/locales/da.ts index b2761965..9f35247c 100644 --- a/frontend/src/i18n/locales/da.ts +++ b/frontend/src/i18n/locales/da.ts @@ -3013,4 +3013,19 @@ export default [ "Brug forløb", "Forløbsstop {0}", "Stop {0} af {1}, {2} procent", + "Afprøvning", + "Afprøver: {0}", + "Behold", + "Forkast", + "Afspil igen", + "Denne effekt afspilles i eksemplet og på det udgivne site.", + "Dit system beder om reduceret bevægelse, så intet afspilles her.", + "Prøv valg på siden, før de beholdes", + "Et klikket valg vises på siden og gemmes, når du trykker på Behold. Når dette er slået fra, gemmes valg med det samme.", + "Prøv valg, før de beholdes", + "Et klikket valg vises nu på siden, indtil du trykker på Behold.", + "Klikkede valg gemmes nu med det samme.", + "Ikke beholdt: {0} er uændret.", + "Elementet blev ændret et andet sted, så afprøvningen blev droppet.", + "Ændringen blev afvist.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/de.ts b/frontend/src/i18n/locales/de.ts index c604ed58..4188c25b 100644 --- a/frontend/src/i18n/locales/de.ts +++ b/frontend/src/i18n/locales/de.ts @@ -3013,4 +3013,19 @@ export default [ "Verlauf verwenden", "Verlaufsstopp {0}", "Stopp {0} von {1}, {2} Prozent", + "Ausprobieren", + "Wird ausprobiert: {0}", + "Behalten", + "Verwerfen", + "Erneut abspielen", + "Dieser Effekt läuft in der Vorschau und auf der veröffentlichten Website.", + "Dein System fordert reduzierte Bewegung an, daher wird hier nichts abgespielt.", + "Auswahlen auf der Seite ausprobieren, bevor sie behalten werden", + "Eine angeklickte Auswahl erscheint auf der Seite und wird gespeichert, wenn du Behalten drückst. Ist dies aus, werden Auswahlen sofort gespeichert.", + "Auswahlen vor dem Behalten ausprobieren", + "Eine angeklickte Auswahl erscheint jetzt auf der Seite, bis du Behalten drückst.", + "Angeklickte Auswahlen werden jetzt sofort gespeichert.", + "Nicht behalten: {0} ist unverändert.", + "Das Element wurde an anderer Stelle geändert, daher wurde der Versuch verworfen.", + "Die Änderung wurde abgelehnt.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/es-MX.ts b/frontend/src/i18n/locales/es-MX.ts index 30a50524..10014817 100644 --- a/frontend/src/i18n/locales/es-MX.ts +++ b/frontend/src/i18n/locales/es-MX.ts @@ -90,4 +90,6 @@ export default { "Type {0} by hand: hide its control and edit the CSS text only. Press again to bring the control back.": "Escribir {0} a mano: oculta su control y edita solo el texto CSS. Presiona de nuevo para recuperar el control.", "No brand or team colors yet. Add them in Window > Brand kit.": "Aún no hay colores de marca ni de equipo. Agrégalos en Ventana > Kit de marca.", "Click to add a stop": "Haz clic para agregar una parada", + "A clicked choice shows on the page and is written when you press Keep. With this off, choices are written at once.": "Una opción en la que haces clic se muestra en la página y se guarda cuando presionas Conservar. Con esto desactivado, las opciones se guardan al instante.", + "A clicked choice now shows on the page until you press Keep.": "Una opción en la que haces clic se muestra ahora en la página hasta que presiones Conservar.", } as Record; diff --git a/frontend/src/i18n/locales/es.ts b/frontend/src/i18n/locales/es.ts index 1d45decc..bbe49a51 100644 --- a/frontend/src/i18n/locales/es.ts +++ b/frontend/src/i18n/locales/es.ts @@ -3013,4 +3013,19 @@ export default [ "Usar degradado", "Parada {0} del degradado", "Parada {0} de {1}, {2} por ciento", + "Prueba", + "Probando: {0}", + "Conservar", + "Revertir", + "Reproducir de nuevo", + "Este efecto se reproduce en la vista previa y en el sitio publicado.", + "Tu sistema pide movimiento reducido, así que aquí no se reproduce nada.", + "Probar opciones en la página antes de conservarlas", + "Una opción en la que haces clic se muestra en la página y se guarda cuando pulsas Conservar. Con esto desactivado, las opciones se guardan al instante.", + "Probar opciones antes de conservarlas", + "Una opción en la que haces clic se muestra ahora en la página hasta que pulses Conservar.", + "Las opciones en las que haces clic ahora se guardan al instante.", + "No se conservó: {0} no cambia.", + "El elemento se cambió en otro lugar, así que la prueba se descartó.", + "Se rechazó el cambio.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/fi.ts b/frontend/src/i18n/locales/fi.ts index 6a435ff2..d3b611f7 100644 --- a/frontend/src/i18n/locales/fi.ts +++ b/frontend/src/i18n/locales/fi.ts @@ -3013,4 +3013,19 @@ export default [ "Käytä liukuväriä", "Liukuvärin väripiste {0}", "Väripiste {0}/{1}, {2} prosenttia", + "Kokeilu", + "Kokeillaan: {0}", + "Säilytä", + "Palauta", + "Toista uudelleen", + "Tämä tehoste toistetaan esikatselussa ja julkaistulla sivustolla.", + "Järjestelmäsi pyytää vähennettyä liikettä, joten tässä ei toisteta mitään.", + "Kokeile valintoja sivulla ennen niiden säilyttämistä", + "Napsautettu valinta näkyy sivulla ja tallennetaan, kun painat Säilytä. Kun tämä on pois päältä, valinnat tallennetaan heti.", + "Kokeile valintoja ennen niiden säilyttämistä", + "Napsautettu valinta näkyy nyt sivulla, kunnes painat Säilytä.", + "Napsautetut valinnat tallennetaan nyt heti.", + "Ei säilytetty: {0} on ennallaan.", + "Elementtiä muutettiin muualla, joten kokeilu hylättiin.", + "Muutos hylättiin.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/fr.ts b/frontend/src/i18n/locales/fr.ts index 342907e7..0f156253 100644 --- a/frontend/src/i18n/locales/fr.ts +++ b/frontend/src/i18n/locales/fr.ts @@ -3013,4 +3013,19 @@ export default [ "Utiliser le dégradé", "Point {0} du dégradé", "Point {0} sur {1}, {2} pour cent", + "Essai", + "À l’essai : {0}", + "Garder", + "Revenir", + "Rejouer", + "Cet effet se joue dans l’aperçu et sur le site publié.", + "Votre système demande des animations réduites, rien n’est donc joué ici.", + "Essayer les choix sur la page avant de les garder", + "Un choix cliqué s’affiche sur la page et est enregistré quand vous appuyez sur Garder. Si cette option est désactivée, les choix sont enregistrés aussitôt.", + "Essayer les choix avant de les garder", + "Un choix cliqué s’affiche maintenant sur la page jusqu’à ce que vous appuyiez sur Garder.", + "Les choix cliqués sont maintenant enregistrés aussitôt.", + "Non gardé : {0} est inchangé.", + "L’élément a été modifié ailleurs, l’essai a donc été abandonné.", + "La modification a été refusée.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/hu.ts b/frontend/src/i18n/locales/hu.ts index b076a64a..c5a2455f 100644 --- a/frontend/src/i18n/locales/hu.ts +++ b/frontend/src/i18n/locales/hu.ts @@ -3013,4 +3013,19 @@ export default [ "Színátmenet használata", "{0}. színpont", "{0}. színpont / {1}, {2}%", + "Kipróbálás", + "Kipróbálás: {0}", + "Megtartás", + "Elvetés", + "Újrajátszás", + "Ez az effektus az előnézetben és a közzétett webhelyen játszódik le.", + "A rendszered csökkentett mozgást kér, ezért itt semmi nem játszódik le.", + "Választások kipróbálása az oldalon megtartás előtt", + "A rákattintott választás megjelenik az oldalon, és akkor kerül mentésre, amikor megnyomod a Megtartás gombot. Ha ez ki van kapcsolva, a választások azonnal mentésre kerülnek.", + "Választások kipróbálása megtartás előtt", + "A rákattintott választás most megjelenik az oldalon, amíg meg nem nyomod a Megtartás gombot.", + "A rákattintott választások most azonnal mentésre kerülnek.", + "Nincs megtartva: {0} változatlan.", + "Az elemet máshol módosították, ezért a kipróbálás elvetve.", + "A módosítást elutasították.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/id.ts b/frontend/src/i18n/locales/id.ts index c5103cfc..dba24e9d 100644 --- a/frontend/src/i18n/locales/id.ts +++ b/frontend/src/i18n/locales/id.ts @@ -3013,4 +3013,19 @@ export default [ "Gunakan gradien", "Stop gradien {0}", "Stop {0} dari {1}, {2} persen", + "Uji coba", + "Mencoba: {0}", + "Pertahankan", + "Kembalikan", + "Putar lagi", + "Efek ini diputar di Pratinjau dan di situs yang diterbitkan.", + "Sistem Anda meminta gerakan dikurangi, jadi tidak ada yang diputar di sini.", + "Coba pilihan di halaman sebelum mempertahankannya", + "Pilihan yang diklik tampil di halaman dan disimpan saat Anda menekan Pertahankan. Jika ini nonaktif, pilihan langsung disimpan.", + "Coba pilihan sebelum mempertahankannya", + "Pilihan yang diklik kini tampil di halaman sampai Anda menekan Pertahankan.", + "Pilihan yang diklik kini langsung disimpan.", + "Tidak dipertahankan: {0} tidak berubah.", + "Elemen diubah di tempat lain, jadi uji coba dibatalkan.", + "Perubahan ditolak.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/it.ts b/frontend/src/i18n/locales/it.ts index 03e498d7..11d1a1f7 100644 --- a/frontend/src/i18n/locales/it.ts +++ b/frontend/src/i18n/locales/it.ts @@ -3013,4 +3013,19 @@ export default [ "Usa la sfumatura", "Punto {0} della sfumatura", "Punto {0} di {1}, {2} percento", + "Prova", + "In prova: {0}", + "Mantieni", + "Ripristina", + "Riproduci di nuovo", + "Questo effetto viene riprodotto nell’anteprima e sul sito pubblicato.", + "Il tuo sistema chiede movimento ridotto, quindi qui non viene riprodotto nulla.", + "Prova le scelte sulla pagina prima di mantenerle", + "Una scelta cliccata appare sulla pagina e viene salvata quando premi Mantieni. Con questa opzione disattivata, le scelte vengono salvate subito.", + "Prova le scelte prima di mantenerle", + "Ora una scelta cliccata appare sulla pagina finché non premi Mantieni.", + "Ora le scelte cliccate vengono salvate subito.", + "Non mantenuto: {0} è invariato.", + "L’elemento è stato modificato altrove, quindi la prova è stata annullata.", + "La modifica è stata rifiutata.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/ja.ts b/frontend/src/i18n/locales/ja.ts index e1af2a5e..9d2ae7a5 100644 --- a/frontend/src/i18n/locales/ja.ts +++ b/frontend/src/i18n/locales/ja.ts @@ -3013,4 +3013,19 @@ export default [ "グラデーションを使用", "グラデーションのストップ {0}", "ストップ {0}/{1}、{2} パーセント", + "試用", + "試用中: {0}", + "確定", + "戻す", + "もう一度再生", + "この効果はプレビューと公開サイトで再生されます。", + "システムが動きを減らす設定になっているため、ここでは何も再生しません。", + "確定する前にページ上で選択肢を試す", + "クリックした選択肢はページ上に表示され、「確定」を押すと保存されます。オフにすると、選択肢はすぐに保存されます。", + "確定する前に選択肢を試す", + "クリックした選択肢は、「確定」を押すまでページ上に表示されるようになりました。", + "クリックした選択肢はすぐに保存されるようになりました。", + "確定されませんでした: {0} は変更されていません。", + "要素が別の場所で変更されたため、試用を取り消しました。", + "変更は拒否されました。", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/ko.ts b/frontend/src/i18n/locales/ko.ts index 11ca11e5..2ff78f3b 100644 --- a/frontend/src/i18n/locales/ko.ts +++ b/frontend/src/i18n/locales/ko.ts @@ -3013,4 +3013,19 @@ export default [ "그레이디언트 사용", "그레이디언트 정지점 {0}", "정지점 {0}/{1}, {2}퍼센트", + "시험 적용", + "시험 적용 중: {0}", + "유지", + "되돌리기", + "다시 재생", + "이 효과는 미리 보기와 게시된 사이트에서 재생됩니다.", + "시스템에서 동작 줄이기를 요청하므로 여기서는 아무것도 재생하지 않습니다.", + "유지하기 전에 페이지에서 선택 항목 시험 적용", + "클릭한 선택 항목은 페이지에 표시되고 유지를 누르면 저장됩니다. 이 설정을 끄면 선택 항목이 바로 저장됩니다.", + "유지하기 전에 선택 항목 시험 적용", + "이제 클릭한 선택 항목은 유지를 누를 때까지 페이지에 표시됩니다.", + "이제 클릭한 선택 항목이 바로 저장됩니다.", + "유지하지 않음: {0}은(는) 변경되지 않았습니다.", + "요소가 다른 곳에서 변경되어 시험 적용을 취소했습니다.", + "변경이 거부되었습니다.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/nb.ts b/frontend/src/i18n/locales/nb.ts index f716b6c6..30ed7456 100644 --- a/frontend/src/i18n/locales/nb.ts +++ b/frontend/src/i18n/locales/nb.ts @@ -3013,4 +3013,19 @@ export default [ "Bruk fargeovergang", "Fargeovergangsstopp {0}", "Stopp {0} av {1}, {2} prosent", + "Utprøving", + "Prøver: {0}", + "Behold", + "Forkast", + "Spill av igjen", + "Denne effekten spilles av i forhåndsvisningen og på det publiserte nettstedet.", + "Systemet ditt ber om redusert bevegelse, så ingenting spilles av her.", + "Prøv valg på siden før de beholdes", + "Et klikket valg vises på siden og lagres når du trykker Behold. Når dette er av, lagres valg med en gang.", + "Prøv valg før de beholdes", + "Et klikket valg vises nå på siden til du trykker Behold.", + "Klikkede valg lagres nå med en gang.", + "Ikke beholdt: {0} er uendret.", + "Elementet ble endret et annet sted, så utprøvingen ble forkastet.", + "Endringen ble avvist.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/nl.ts b/frontend/src/i18n/locales/nl.ts index 43662d30..ba9c6f61 100644 --- a/frontend/src/i18n/locales/nl.ts +++ b/frontend/src/i18n/locales/nl.ts @@ -3013,4 +3013,19 @@ export default [ "Verloop gebruiken", "Verloopstop {0}", "Stop {0} van {1}, {2} procent", + "Uitproberen", + "Proberen: {0}", + "Behouden", + "Terugzetten", + "Opnieuw afspelen", + "Dit effect speelt in het voorbeeld en op de gepubliceerde site.", + "Je systeem vraagt om minder beweging, dus hier wordt niets afgespeeld.", + "Keuzes op de pagina uitproberen voordat je ze behoudt", + "Een aangeklikte keuze verschijnt op de pagina en wordt opgeslagen als je op Behouden drukt. Staat dit uit, dan worden keuzes meteen opgeslagen.", + "Keuzes uitproberen voordat je ze behoudt", + "Een aangeklikte keuze verschijnt nu op de pagina tot je op Behouden drukt.", + "Aangeklikte keuzes worden nu meteen opgeslagen.", + "Niet behouden: {0} is ongewijzigd.", + "Het element is elders gewijzigd, dus de proef is vervallen.", + "De wijziging is geweigerd.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/pl.ts b/frontend/src/i18n/locales/pl.ts index d52c784d..9821f83c 100644 --- a/frontend/src/i18n/locales/pl.ts +++ b/frontend/src/i18n/locales/pl.ts @@ -3013,4 +3013,19 @@ export default [ "Użyj gradientu", "Punkt gradientu {0}", "Punkt {0} z {1}, {2}%", + "Próba", + "Próba: {0}", + "Zachowaj", + "Odrzuć", + "Odtwórz ponownie", + "Ten efekt jest odtwarzany w podglądzie i na opublikowanej witrynie.", + "Twój system prosi o ograniczenie ruchu, więc nic nie jest tu odtwarzane.", + "Wypróbowuj opcje na stronie przed zachowaniem", + "Kliknięta opcja pojawia się na stronie i zostaje zapisana, gdy naciśniesz Zachowaj. Gdy to jest wyłączone, opcje są zapisywane od razu.", + "Wypróbowuj opcje przed zachowaniem", + "Kliknięta opcja pojawia się teraz na stronie, dopóki nie naciśniesz Zachowaj.", + "Kliknięte opcje są teraz zapisywane od razu.", + "Nie zachowano: {0} bez zmian.", + "Element został zmieniony gdzie indziej, więc próba została odrzucona.", + "Zmiana została odrzucona.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/pt-BR.ts b/frontend/src/i18n/locales/pt-BR.ts index 36d928d4..57dfdb56 100644 --- a/frontend/src/i18n/locales/pt-BR.ts +++ b/frontend/src/i18n/locales/pt-BR.ts @@ -3013,4 +3013,19 @@ export default [ "Usar gradiente", "Parada {0} do gradiente", "Parada {0} de {1}, {2} por cento", + "Teste", + "Testando: {0}", + "Manter", + "Reverter", + "Reproduzir de novo", + "Este efeito é reproduzido na visualização e no site publicado.", + "Seu sistema pede movimento reduzido, então nada é reproduzido aqui.", + "Testar opções na página antes de mantê-las", + "Uma opção clicada aparece na página e é gravada quando você pressiona Manter. Com isto desligado, as opções são gravadas na hora.", + "Testar opções antes de mantê-las", + "Uma opção clicada agora aparece na página até você pressionar Manter.", + "As opções clicadas agora são gravadas na hora.", + "Não mantido: {0} não mudou.", + "O elemento foi alterado em outro lugar, então o teste foi descartado.", + "A alteração foi recusada.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/ru.ts b/frontend/src/i18n/locales/ru.ts index e2e7b1fc..12ba244b 100644 --- a/frontend/src/i18n/locales/ru.ts +++ b/frontend/src/i18n/locales/ru.ts @@ -3013,4 +3013,19 @@ export default [ "Применить градиент", "Опорная точка градиента {0}", "Точка {0} из {1}, {2} %", + "Проба", + "Проба: {0}", + "Оставить", + "Вернуть", + "Воспроизвести снова", + "Этот эффект воспроизводится в предпросмотре и на опубликованном сайте.", + "Ваша система просит уменьшить движение, поэтому здесь ничего не воспроизводится.", + "Пробовать варианты на странице, прежде чем оставить их", + "Выбранный щелчком вариант показывается на странице и сохраняется, когда вы нажимаете «Оставить». Если это выключено, варианты сохраняются сразу.", + "Пробовать варианты, прежде чем оставить их", + "Теперь выбранный щелчком вариант показывается на странице, пока вы не нажмёте «Оставить».", + "Теперь выбранные щелчком варианты сохраняются сразу.", + "Не оставлено: {0} без изменений.", + "Элемент был изменён в другом месте, поэтому проба отменена.", + "Изменение отклонено.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/sv.ts b/frontend/src/i18n/locales/sv.ts index ebdf9464..1e1e33d8 100644 --- a/frontend/src/i18n/locales/sv.ts +++ b/frontend/src/i18n/locales/sv.ts @@ -3013,4 +3013,19 @@ export default [ "Använd toning", "Toningsstopp {0}", "Stopp {0} av {1}, {2} procent", + "Provning", + "Provar: {0}", + "Behåll", + "Återgå", + "Spela igen", + "Den här effekten spelas i förhandsgranskningen och på den publicerade webbplatsen.", + "Ditt system ber om minskad rörelse, så inget spelas här.", + "Prova val på sidan innan de behålls", + "Ett klickat val visas på sidan och sparas när du trycker på Behåll. När detta är av sparas val direkt.", + "Prova val innan de behålls", + "Ett klickat val visas nu på sidan tills du trycker på Behåll.", + "Klickade val sparas nu direkt.", + "Inte behållet: {0} är oförändrat.", + "Elementet ändrades på annat håll, så provningen släpptes.", + "Ändringen avvisades.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/th.ts b/frontend/src/i18n/locales/th.ts index b48228f0..0161dc90 100644 --- a/frontend/src/i18n/locales/th.ts +++ b/frontend/src/i18n/locales/th.ts @@ -3013,4 +3013,19 @@ export default [ "ใช้การไล่ระดับสี", "จุดหยุดการไล่ระดับสี {0}", "จุดหยุด {0} จาก {1}, {2} เปอร์เซ็นต์", + "การลองใช้", + "กำลังลอง: {0}", + "เก็บไว้", + "ย้อนกลับ", + "เล่นอีกครั้ง", + "เอฟเฟกต์นี้เล่นในตัวอย่างและบนไซต์ที่เผยแพร่", + "ระบบของคุณขอให้ลดการเคลื่อนไหว จึงไม่มีการเล่นที่นี่", + "ลองตัวเลือกบนหน้าก่อนเก็บไว้", + "ตัวเลือกที่คลิกจะแสดงบนหน้าและจะบันทึกเมื่อคุณกดเก็บไว้ หากปิดตัวเลือกนี้ ตัวเลือกจะบันทึกทันที", + "ลองตัวเลือกก่อนเก็บไว้", + "ตอนนี้ตัวเลือกที่คลิกจะแสดงบนหน้าจนกว่าคุณจะกดเก็บไว้", + "ตอนนี้ตัวเลือกที่คลิกจะบันทึกทันที", + "ไม่ได้เก็บไว้: {0} ไม่เปลี่ยนแปลง", + "องค์ประกอบถูกเปลี่ยนจากที่อื่น จึงยกเลิกการลองใช้", + "การเปลี่ยนแปลงถูกปฏิเสธ", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/tr.ts b/frontend/src/i18n/locales/tr.ts index 94547158..d4875efe 100644 --- a/frontend/src/i18n/locales/tr.ts +++ b/frontend/src/i18n/locales/tr.ts @@ -3013,4 +3013,19 @@ export default [ "Degradeyi kullan", "Degrade durağı {0}", "Durak {0}/{1}, yüzde {2}", + "Deneme", + "Deneniyor: {0}", + "Koru", + "Vazgeç", + "Yeniden oynat", + "Bu efekt önizlemede ve yayımlanan sitede oynatılır.", + "Sisteminiz azaltılmış hareket istiyor, bu yüzden burada hiçbir şey oynatılmaz.", + "Seçimleri korumadan önce sayfada dene", + "Tıklanan bir seçim sayfada görünür ve Koru'ya bastığınızda kaydedilir. Bu kapalıyken seçimler hemen kaydedilir.", + "Seçimleri korumadan önce dene", + "Tıklanan bir seçim artık siz Koru'ya basana kadar sayfada görünür.", + "Tıklanan seçimler artık hemen kaydedilir.", + "Korunmadı: {0} değişmedi.", + "Öğe başka bir yerde değiştirildi, bu yüzden deneme bırakıldı.", + "Değişiklik reddedildi.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/uk.ts b/frontend/src/i18n/locales/uk.ts index 29d0fd6e..ee962a0c 100644 --- a/frontend/src/i18n/locales/uk.ts +++ b/frontend/src/i18n/locales/uk.ts @@ -3013,4 +3013,19 @@ export default [ "Застосувати градієнт", "Опорна точка градієнта {0}", "Точка {0} з {1}, {2} %", + "Проба", + "Проба: {0}", + "Залишити", + "Повернути", + "Відтворити знову", + "Цей ефект відтворюється в попередньому перегляді та на опублікованому сайті.", + "Ваша система просить зменшити рух, тому тут нічого не відтворюється.", + "Пробувати варіанти на сторінці, перш ніж залишити їх", + "Вибраний клацанням варіант показується на сторінці й зберігається, коли ви натискаєте «Залишити». Якщо це вимкнено, варіанти зберігаються одразу.", + "Пробувати варіанти, перш ніж залишити їх", + "Тепер вибраний клацанням варіант показується на сторінці, доки ви не натиснете «Залишити».", + "Тепер вибрані клацанням варіанти зберігаються одразу.", + "Не залишено: {0} без змін.", + "Елемент змінено в іншому місці, тому пробу скасовано.", + "Зміну відхилено.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/vi.ts b/frontend/src/i18n/locales/vi.ts index b5b2ffa0..bd8e57bf 100644 --- a/frontend/src/i18n/locales/vi.ts +++ b/frontend/src/i18n/locales/vi.ts @@ -3013,4 +3013,19 @@ export default [ "Dùng chuyển màu", "Điểm dừng chuyển màu {0}", "Điểm dừng {0}/{1}, {2} phần trăm", + "Dùng thử", + "Đang thử: {0}", + "Giữ", + "Hoàn nguyên", + "Phát lại", + "Hiệu ứng này phát trong Xem trước và trên trang web đã xuất bản.", + "Hệ thống của bạn yêu cầu giảm chuyển động, nên không phát gì ở đây.", + "Thử lựa chọn trên trang trước khi giữ", + "Lựa chọn được nhấp sẽ hiện trên trang và được lưu khi bạn nhấn Giữ. Khi tắt mục này, lựa chọn được lưu ngay.", + "Thử lựa chọn trước khi giữ", + "Giờ lựa chọn được nhấp sẽ hiện trên trang cho đến khi bạn nhấn Giữ.", + "Giờ các lựa chọn được nhấp sẽ được lưu ngay.", + "Chưa giữ: {0} không thay đổi.", + "Phần tử đã được thay đổi ở nơi khác, nên bản thử đã bị bỏ.", + "Thay đổi đã bị từ chối.", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index c06909ca..326304de 100644 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -3013,4 +3013,19 @@ export default [ "使用渐变", "渐变色标 {0}", "第 {0} 个色标,共 {1} 个,{2}%", + "试用", + "正在试用:{0}", + "保留", + "还原", + "再次播放", + "此效果在预览和已发布的站点中播放。", + "系统要求减少动态效果,因此这里不播放任何内容。", + "保留前先在页面上试用选项", + "点击的选项会显示在页面上,按“保留”后才会保存。关闭此项后,选项会立即保存。", + "保留前先试用选项", + "现在点击的选项会显示在页面上,直到按下“保留”。", + "现在点击的选项会立即保存。", + "未保留:{0} 未更改。", + "该元素已在别处更改,因此已放弃试用。", + "更改被拒绝。", ] as readonly string[]; diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts index 8fe58323..d746332f 100644 --- a/frontend/src/i18n/locales/zh-TW.ts +++ b/frontend/src/i18n/locales/zh-TW.ts @@ -3013,4 +3013,19 @@ export default [ "使用漸層", "漸層色標 {0}", "第 {0} 個色標,共 {1} 個,{2}%", + "試用", + "正在試用:{0}", + "保留", + "還原", + "再次播放", + "此效果會在預覽和已發布的網站中播放。", + "系統要求減少動態效果,因此這裡不會播放任何內容。", + "保留前先在頁面上試用選項", + "按一下的選項會顯示在頁面上,按「保留」後才會儲存。關閉此項後,選項會立即儲存。", + "保留前先試用選項", + "現在按一下的選項會顯示在頁面上,直到按下「保留」。", + "現在按一下的選項會立即儲存。", + "未保留:{0} 未變更。", + "此元素已在別處變更,因此已放棄試用。", + "變更遭到拒絕。", ] as readonly string[]; From c1cd8ae4c4b4bbc1e54860a52a6a495e75309461 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 05:03:40 -0500 Subject: [PATCH 08/17] fix(editor): Undo by key, menu or toolbar during a trial only puts the trial back, also on a site with no history, while an agent's undo is never used up; a pending Keep frees the field when the selection changes; Undo and Redo work from a Design list field; a Reset click and a closed trial never leave focus where Backspace removes the element; an unset trial reads Inherit; motion entries are bounded before they are played --- frontend/src/commands/keymap.ts | 3 +- frontend/src/commands/registry.ts | 8 +- frontend/src/features/motion/play.ts | 44 ++++++--- frontend/src/features/try/bar.ts | 34 ++++--- frontend/src/features/try/choice-list.ts | 41 +++++++- frontend/src/features/try/index.ts | 113 ++++++++++++++++++----- frontend/src/features/try/segments.ts | 20 ++-- frontend/src/main.ts | 9 +- frontend/src/styles/try-bar.css | 2 +- frontend/src/styles/try-list.css | 7 +- 10 files changed, 200 insertions(+), 81 deletions(-) diff --git a/frontend/src/commands/keymap.ts b/frontend/src/commands/keymap.ts index 48bb8283..49d30e88 100644 --- a/frontend/src/commands/keymap.ts +++ b/frontend/src/commands/keymap.ts @@ -12,7 +12,8 @@ export function installKeymap(registry: Commands, ready: () => boolean): void { const mod = comboOf(event).includes('Mod+'); const target = event.target as Element | null; const typing = !!target?.closest?.(TYPING); - if (typing && !(mod && (command.global || target?.matches?.('select[data-style]')))) return; + const history = command.id === 'edit.undo' || command.id === 'edit.redo'; + if (typing && !(mod && (command.global || (history && target?.matches?.('select[data-style]'))))) return; if (!mod && target?.closest?.(OWN_KEYS)) return; if (command.native?.()) return; if (event.repeat && !command.repeat) { if (mod) event.preventDefault(); return; } diff --git a/frontend/src/commands/registry.ts b/frontend/src/commands/registry.ts index d77d966b..94c6c59b 100644 --- a/frontend/src/commands/registry.ts +++ b/frontend/src/commands/registry.ts @@ -164,8 +164,9 @@ export class Commands { run(id: string, params?: Record): boolean { const command = this.map.get(id); - if (!command || !this.enabled(command)) return false; + if (!command) return false; if (this.intercept?.(id)) return true; + if (!this.enabled(command)) return false; const label = this.label(command); void this.execute(() => command.run(params)); this.onRun?.(command, label); @@ -174,8 +175,9 @@ export class Commands { async call(id: string, params?: Record): Promise<{ ran: boolean; result?: unknown }> { const command = this.map.get(id); - if (!command || !this.enabled(command)) return { ran: false }; - if (this.intercept?.(id)) return { ran: true }; + if (!command) return { ran: false }; + this.intercept?.(id); + if (!this.enabled(command)) return { ran: false }; const label = this.label(command); const result = await command.run(params); this.onRun?.(command, label); diff --git a/frontend/src/features/motion/play.ts b/frontend/src/features/motion/play.ts index d80d6627..07c8ba2f 100644 --- a/frontend/src/features/motion/play.ts +++ b/frontend/src/features/motion/play.ts @@ -16,7 +16,16 @@ export interface Player { const SAFE = new Set(MOTION_SAFE); const NAMED = new Set(['linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out']); const LOOP_MAX = 2000; +const TIME_MAX = 10000; +const TOTAL_MAX = 2 * TIME_MAX; +const CHILDREN_MAX = 100; +const TEXT_MAX = 200; +const NUMBER = /-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?/gi; const kebab = (key: string): string => key.replace(/[A-Z]/g, c => '-' + c.toLowerCase()); +const bounded = (value: unknown, fallback: number, max: number): number => { + const n = Number(value); + return Number.isFinite(n) ? clamp(n, 0, max) : fallback; +}; export function playableKind(group: MotionGroup, node: SiteNode, first?: MotionKind): PlayKind | '' { const reveal = group.reveals[node.id] as { from?: Record } | undefined; @@ -33,8 +42,9 @@ function revealEase(name: unknown): Ease { } function identity(key: string, from: string): string { - const zero = (text: string): string => text.replace(/-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/gi, '0'); - const one = (text: string): string => text.replace(/-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/gi, '1'); + const zero = (text: string): string => text.replace(NUMBER, '0'); + const one = (text: string): string => text.replace(NUMBER, '1'); + if (from.length > TEXT_MAX) return ''; if (key === 'opacity') return '1'; if (key === 'scale') return one(from); if (key === 'translate' || key === 'rotate') return zero(from); @@ -103,21 +113,23 @@ export function createPlayer(canvas: Canvas, live: () => boolean): Player { function revealTracks(id: string, entry: Record, children: readonly string[]): Track[] { const from = (entry.from && typeof entry.from === 'object' ? entry.from : {}) as Record; - const keys = Object.keys(from).map(key => [kebab(key), String(from[key])] as const).filter(([key]) => SAFE.has(key)); - const duration = Math.max(0, Number(entry.duration ?? 600) || 0); - const delay = Math.max(0, Number(entry.delay || 0) || 0); - const stagger = Math.max(0, Number(entry.stagger || 0) || 0); - const ease = revealEase(entry.easing); - const targets = entry.children ? children : [id]; + const keys = Object.keys(from).map(key => [kebab(key), String(from[key])] as const).filter(([key, text]) => SAFE.has(key) && text.length <= TEXT_MAX); + const duration = bounded(entry.duration ?? 600, 600, TIME_MAX); + const delay = bounded(entry.delay ?? 0, 0, TIME_MAX); + const stagger = bounded(entry.stagger ?? 0, 0, TIME_MAX); + const ease = revealEase(typeof entry.easing === 'string' ? entry.easing.slice(0, TEXT_MAX) : entry.easing); + const targets = entry.children ? children.slice(0, CHILDREN_MAX) : [id]; const out: Track[] = []; targets.forEach((target, index) => { const el = nodeOf(target); if (!el) return; for (const [key, start] of keys) { const end = ownValue(el, key); + const begin = Math.min(delay + index * stagger, TOTAL_MAX); + if (end.length > TEXT_MAX) { out.push({ id: target, key, from: start, via: end, end, start: begin, length: duration, ease, shape: () => start }); continue; } const neutral = !el.style.getPropertyValue(key).trim() ? identity(key, start) : ''; const via = fits(start, end) ? end : neutral && fits(start, neutral) ? neutral : end; - out.push({ id: target, key, from: start, via, end, start: delay + index * stagger, length: duration, ease }); + out.push({ id: target, key, from: start, via, end, start: begin, length: duration, ease }); } }); return out; @@ -126,18 +138,20 @@ export function createPlayer(canvas: Canvas, live: () => boolean): Player { function loopTracks(id: string, entry: Record): Track[] { const el = nodeOf(id); if (!el) return []; - const amount = Number(entry.amount ?? (entry.type === 'spin' ? 360 : 12)) || 0; - const period = clamp(Number(entry.duration) || (entry.type === 'spin' ? 8000 : 4000), 100, 120000); + const raw = Number(entry.amount ?? (entry.type === 'spin' ? 360 : 12)); + const amount = Number.isFinite(raw) ? clamp(raw, -100000, 100000) : 0; + const period = clamp(bounded(entry.duration, 0, 120000) || (entry.type === 'spin' ? 8000 : 4000), 100, 120000); + const own = (key: string): string => { const text = el.style.getPropertyValue(key).trim(); return text.length > TEXT_MAX ? '' : text; }; const there = (p: number): number => 1 - Math.abs(2 * p - 1); if (entry.type === 'spin') { const end = ownValue(el, 'rotate'); - const base = Number(/^(-?(?:\d+\.?\d*|\.\d+))deg$/.exec(el.style.getPropertyValue('rotate').trim())?.[1] || 0); + const base = Number(/^(-?(?:\d+(?:\.\d*)?|\.\d+))deg$/.exec(own('rotate'))?.[1] || 0); const whole = amount % 360 === 0; return [{ id, key: 'rotate', from: `${base}deg`, via: end, end, start: 0, length: Math.min(LOOP_MAX, period), ease: easing('linear'), shape: p => `${Math.round((base + amount * (whole ? p : there(p))) * 1000) / 1000}deg` }]; } const end = ownValue(el, 'translate'); - const parts = el.style.getPropertyValue('translate').trim().split(/\s+/); - const px = (part: string | undefined): number => Number(/^(-?(?:\d+\.?\d*|\.\d+))(px)?$/.exec(part || '0')?.[1] || 0); + const parts = own('translate').split(/\s+/); + const px = (part: string | undefined): number => Number(/^(-?(?:\d+(?:\.\d*)?|\.\d+))(px)?$/.exec(part || '0')?.[1] || 0); const x = px(parts[0]), y = px(parts[1]); const ease = easing('ease-in-out'); return [{ id, key: 'translate', from: `${x}px ${y}px`, via: end, end, start: 0, length: Math.min(LOOP_MAX, period * 2), ease, shape: p => `${x}px ${Math.round((y - amount * ease(there(p))) * 1000) / 1000}px` }]; @@ -150,7 +164,7 @@ export function createPlayer(canvas: Canvas, live: () => boolean): Player { const next = kind === 'reveals' ? revealTracks(id, entry as Record, children) : loopTracks(id, entry as Record); if (!next.length) return false; tracks = next; - total = Math.max(...next.map(track => track.start + track.length)); + total = Math.min(TOTAL_MAX, next.reduce((most, track) => Math.max(most, track.start + track.length), 0)); current = id; begun = performance.now(); draw(0, false); diff --git a/frontend/src/features/try/bar.ts b/frontend/src/features/try/bar.ts index 0909bd93..2c5f5f8a 100644 --- a/frontend/src/features/try/bar.ts +++ b/frontend/src/features/try/bar.ts @@ -133,12 +133,8 @@ export function mountBar(overlay: HTMLElement, actions: TryBarActions): TryBar { const target = !anchor || !visible(anchor) ? null : anchor.matches(FOCUSABLE) ? anchor : anchor.querySelector('[data-trying]:not(:disabled)') ?? anchor.querySelector('[aria-pressed="true"]:not(:disabled)') ?? anchor.querySelector(FOCUSABLE); - if (target) { target.focus({ preventScroll: true }); return; } - for (let at = anchor?.parentElement; at && at !== document.body; at = at.parentElement) { - if (!visible(at)) continue; - const next = Array.from(at.querySelectorAll(FOCUSABLE)).find(visible); - if (next) { next.focus({ preventScroll: true }); return; } - } + const tab = target ? null : Array.from(document.querySelectorAll('.inspector-tabs button.active')).find(visible); + (target ?? tab)?.focus({ preventScroll: true }); }; const pending = (on: boolean): void => { @@ -166,6 +162,7 @@ export function mountBar(overlay: HTMLElement, actions: TryBarActions): TryBar { clip = null; last = null; shownName = ''; + text.textContent = ''; listen(false); cancelAnimationFrame(frame); frame = 0; @@ -200,21 +197,22 @@ export function mountBar(overlay: HTMLElement, actions: TryBarActions): TryBar { element: root, show(next, name) { const again = owner === next && !root.hidden; + if (!again) { + owner = next; + last = null; + clip = scroller(next.anchor); + if (root.hidden) { + root.style.left = '0px'; + root.style.top = '0px'; + root.hidden = false; + listen(true); + } + } if (shownName !== name || !again) { - label(text, 'Trying: {0}', [name]); + label(text, 'Trying: {0}', [{ t: name }]); shownName = name; } - if (again) { place(false); return; } - owner = next; - last = null; - clip = scroller(next.anchor); - if (root.hidden) { - root.style.left = '0px'; - root.style.top = '0px'; - root.hidden = false; - listen(true); - } - place(true); + place(!again); }, pending, hide, diff --git a/frontend/src/features/try/choice-list.ts b/frontend/src/features/try/choice-list.ts index 549ca243..a8daaef9 100644 --- a/frontend/src/features/try/choice-list.ts +++ b/frontend/src/features/try/choice-list.ts @@ -52,6 +52,7 @@ export function installChoiceLists(kit: TryKit, options: TryOptions): void { let frame = 0; let placedAt = ''; let made = 0; + let held: { target: Field; seen: string; frame: number } | null = null; const bar = (): HTMLElement | null => document.querySelector('[data-try-bar]'); const inBar = (node: Node | null): boolean => !!node && !!bar()?.contains(node); @@ -134,7 +135,7 @@ export function installChoiceLists(kit: TryKit, options: TryOptions): void { const shown = Math.min(height, room); let top = under ? box.bottom + GAP : box.top - GAP - shown; top = Math.max(MARGIN, Math.min(top, window.innerHeight - shown - MARGIN)); - const left = Math.max(MARGIN, Math.min(box.left, window.innerWidth - width - MARGIN)); + const left = Math.max(MARGIN, Math.min(box.left, window.innerWidth - (height > room ? pop.offsetWidth : width) - MARGIN)); pop.style.left = `${Math.round(left)}px`; pop.style.top = `${Math.round(top)}px`; } @@ -342,10 +343,46 @@ export function installChoiceLists(kit: TryKit, options: TryOptions): void { tryAt(index); }); + function follow(): void { + if (!held) return; + const { target } = held; + if (document.activeElement !== target.select) { held = null; return; } + const now = options.stored(target.key); + if (now !== held.seen) { + held.seen = now; + if (kit.enabled() && !field && target.select.value !== now) target.select.value = now; + } + held.frame = requestAnimationFrame(follow); + } + + function hold(target: Field): void { + if (held) cancelAnimationFrame(held.frame); + held = { target, seen: options.stored(target.key), frame: requestAnimationFrame(follow) }; + } + + function onward(from: HTMLElement): HTMLElement | null { + const stops = Array.from(document.querySelectorAll('a[href], button, input, select, textarea, [tabindex]')) + .filter(node => node.tabIndex >= 0 && !(node as HTMLButtonElement).disabled && !node.closest('[hidden], [inert]') && rendered(node) && !pop.contains(node) && !inBar(node)); + return stops.find(node => node !== from && !from.contains(node) && !!(from.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING)) || null; + } + + document.addEventListener('keydown', event => { + if (!field || event.key !== 'Tab' || event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return; + const at = event.target as HTMLElement; + if (!live() || trial!.pending || !inBar(at)) return; + const buttons = Array.from(bar()!.querySelectorAll('button:not(:disabled)')); + if (at !== bar() && at !== buttons.at(-1)) return; + const next = onward(field.select); + if (!next) return; + event.preventDefault(); + event.stopPropagation(); + next.focus(); + }, true); + for (const target of fields) { const { select } = target; aria(select); - select.addEventListener('focus', () => aria(select)); + select.addEventListener('focus', () => { aria(select); hold(target); }); select.addEventListener('mousedown', event => { aria(select); if (!kit.enabled() || select.disabled || event.button !== 0) return; diff --git a/frontend/src/features/try/index.ts b/frontend/src/features/try/index.ts index 92ea8250..73b4f3e1 100644 --- a/frontend/src/features/try/index.ts +++ b/frontend/src/features/try/index.ts @@ -5,9 +5,21 @@ import { installChoiceLists } from './choice-list'; import type { LayerFrame, Trial, TrialEnd, TrialOwner, TryKit, TryOptions } from './types'; const STORE = 'formweb.try-choices'; -const PASS = new Set(['edit.copy', 'view.try-choices']); +const PASS = new Set(['edit.copy', 'file.save', 'view.search', 'view.try-choices']); +const SURFACE = '.fw-menubar, .fw-menu, .fw-search-pop, [data-cmd]'; +const MENU = '.fw-menubar, .fw-menu, .fw-search-pop'; +const LANDING_MS = 30000; +const AIMED_MS = 15000; -type Live = { trial: Trial; owner: TrialOwner; node: string; scope: string; base: string; value: string | null; pending: boolean; over: boolean; end(how: TrialEnd, message?: string): void }; +type Live = { trial: Trial; owner: TrialOwner; node: string; scope: string; base: string; value: string | null; pending: boolean; over: boolean; detached: boolean; end(how: TrialEnd, message?: string): void }; + +function ended(owner: TrialOwner, how: TrialEnd): void { + try { owner.ended(how); } catch (error) { console.error(error); } +} + +function within(target: EventTarget | null, selector: string): boolean { + return target instanceof Element && !!target.closest(selector); +} function readOn(): boolean { try { return localStorage.getItem(STORE) !== '0'; } catch { return true; } @@ -26,6 +38,20 @@ export function installTry(options: TryOptions): TryKit { let liveNode = ''; let liveScope = ''; let watching = 0; + let aimed = 0; + let said = ''; + let swallowing = false; + let repeat = false; + + const say = (message: string, error = false): void => { + said = message; + options.status(message, error); + }; + const unsay = (): void => { + const line = document.querySelector('.status-message'); + if (said && line && line.textContent === said) options.status(''); + said = ''; + }; const draw = (): void => { const frame: LayerFrame = {}; @@ -43,7 +69,8 @@ export function installTry(options: TryOptions): TryKit { const editing = options.editing(); if (lives.size && (scope !== liveScope || !editing)) lives.clear(); const entry = current; - if (entry && !entry.over && !entry.pending) { + if (entry && entry.pending && (scope !== entry.scope || !editing)) retire(); + else if (entry && !entry.over && !entry.pending) { if (fromSync && options.exists && !options.exists(entry.node)) entry.end('dropped', t('The element was changed elsewhere, so the trial was dropped.')); else if (scope !== entry.scope || !editing) entry.end('dropped'); else if (fromSync && options.stored(entry.trial.key) !== entry.base) entry.end('dropped', t('The element was changed elsewhere, so the trial was dropped.')); @@ -93,6 +120,7 @@ export function installTry(options: TryOptions): TryKit { pending: false, over: false, trial: undefined as unknown as Trial, + detached: false, end(how, message) { if (entry.over) return; entry.over = true; @@ -106,15 +134,17 @@ export function installTry(options: TryOptions): TryKit { bar.hide(); } draw(); - if (message) options.status(message, how === 'refused'); - else if (how === 'reverted' && shown) options.status(t('Not kept: {0} is unchanged.', [owner.label])); - owner.ended(how); + if (message && how === 'refused') { said = ''; options.status(message, true); } + else if (message) say(message); + else if (how === 'reverted' && shown) say(t('Not kept: {0} is unchanged.', [{ t: owner.label }])); + else if (how === 'kept') unsay(); + if (!entry.detached) ended(owner, how); } }; entry.trial = { key: owner.key, - get pending() { return entry.pending; }, - get over() { return entry.over; }, + get pending() { return entry.pending && !entry.detached; }, + get over() { return entry.over || entry.detached; }, value: () => entry.value ?? options.stored(owner.key), put(value: string, name: string) { if (entry.over || entry.pending || current !== entry) return; @@ -125,18 +155,29 @@ export function installTry(options: TryOptions): TryKit { }, async keep() { if (entry.over || entry.pending) return; - if (entry.value === null) { entry.end('reverted'); return; } - if (options.scope() !== entry.scope || options.node() !== entry.node || !options.editing()) { entry.end('dropped'); return; } - const value = entry.value; - if (value.trim() === options.stored(owner.key).trim()) { entry.end('reverted'); return; } - entry.pending = true; - shelter(entry); - bar.pending(true); - let failure: unknown = null; - try { await options.setStyle(owner.key, value); } catch (error) { failure = error ?? new Error(t('The change was refused.')); } - if (entry.over) return; - if (failure) entry.end('refused', failure instanceof Error ? failure.message : String(failure)); - else entry.end('kept'); + try { + if (entry.value === null) { entry.end('reverted'); return; } + if (options.scope() !== entry.scope || options.node() !== entry.node || !options.editing()) { entry.end('dropped'); return; } + const value = entry.value; + if (value.trim() === options.stored(owner.key).trim()) { entry.end('reverted'); return; } + entry.pending = true; + shelter(entry); + bar.pending(true); + const late = setTimeout(() => { + if (entry.over || !entry.pending) return; + if (current === entry) retire(); + if (landing.delete(entry)) draw(); + }, LANDING_MS); + let failure: unknown = null; + try { await options.setStyle(owner.key, value); } catch (error) { failure = error ?? new Error(t('The change was refused.')); } + clearTimeout(late); + if (entry.over) return; + if (failure) entry.end('refused', failure instanceof Error ? failure.message : String(failure)); + else entry.end('kept'); + } catch (error) { + console.error(error); + if (!entry.over) { entry.pending = false; entry.end('dropped'); } + } }, revert() { if (entry.over || entry.pending) return; @@ -152,8 +193,11 @@ export function installTry(options: TryOptions): TryKit { if (entry.pending) { landing.add(entry); current = null; + entry.detached = true; + shelter(entry); bar.pending(false); bar.hide(); + ended(entry.owner, 'dropped'); return; } entry.trial.revert(); @@ -163,11 +207,23 @@ export function installTry(options: TryOptions): TryKit { const entry = current; if (!entry || entry.over || entry.pending) return; const target = event.target as Node | null; - if (!target || target === document.body) return; + if (!target || target === document.body || within(target, '.fw-search-pop')) return; if (bar.element.contains(target) || entry.owner.anchor.contains(target) || (entry.owner.inside?.() ?? []).some(part => part.contains(target))) return; + const shown = entry.value !== null; entry.trial.revert(); + aimed = shown && within(target, SURFACE) ? performance.now() : 0; }, true); + document.addEventListener('pointerdown', event => { if (aimed && !within(event.target, MENU)) aimed = 0; }, true); + document.addEventListener('input', event => { if (aimed && !within(event.target, MENU)) aimed = 0; }, true); + document.addEventListener('keydown', event => { + repeat = event.repeat; + const undo = (event.ctrlKey || event.metaKey) && event.code === 'KeyZ'; + if (aimed && !undo && !['Control', 'Meta', 'Shift', 'Alt'].includes(event.key) && !within(event.target, MENU)) aimed = 0; + if (!undo) swallowing = false; + }, true); + document.addEventListener('keyup', event => { if (event.code === 'KeyZ' || event.key === 'Control' || event.key === 'Meta') swallowing = false; }, true); + document.addEventListener('focusout', event => { const entry = current; const left = event.target as HTMLElement | null; @@ -187,6 +243,7 @@ export function installTry(options: TryOptions): TryKit { if (!next && current) { if (current.pending) retire(); else current.end('dropped'); } }, begin(owner: TrialOwner): Trial { + aimed = 0; retire(); const entry = create(owner); current = entry; @@ -218,11 +275,21 @@ export function installTry(options: TryOptions): TryKit { draw(); }, intercept(command: string): boolean { + if (PASS.has(command)) return false; + const undo = command === 'edit.undo'; + const wasAimed = aimed && performance.now() - aimed < AIMED_MS; + aimed = 0; + if (undo && swallowing && repeat) return true; + swallowing = false; const entry = current; - if (!entry || entry.over || entry.pending || PASS.has(command)) return false; + if (!entry || entry.over || entry.pending) { + if (undo && wasAimed) { swallowing = true; return true; } + return false; + } const shown = entry.value !== null; entry.trial.revert(); - return shown && command === 'edit.undo'; + if (undo && shown) { swallowing = true; return true; } + return false; }, sync() { check(true); } }; diff --git a/frontend/src/features/try/segments.ts b/frontend/src/features/try/segments.ts index 80f289eb..31784808 100644 --- a/frontend/src/features/try/segments.ts +++ b/frontend/src/features/try/segments.ts @@ -3,19 +3,10 @@ import type { Trial, TrialOwner, TryKit, TryOptions } from './types'; import '../../styles/try-bar.css'; const STEPS: Record = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }; -const FOCUSABLE = 'button:not(:disabled), select:not(:disabled), input:not(:disabled), [tabindex]:not([tabindex="-1"])'; - const shown = (node: HTMLElement): boolean => node.isConnected && node.getClientRects().length > 0; -function shelter(group: HTMLElement): void { - let at = group.parentElement; - while (at && at !== document.body) { - if (shown(at)) { - const next = Array.from(at.querySelectorAll(FOCUSABLE)).find(node => !group.contains(node) && shown(node)); - if (next) { next.focus({ preventScroll: true }); return; } - } - at = at.parentElement; - } +function shelter(): void { + Array.from(document.querySelectorAll('.inspector-tabs button.active')).find(shown)?.focus({ preventScroll: true }); } function installGroup(kit: TryKit, options: TryOptions, key: string, buttons: HTMLButtonElement[]): void { @@ -49,7 +40,10 @@ function installGroup(kit: TryKit, options: TryOptions, key: string, buttons: HT if (trial !== mine) return; trial = null; unmark(); - if (group.contains(document.activeElement) && !shown(document.activeElement as HTMLElement)) shelter(group); + if (group.contains(document.activeElement) && !shown(document.activeElement as HTMLElement)) { + const stay = buttons.find(button => button.getAttribute('aria-pressed') === 'true' && shown(button)) ?? buttons.find(button => !button.disabled && shown(button)); + if (stay) stay.focus({ preventScroll: true }); else shelter(); + } } }; const mine = kit.begin(owner); @@ -60,7 +54,7 @@ function installGroup(kit: TryKit, options: TryOptions, key: string, buttons: HT const put = (button: HTMLButtonElement | null): void => { const current = live() ?? start(); mark(button); - current.put(button ? button.dataset.value || '' : '', button ? (button.textContent || '').trim() : t('None')); + current.put(button ? button.dataset.value || '' : '', button ? (button.textContent || '').trim() : t('Inherit')); }; const usable = (): HTMLButtonElement[] => buttons.filter(button => !button.disabled && shown(button)); diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 146e02f5..6ff4cba0 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -493,6 +493,7 @@ const inspectorTag = element('div', 'inspector-tag'); inspectorLabel.append(inspectorName, inspectorTag); inspectorIdentity.append(icon('box'), inspectorLabel, collapseButton({ command: 'window.toggle-right', label: 'Collapse right panel', icon: 'chevronsRight' })); const inspectorTabs = element('div', 'inspector-tabs'); +inspectorTabs.dataset.ownKeys = ''; const inspectorTabButtons = new Map(); for (const id of ['design', 'motion', 'content', 'page']) { const node = button(id[0].toUpperCase() + id.slice(1), undefined, () => setInspector(id), 'quiet'); @@ -570,7 +571,13 @@ function resetButton(label: string, key: string): HTMLButtonElement { labelAttr(reset, 'aria-label', 'Reset {0} to the inherited value', [{ t: label }]); reset.dataset.reset = key; reset.hidden = true; - reset.addEventListener('click', event => { event.preventDefault(); event.stopPropagation(); void run(() => setStyle(key, '')); }); + reset.addEventListener('click', event => { + event.preventDefault(); + event.stopPropagation(); + const segments = segmentFields.get(key); + (styleFields.get(key) ?? segments?.find(node => node.classList.contains('is-on')) ?? segments?.[0])?.focus({ preventScroll: true }); + void run(() => setStyle(key, '')); + }); resetButtons.set(key, reset); return reset; } diff --git a/frontend/src/styles/try-bar.css b/frontend/src/styles/try-bar.css index 7cc5f691..07a4d976 100644 --- a/frontend/src/styles/try-bar.css +++ b/frontend/src/styles/try-bar.css @@ -8,7 +8,7 @@ .fw-try-revert { border-color: var(--line-2); background: transparent; color: var(--text-primary); } .fw-try-key { position: relative; color: var(--text-muted); font-size: var(--fs-11); font-weight: 400; letter-spacing: 0.04em; font-variant-numeric: tabular-nums; } .fw-try-btn:disabled { opacity: 0.55; } -.fw-try-wait { position: absolute; top: 50%; left: 50%; width: 14px; height: 14px; margin: -7px 0 0 -7px; color: var(--accent-ink); visibility: hidden; } +.fw-try-wait { position: absolute; top: 50%; left: 50%; width: var(--space-4); height: var(--space-4); margin: calc(var(--space-4) / -2) 0 0 calc(var(--space-4) / -2); color: var(--accent-ink); visibility: hidden; } .fw-try-bar.is-waiting .fw-try-keep .fw-try-key { color: transparent; } .fw-try-bar.is-waiting .fw-try-wait { visibility: visible; animation: fw-try-turn 1.2s linear infinite; } @keyframes fw-try-turn { to { transform: rotate(360deg); } } diff --git a/frontend/src/styles/try-list.css b/frontend/src/styles/try-list.css index cfdfdcfb..0ffd573e 100644 --- a/frontend/src/styles/try-list.css +++ b/frontend/src/styles/try-list.css @@ -1,13 +1,12 @@ -.fw-tlist { position: fixed; top: 0; left: 0; z-index: var(--z-popover); box-sizing: border-box; display: flex; flex-direction: column; gap: 1px; min-width: 120px; max-width: calc(100vw - var(--space-4)); max-height: calc(100vh - var(--space-4)); overflow-y: auto; overscroll-behavior: contain; scrollbar-width: none; padding: var(--space-1); pointer-events: auto; border: 1px solid var(--line-2); border-radius: var(--radius-xl); background: color-mix(in srgb, var(--surface-2) 94%, transparent); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); box-shadow: var(--shadow-lg); color: var(--text-primary); font-size: var(--fs-12); outline: none; } -.fw-tlist::-webkit-scrollbar { display: none; } +.fw-tlist { position: fixed; top: 0; left: 0; z-index: var(--z-popover); box-sizing: border-box; display: flex; flex-direction: column; gap: 1px; min-width: calc(var(--ctl-xl) * 3); max-width: calc(100vw - var(--space-4)); max-height: calc(100vh - var(--space-4)); overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; scrollbar-color: var(--line-3) transparent; padding: var(--space-1); pointer-events: auto; border: 1px solid var(--line-2); border-radius: var(--radius-xl); background: color-mix(in srgb, var(--surface-2) 94%, transparent); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); box-shadow: var(--shadow-lg); color: var(--text-primary); font-size: var(--fs-12); outline: none; } .fw-tlist[hidden] { display: none; } -.fw-tlist-row { display: grid; flex: none; grid-template-columns: 16px minmax(0, 1fr); align-items: center; column-gap: var(--space-2); height: var(--ctl-md); padding: 0 var(--space-3) 0 var(--space-1); border-radius: var(--radius); color: var(--text-secondary); white-space: nowrap; cursor: default; user-select: none; } +.fw-tlist-row { display: grid; flex: none; grid-template-columns: var(--check-size) minmax(0, 1fr); align-items: center; column-gap: var(--space-2); height: var(--ctl-md); padding: 0 var(--space-3) 0 var(--space-1); border-radius: var(--radius); color: var(--text-secondary); white-space: nowrap; cursor: default; user-select: none; } .fw-tlist-row:hover { background: var(--bg-hover); color: var(--text-primary); } .fw-tlist-row[aria-selected='true'] { background: var(--accent-wash); color: var(--text-primary); } .fw-tlist-row[data-trying] { background: var(--accent-soft); outline: 1px solid var(--accent-line); outline-offset: -1px; } .fw-tlist:focus-visible .fw-tlist-row.is-active { outline: 2px solid var(--accent-color); outline-offset: -2px; } -.fw-tlist-tick { display: inline-flex; align-items: center; justify-content: center; width: 16px; height: 16px; color: var(--accent-color); visibility: hidden; } +.fw-tlist-tick { display: inline-flex; align-items: center; justify-content: center; width: var(--check-size); height: var(--check-size); color: var(--accent-color); visibility: hidden; } .fw-tlist-row[data-stored] .fw-tlist-tick { visibility: visible; } .fw-tlist-name { overflow: hidden; text-overflow: ellipsis; } .fw-tlist[aria-busy='true'] .fw-tlist-row { cursor: progress; } From eb89cdc02917f6500db0e8a53e0f7854e20df605 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 06:35:11 -0500 Subject: [PATCH 09/17] fix(inspector): the try bar stays inside the panel of its field in two rows and cuts a long name with an ellipsis, a Keep on the value already stored ends without a sentence, the Preview note under the presets shows only when nothing can be played, and a section title keeps Delete and Backspace to itself --- frontend/src/features/motion/presets.ts | 11 ++--------- frontend/src/features/try/bar.ts | 21 +++++++++++++++------ frontend/src/features/try/index.ts | 2 +- frontend/src/main.ts | 1 + frontend/src/styles/try-bar.css | 13 +++++++------ 5 files changed, 26 insertions(+), 22 deletions(-) diff --git a/frontend/src/features/motion/presets.ts b/frontend/src/features/motion/presets.ts index 4bfee451..c1c5f0cc 100644 --- a/frontend/src/features/motion/presets.ts +++ b/frontend/src/features/motion/presets.ts @@ -75,7 +75,6 @@ export function installPresets(ctx: MotionContext, container: HTMLElement): Moti let current: SiteNode | undefined; let parent = ''; let latest: EditorState | undefined; - let laterFor = ''; let playedAt = -1; let playedIn = ''; const reduced = window.matchMedia('(prefers-reduced-motion: reduce)'); @@ -121,7 +120,6 @@ export function installPresets(ctx: MotionContext, container: HTMLElement): Moti void ctx.set(preset.kind, node.id, entry).then(() => { if (!current || current.id !== node.id || !latest) return; if (!matches(preset, current, ctx.motion(latest)[preset.kind][node.id])) return; - laterFor = shows ? '' : node.id; refresh(); if (!shows || still()) return; const at = latest.revision; @@ -145,11 +143,7 @@ export function installPresets(ctx: MotionContext, container: HTMLElement): Moti const attrs: Record = { ...node.attrs, 'data-fw-effect': on ? null : preset.effect }; if (on) attrs['data-fw-effect-speed'] = null; player.stop(); - void ctx.run(() => ctx.nodePatch({ attrs })).then(() => { - if (on || !current || current.id !== node.id || current.attrs['data-fw-effect'] !== preset.effect) return; - laterFor = node.id; - refresh(); - }); + void ctx.run(() => ctx.nodePatch({ attrs })); }); effectGroup.append(choice); return { preset, choice }; @@ -183,7 +177,7 @@ export function installPresets(ctx: MotionContext, container: HTMLElement): Moti const id = current.id; const elsewhere = !!current.attrs['data-fw-effect'] || (['text', 'counters', 'pointer'] as const).some(kind => !!group[kind][id]) || (!!loop && loop.type !== 'spin' && loop.type !== 'float'); const quiet = still(); - const said = quiet ? REDUCED : elsewhere && (!playable || laterFor === current.id) ? SHOWN_LATER : ''; + const said = quiet ? REDUCED : elsewhere && !playable ? SHOWN_LATER : ''; if (said) label(note, said); else if (note.textContent) note.textContent = ''; const off = quiet || !playable; @@ -207,7 +201,6 @@ export function installPresets(ctx: MotionContext, container: HTMLElement): Moti update(next, node) { const playing = player.playing(); if (playing && (playing !== node.id || next.revision !== playedAt || viewOf() !== playedIn || !live())) player.stop(); - if (current?.id !== node.id) laterFor = ''; latest = next; current = node; const owner = Object.values(next.site.nodes).find(candidate => candidate.children.includes(node.id)); diff --git a/frontend/src/features/try/bar.ts b/frontend/src/features/try/bar.ts index 2c5f5f8a..9e6c69db 100644 --- a/frontend/src/features/try/bar.ts +++ b/frontend/src/features/try/bar.ts @@ -65,7 +65,7 @@ export function mountBar(overlay: HTMLElement, actions: TryBarActions): TryBar { text.setAttribute('aria-live', 'polite'); const keep = button('Keep', 'Enter', 'fw-try-keep'); const revert = button('Revert', 'Escape', 'fw-try-revert'); - keep.querySelector('.fw-try-key')!.append(spinner()); + keep.append(spinner()); root.append(text, keep, revert); overlay.append(root); @@ -74,6 +74,7 @@ export function mountBar(overlay: HTMLElement, actions: TryBarActions): TryBar { let shownName = ''; let last: Box | null = null; let width = 0; + let edge = 0; let frame = 0; let waiting = 0; let busy = false; @@ -87,10 +88,17 @@ export function mountBar(overlay: HTMLElement, actions: TryBarActions): TryBar { const place = (force: boolean): void => { if (!owner) return; const anchor = boxOf(owner.anchor); - const size = root.offsetWidth; - if (!force && same(last, anchor) && size === width) return; + const panel = (clip ?? owner.anchor.parentElement ?? owner.anchor).getBoundingClientRect(); + const size = Math.round(Math.min(panel.width - 2 * GAP, window.innerWidth - 2 * MARGIN)); + if (!force && same(last, anchor) && size === width && panel.left === edge) return; last = anchor; - width = size; + edge = panel.left; + if (size !== width || force) { + width = size; + root.style.width = `${size}px`; + root.classList.remove('is-tight'); + if (root.scrollWidth > root.clientWidth) root.classList.add('is-tight'); + } const height = root.offsetHeight; const keepClear = { ...anchor }; for (const node of owner.inside?.() ?? []) { @@ -110,7 +118,7 @@ export function mountBar(overlay: HTMLElement, actions: TryBarActions): TryBar { if (anchor.bottom <= view.top) top = Math.max(top, view.top + GAP); else if (anchor.top >= view.bottom) top = Math.min(top, view.bottom - height - GAP); } - const left = Math.max(MARGIN, Math.min(anchor.left, window.innerWidth - size - MARGIN)); + const left = Math.max(MARGIN, Math.min(panel.left + GAP, window.innerWidth - size - MARGIN)); const x = `${Math.round(left)}px`; const y = `${Math.round(top)}px`; if (root.style.left !== x) root.style.left = x; @@ -200,7 +208,7 @@ export function mountBar(overlay: HTMLElement, actions: TryBarActions): TryBar { if (!again) { owner = next; last = null; - clip = scroller(next.anchor); + clip = scroller(next.anchor) ?? (next.inside?.() ?? []).map(scroller).find(Boolean) ?? null; if (root.hidden) { root.style.left = '0px'; root.style.top = '0px'; @@ -210,6 +218,7 @@ export function mountBar(overlay: HTMLElement, actions: TryBarActions): TryBar { } if (shownName !== name || !again) { label(text, 'Trying: {0}', [{ t: name }]); + labelAttr(text, 'title', 'Trying: {0}', [{ t: name }]); shownName = name; } place(!again); diff --git a/frontend/src/features/try/index.ts b/frontend/src/features/try/index.ts index 73b4f3e1..ff6bc5bb 100644 --- a/frontend/src/features/try/index.ts +++ b/frontend/src/features/try/index.ts @@ -159,7 +159,7 @@ export function installTry(options: TryOptions): TryKit { if (entry.value === null) { entry.end('reverted'); return; } if (options.scope() !== entry.scope || options.node() !== entry.node || !options.editing()) { entry.end('dropped'); return; } const value = entry.value; - if (value.trim() === options.stored(owner.key).trim()) { entry.end('reverted'); return; } + if (value.trim() === options.stored(owner.key).trim()) { entry.value = null; unsay(); entry.end('reverted'); return; } entry.pending = true; shelter(entry); bar.pending(true); diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 6ff4cba0..3de8c517 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -141,6 +141,7 @@ function section(container: HTMLElement, title: string, hint = ''): HTMLElement if (hint) { const note = element('span', 'hint'); label(note, hint); head.append(note); head.classList.toggle('has-note', hint.length > NOTE_BELOW); } head.setAttribute('role', 'button'); head.tabIndex = 0; + head.dataset.ownKeys = ''; head.setAttribute('aria-expanded', 'true'); const toggle = (): void => { const collapsed = node.classList.toggle('is-collapsed'); head.setAttribute('aria-expanded', String(!collapsed)); }; head.addEventListener('click', event => { if (!(event.target as Element).closest('button, input, select, a')) toggle(); }); diff --git a/frontend/src/styles/try-bar.css b/frontend/src/styles/try-bar.css index 07a4d976..6b901cff 100644 --- a/frontend/src/styles/try-bar.css +++ b/frontend/src/styles/try-bar.css @@ -1,15 +1,16 @@ -.fw-try-bar { position: fixed; top: 0; left: 0; z-index: var(--z-popover); box-sizing: border-box; display: flex; align-items: center; gap: var(--space-1); width: max-content; max-width: calc(100vw - var(--space-4)); padding: var(--space-1) var(--space-1) var(--space-1) var(--space-3); pointer-events: auto; border: 1px solid var(--line-2); border-radius: var(--radius-lg); background: color-mix(in srgb, var(--surface-2) 94%, transparent); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); box-shadow: var(--shadow-lg); color: var(--text-primary); font-size: var(--fs-12); white-space: nowrap; } +.fw-try-bar { position: fixed; top: 0; left: 0; z-index: var(--z-popover); box-sizing: border-box; display: grid; grid-template-columns: minmax(0, 1fr) auto auto; align-items: center; gap: var(--space-1); max-width: calc(100vw - var(--space-4)); padding: var(--space-1) var(--space-1) var(--space-1) var(--space-2); pointer-events: auto; border: 1px solid var(--line-2); border-radius: var(--radius-lg); background: color-mix(in srgb, var(--surface-2) 94%, transparent); -webkit-backdrop-filter: var(--glass-filter); backdrop-filter: var(--glass-filter); box-shadow: var(--shadow-lg); color: var(--text-primary); font-size: var(--fs-12); white-space: nowrap; } .fw-try-bar[hidden] { display: none; } .fw-try-bar:focus { outline: none; } -.fw-try-text { flex: 0 1 auto; min-width: 0; max-width: 18em; margin-right: var(--space-1); overflow: hidden; text-overflow: ellipsis; color: var(--text-secondary); } -.fw-try-btn { flex: none; min-height: 0; height: var(--ctl-sm); padding: 0 var(--space-2); gap: var(--space-2); border-radius: var(--radius); font-size: var(--fs-12); } -.fw-try-keep { border-color: var(--accent-line); background: var(--accent-soft); color: var(--accent-ink); font-weight: 600; } +.fw-try-text { grid-column: 1 / -1; min-width: 0; padding: var(--space-1) var(--space-1) 0; overflow: hidden; text-overflow: ellipsis; color: var(--text-secondary); } +.fw-try-btn { position: relative; flex: none; min-height: 0; height: var(--ctl-sm); padding: 0 var(--space-2); gap: var(--space-2); border-radius: var(--radius); font-size: var(--fs-12); } +.fw-try-keep { grid-column: 2; border-color: var(--accent-line); background: var(--accent-soft); color: var(--accent-ink); font-weight: 600; } .fw-try-keep:hover:not(:disabled) { background: color-mix(in srgb, var(--accent-color) 26%, var(--surface-2)); } .fw-try-revert { border-color: var(--line-2); background: transparent; color: var(--text-primary); } -.fw-try-key { position: relative; color: var(--text-muted); font-size: var(--fs-11); font-weight: 400; letter-spacing: 0.04em; font-variant-numeric: tabular-nums; } +.fw-try-key { color: var(--text-muted); font-size: var(--fs-11); font-weight: 400; letter-spacing: 0.04em; font-variant-numeric: tabular-nums; } +.fw-try-bar.is-tight .fw-try-key { display: none; } .fw-try-btn:disabled { opacity: 0.55; } .fw-try-wait { position: absolute; top: 50%; left: 50%; width: var(--space-4); height: var(--space-4); margin: calc(var(--space-4) / -2) 0 0 calc(var(--space-4) / -2); color: var(--accent-ink); visibility: hidden; } -.fw-try-bar.is-waiting .fw-try-keep .fw-try-key { color: transparent; } +.fw-try-bar.is-waiting .fw-try-keep > span { color: transparent; } .fw-try-bar.is-waiting .fw-try-wait { visibility: visible; animation: fw-try-turn 1.2s linear infinite; } @keyframes fw-try-turn { to { transform: rotate(360deg); } } @media (prefers-reduced-motion: reduce) { .fw-try-bar.is-waiting .fw-try-wait { animation: none; } } From b73bff9d26372af42b3cd66da067b1a45fbcec9c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 07:32:41 -0500 Subject: [PATCH 10/17] fix(editor): a pointer press on the canvas ends a trial, also on the element that is already selected, so a double-click into its text no longer edits under a tried value --- frontend/src/features/try/index.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/frontend/src/features/try/index.ts b/frontend/src/features/try/index.ts index ff6bc5bb..23d8d911 100644 --- a/frontend/src/features/try/index.ts +++ b/frontend/src/features/try/index.ts @@ -214,6 +214,14 @@ export function installTry(options: TryOptions): TryKit { aimed = shown && within(target, SURFACE) ? performance.now() : 0; }, true); + const host = options.canvas as Partial<{ frame: HTMLIFrameElement; loaded(): Promise }>; + void host.loaded?.().then(() => { + host.frame?.contentDocument?.addEventListener('pointerdown', () => { + const entry = current; + if (entry && !entry.over && !entry.pending && entry.value !== null) entry.trial.revert(); + }, true); + }); + document.addEventListener('pointerdown', event => { if (aimed && !within(event.target, MENU)) aimed = 0; }, true); document.addEventListener('input', event => { if (aimed && !within(event.target, MENU)) aimed = 0; }, true); document.addEventListener('keydown', event => { From ce786be37b2b0431a9e729d8f98ecd4e8d9dffe5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 08:35:57 -0500 Subject: [PATCH 11/17] fix(inspector): a Reset click empties the field as it takes the focus, so the text box no longer keeps showing the cleared value --- frontend/src/main.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 3de8c517..a5b15372 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -576,7 +576,9 @@ function resetButton(label: string, key: string): HTMLButtonElement { event.preventDefault(); event.stopPropagation(); const segments = segmentFields.get(key); - (styleFields.get(key) ?? segments?.find(node => node.classList.contains('is-on')) ?? segments?.[0])?.focus({ preventScroll: true }); + const control = styleFields.get(key); + (control ?? segments?.find(node => node.classList.contains('is-on')) ?? segments?.[0])?.focus({ preventScroll: true }); + if (control) control.value = ''; void run(() => setStyle(key, '')); }); resetButtons.set(key, reset); From b09abac2396e79c0235963bcc55dc848984f6562 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 08:35:58 -0500 Subject: [PATCH 12/17] test(editor): the canvas layers through render and setLayer (which layer wins, an empty value under each breakpoint, the same node before and after, refused values) and the preset player through its exported functions (the last frame equals the stored look and the layer is then cleared, delay, stagger, loops, every stop, entries with endless or broken times always end) (38 tests) --- frontend/tests/unit/canvas/layers.test.ts | 153 +++++++++++++ frontend/tests/unit/motion/play.test.ts | 255 ++++++++++++++++++++++ 2 files changed, 408 insertions(+) create mode 100644 frontend/tests/unit/canvas/layers.test.ts create mode 100644 frontend/tests/unit/motion/play.test.ts diff --git a/frontend/tests/unit/canvas/layers.test.ts b/frontend/tests/unit/canvas/layers.test.ts new file mode 100644 index 00000000..9b2c18fb --- /dev/null +++ b/frontend/tests/unit/canvas/layers.test.ts @@ -0,0 +1,153 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { Canvas } from '../../../src/ui/canvas'; +import type { Site } from '../../../src/types'; +import { makeSite } from '../site'; + +const BREAKPOINTS = [{ id: 'desktop', name: 'Desktop', maxWidth: 100000 }, { id: 'tablet', name: 'Tablet', maxWidth: 991 }, { id: 'mobile', name: 'Mobile', maxWidth: 767 }]; + +function siteWith(styles: Record, breakpoints: Record> = {}): Site { + const site = makeSite([{ id: 'home', name: 'Home', slug: '/', root: 'root' }], { + root: { tag: 'main', children: ['box', 'other'] }, + box: { tag: 'div', styles }, + other: { tag: 'p', styles: { color: 'olive' } } + }); + site.breakpoints = BREAKPOINTS.map(breakpoint => ({ ...breakpoint })); + site.nodes.box.breakpoints = structuredClone(breakpoints); + return site; +} + +let stage: HTMLElement | undefined; +afterEach(() => { stage?.remove(); stage = undefined; }); + +async function drawn(site: Site, scope = ''): Promise<{ canvas: Canvas; node: () => HTMLElement }> { + stage = document.createElement('div'); + const canvas = new Canvas(stage, () => undefined, () => undefined); + document.body.append(stage); + canvas.render(site, site.pages[0], '', 1280, 'en', scope); + await canvas.loaded(); + const doc = canvas.frame.contentDocument!; + return { canvas, node: () => doc.querySelector('[data-fw-id="box"]')! }; +} + +const own = (node: HTMLElement, property: string): string => node.style.getPropertyValue(property); + +describe('a trial layer on the canvas', () => { + it('a trial value shows on the element and clearing the layer puts back exactly the stored value', async () => { + const { canvas, node } = await drawn(siteWith({ textAlign: 'left', color: 'red' })); + const stored = node().getAttribute('style'); + expect(own(node(), 'text-align')).toBe('left'); + canvas.setLayer('trial', { box: { 'text-align': 'center' } }); + expect(own(node(), 'text-align')).toBe('center'); + expect(own(node(), 'color')).toBe('red'); + canvas.setLayer('trial', null); + expect(own(node(), 'text-align')).toBe('left'); + expect(node().getAttribute('style')).toBe(stored); + }); + + it('a layer value for a property the element does not store is removed again when the layer is cleared', async () => { + const { canvas, node } = await drawn(siteWith({ color: 'red' })); + const stored = node().getAttribute('style'); + canvas.setLayer('play', { box: { opacity: '0.25' } }); + expect(own(node(), 'opacity')).toBe('0.25'); + canvas.setLayer('play', null); + expect(own(node(), 'opacity')).toBe(''); + expect(node().getAttribute('style')).toBe(stored); + }); + + it('a layer changes only the element it names', async () => { + const { canvas } = await drawn(siteWith({ color: 'red' })); + const other = canvas.frame.contentDocument!.querySelector('[data-fw-id="other"]')!; + const before = other.getAttribute('style'); + canvas.setLayer('trial', { box: { color: 'blue' } }); + expect(other.getAttribute('style')).toBe(before); + }); + + it('the trial layer wins over the play layer, which wins over the motion frame, which wins over the stored value', async () => { + const { canvas, node } = await drawn(siteWith({ opacity: '0.1' })); + canvas.setMotionFrame({ box: { opacity: '0.2' } }); + expect(own(node(), 'opacity')).toBe('0.2'); + canvas.setLayer('play', { box: { opacity: '0.3' } }); + expect(own(node(), 'opacity')).toBe('0.3'); + canvas.setLayer('trial', { box: { opacity: '0.4' } }); + expect(own(node(), 'opacity')).toBe('0.4'); + canvas.setLayer('play', { box: { opacity: '0.35' } }); + expect(own(node(), 'opacity')).toBe('0.4'); + canvas.setMotionFrame({ box: { opacity: '0.25' } }); + expect(own(node(), 'opacity')).toBe('0.4'); + canvas.setLayer('trial', null); + expect(own(node(), 'opacity')).toBe('0.35'); + canvas.setLayer('play', null); + expect(own(node(), 'opacity')).toBe('0.25'); + canvas.setMotionFrame(null); + expect(own(node(), 'opacity')).toBe('0.1'); + }); + + it('a null value under a narrower breakpoint shows what the wider breakpoint stores', async () => { + const { canvas, node } = await drawn(siteWith({ color: 'red' }, { tablet: { color: 'blue' }, mobile: { color: 'green' } }), 'mobile'); + expect(own(node(), 'color')).toBe('green'); + canvas.setLayer('trial', { box: { color: null } }); + expect(own(node(), 'color')).toBe('blue'); + canvas.setLayer('trial', null); + expect(own(node(), 'color')).toBe('green'); + }); + + it('a null value under a narrower breakpoint with nothing stored above it falls back to the base value', async () => { + const { canvas, node } = await drawn(siteWith({ color: 'red' }, { tablet: { color: 'blue' } }), 'tablet'); + expect(own(node(), 'color')).toBe('blue'); + canvas.setLayer('trial', { box: { color: null } }); + expect(own(node(), 'color')).toBe('red'); + }); + + it('a null value at the base breakpoint leaves the element with no own value for that property', async () => { + const { canvas, node } = await drawn(siteWith({ color: 'red', opacity: '0.5' })); + canvas.setLayer('trial', { box: { color: null } }); + expect(own(node(), 'color')).toBe(''); + expect(own(node(), 'opacity')).toBe('0.5'); + canvas.setLayer('trial', null); + expect(own(node(), 'color')).toBe('red'); + }); + + it('setting and clearing a layer keeps the same element object, parent and place on the canvas', async () => { + const { canvas, node } = await drawn(siteWith({ color: 'red' })); + const before = node(); + const parent = before.parentElement; + const index = Array.from(parent!.children).indexOf(before); + canvas.setLayer('trial', { box: { color: 'blue', display: 'flex' } }); + canvas.setLayer('play', { box: { opacity: '0' } }); + expect(node()).toBe(before); + canvas.setLayer('trial', null); + canvas.setLayer('play', null); + expect(node()).toBe(before); + expect(before.parentElement).toBe(parent); + expect(Array.from(parent!.children).indexOf(before)).toBe(index); + }); + + it.each([ + ['a url() value', '--picture', 'url(https://example.invalid/a.png)'], + ['a url() holding a javascript: address', '--link', 'url(javascript:alert(1))'], + ['an expression()', '--size', 'expression(alert(1))'] + ])('%s that the canvas refuses as a stored style is refused in a layer too', async (_what, property, value) => { + const { canvas, node } = await drawn(siteWith({ '--plain': '4px', [property]: value })); + expect(own(node(), '--plain')).toBe('4px'); + expect(own(node(), property)).toBe(''); + canvas.setLayer('trial', { box: { '--plain': '8px', [property]: value } }); + expect(own(node(), '--plain')).toBe('8px'); + expect(own(node(), property)).toBe(''); + canvas.setLayer('play', { box: { [property]: value } }); + expect(own(node(), property)).toBe(''); + }); + + it('a new stored value drawn while a layer is on stays under the layer and shows once the layer is cleared', async () => { + const site = siteWith({ color: 'red' }); + const { canvas, node } = await drawn(site); + const before = node(); + canvas.setLayer('trial', { box: { color: 'blue' } }); + const next = structuredClone(site); + next.nodes.box.styles.color = 'purple'; + canvas.render(next, next.pages[0], '', 1280, 'en', ''); + expect(own(node(), 'color')).toBe('blue'); + canvas.setLayer('trial', null); + expect(own(node(), 'color')).toBe('purple'); + expect(node()).toBe(before); + }); +}); diff --git a/frontend/tests/unit/motion/play.test.ts b/frontend/tests/unit/motion/play.test.ts new file mode 100644 index 00000000..4c77d164 --- /dev/null +++ b/frontend/tests/unit/motion/play.test.ts @@ -0,0 +1,255 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createPlayer } from '../../../src/features/motion/play'; +import type { Canvas } from '../../../src/ui/canvas'; + +type Frame = Record> | null; + +const TWO_MINUTES = 120_000; + +function recorder(): { canvas: Canvas; sent: Frame[] } { + const sent: Frame[] = []; + const canvas = { frame: { contentDocument: document }, setLayer: (name: string, frame: Frame) => { if (name === 'play') sent.push(frame === null ? null : structuredClone(frame)); } }; + return { canvas: canvas as unknown as Canvas, sent }; +} + +function element(id: string, style = ''): HTMLElement { + const node = document.createElement('div'); + node.dataset.fwId = id; + node.setAttribute('style', style); + document.body.append(node); + return node; +} + +const reveal = (from: Record, extra: Record = {}): Record => ({ from, duration: 600, delay: 0, stagger: 0, children: false, easing: 'ease-out', ...extra }); +const drawnFrames = (sent: Frame[]): Record>[] => sent.filter((frame): frame is NonNullable => frame !== null); +const lastDrawn = (sent: Frame[]): NonNullable => drawnFrames(sent).at(-1)!; +const opacityOf = (frame: NonNullable, id: string): number => Number(frame[id]?.opacity); + +beforeEach(() => { + vi.useFakeTimers({ toFake: ['requestAnimationFrame', 'cancelAnimationFrame', 'performance', 'setTimeout', 'clearTimeout', 'Date'] }); +}); + +afterEach(() => { + vi.useRealTimers(); + document.body.replaceChildren(); +}); + +describe('playing a reveal once on the canvas', () => { + it('a fade up starts at its from values and its last frame is exactly the stored look, then the layer is cleared', () => { + element('box', 'opacity: 0.8; translate: 4px 2px'); + const { canvas, sent } = recorder(); + const player = createPlayer(canvas, () => true); + expect(player.play('box', 'reveals', reveal({ opacity: '0', translate: '0 24px' }), [])).toBe(true); + expect(player.playing()).toBe('box'); + expect(sent[0]).toEqual({ box: { opacity: '0', translate: '0 24px' } }); + vi.advanceTimersByTime(TWO_MINUTES); + expect(sent.at(-1)).toBeNull(); + expect(lastDrawn(sent)).toEqual({ box: { opacity: '0.8', translate: '4px 2px' } }); + expect(player.playing()).toBe(''); + const between = drawnFrames(sent).map(frame => opacityOf(frame, 'box')).filter(value => value > 0 && value < 0.8); + expect(between.length).toBeGreaterThan(0); + }); + + it('the opacity of an ease-out fade only rises on its way from the from value to the stored value', () => { + element('box', 'opacity: 0.6'); + const { canvas, sent } = recorder(); + createPlayer(canvas, () => true).play('box', 'reveals', reveal({ opacity: '0' }), []); + vi.advanceTimersByTime(TWO_MINUTES); + const values = drawnFrames(sent).map(frame => opacityOf(frame, 'box')); + expect(values[0]).toBe(0); + expect(values.at(-1)).toBe(0.6); + values.forEach((value, index) => { if (index) expect(value).toBeGreaterThanOrEqual(values[index - 1]); }); + }); + + it('nothing more is sent to the canvas once the layer has been cleared', () => { + element('box', 'opacity: 1'); + const { canvas, sent } = recorder(); + createPlayer(canvas, () => true).play('box', 'reveals', reveal({ opacity: '0' }), []); + vi.advanceTimersByTime(TWO_MINUTES); + const count = sent.length; + vi.advanceTimersByTime(TWO_MINUTES); + expect(sent.length).toBe(count); + expect(sent.at(-1)).toBeNull(); + }); + + it('a delay holds the element at its from look before it moves', () => { + element('box', 'opacity: 1'); + const { canvas, sent } = recorder(); + createPlayer(canvas, () => true).play('box', 'reveals', reveal({ opacity: '0' }, { delay: 1000 }), []); + vi.advanceTimersByTime(900); + expect(new Set(drawnFrames(sent).map(frame => frame.box.opacity))).toEqual(new Set(['0'])); + vi.advanceTimersByTime(TWO_MINUTES); + expect(lastDrawn(sent)).toEqual({ box: { opacity: '1' } }); + expect(sent.at(-1)).toBeNull(); + }); + + it('stagger children plays each child after the one before it and ends with every child at its stored look', () => { + const kids = ['one', 'two', 'three']; + kids.forEach(id => element(id, 'opacity: 0.9')); + element('list'); + const { canvas, sent } = recorder(); + createPlayer(canvas, () => true).play('list', 'reveals', reveal({ opacity: '0' }, { children: true, stagger: 200 }), kids); + vi.advanceTimersByTime(TWO_MINUTES); + const frames = drawnFrames(sent); + const firstMoved = kids.map(id => frames.findIndex(frame => opacityOf(frame, id) > 0)); + expect(firstMoved[0]).toBeGreaterThan(-1); + expect(firstMoved[1]).toBeGreaterThan(firstMoved[0]); + expect(firstMoved[2]).toBeGreaterThan(firstMoved[1]); + for (const frame of frames) { + expect(opacityOf(frame, 'one')).toBeGreaterThanOrEqual(opacityOf(frame, 'two')); + expect(opacityOf(frame, 'two')).toBeGreaterThanOrEqual(opacityOf(frame, 'three')); + } + expect(lastDrawn(sent)).toEqual({ one: { opacity: '0.9' }, two: { opacity: '0.9' }, three: { opacity: '0.9' } }); + expect(sent.at(-1)).toBeNull(); + }); +}); + +describe('looping presets shown once', () => { + it('spin turns the element and ends at the rotation it started from, then the layer is cleared', () => { + element('box', 'rotate: 15deg'); + const { canvas, sent } = recorder(); + createPlayer(canvas, () => true).play('box', 'loops', { type: 'spin', duration: 8000, amount: 360, easing: 'linear' }, []); + vi.advanceTimersByTime(TWO_MINUTES); + const angles = drawnFrames(sent).map(frame => parseFloat(frame.box.rotate!)); + expect(angles.some(angle => angle > 100)).toBe(true); + expect(lastDrawn(sent)).toEqual({ box: { rotate: '15deg' } }); + expect(sent.at(-1)).toBeNull(); + }); + + it('float moves the element and ends where it began, then the layer is cleared', () => { + element('box', 'translate: 0px 10px'); + const { canvas, sent } = recorder(); + createPlayer(canvas, () => true).play('box', 'loops', { type: 'float', duration: 3000, amount: 12, easing: 'ease-in-out' }, []); + vi.advanceTimersByTime(TWO_MINUTES); + expect(drawnFrames(sent).some(frame => frame.box.translate !== '0px 10px')).toBe(true); + expect(lastDrawn(sent)).toEqual({ box: { translate: '0px 10px' } }); + expect(sent.at(-1)).toBeNull(); + }); +}); + +describe('stopping a playback', () => { + it('stop clears the layer at once and nothing more is drawn afterwards', () => { + element('box', 'opacity: 1'); + const { canvas, sent } = recorder(); + const player = createPlayer(canvas, () => true); + player.play('box', 'reveals', reveal({ opacity: '0' }, { duration: 5000 }), []); + vi.advanceTimersByTime(1000); + expect(opacityOf(lastDrawn(sent), 'box')).toBeLessThan(1); + player.stop(); + expect(sent.at(-1)).toBeNull(); + expect(player.playing()).toBe(''); + const count = sent.length; + vi.advanceTimersByTime(TWO_MINUTES); + expect(sent.length).toBe(count); + }); + + it('when the canvas stops being shown during playback the layer is cleared on the next frame', () => { + element('box', 'opacity: 1'); + const { canvas, sent } = recorder(); + let shown = true; + createPlayer(canvas, () => shown).play('box', 'reveals', reveal({ opacity: '0' }, { duration: 5000 }), []); + vi.advanceTimersByTime(1000); + expect(opacityOf(lastDrawn(sent), 'box')).toBeLessThan(1); + shown = false; + vi.advanceTimersByTime(100); + expect(sent.at(-1)).toBeNull(); + const count = sent.length; + vi.advanceTimersByTime(TWO_MINUTES); + expect(sent.length).toBe(count); + }); + + it('nothing is drawn when the canvas is not being shown', () => { + element('box', 'opacity: 1'); + const { canvas, sent } = recorder(); + expect(createPlayer(canvas, () => false).play('box', 'reveals', reveal({ opacity: '0' }), [])).toBe(false); + vi.advanceTimersByTime(TWO_MINUTES); + expect(sent).toEqual([]); + }); + + it('a second play restarts from the from values and still ends at the stored look', () => { + element('box', 'opacity: 0.7'); + const { canvas, sent } = recorder(); + const player = createPlayer(canvas, () => true); + player.play('box', 'reveals', reveal({ opacity: '0' }, { duration: 2000 }), []); + vi.advanceTimersByTime(1000); + const at = sent.length; + player.play('box', 'reveals', reveal({ opacity: '0' }, { duration: 2000 }), []); + expect(sent.slice(at)).toEqual([null, { box: { opacity: '0' } }]); + vi.advanceTimersByTime(TWO_MINUTES); + expect(lastDrawn(sent)).toEqual({ box: { opacity: '0.7' } }); + expect(sent.at(-1)).toBeNull(); + }); +}); + +describe('a hostile motion entry still ends with the stored look', () => { + it.each([ + ['a duration of 1e12', { duration: 1e12 }], + ['an infinite duration', { duration: Infinity }], + ['a duration that is not a number', { duration: NaN }], + ['a duration written as text', { duration: 'Infinity' }], + ['a negative duration', { duration: -5 }], + ['a delay of 1e12', { delay: 1e12 }], + ['an infinite delay', { delay: Infinity }], + ['a negative infinite delay', { delay: -Infinity }], + ['an easing name of 50,000 letters', { easing: 'e'.repeat(50_000) }] + ])('%s ends within two minutes with the layer cleared', (_what, extra) => { + element('box', 'opacity: 0.8'); + const { canvas, sent } = recorder(); + const player = createPlayer(canvas, () => true); + player.play('box', 'reveals', reveal({ opacity: '0' }, extra), []); + vi.advanceTimersByTime(TWO_MINUTES); + expect(sent.at(-1)).toBeNull(); + expect(lastDrawn(sent)).toEqual({ box: { opacity: '0.8' } }); + expect(player.playing()).toBe(''); + }); + + it('a from text of 50,000 characters ends within two minutes with the layer cleared and the other properties at their stored look', () => { + element('box', 'opacity: 0.8; translate: 4px 2px; filter: blur(1px)'); + const { canvas, sent } = recorder(); + const long = '1'.repeat(50_000); + const player = createPlayer(canvas, () => true); + player.play('box', 'reveals', reveal({ opacity: '0', translate: `${long}px 0`, filter: `blur(${long}px)` }), []); + vi.advanceTimersByTime(TWO_MINUTES); + expect(sent.at(-1)).toBeNull(); + const last = lastDrawn(sent); + expect(last.box.opacity).toBe('0.8'); + for (const [key, value] of Object.entries(last.box)) expect(value).toBe({ opacity: '0.8', translate: '4px 2px', filter: 'blur(1px)' }[key]); + expect(player.playing()).toBe(''); + }); + + it.each([ + ['2,000 children with a stagger of 1e9', { stagger: 1e9 }], + ['2,000 children with an infinite stagger and a duration of 1e12', { stagger: Infinity, duration: 1e12 }], + ['2,000 children with an ordinary stagger', { stagger: 80 }] + ])('%s end within two minutes with every child drawn at its stored look and the layer cleared', (_what, extra) => { + const kids = Array.from({ length: 2000 }, (_, index) => `kid-${index}`); + kids.forEach(id => element(id, 'opacity: 0.5')); + element('list'); + const { canvas, sent } = recorder(); + const player = createPlayer(canvas, () => true); + player.play('list', 'reveals', reveal({ opacity: '0' }, { children: true, ...extra }), kids); + vi.advanceTimersByTime(TWO_MINUTES); + expect(sent.at(-1)).toBeNull(); + const last = lastDrawn(sent); + expect(Object.keys(last).length).toBeGreaterThan(0); + for (const [id, values] of Object.entries(last)) { + expect(kids).toContain(id); + expect(values).toEqual({ opacity: '0.5' }); + } + expect(player.playing()).toBe(''); + }); + + it.each([ + ['spin with an infinite amount and a negative duration', { type: 'spin', amount: Infinity, duration: -5 }, 'rotate', '15deg', 'rotate: 15deg'], + ['float with an amount of 1e300 and a duration that is not a number', { type: 'float', amount: 1e300, duration: NaN }, 'translate', '0px 10px', 'translate: 0px 10px'] + ])('%s ends within two minutes where it began', (_what, entry, key, stored, style) => { + element('box', style); + const { canvas, sent } = recorder(); + const player = createPlayer(canvas, () => true); + player.play('box', 'loops', entry, []); + vi.advanceTimersByTime(TWO_MINUTES); + expect(sent.at(-1)).toBeNull(); + expect(lastDrawn(sent)).toEqual({ box: { [key]: stored } }); + expect(player.playing()).toBe(''); + }); +}); From a4d578f404ce71428b67e806f9cd22268e8d72d0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 08:35:58 -0500 Subject: [PATCH 13/17] test(window): trying a choice in the real window: segment groups and the bar, the list fields, every way a trial ends without writing, Undo by key, menu and toolbar, a slow and a refused Keep, values shown on the page while a slider, the color picker or a gradient stop is dragged, motion presets played once and stopped, the switch, and Delete and Backspace never removing an element from a choice, a list, the bar, a tab, a section title or after Reset (134 tests) --- frontend/tests/window/test_motion_play.py | 426 +++++++++ frontend/tests/window/test_try_choices.py | 1023 +++++++++++++++++++++ frontend/tests/window/test_try_drags.py | 699 ++++++++++++++ frontend/tests/window/test_try_lists.py | 584 ++++++++++++ 4 files changed, 2732 insertions(+) create mode 100644 frontend/tests/window/test_motion_play.py create mode 100644 frontend/tests/window/test_try_choices.py create mode 100644 frontend/tests/window/test_try_drags.py create mode 100644 frontend/tests/window/test_try_lists.py diff --git a/frontend/tests/window/test_motion_play.py b/frontend/tests/window/test_motion_play.py new file mode 100644 index 00000000..db6701b6 --- /dev/null +++ b/frontend/tests/window/test_motion_play.py @@ -0,0 +1,426 @@ +import re + +import pytest +from playwright.sync_api import expect + +OWN_CHANGE = re.compile(r"/api/(command|batch)$") +TARGET = "hero-h" +STORED_OPACITY = "0.8" +KEYS = ("opacity", "translate", "scale", "rotate", "filter") +KINDS = ("reveals", "loops", "text", "counters", "pointer") +PLAYS_IN_PREVIEW = "This effect plays in Preview and on the published site." +REDUCED = "Your system asks for reduced motion, so nothing is played here." +NOT_SHOWN = ("Split words", "Split characters", "Typewriter", "Count up", "Marquee left", "Marquee right", "Tilt", "Follow pointer") +LONG = {"from": {"opacity": "0", "translate": "0 24px"}, "duration": 10000, "delay": 10000, "stagger": 0, "children": False, "easing": "linear", "trigger": "view"} +LOOK = """(ids, keys) => { + const doc = document.querySelector('iframe[title="Website canvas"]').contentDocument; + return ids.map(id => { + const el = doc.querySelector(`[data-fw-id="${id}"]`); + if (!el) return null; + const shown = getComputedStyle(el); + return [el.getAttribute('style') || '', ...keys.map(key => shown.getPropertyValue(key)), ...keys.map(key => el.style.getPropertyValue(key))]; + }); +}""" +WATCH = f"""([ids, keys]) => {{ + const look = {LOOK}; + const frame = document.querySelector('iframe[title="Website canvas"]'); + const doc = frame.contentDocument; + const generation = window.__motionWatch = (window.__motionWatch || 0) + 1; + window.__looks = []; + window.__canvas = []; + const tick = () => {{ + if (generation !== window.__motionWatch) return; + window.__looks.push(look(ids, keys)); + window.__canvas.push([doc.querySelectorAll('script').length, doc.querySelectorAll('style').length, doc.getAnimations().length, frame.getAttribute('sandbox'), doc.querySelector('meta[http-equiv="Content-Security-Policy"]')?.getAttribute('content')]); + requestAnimationFrame(tick); + }}; + requestAnimationFrame(tick); +}}""" +SETTLED_LOOK = f"""async ([ids, keys]) => {{ + await new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done))); + return ({LOOK})(ids, keys); +}}""" + + +def select(editor, node): + editor.layer_row(node).click() + expect(editor.page.locator(".inspector-tag")).to_have_text(re.compile(rf"· {re.escape(node)}$")) + + +def open_motion(editor): + editor.page.locator(".inspector button.quiet", has_text="Motion").click() + expect(presets(editor)).to_be_visible() + + +def presets(editor): + return editor.page.get_by_role("group", name="Motion presets") + + +def preset(editor, name): + return presets(editor).get_by_role("button", name=name, exact=True) + + +def play_again(editor): + return editor.page.get_by_role("button", name="Play again", exact=True) + + +def note(editor): + return play_again(editor).locator("xpath=following-sibling::*[@aria-live]") + + +def motion_of(site, node): + group = site.get("extensions", {}).get("motion", {}) + return {kind: group[kind][node] for kind in KINDS if node in group.get(kind, {})} + + +def clear_motion(editor, nodes): + site = editor.site()["site"] + found = [{"command": "motion.remove", "params": {"kind": kind, "node": node}} for node in nodes for kind in motion_of(site, node)] + if found: + editor.command(None, found, batch=True) + editor.until(lambda s: not any(motion_of(s, node) for node in nodes), f"the motion of {nodes} to be removed") + + +def revision(editor): + return editor.site()["revision"] + + +def look(editor, ids=(TARGET,)): + return editor.page.evaluate(SETTLED_LOOK, [list(ids), list(KEYS)]) + + +def watch(editor, ids=(TARGET,)): + editor.page.evaluate(WATCH, [list(ids), list(KEYS)]) + + +def looks(editor): + return editor.page.evaluate("window.__looks") + + +def shown(entry, key): + return entry[1 + KEYS.index(key)] + + +def own(entry, key): + return entry[1 + len(KEYS) + KEYS.index(key)] + + +def computed_and_own(entry): + return entry[1:] + + +def fainter(entry): + return entry is not None and float(shown(entry, "opacity")) < float(STORED_OPACITY) + + +def wait_for_play_and_rest(editor, rest, moved, what, ids=(TARGET,)): + editor.eventually(lambda: any(moved(frame) for frame in looks(editor)), f"{what} to be seen moving on the canvas") + editor.eventually(lambda: looks(editor)[-1] == rest, f"{what} to end at the stored look") + assert look(editor, ids) == rest, f"{what} did not stay at the stored look" + return looks(editor) + + +def open_view_menu_item(editor, command): + editor.page.locator('[data-menu="View"]').click() + editor.page.locator(f'[role="menu"]:visible [data-command="{command}"]').click() + + +@pytest.fixture +def heading(harbour): + clear_motion(harbour, [TARGET]) + harbour.command("node.update", {"id": TARGET, "patch": {"styles": {"opacity": STORED_OPACITY}}}) + harbour.until(lambda site: site["nodes"][TARGET]["styles"].get("opacity") == STORED_OPACITY, "the heading to store an opacity of 0.8") + select(harbour, TARGET) + open_motion(harbour) + return harbour + + +@pytest.fixture +def playing(heading): + heading.command("motion.set", {"kind": "reveals", "node": TARGET, "value": LONG}) + heading.until(lambda site: motion_of(site, TARGET).get("reveals", {}).get("delay") == LONG["delay"], "the long reveal to be stored") + expect(play_again(heading)).to_be_enabled() + rest = look(heading) + watch(heading) + play_again(heading).click() + heading.eventually(lambda: any(fainter(frame[0]) for frame in looks(heading)), "the long reveal to be playing") + return heading, rest + + +def test_a_click_on_fade_up_sets_it_with_one_revision_and_plays_it_once_from_faint_and_lower_to_exactly_the_stored_look(heading): + rest = look(heading) + assert shown(rest[0], "opacity") == STORED_OPACITY and shown(rest[0], "translate") == "none" + before = revision(heading) + watch(heading) + preset(heading, "Fade up").click() + site = heading.until(lambda s: "reveals" in motion_of(s, TARGET), "Fade up to be stored") + assert motion_of(site, TARGET)["reveals"]["from"] == {"opacity": "0", "translate": "0 24px"} + assert revision(heading) == before + 1 + expect(preset(heading, "Fade up")).to_have_attribute("aria-pressed", "true") + frames = wait_for_play_and_rest(heading, rest, lambda frame: fainter(frame[0]) and shown(frame[0], "translate") not in ("none", "0px", "0px 0px"), "Fade up") + lower = [frame[0] for frame in frames if frame[0] != rest[0]] + assert all(float(shown(entry, "translate").split()[-1].rstrip("px")) >= 0 for entry in lower if shown(entry, "translate") != "none"), "the element moved up instead of rising from below" + assert revision(heading) == before + 1 + + +def test_play_again_replays_the_motion_and_the_revision_does_not_change(heading): + rest = look(heading) + preset(heading, "Fade up").click() + heading.until(lambda s: "reveals" in motion_of(s, TARGET), "Fade up to be stored") + expect(play_again(heading)).to_be_enabled() + heading.eventually(lambda: look(heading) == rest, "the first playback to end") + before = heading.until(lambda s: True, "the window to show the newest revision") + count = revision(heading) + watch(heading) + play_again(heading).click() + wait_for_play_and_rest(heading, rest, lambda frame: fainter(frame[0]), "Play again") + assert revision(heading) == count + assert heading.site()["site"] == before + expect(heading.page.locator("footer.statusbar .status-revision")).to_contain_text(re.compile(rf"\brev {count}\b")) + + +def test_each_reveal_preset_plays_its_own_movement_and_ends_at_the_stored_look(heading): + rest = look(heading) + moves = { + "Fade in": lambda e: fainter(e), + "Scale in": lambda e: fainter(e) and shown(e, "scale") not in ("none", "1"), + "Blur in": lambda e: fainter(e) and "blur" in shown(e, "filter"), + "Slide from left": lambda e: fainter(e) and shown(e, "translate").startswith("-"), + "Slide from right": lambda e: fainter(e) and re.match(r"^[1-9]", shown(e, "translate")) is not None, + } + for name, moved in moves.items(): + before = revision(heading) + watch(heading) + preset(heading, name).click() + expect(preset(heading, name)).to_have_attribute("aria-pressed", "true") + assert revision(heading) == before + 1, name + wait_for_play_and_rest(heading, rest, lambda frame: moved(frame[0]), name) + + +def test_stagger_children_plays_the_children_one_after_another_and_each_ends_at_its_stored_look(harbour): + parent = "hero-copy" + kids = harbour.site()["site"]["nodes"][parent]["children"] + assert len(kids) >= 3 + clear_motion(harbour, [parent, *kids]) + select(harbour, parent) + open_motion(harbour) + rest = look(harbour, kids) + watch(harbour, kids) + preset(harbour, "Stagger children").click() + harbour.until(lambda s: motion_of(s, parent).get("reveals", {}).get("children") is True, "Stagger children to be stored") + harbour.eventually(lambda: any(all(fainter(entry) or float(shown(entry, "opacity")) < 1 for entry in frame) for frame in looks(harbour)), "the children to start faint") + harbour.eventually(lambda: looks(harbour)[-1] == rest, "every child to end at its stored look") + frames = looks(harbour) + start = next(i for i, frame in enumerate(frames) if all(float(shown(entry, "opacity")) == 0 for entry in frame)) + first_move = [next((i for i in range(start, len(frames)) if float(shown(frames[i][k], "opacity")) > 0), None) for k in range(len(kids))] + assert None not in first_move, f"a child never moved: {dict(zip(kids, first_move))}" + assert first_move == sorted(first_move) and first_move[0] < first_move[-1], f"the children did not start one after another: {dict(zip(kids, first_move))}" + assert look(harbour, kids) == rest + + +@pytest.mark.parametrize("name, key", [("Spin", "rotate"), ("Float", "translate")]) +def test_a_spin_or_float_shows_its_movement_for_a_while_and_stops_where_it_began(heading, name, key): + rest = look(heading) + watch(heading) + preset(heading, name).click() + heading.until(lambda s: motion_of(s, TARGET).get("loops", {}).get("type") == name.lower(), f"{name} to be stored") + frames = wait_for_play_and_rest(heading, rest, lambda frame: shown(frame[0], key) not in ("none", shown(rest[0], key)), name) + assert len({shown(frame[0], key) for frame in frames}) > 2, f"{name} showed no movement" + + +def test_a_preset_that_cannot_be_shown_on_the_canvas_is_still_set_and_the_row_says_it_plays_in_preview(heading): + rest = look(heading) + expect(play_again(heading)).to_be_disabled() + watch(heading) + for name in NOT_SHOWN: + before = revision(heading) + preset(heading, name).click() + expect(preset(heading, name)).to_have_attribute("aria-pressed", "true") + assert revision(heading) == before + 1, name + expect(note(heading)).to_have_text(PLAYS_IN_PREVIEW) + expect(play_again(heading)).to_be_disabled() + preset(heading, name).click() + expect(preset(heading, name)).to_have_attribute("aria-pressed", "false") + heading.until(lambda s: not motion_of(s, TARGET), "every effect to be removed again") + assert all(frame == rest for frame in looks(heading)), "the canvas changed for an effect that only plays in Preview" + preset(heading, "Fade in").click() + wait_for_play_and_rest(heading, rest, lambda frame: fainter(frame[0]), "Fade in") + expect(note(heading)).to_have_text("") + + +def test_with_reduced_motion_a_click_sets_the_preset_nothing_plays_play_again_is_off_and_the_row_says_why(heading): + rest = look(heading) + watch(heading) + preset(heading, "Fade in").click() + heading.until(lambda s: "reveals" in motion_of(s, TARGET), "Fade in to be stored") + wait_for_play_and_rest(heading, rest, lambda frame: fainter(frame[0]), "Fade in without reduced motion") + expect(play_again(heading)).to_be_enabled() + preset(heading, "Fade in").click() + heading.until(lambda s: not motion_of(s, TARGET), "Fade in to be removed") + heading.page.emulate_media(reduced_motion="reduce") + expect(note(heading)).to_have_text(REDUCED) + watch(heading) + before = revision(heading) + preset(heading, "Fade up").click() + heading.until(lambda s: "reveals" in motion_of(s, TARGET), "Fade up to be stored under reduced motion") + assert revision(heading) == before + 1 + expect(preset(heading, "Fade up")).to_have_attribute("aria-pressed", "true") + expect(play_again(heading)).to_be_disabled() + expect(note(heading)).to_have_text(REDUCED) + heading.page.evaluate("() => new Promise(done => { let n = 0; const tick = () => ++n > 30 ? done() : requestAnimationFrame(tick); requestAnimationFrame(tick); })") + frames = looks(heading) + assert frames and all(frame[0] == rest[0] for frame in frames), "the canvas moved under reduced motion" + + +def test_turning_on_reduced_motion_during_playback_stops_it_at_once_and_focus_stays_off_the_page_body(playing): + editor, rest = playing + expect(play_again(editor)).to_be_focused() + editor.page.emulate_media(reduced_motion="reduce") + expect(note(editor)).to_have_text(REDUCED) + assert look(editor) == rest + expect(play_again(editor)).to_be_disabled() + assert editor.page.evaluate("document.activeElement !== document.body") + editor.page.emulate_media(reduced_motion="no-preference") + expect(note(editor)).to_have_text("") + expect(play_again(editor)).to_be_enabled() + + +def _select_other(editor): + select(editor, "hero-p") + + +def _tablet(editor): + editor.page.get_by_role("combobox", name="Responsive breakpoint").select_option("tablet") + expect(editor.page.get_by_role("combobox", name="Responsive breakpoint")).to_have_value("tablet") + + +def _live_preview(editor): + open_view_menu_item(editor, "view.preview") + + +def _full_preview(editor): + editor.page.keyboard.press("Control+Shift+P") + expect(editor.page.get_by_role("dialog", name="Preview as published")).to_be_visible() + + +def _undo(editor): + count = revision(editor) + editor.undo() + editor.until(lambda s: "reveals" not in motion_of(s, TARGET), "the undo to remove the long reveal") + assert revision(editor) != count + + +def _outside_style(editor): + editor.command("node.update", {"id": TARGET, "patch": {"styles": {"color": "rgb(200, 0, 0)"}}}) + editor.until(lambda s: s["nodes"][TARGET]["styles"].get("color") == "rgb(200, 0, 0)", "the outside change to be drawn") + + +def _outside_motion(editor): + editor.command("motion.set", {"kind": "reveals", "node": TARGET, "value": dict(LONG, duration=9000)}) + editor.until(lambda s: motion_of(s, TARGET)["reveals"]["duration"] == 9000, "the outside motion change to be drawn") + + +def _page_and_back(editor): + editor.page_row("p-fares").click() + expect(editor.page_row("p-fares")).to_have_attribute("aria-current", "page") + expect(editor.canvas.locator(f'[data-fw-id="{TARGET}"]')).to_be_hidden() + editor.page_row("home").click() + expect(editor.page_row("home")).to_have_attribute("aria-current", "page") + expect(editor.canvas.locator(f'[data-fw-id="{TARGET}"]')).to_be_visible() + + +@pytest.mark.parametrize("interrupt", [_select_other, _tablet, _live_preview, _full_preview, _undo, _outside_style, _outside_motion, _page_and_back], + ids=["selection", "breakpoint", "live-preview", "full-preview", "undo", "outside-style", "outside-motion", "page"]) +def test_a_playback_stops_at_once_and_the_page_shows_the_stored_look_when(playing, interrupt): + editor, rest = playing + interrupt(editor) + now = look(editor)[0] + assert now is not None + assert computed_and_own(now)[:len(KEYS)] == computed_and_own(rest[0])[:len(KEYS)], f"after the interruption the canvas shows {dict(zip(KEYS, computed_and_own(now)))}" + assert computed_and_own(now)[len(KEYS):] == computed_and_own(rest[0])[len(KEYS):], f"the play layer left inline values {dict(zip(KEYS, own_values(now)))}" + editor.page.evaluate("() => new Promise(done => { let n = 0; const tick = () => ++n > 10 ? done() : requestAnimationFrame(tick); requestAnimationFrame(tick); })") + later = look(editor)[0] + assert computed_and_own(later) == computed_and_own(now), "the playback came back after the interruption" + + +def own_values(entry): + return [own(entry, key) for key in KEYS] + + +def test_another_preset_click_during_playback_shows_the_stored_look_at_once_and_then_plays_the_new_one(playing): + editor, rest = playing + held = [] + editor.page.route(OWN_CHANGE, lambda route: held.append(route)) + preset(editor, "Fade in").click() + editor.eventually(lambda: len(held) == 1, "the Fade in command to be sent") + assert look(editor) == rest + watch(editor) + held.pop().continue_() + editor.page.unroute(OWN_CHANGE) + editor.until(lambda s: motion_of(s, TARGET)["reveals"]["from"] == {"opacity": "0"}, "Fade in to be stored") + frames = wait_for_play_and_rest(editor, rest, lambda frame: fainter(frame[0]), "Fade in") + assert all(shown(frame[0], "translate") == "none" for frame in frames), "Fade in moved the element" + + +def test_clicking_the_active_preset_removes_it_and_nothing_plays(heading): + rest = look(heading) + watch(heading) + preset(heading, "Fade up").click() + heading.until(lambda s: "reveals" in motion_of(s, TARGET), "Fade up to be stored") + wait_for_play_and_rest(heading, rest, lambda frame: fainter(frame[0]), "Fade up") + before = revision(heading) + watch(heading) + preset(heading, "Fade up").click() + heading.until(lambda s: not motion_of(s, TARGET), "Fade up to be removed") + assert revision(heading) == before + 1 + expect(preset(heading, "Fade up")).to_have_attribute("aria-pressed", "false") + expect(play_again(heading)).to_be_disabled() + heading.page.evaluate("() => new Promise(done => { let n = 0; const tick = () => ++n > 30 ? done() : requestAnimationFrame(tick); requestAnimationFrame(tick); })") + assert all(frame == rest for frame in looks(heading)), "something played after the preset was removed" + + +def test_blur_in_shows_as_active_after_it_is_clicked(heading): + preset(heading, "Blur in").click() + heading.until(lambda s: motion_of(s, TARGET).get("reveals", {}).get("from") == {"filter": "blur(12px)", "opacity": "0"}, "Blur in to be stored") + expect(preset(heading, "Blur in")).to_have_attribute("aria-pressed", "true") + expect(presets(heading).locator('[aria-pressed="true"]')).to_have_count(1) + + +def test_the_canvas_holds_no_script_no_added_style_sheet_and_no_animation_and_keeps_its_policy_while_a_preset_plays(heading): + rest = look(heading) + watch(heading) + heading.page.evaluate("() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))") + idle = heading.page.evaluate("window.__canvas")[0] + assert idle[0] == 0 and idle[2] == 0 and idle[3] and idle[4] + preset(heading, "Fade up").click() + heading.until(lambda s: "reveals" in motion_of(s, TARGET), "Fade up to be stored") + frames = wait_for_play_and_rest(heading, rest, lambda frame: fainter(frame[0]), "Fade up") + canvas = heading.page.evaluate("window.__canvas") + during = [canvas[i] for i, frame in enumerate(frames[:len(canvas)]) if frame[0] != rest[0]] + assert during, "no frame of the playback was seen" + assert all(entry == idle for entry in canvas), f"the canvas document changed: {[entry for entry in canvas if entry != idle][:3]} against {idle}" + + +def test_nothing_else_in_the_window_moves_while_a_preset_plays_at_four_times_slower_cpu(heading): + rest = look(heading) + cdp = heading.page.context.new_cdp_session(heading.page) + cdp.send("Emulation.setCPUThrottlingRate", {"rate": 4}) + heading.page.evaluate("""() => { + const again = [...document.querySelectorAll('button')].find(b => b.textContent.trim() === 'Play again'); + const parts = [document.querySelector('[role="group"][aria-label="Motion presets"]'), ...document.querySelectorAll('[role="group"][aria-label="Motion presets"] button'), + again, again.parentElement.querySelector('[aria-live]'), document.querySelector('iframe[title="Website canvas"]'), document.querySelector('.inspector-tag')]; + window.__boxes = []; + const tick = () => { window.__boxes.push(JSON.stringify(parts.map(p => { const r = p.getBoundingClientRect(); return [r.x, r.y, r.width, r.height]; }))); requestAnimationFrame(tick); }; + requestAnimationFrame(tick); + }""") + watch(heading) + preset(heading, "Fade up").click() + heading.until(lambda s: "reveals" in motion_of(s, TARGET), "Fade up to be stored") + wait_for_play_and_rest(heading, rest, lambda frame: fainter(frame[0]), "Fade up") + watch(heading) + play_again(heading).click() + wait_for_play_and_rest(heading, rest, lambda frame: fainter(frame[0]), "Play again") + cdp.send("Emulation.setCPUThrottlingRate", {"rate": 1}) + boxes = heading.page.evaluate("window.__boxes") + assert len(boxes) > 5 + assert len(set(boxes)) == 1, f"the window took {len(set(boxes))} different layouts while the preset played" diff --git a/frontend/tests/window/test_try_choices.py b/frontend/tests/window/test_try_choices.py new file mode 100644 index 00000000..853afe6a --- /dev/null +++ b/frontend/tests/window/test_try_choices.py @@ -0,0 +1,1023 @@ +import hashlib +import io +import json +import re +import urllib.request +import zipfile + +import pytest +from playwright.sync_api import expect + +OWN_CHANGE = re.compile(r"/api/(command|batch)$") +QUIET = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(done))))" +LOOK = "(node, prop) => getComputedStyle(node).getPropertyValue(prop)" +FIELD_BOXES = """() => [...document.querySelectorAll('.inspector .field')].filter(node => node.getClientRects().length).map(node => { + const scroller = node.closest('.inspector-scroll'); + const origin = scroller.getBoundingClientRect(); + const box = node.getBoundingClientRect(); + return [box.x - origin.x, box.y - origin.y + scroller.scrollTop, box.width, box.height]; +})""" +RECORD = """(node) => { + window.__seen = []; + const frame = document.querySelector('iframe[title="Website canvas"]'); + const look = () => { + if (window.__seen === null) return; + const target = frame.contentDocument.querySelector(`[data-fw-id="${node}"]`); + window.__seen.push(target ? getComputedStyle(target).textAlign : 'gone'); + requestAnimationFrame(look); + }; + requestAnimationFrame(look); +}""" +STOP = "() => { const seen = window.__seen; window.__seen = null; return seen; }" +REST = "() => new Promise(done => { let left = 30; const tick = () => (--left ? requestAnimationFrame(tick) : done()); requestAnimationFrame(tick); })" +WATCH = """() => { + window.__before = 0; + window.__after = 0; + window.__framesBefore = 0; + const look = () => { + const ready = document.body && document.body.classList.contains('app-ready'); + if (!ready) window.__framesBefore += 1; + for (const el of document.querySelectorAll('[data-try-bar]')) { + const box = el.getBoundingClientRect(); + if (box.width > 0 && box.height > 0 && el.checkVisibility({ opacityProperty: true, visibilityProperty: true })) { + if (ready) window.__after += 1; else window.__before += 1; + } + } + requestAnimationFrame(look); + }; + requestAnimationFrame(look); +}""" +NOT_KEPT = "Not kept: Text alignment is unchanged." +ELSEWHERE = "The element was changed elsewhere, so the trial was dropped." +SWITCH = "Try choices on the page before keeping them" + + +class Changes: + def __init__(self, editor): + self.editor = editor + self.sent = [] + self.done = [] + editor.page.on("request", lambda r: self.sent.append(r) if OWN_CHANGE.search(r.url) else None) + editor.page.on("requestfinished", lambda r: self.done.append(r) if OWN_CHANGE.search(r.url) else None) + editor.page.on("requestfailed", lambda r: self.done.append(r) if OWN_CHANGE.search(r.url) else None) + + def settled(self): + self.editor.page.evaluate(QUIET) + self.editor.eventually(lambda: len(self.done) == len(self.sent), "every change the window sent to be answered") + return self.editor.until(lambda site: True, "the window to show the newest revision") + + def bodies(self): + return [r.post_data_json for r in self.sent] + + +def select(editor, node): + editor.layer_row(node).click() + expect(editor.page.locator(".inspector-tag")).to_have_text(re.compile(rf"· {re.escape(node)}$")) + + +def group(editor, label="Text alignment"): + return editor.page.get_by_role("group", name=label, exact=True) + + +def segment(editor, name, label="Text alignment"): + return group(editor, label).get_by_role("button", name=name, exact=True) + + +def bar(editor): + return editor.page.locator("[data-try-bar]") + + +def keep_button(editor): + return bar(editor).get_by_role("button", name=re.compile(r"^Keep\b")) + + +def revert_button(editor): + return bar(editor).get_by_role("button", name=re.compile(r"^Revert\b")) + + +def look(editor, node, prop="text-align"): + return editor.canvas.locator(f'[data-fw-id="{node}"]').evaluate(LOOK, prop) + + +def shows(editor, node, value, prop="text-align"): + editor.eventually(lambda: look(editor, node, prop) == value, f"{node} to show {prop} {value} on the page (it shows {look(editor, node, prop)!r})") + + +def styles(site, node, breakpoint="desktop"): + item = site["nodes"][node] + return item["styles"] if breakpoint == "desktop" else item.get("breakpoints", {}).get(breakpoint, {}) + + +def stored(editor, node, key="text-align", breakpoint="desktop"): + return styles(editor.site()["site"], node, breakpoint).get(key) + + +def open_menu(editor, menu, command): + editor.page.locator(f'[data-menu="{menu}"]').click() + return editor.page.locator(f'[role="menu"]:visible [data-command="{command}"]') + + +def open_preferences(editor): + open_menu(editor, "Edit", "edit.settings").click() + dialog = editor.page.get_by_role("dialog", name="Preferences") + dialog.get_by_role("tab", name="Interface").click() + return dialog + + +def export_files(editor): + with urllib.request.urlopen(editor.base + "/api/export", timeout=60) as reply: + archive = zipfile.ZipFile(io.BytesIO(reply.read())) + return {name: hashlib.sha256(archive.read(name)).hexdigest() for name in archive.namelist()} + + +def outside(editor, node, style): + editor.command("node.update", {"id": node, "patch": {"styles": style}}) + + +def hold_changes(editor): + held = [] + editor.page.route(OWN_CHANGE, lambda route: held.append(route)) + return held + + +def try_center(editor, node="hero-h"): + segment(editor, "Center").click() + shows(editor, node, "center") + expect(bar(editor)).to_be_visible() + expect(bar(editor)).to_contain_text("Trying: Center") + + +@pytest.fixture +def heading(harbour): + select(harbour, "hero-h") + shows(harbour, "hero-h", "start") + return harbour + + +@pytest.fixture +def trial(heading): + changes = Changes(heading) + before = heading.site() + try_center(heading) + return heading, changes, before + + +def nothing_written(editor, changes, before): + after = changes.settled() + assert [r.post_data_json for r in changes.sent] == [], "the window sent a change" + assert editor.site()["revision"] == before["revision"] + assert after == before["site"] + + +def test_a_click_on_a_segment_shows_the_choice_on_the_page_and_writes_nothing(trial): + editor, changes, before = trial + assert look(editor, "hero-p") == "start" + nothing_written(editor, changes, before) + assert stored(editor, "hero-h") is None + expect(editor.page.locator("footer.statusbar .status-revision")).to_contain_text(re.compile(rf"\brev {before['revision']}\b")) + + +def test_the_bar_names_the_tried_choice_and_the_tried_segment_looks_unlike_the_stored_and_the_others(heading): + outside(heading, "hero-h", {"text-align": "right"}) + shows(heading, "hero-h", "right") + expect(segment(heading, "Right")).to_have_attribute("aria-pressed", "true") + look_of = "node => { const s = getComputedStyle(node); return [s.outlineStyle, s.outlineColor, s.backgroundColor, s.color].join(' ') }" + plain = segment(heading, "Left").evaluate(look_of) + kept = segment(heading, "Right").evaluate(look_of) + try_center(heading) + expect(keep_button(heading)).to_be_visible() + expect(revert_button(heading)).to_be_visible() + expect(segment(heading, "Center")).to_have_attribute("aria-pressed", "false") + expect(segment(heading, "Right")).to_have_attribute("aria-pressed", "true") + tried = segment(heading, "Center").evaluate(look_of) + assert tried != plain and tried != kept, f"the tried segment looks like another one: tried {tried}, stored {kept}, plain {plain}" + shown, field = bar(heading).bounding_box(), group(heading).bounding_box() + apart = shown["y"] >= field["y"] + field["height"] or shown["y"] + shown["height"] <= field["y"] + assert apart, f"the bar {shown} covers the field {field}" + gap = max(shown["y"] - (field["y"] + field["height"]), field["y"] - (shown["y"] + shown["height"])) + assert gap < shown["height"], f"the bar is {gap} px away from the field" + panel = heading.page.locator("aside.inspector").bounding_box() + assert heading.page.viewport_size["width"] == 1440 + inside = panel["x"] <= shown["x"] and shown["x"] + shown["width"] <= panel["x"] + panel["width"] + assert inside, f"the bar spans x {shown['x']} to {shown['x'] + shown['width']}, outside the right panel's {panel['x']} to {panel['x'] + panel['width']}" + + +def test_arrow_keys_home_and_end_try_each_choice_in_turn_without_writing(trial): + editor, changes, before = trial + for key, value in (("ArrowRight", "right"), ("ArrowRight", "justify"), ("ArrowLeft", "right"), ("Home", "left"), ("End", "justify")): + editor.page.keyboard.press(key) + shows(editor, "hero-h", value) + assert editor.site()["revision"] == before["revision"], f"{key} wrote a change" + expect(bar(editor)).to_contain_text("Trying: Justify") + nothing_written(editor, changes, before) + + +@pytest.mark.parametrize("how", ["enter", "button"]) +def test_keep_writes_the_tried_value_in_one_undo_step(trial, how): + editor, changes, before = trial + if how == "enter": + editor.page.keyboard.press("Enter") + else: + keep_button(editor).click() + after = editor.until(lambda site: styles(site, "hero-h").get("text-align") == "center", "center to be stored") + assert editor.site()["revision"] == before["revision"] + 1 + assert len(changes.sent) == 1 + expect(bar(editor)).to_be_hidden() + shows(editor, "hero-h", "center") + assert {k: v for k, v in after["nodes"].items() if k != "hero-h"} == {k: v for k, v in before["site"]["nodes"].items() if k != "hero-h"} + editor.undo() + editor.restored_to(before["site"]) + shows(editor, "hero-h", "start") + + +@pytest.mark.parametrize("how", ["escape", "button"]) +def test_revert_puts_the_page_back_and_says_the_field_is_unchanged(trial, how): + editor, changes, before = trial + if how == "escape": + editor.page.keyboard.press("Escape") + else: + revert_button(editor).click() + shows(editor, "hero-h", "start") + expect(bar(editor)).to_be_hidden() + expect(editor.status).to_have_text(NOT_KEPT) + nothing_written(editor, changes, before) + + +def test_keep_on_the_value_already_stored_ends_quietly_and_sends_nothing(heading): + outside(heading, "hero-h", {"text-align": "right"}) + shows(heading, "hero-h", "right") + expect(segment(heading, "Right")).to_have_attribute("aria-pressed", "true") + changes = Changes(heading) + before = heading.site() + try_center(heading) + heading.page.keyboard.press("ArrowRight") + expect(bar(heading)).to_contain_text("Trying: Right") + heading.page.keyboard.press("Enter") + expect(bar(heading)).to_be_hidden() + shows(heading, "hero-h", "right") + heading.page.evaluate(QUIET) + expect(heading.status).not_to_contain_text("Not kept") + nothing_written(heading, changes, before) + + +def test_a_click_on_the_stored_segment_tries_no_own_value_and_keep_clears_it(heading): + outside(heading, "hero-h", {"text-align": "right"}) + shows(heading, "hero-h", "right") + expect(segment(heading, "Right")).to_have_attribute("aria-pressed", "true") + before = heading.site() + segment(heading, "Right").click() + shows(heading, "hero-h", "start") + expect(bar(heading)).to_contain_text("Trying: Inherit") + assert heading.site() == before + keep_button(heading).click() + heading.until(lambda site: "text-align" not in styles(site, "hero-h"), "text-align to be cleared") + assert heading.site()["revision"] == before["revision"] + 1 + shows(heading, "hero-h", "start") + expect(segment(heading, "Right")).to_have_attribute("aria-pressed", "false") + + +def test_under_tablet_a_trial_and_its_keep_touch_the_tablet_value_only(heading): + picker = heading.page.get_by_role("combobox", name="Responsive breakpoint") + picker.select_option("tablet") + expect(picker).to_have_value("tablet") + changes = Changes(heading) + before = heading.site() + try_center(heading) + assert heading.site() == before + heading.page.keyboard.press("Enter") + after = heading.until(lambda site: styles(site, "hero-h", "tablet").get("text-align") == "center", "the tablet value") + assert "text-align" not in after["nodes"]["hero-h"]["styles"] + assert after["nodes"]["hero-h"]["breakpoints"].get("mobile", {}) == before["site"]["nodes"]["hero-h"]["breakpoints"].get("mobile", {}) + assert len(changes.sent) == 1 + + +def test_trying_hidden_hides_the_element_and_revert_shows_it_again_still_selected(heading): + changes = Changes(heading) + before = heading.site() + shown = look(heading, "hero-h", "display") + assert shown != "none" + segment(heading, "Hidden", "Display").click() + shows(heading, "hero-h", "none", "display") + expect(bar(heading)).to_contain_text("Trying: Hidden") + revert_button(heading).click() + shows(heading, "hero-h", shown, "display") + expect(heading.page.locator(".inspector-tag")).to_have_text(re.compile(r"· hero-h$")) + expect(heading.layer_row("hero-h")).to_have_attribute("aria-selected", "true") + nothing_written(heading, changes, before) + + +def test_with_trying_switched_off_a_segment_click_writes_at_once_and_shows_no_bar(heading): + open_menu(heading, "View", "view.try-choices").click() + expect(heading.status).to_have_text("Clicked choices are now written at once.") + before = heading.site() + segment(heading, "Center").click() + heading.until(lambda site: styles(site, "hero-h").get("text-align") == "center", "center to be stored") + assert heading.site()["revision"] == before["revision"] + 1 + shows(heading, "hero-h", "center") + expect(bar(heading)).to_be_hidden() + + +def test_a_canvas_click_on_another_element_drops_the_trial_and_writes_nothing(trial): + editor, changes, before = trial + editor.canvas.locator('[data-fw-id="hero-p"]').click() + expect(editor.page.locator(".inspector-tag")).to_have_text(re.compile(r"· hero-p$")) + shows(editor, "hero-h", "start") + assert look(editor, "hero-p") == "start" + expect(bar(editor)).to_be_hidden() + nothing_written(editor, changes, before) + + +@pytest.mark.parametrize("how", ["click", "double-click"]) +def test_a_canvas_press_on_the_element_already_selected_reverts_the_trial_and_writes_nothing(trial, how): + editor, changes, before = trial + target = editor.canvas.locator('[data-fw-id="hero-h"]') + editing = editor.canvas.locator('[data-fw-text="hero-h"][contenteditable="true"]') + if how == "click": + target.click() + else: + target.dblclick() + expect(editing).to_be_visible() + expect(editing).to_be_focused() + shows(editor, "hero-h", "start") + expect(bar(editor)).to_be_hidden() + expect(editor.page.locator(".inspector-tag")).to_have_text(re.compile(r"· hero-h$")) + nothing_written(editor, changes, before) + if how == "double-click": + text = before["site"]["nodes"]["hero-h"]["text"] + editor.page.keyboard.press("Tab") + expect(editing).to_have_count(0) + after = changes.settled() + assert after == before["site"], "leaving text editing changed the site" + assert editor.site()["revision"] == before["revision"] + assert all(json.dumps(body["params"]["patch"]) == json.dumps({"text": text}) for body in changes.bodies()), f"leaving text editing sent more than the unchanged text: {changes.bodies()}" + shows(editor, "hero-h", "start") + + +@pytest.mark.parametrize("how", ["layers", "select-parent"]) +def test_selecting_another_element_from_layers_or_the_edit_menu_ends_the_trial_and_writes_nothing(trial, how): + editor, changes, before = trial + if how == "layers": + select(editor, "hero-p") + else: + open_menu(editor, "Edit", "edit.select-parent").click() + expect(editor.page.locator(".inspector-tag")).to_have_text(re.compile(r"· hero-copy$")) + shows(editor, "hero-h", "start") + assert look(editor, "hero-p") == "start" + assert look(editor, "hero-copy") == "start" + expect(bar(editor)).to_be_hidden() + nothing_written(editor, changes, before) + + +def test_picking_another_breakpoint_ends_the_trial_and_the_fields_show_that_breakpoints_stored_value(heading): + heading.command("node.update", {"id": "hero-h", "patch": {"breakpoints": {"tablet": {"text-align": "right"}}}}) + heading.until(lambda site: styles(site, "hero-h", "tablet").get("text-align") == "right", "the tablet value") + changes = Changes(heading) + before = heading.site() + try_center(heading) + picker = heading.page.get_by_role("combobox", name="Responsive breakpoint") + picker.select_option("tablet") + expect(picker).to_have_value("tablet") + shows(heading, "hero-h", "right") + expect(bar(heading)).to_be_hidden() + expect(segment(heading, "Right")).to_have_attribute("aria-pressed", "true") + expect(segment(heading, "Center")).to_have_attribute("aria-pressed", "false") + expect(group(heading).locator("[data-trying]")).to_have_count(0) + nothing_written(heading, changes, before) + + +def test_opening_another_page_ends_the_trial_and_coming_back_shows_the_stored_look(trial): + editor, changes, before = trial + editor.page_row("p-fares").click() + editor.canvas.locator('[data-fw-id="p-fares-root"]').wait_for() + expect(bar(editor)).to_be_hidden() + editor.page_row("home").click() + editor.canvas.locator('[data-fw-id="hero-h"]').wait_for() + shows(editor, "hero-h", "start") + nothing_written(editor, changes, before) + + +@pytest.mark.parametrize("how", ["live-preview", "full-preview"]) +def test_leaving_design_for_a_preview_ends_the_trial_and_the_page_shows_the_stored_look_on_return(trial, how): + editor, changes, before = trial + if how == "live-preview": + open_menu(editor, "View", "view.preview").click() + expect(bar(editor)).to_be_hidden() + item = open_menu(editor, "View", "view.preview") + expect(item).to_have_attribute("aria-checked", "true") + item.click() + else: + editor.page.locator('[data-cmd="view.preview-full"]').click() + dialog = editor.page.get_by_role("dialog", name="Preview as published") + expect(dialog).to_be_visible() + expect(bar(editor)).to_be_hidden() + dialog.get_by_role("button", name="Close").click() + expect(dialog).to_be_hidden() + editor.canvas.locator('[data-fw-id="hero-h"]').wait_for() + shows(editor, "hero-h", "start") + expect(bar(editor)).to_be_hidden() + nothing_written(editor, changes, before) + + +def kept_right(editor): + segment(editor, "Right").click() + shows(editor, "hero-h", "right") + editor.page.keyboard.press("Enter") + return editor.until(lambda site: styles(site, "hero-h").get("text-align") == "right", "right to be kept") + + +@pytest.mark.parametrize("how", ["ctrl-z", "toolbar", "menu"]) +def test_undo_during_a_trial_reverts_the_trial_and_undoes_nothing_and_the_next_undo_really_undoes(heading, how): + start = heading.site() + kept_right(heading) + before = heading.site() + assert before["canUndo"] is True + changes = Changes(heading) + + def undo(): + if how == "ctrl-z": + heading.undo() + elif how == "toolbar": + heading.page.locator('button[data-cmd="edit.undo"]').click() + else: + open_menu(heading, "Edit", "edit.undo").click() + + try_center(heading) + undo() + shows(heading, "hero-h", "right") + expect(bar(heading)).to_be_hidden() + nothing_written(heading, changes, before) + assert heading.site()["canRedo"] is False, "Redo became available, so the undo undid a kept change" + assert stored(heading, "hero-h") == "right" + undo() + heading.restored_to(start["site"]) + shows(heading, "hero-h", "start") + + +def test_ctrl_z_on_a_site_with_no_undo_history_still_reverts_the_trial(trial): + editor, changes, before = trial + assert before["canUndo"] is False, "the freshly opened site already has undo history" + editor.undo() + shows(editor, "hero-h", "start") + expect(bar(editor)).to_be_hidden() + expect(editor.status).to_have_text(NOT_KEPT) + nothing_written(editor, changes, before) + + +def test_an_undo_run_by_a_program_during_a_trial_reverts_the_trial_and_really_undoes(heading): + start = heading.site() + kept_right(heading) + try_center(heading) + answer = heading.page.evaluate("window.formweb.run('edit.undo')") + assert answer.get("ran") is True, answer + heading.restored_to(start["site"]) + shows(heading, "hero-h", "start") + expect(bar(heading)).to_be_hidden() + + +def test_duplicate_from_the_menu_during_a_trial_reverts_it_first_and_copies_the_stored_element(trial): + editor, changes, before = trial + open_menu(editor, "Edit", "edit.duplicate").click() + after = editor.changed_from(before["site"]) + copies = [k for k in after["nodes"]["hero-copy"]["children"] if k not in before["site"]["nodes"]] + assert len(copies) == 1 + assert "text-align" not in after["nodes"][copies[0]]["styles"] + assert after["nodes"]["hero-h"] == before["site"]["nodes"]["hero-h"] + shows(editor, "hero-h", "start") + shows(editor, copies[0], "start") + assert editor.site()["revision"] == before["revision"] + 1 + + +def test_delete_from_the_menu_during_a_trial_reverts_it_first_and_undo_brings_back_the_stored_element(trial): + editor, changes, before = trial + open_menu(editor, "Edit", "edit.delete").click() + editor.until(lambda site: "hero-h" not in site["nodes"], "hero-h to be deleted") + assert editor.site()["revision"] == before["revision"] + 1 + expect(bar(editor)).to_be_hidden() + editor.undo() + editor.restored_to(before["site"]) + shows(editor, "hero-h", "start") + + +def reset_link(editor): + return editor.page.get_by_role("button", name="Reset Text alignment to the inherited value", exact=True) + + +def test_reset_on_the_tried_field_reverts_the_trial_and_then_clears_the_stored_value(heading): + outside(heading, "hero-h", {"text-align": "right"}) + before = heading.until(lambda site: styles(site, "hero-h").get("text-align") == "right", "right to be stored") + changes = Changes(heading) + try_center(heading) + reset_link(heading).click() + heading.until(lambda site: "text-align" not in styles(site, "hero-h"), "text-align to be reset") + assert len(changes.sent) == 1 + shows(heading, "hero-h", "start") + expect(bar(heading)).to_be_hidden() + heading.undo() + heading.restored_to(before) + + +def test_backspace_right_after_a_click_on_reset_during_a_trial_removes_nothing(heading): + outside(heading, "hero-h", {"text-align": "right"}) + heading.until(lambda site: styles(site, "hero-h").get("text-align") == "right", "right to be stored") + changes = Changes(heading) + try_center(heading) + reset_link(heading).click() + heading.page.keyboard.press("Backspace") + heading.page.keyboard.press("Delete") + after = changes.settled() + assert "hero-h" in after["nodes"], "Backspace after Reset removed the selected element" + assert "text-align" not in styles(after, "hero-h") + expect(heading.layer_row("hero-h")).to_be_visible() + shows(heading, "hero-h", "start") + + +def test_an_outside_change_to_another_element_leaves_the_trial_on_and_keep_still_works(trial): + editor, changes, before = trial + outside(editor, "hero-p", {"color": "rgb(1, 2, 3)"}) + shows(editor, "hero-p", "rgb(1, 2, 3)", "color") + assert look(editor, "hero-h") == "center", "the trial left the page" + expect(bar(editor)).to_be_visible() + keep_button(editor).click() + after = editor.until(lambda site: styles(site, "hero-h").get("text-align") == "center", "center to be kept") + assert styles(after, "hero-p").get("color") == "rgb(1, 2, 3)" + assert len(changes.sent) == 1 + + +def test_an_outside_change_to_the_tried_field_drops_the_trial_and_shows_the_outside_value(trial): + editor, changes, before = trial + outside(editor, "hero-h", {"text-align": "right"}) + shows(editor, "hero-h", "right") + expect(bar(editor)).to_be_hidden() + expect(editor.status).to_have_text(ELSEWHERE) + expect(segment(editor, "Right")).to_have_attribute("aria-pressed", "true") + expect(segment(editor, "Center")).not_to_have_attribute("data-trying", "") + changes.settled() + assert changes.sent == [] + assert stored(editor, "hero-h") == "right" + + +def test_an_outside_removal_of_the_tried_element_ends_the_trial_without_an_error(trial): + editor, changes, before = trial + errors = [] + editor.page.on("pageerror", lambda error: errors.append(error)) + editor.command("node.remove", {"id": "hero-h"}) + editor.until(lambda site: "hero-h" not in site["nodes"], "hero-h to be removed") + expect(editor.canvas.locator('[data-fw-id="hero-h"]')).to_have_count(0) + expect(bar(editor)).to_be_hidden() + expect(editor.status).to_have_text(ELSEWHERE) + expect(editor.status).not_to_have_class(re.compile(r"\berror\b")) + changes.settled() + assert changes.sent == [] + assert errors == [] + + +@pytest.mark.parametrize("how", ["tab", "click"]) +def test_moving_focus_to_another_field_reverts_the_trial(trial, how): + editor, changes, before = trial + if how == "tab": + editor.page.keyboard.press("Tab") + expect(keep_button(editor)).to_be_focused() + editor.page.keyboard.press("Tab") + expect(revert_button(editor)).to_be_focused() + assert look(editor, "hero-h") == "center" + editor.page.keyboard.press("Tab") + assert not editor.page.evaluate("document.activeElement.closest('[data-try-bar], .fw-seg') !== null") + else: + editor.page.locator('input[data-style="font-size"]').click() + shows(editor, "hero-h", "start") + expect(bar(editor)).to_be_hidden() + expect(editor.status).to_have_text(NOT_KEPT) + nothing_written(editor, changes, before) + + +def test_switching_to_another_window_and_back_leaves_the_trial_on(trial): + editor, changes, before = trial + other = editor.page.context.new_page() + other.bring_to_front() + editor.page.evaluate("window.dispatchEvent(new FocusEvent('blur'))") + editor.page.bring_to_front() + editor.page.evaluate("window.dispatchEvent(new FocusEvent('focus'))") + editor.page.evaluate(QUIET) + other.close() + assert look(editor, "hero-h") == "center", "the trial left the page" + expect(bar(editor)).to_be_visible() + editor.page.keyboard.press("Enter") + editor.until(lambda site: styles(site, "hero-h").get("text-align") == "center", "center to be kept") + assert len(changes.sent) == 1 + + +def test_scrolling_the_page_and_the_inspector_with_the_wheel_leaves_the_trial_on(trial): + editor, changes, before = trial + frame = editor.page.locator('iframe[title="Website canvas"]').bounding_box() + editor.page.mouse.move(frame["x"] + frame["width"] / 2, frame["y"] + frame["height"] / 2) + editor.page.mouse.wheel(0, 400) + editor.eventually(lambda: editor.canvas.locator("html").evaluate("node => node.ownerDocument.defaultView.scrollY") > 0, "the page to scroll") + scroller = editor.page.locator(".inspector-scroll:visible").first + start = scroller.evaluate("node => node.scrollTop") + box = scroller.bounding_box() + editor.page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2) + editor.page.mouse.wheel(0, 300) + editor.eventually(lambda: scroller.evaluate("node => node.scrollTop") != start, "the inspector to scroll") + editor.page.evaluate(QUIET) + assert look(editor, "hero-h") == "center", "the trial left the page" + expect(bar(editor)).to_be_visible() + nothing_written(editor, changes, before) + + +EMPTY_SPOT = """(seg) => { + const area = seg.closest('.inspector-section'); + const box = area.getBoundingClientRect(); + for (let y = box.top + 2; y < box.bottom; y += 2) { + for (const x of [box.left + 2, box.right - 3]) { + const hit = document.elementFromPoint(x, y); + if (hit && (hit === area || hit.classList.contains('form-grid')) && hit.tabIndex < 0) return [x, y]; + } + } + return null; +}""" + + +def test_a_press_on_empty_inspector_padding_leaves_the_trial_on_and_backspace_then_removes_nothing(trial): + editor, changes, before = trial + spot = group(editor).evaluate(EMPTY_SPOT) + assert spot, "no empty spot in the Typography section" + editor.page.mouse.click(*spot) + editor.page.evaluate(QUIET) + assert look(editor, "hero-h") == "center", "the trial left the page" + expect(bar(editor)).to_be_visible() + assert not editor.page.evaluate("document.activeElement === document.body"), "focus fell to the page body" + editor.page.keyboard.press("Backspace") + editor.page.keyboard.press("Delete") + nothing_written(editor, changes, before) + expect(editor.layer_row("hero-h")).to_be_visible() + + +def test_a_trial_on_another_field_reverts_the_first_so_only_the_second_is_on_the_page(trial): + editor, changes, before = trial + segment(editor, "Flex", "Display").click() + shows(editor, "hero-h", "flex", "display") + shows(editor, "hero-h", "start") + expect(bar(editor)).to_contain_text("Trying: Flex") + expect(group(editor).locator("[data-trying]")).to_have_count(0) + nothing_written(editor, changes, before) + + +def test_starting_to_drag_a_slider_reverts_the_trial(trial): + editor, changes, before = trial + thumb = editor.page.get_by_role("slider", name="Opacity", exact=True) + thumb.scroll_into_view_if_needed() + box = thumb.bounding_box() + pointer = editor.canvas_pointer() + y = box["y"] + box["height"] / 2 + pointer.move(box["x"] + box["width"] * 0.9, y) + pointer.down() + pointer.move(box["x"] + box["width"] * 0.5, y, steps=6, held=True) + shows(editor, "hero-h", "start") + expect(bar(editor)).to_be_hidden() + pointer.up() + after = editor.until(lambda site: "opacity" in styles(site, "hero-h"), "the dragged opacity") + assert "text-align" not in styles(after, "hero-h") + shows(editor, "hero-h", "start") + + +@pytest.mark.parametrize("how", ["view-menu", "preferences"]) +def test_turning_the_switch_off_ends_the_trial_and_writes_nothing(trial, how): + editor, changes, before = trial + if how == "view-menu": + open_menu(editor, "View", "view.try-choices").click() + else: + box = open_preferences(editor).get_by_role("checkbox", name=SWITCH) + expect(box).to_be_checked() + box.uncheck() + shows(editor, "hero-h", "start") + expect(bar(editor)).to_be_hidden() + nothing_written(editor, changes, before) + assert editor.page.evaluate("localStorage.getItem('formweb.try-choices')") == "0" + + +def test_a_reload_during_a_trial_leaves_the_site_as_stored(trial): + editor, changes, before = trial + editor.page.reload() + editor.page.get_by_role("button", name="Back to Editor").click() + editor.canvas.locator('[data-fw-id="hero-h"]').wait_for() + shows(editor, "hero-h", "start") + assert changes.sent == [] + assert editor.site() == before + + +@pytest.mark.parametrize("trying", [True, False], ids=["during-a-trial", "no-trial"]) +def test_folding_the_section_by_a_click_on_its_title_reverts_a_trial_and_a_backspace_right_after_removes_nothing(heading, trying): + changes = Changes(heading) + before = heading.site() + if trying: + try_center(heading) + title = heading.page.locator(".inspector-section .section-title", has_text="Typography") + title.click() + expect(title).to_have_attribute("aria-expanded", "false") + expect(group(heading)).to_be_hidden() + expect(title).to_be_focused() + shows(heading, "hero-h", "start") + expect(bar(heading)).to_be_hidden() + if trying: + expect(heading.status).to_have_text(NOT_KEPT) + heading.page.keyboard.press("Backspace") + heading.page.keyboard.press("Delete") + after = changes.settled() + assert "hero-h" in after["nodes"], "Backspace on the folded section's title removed the selected element" + nothing_written(heading, changes, before) + expect(heading.layer_row("hero-h")).to_be_visible() + expect(heading.layer_row("hero-h")).to_have_attribute("aria-selected", "true") + + +@pytest.mark.parametrize("how", ["tab", "search"]) +def test_hiding_the_field_reverts_the_trial_and_a_backspace_right_after_removes_nothing(trial, how): + editor, changes, before = trial + if how == "tab": + editor.page.locator(".inspector button.quiet", has_text="Motion").click() + expect(group(editor)).to_be_hidden() + else: + editor.page.get_by_placeholder("Search properties").fill("opacity") + expect(group(editor)).to_be_hidden() + shows(editor, "hero-h", "start") + expect(bar(editor)).to_be_hidden() + editor.page.keyboard.press("Backspace") + editor.page.keyboard.press("Delete") + assert not editor.page.evaluate("document.activeElement === document.body"), "focus fell to the page body" + nothing_written(editor, changes, before) + expect(editor.layer_row("hero-h")).to_be_visible() + + +@pytest.mark.parametrize("target", ["segment", "keep", "revert"]) +def test_delete_and_backspace_with_focus_on_a_segment_or_the_bar_remove_nothing(trial, target): + editor, changes, before = trial + part = {"segment": segment(editor, "Center"), "keep": keep_button(editor), "revert": revert_button(editor)}[target] + part.focus() + expect(part).to_be_focused() + editor.page.keyboard.press("Delete") + editor.page.keyboard.press("Backspace") + assert look(editor, "hero-h") == "center", "the trial left the page" + nothing_written(editor, changes, before) + expect(editor.layer_row("hero-h")).to_be_visible() + + +def test_with_a_slow_engine_keys_and_clicks_after_keep_change_nothing_and_one_write_lands_with_no_old_frame(trial): + editor, changes, before = trial + held = hold_changes(editor) + editor.page.evaluate(RECORD, "hero-h") + editor.page.keyboard.press("Enter") + editor.eventually(lambda: held, "Keep to reach the engine") + expect(bar(editor)).to_have_attribute("aria-busy", "true") + for key in ("Enter", "Escape", "ArrowRight"): + editor.page.keyboard.press(key) + segment(editor, "Justify").click() + editor.page.evaluate(QUIET) + assert look(editor, "hero-h") == "center" + assert len(changes.sent) == 1 + held[0].continue_() + editor.until(lambda site: styles(site, "hero-h").get("text-align") == "center", "center to be kept") + expect(bar(editor)).to_be_hidden() + editor.page.evaluate(QUIET) + seen = editor.page.evaluate(STOP) + assert len(seen) > 1 + assert set(seen) == {"center"}, f"the page showed {sorted(set(seen))} between Enter and the answer" + changes.settled() + assert len(changes.sent) == 1 + body = json.dumps(changes.bodies()[0]) + assert '"hero-h"' in body and '"center"' in body and '"justify"' not in body and '"right"' not in body, body + assert editor.site()["revision"] == before["revision"] + 1 + assert {k: v for k, v in editor.site()["site"]["nodes"].items() if k != "hero-h"} == {k: v for k, v in before["site"]["nodes"].items() if k != "hero-h"} + + +def test_selecting_another_element_while_keep_is_pending_lands_the_value_on_the_first_and_the_field_takes_a_new_trial_at_once(trial): + editor, changes, before = trial + held = hold_changes(editor) + editor.page.evaluate(RECORD, "hero-h") + editor.page.keyboard.press("Enter") + editor.eventually(lambda: held, "Keep to reach the engine") + select(editor, "hero-p") + expect(bar(editor)).to_be_hidden() + segment(editor, "Right").click() + shows(editor, "hero-p", "right") + expect(bar(editor)).to_contain_text("Trying: Right") + assert look(editor, "hero-h") == "center" + held[0].continue_() + after = editor.until(lambda site: styles(site, "hero-h").get("text-align") == "center", "center to land on hero-h") + assert "text-align" not in styles(after, "hero-p") + seen = editor.page.evaluate(STOP) + assert set(seen) == {"center"}, f"hero-h showed {sorted(set(seen))} while its Keep was on the way" + assert look(editor, "hero-p") == "right", "the new trial on hero-p left the page when the first Keep landed" + expect(bar(editor)).to_be_visible() + editor.page.keyboard.press("Escape") + shows(editor, "hero-p", "start") + changes.settled() + assert len(changes.sent) == 1 + assert stored(editor, "hero-p") is None + + +@pytest.mark.parametrize("how", ["refused", "conflict"]) +def test_a_keep_the_engine_refuses_puts_the_page_and_the_field_back_to_the_stored_value_and_says_why(heading, how): + outside(heading, "hero-h", {"text-align": "right"}) + heading.until(lambda site: styles(site, "hero-h").get("text-align") == "right", "right to be stored") + try_center(heading) + if how == "refused": + heading.page.route(OWN_CHANGE, lambda route: route.fulfill(status=400, content_type="application/json", body=json.dumps({"detail": "Refused for this test."}))) + keep_button(heading).click() + expect(heading.status).to_have_text("Refused for this test.") + else: + held = hold_changes(heading) + keep_button(heading).click() + heading.eventually(lambda: held, "Keep to reach the engine") + outside(heading, "hero-p", {"color": "rgb(1, 2, 3)"}) + heading.until(lambda site: styles(site, "hero-p").get("color") == "rgb(1, 2, 3)", "the outside change") + held[0].continue_() + expect(heading.status).to_contain_text("revision", ignore_case=True) + expect(heading.status).to_have_class(re.compile(r"\berror\b")) + shows(heading, "hero-h", "right") + expect(bar(heading)).to_be_hidden() + expect(segment(heading, "Right")).to_have_attribute("aria-pressed", "true") + expect(group(heading).locator("[data-trying]")).to_have_count(0) + assert stored(heading, "hero-h") == "right" + + +def test_with_two_elements_selected_the_trial_and_its_keep_touch_the_last_picked_only(heading): + heading.layer_row("hero-k").click() + heading.layer_row("hero-p").click(modifiers=["Control"]) + expect(heading.page.locator('#fw-layers-list .layer-row[aria-selected="true"]')).to_have_count(2) + changes = Changes(heading) + before = heading.site() + segment(heading, "Center").click() + shows(heading, "hero-p", "center") + assert look(heading, "hero-k") == "start" + assert heading.site() == before + keep_button(heading).click() + after = heading.until(lambda site: styles(site, "hero-p").get("text-align") == "center", "center on hero-p") + assert "text-align" not in styles(after, "hero-k") + assert look(heading, "hero-k") == "start" + assert len(changes.sent) == 1 + + +def test_with_the_scene_scrubber_on_a_trial_still_shows_on_the_page(heading): + frames = [{"at": 0, "styles": {"opacity": "0.25"}}, {"at": 1, "styles": {"opacity": "0.25"}}] + heading.command("motion.set", {"kind": "scenes", "node": "hero", "value": {"stage": "hero-in", "length": 400, "tracks": [{"node": "hero-h", "keyframes": frames}]}}) + scrubber = heading.page.get_by_role("group", name="Scene scrubber") + expect(scrubber).to_be_visible() + assert look(heading, "hero-h", "opacity") == "1" + scrubber.get_by_role("slider", name="Scene progress").fill("50") + shows(heading, "hero-h", "0.25", "opacity") + changes = Changes(heading) + before = heading.site() + try_center(heading) + assert look(heading, "hero-h", "opacity") == "0.25", "the scrubbed frame left the page when the trial began" + nothing_written(heading, changes, before) + + +def test_preferences_has_the_switch_on_by_default_with_a_sentence_that_explains_it(heading): + dialog = open_preferences(heading) + box = dialog.get_by_role("checkbox", name=SWITCH) + expect(box).to_be_visible() + expect(box).to_be_checked() + expect(dialog.get_by_text("A clicked choice shows on the page and is written when you press Keep.", exact=False)).to_be_visible() + + +def test_the_view_menu_switch_carries_a_check_mark_and_says_what_it_did(heading): + item = open_menu(heading, "View", "view.try-choices") + expect(item).to_have_attribute("aria-checked", "true") + item.click() + expect(heading.status).to_have_text("Clicked choices are now written at once.") + item = open_menu(heading, "View", "view.try-choices") + expect(item).to_have_attribute("aria-checked", "false") + item.click() + expect(heading.status).to_have_text("A clicked choice now shows on the page until you press Keep.") + expect(open_menu(heading, "View", "view.try-choices")).to_have_attribute("aria-checked", "true") + heading.page.keyboard.press("Escape") + try_center(heading) + + +def test_the_switch_survives_a_reload_stays_out_of_the_site_and_reset_all_preferences_turns_it_back_on(heading): + before = heading.site() + files = export_files(heading) + open_menu(heading, "View", "view.try-choices").click() + expect(heading.status).to_have_text("Clicked choices are now written at once.") + assert heading.site() == before + assert export_files(heading) == files + heading.page.reload() + heading.page.get_by_role("button", name="Back to Editor").click() + select(heading, "hero-h") + expect(open_menu(heading, "View", "view.try-choices")).to_have_attribute("aria-checked", "false") + heading.page.keyboard.press("Escape") + segment(heading, "Center").click() + heading.until(lambda site: styles(site, "hero-h").get("text-align") == "center", "center written at once") + expect(bar(heading)).to_be_hidden() + dialog = open_preferences(heading) + dialog.get_by_role("tab", name="General").click() + dialog.get_by_role("button", name="Reset All Preferences...").click() + with heading.page.expect_navigation(): + dialog.get_by_role("button", name="Reset", exact=True).click() + heading.page.get_by_role("button", name="Back to Editor").click() + select(heading, "hero-h") + expect(open_menu(heading, "View", "view.try-choices")).to_have_attribute("aria-checked", "true") + heading.page.keyboard.press("Escape") + segment(heading, "Right").click() + shows(heading, "hero-h", "right") + expect(bar(heading)).to_contain_text("Trying: Right") + assert stored(heading, "hero-h") == "center", "the trial after Reset All Preferences wrote at once" + + +def rest_over(editor, pointer, part): + part.scroll_into_view_if_needed() + box = part.bounding_box() + pointer.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2, steps=5) + editor.page.evaluate(REST) + + +def test_moving_and_resting_the_pointer_on_choices_and_on_the_bar_changes_nothing(heading): + changes = Changes(heading) + before = heading.site() + pointer = heading.canvas_pointer() + shown = look(heading, "hero-h", "display") + for label, names in (("Text alignment", ("Left", "Center", "Right", "Justify")), ("Display", ("Flex", "Grid", "Hidden"))): + for name in names: + rest_over(heading, pointer, segment(heading, name, label)) + assert look(heading, "hero-h") == "start", f"resting on {name} changed the page" + assert look(heading, "hero-h", "display") == shown, f"resting on {name} changed the page" + expect(bar(heading)).to_be_hidden() + try_center(heading) + for part in (keep_button(heading), revert_button(heading), segment(heading, "Justify"), segment(heading, "Hidden", "Display")): + rest_over(heading, pointer, part) + assert look(heading, "hero-h") == "center", "resting on a choice or the bar changed the trial on the page" + assert look(heading, "hero-h", "display") == shown + expect(bar(heading)).to_contain_text("Trying: Center") + nothing_written(heading, changes, before) + + +def test_keyboard_focus_arriving_on_a_segment_group_by_tab_changes_nothing_until_an_arrow_key(heading): + changes = Changes(heading) + before = heading.site() + heading.page.locator('input[data-style="letter-spacing"]').focus() + for _ in range(8): + heading.page.keyboard.press("Tab") + if heading.page.evaluate("document.activeElement.closest('[role=group]')?.getAttribute('aria-label') === 'Text alignment'"): + break + assert heading.page.evaluate("document.activeElement.closest('[role=group]')?.getAttribute('aria-label')") == "Text alignment", "Tab never reached Text alignment" + heading.page.evaluate(REST) + assert look(heading, "hero-h") == "start" + expect(bar(heading)).to_be_hidden() + nothing_written(heading, changes, before) + heading.page.keyboard.press("ArrowRight") + shows(heading, "hero-h", "left") + expect(bar(heading)).to_contain_text("Trying: Left") + nothing_written(heading, changes, before) + + +def test_while_a_trial_is_on_the_engine_a_second_window_and_the_export_hold_the_stored_value(heading): + files = export_files(heading) + changes = Changes(heading) + before = heading.site() + try_center(heading) + assert heading.site() == before + assert export_files(heading) == files + context = heading.page.context.browser.new_context(viewport={"width": 1440, "height": 900}) + try: + page = context.new_page() + page.goto(heading.base + "/", wait_until="domcontentloaded") + page.get_by_role("button", name="Back to Editor").click() + other = page.frame_locator('iframe[title="Website canvas"]').locator('[data-fw-id="hero-h"]') + other.wait_for() + assert other.evaluate(LOOK, "text-align") == "start", "the second window shows the trial" + finally: + context.close() + assert look(heading, "hero-h") == "center" + nothing_written(heading, changes, before) + + +def test_no_inspector_field_moves_when_a_trial_starts_changes_and_ends(heading): + start = heading.page.evaluate(FIELD_BOXES) + assert len(start) > 20 + segment(heading, "Center").click() + expect(bar(heading)).to_be_visible() + assert heading.page.evaluate(FIELD_BOXES) == start, "a field moved when the trial started" + heading.page.keyboard.press("ArrowRight") + expect(bar(heading)).to_contain_text("Trying: Right") + assert heading.page.evaluate(FIELD_BOXES) == start, "a field moved when the trial changed" + heading.page.keyboard.press("Escape") + expect(bar(heading)).to_be_hidden() + assert heading.page.evaluate(FIELD_BOXES) == start, "a field moved when the trial ended" + + +def test_on_a_cold_load_nothing_of_the_bar_is_visible_before_the_editor_is_ready(chromium, fresh_engine): + context = chromium.new_context(viewport={"width": 1440, "height": 900}) + try: + page = context.new_page() + page.add_init_script(f"({WATCH})()") + cdp = context.new_cdp_session(page) + cdp.send("Emulation.setCPUThrottlingRate", {"rate": 4}) + page.goto(fresh_engine + "/", wait_until="load") + expect(page.locator("body")).to_have_class(re.compile(r"\bapp-ready\b"), timeout=60_000) + page.locator('[data-demo="harbour-ferries"]').click() + page.locator('#fw-layers-list .layer-row[data-key="hero-h"]').click() + page.get_by_role("group", name="Text alignment", exact=True).get_by_role("button", name="Center", exact=True).click() + page.wait_for_function("() => window.__after > 0", timeout=30_000) + assert page.evaluate("window.__framesBefore") > 0 + assert page.evaluate("window.__before") == 0, "the bar was visible in a frame before the editor was ready" + finally: + context.close() diff --git a/frontend/tests/window/test_try_drags.py b/frontend/tests/window/test_try_drags.py new file mode 100644 index 00000000..4cee49a6 --- /dev/null +++ b/frontend/tests/window/test_try_drags.py @@ -0,0 +1,699 @@ +import json +import re +import time + +import pytest +from playwright.sync_api import expect + +OWN_CHANGE = re.compile(r"/api/(command|batch)$") +QUIET = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(done))))" +FRAMES = "(n) => new Promise(done => { const next = left => left ? requestAnimationFrame(() => next(left - 1)) : done(); next(n); })" +NODE = "h-logo-word" +PARENT = "h-logo" +THREE = "linear-gradient(90deg, #ff0000 0%, #00ff00 50%, #0000ff 100%)" +WAIT_S = 15 +CSS = """([key, value, read]) => { + const probe = document.createElement('div'); + probe.style.setProperty(key, value); + document.body.append(probe); + const seen = getComputedStyle(probe).getPropertyValue(read); + probe.remove(); + return seen; +}""" +SAMPLE = """([id, read]) => { + window.__samples = []; + window.__sampling = true; + const look = () => { + const frame = document.querySelector('iframe[title="Website canvas"]'); + const doc = frame && frame.contentDocument; + const node = doc && doc.querySelector(`[data-fw-id="${id}"]`); + const revision = document.querySelector('footer.statusbar .status-revision'); + window.__samples.push([node ? frame.contentWindow.getComputedStyle(node).getPropertyValue(read) : null, revision ? revision.textContent : '']); + if (window.__sampling) requestAnimationFrame(look); + }; + look(); +}""" +STEP = """([id, key, previous]) => { + const value = document.querySelector(`input[data-style="${key}"]`).value; + if (!value || value === previous) return false; + const frame = document.querySelector('iframe[title="Website canvas"]'); + const node = frame.contentDocument.querySelector(`[data-fw-id="${id}"]`); + const probe = document.createElement('div'); + probe.style.setProperty(key, value); + document.body.append(probe); + const want = getComputedStyle(probe).getPropertyValue(key); + probe.remove(); + return frame.contentWindow.getComputedStyle(node).getPropertyValue(key) === want ? value : false; +}""" + + +class Changes: + def __init__(self, editor): + self.editor = editor + self.sent = [] + self.done = [] + editor.page.on("request", lambda r: self.sent.append(r) if OWN_CHANGE.search(r.url) else None) + editor.page.on("requestfinished", lambda r: self.done.append(r) if OWN_CHANGE.search(r.url) else None) + editor.page.on("requestfailed", lambda r: self.done.append(r) if OWN_CHANGE.search(r.url) else None) + + def settled(self): + self.editor.page.evaluate(QUIET) + self.editor.eventually(lambda: len(self.done) == len(self.sent), "every change the window sent to be answered") + return self.editor.until(lambda site: True, "the window to show the newest revision") + + +def sent(changes, count): + bodies = [request.post_data for request in changes.sent] + assert len(bodies) == count, f"the window sent {len(bodies)} changes where {count} belong: {bodies}" + + +def select(editor, node): + editor.layer_row(node).click() + expect(editor.page.locator(".inspector-tag")).to_have_text(re.compile(rf"· {re.escape(node)}$")) + + +def field(editor, key): + return editor.page.locator(f'input[data-style="{key}"]') + + +def slider(editor, name): + return editor.page.get_by_role("slider", name=name, exact=True) + + +def styles(site, node=NODE, breakpoint="desktop"): + item = site["nodes"][node] + return item["styles"] if breakpoint == "desktop" else item.get("breakpoints", {}).get(breakpoint, {}) + + +def stored(editor, key, node=NODE, breakpoint="desktop"): + return styles(editor.site()["site"], node, breakpoint).get(key) + + +def typed(editor, key, value): + box = field(editor, key) + box.fill(value) + box.press("Enter") + site = editor.until(lambda s: styles(s).get(key) == value, f"{key} {value} to be stored") + box.blur() + return site + + +def run(editor, command): + editor.page.evaluate(f"window.formweb.run('{command}')") + + +def read_of(key): + return "background-image" if key == "background" else key + + +def css(editor, key, value): + return editor.page.evaluate(CSS, [key, value, read_of(key)]) + + +def on_page(editor, key, node=NODE): + return editor.canvas.locator(f'[data-fw-id="{node}"]').evaluate(f"el => getComputedStyle(el).getPropertyValue('{read_of(key)}')") + + +def page_shows(editor, key, want, what, node=NODE): + deadline = time.monotonic() + WAIT_S + while True: + seen = on_page(editor, key, node) + if seen == want: + return + if time.monotonic() > deadline: + raise AssertionError(f"{what}: the page shows {read_of(key)} {seen!r} on {node}, not {want!r}") + editor.page.wait_for_timeout(50) + + +def shown_live(editor, key, other_than): + """Waits until the field shows a value the gesture made (none of other_than) and the page shows what CSS makes of it.""" + deadline = time.monotonic() + WAIT_S + while True: + value = field(editor, key).input_value() + seen = on_page(editor, key) + want = css(editor, key, value) if value else None + if value and value not in other_than and seen == want: + return value + if time.monotonic() > deadline: + raise AssertionError(f"the page does not show the dragged {key}: the field shows {value!r}, so the page should show {want!r}, but it shows {seen!r}") + editor.page.wait_for_timeout(50) + + +def drag_from(editor, target, start): + target.scroll_into_view_if_needed() + box = target.bounding_box() + pointer = editor.canvas_pointer() + y = box["y"] + box["height"] / 2 + pointer.move(box["x"] + box["width"] * start, y) + pointer.down() + return pointer, lambda f: (box["x"] + box["width"] * f, y) + + +def swatch(editor, label): + return editor.page.get_by_role("button", name=f"Choose {label}", exact=True) + + +def picker(editor, label): + return editor.page.get_by_role("dialog", name=f"Color picker for {label}") + + +def open_picker(editor, label): + swatch(editor, label).click() + dialog = picker(editor, label) + expect(dialog).to_be_visible() + return dialog + + +def square(editor, label): + return slider(editor, f"Saturation and brightness of {label}") + + +def drag_in(editor, target, start, to, steps=8): + target.scroll_into_view_if_needed() + box = target.bounding_box() + pointer = editor.canvas_pointer() + at = lambda x, y: (box["x"] + box["width"] * x, box["y"] + box["height"] * y) + pointer.move(*at(*start)) + pointer.down() + pointer.move(*at(*to), steps=steps, held=True) + return pointer, at + + +def sample(editor, key, node=NODE): + editor.page.evaluate(SAMPLE, [node, read_of(key)]) + + +def samples(editor): + editor.page.evaluate("window.__sampling = false") + editor.page.evaluate(QUIET) + return editor.page.evaluate("window.__samples") + + +def story(seen): + """The frames with repeats folded: each change of the page or of the revision once.""" + return [frame for i, frame in enumerate(seen) if i == 0 or frame != seen[i - 1]] + + +def revisions(seen): + return {int(m.group(1)) for _, text in seen if (m := re.search(r"\brev (\d+)\b", text))} + + +def step_shown(editor, previous): + try: + return editor.page.wait_for_function(STEP, arg=[NODE, "opacity", previous], timeout=WAIT_S * 1000).json_value() + except Exception: + raise AssertionError(f"the held key did not show a new opacity on the page: the field shows {field(editor, 'opacity').input_value()!r}, the page {on_page(editor, 'opacity')!r}") from None + + +def hold_changes(editor): + held = [] + editor.page.route(OWN_CHANGE, lambda route: held.append(route)) + return held + + +def breakpoint_choice(editor): + return editor.page.get_by_role("combobox", name="Responsive breakpoint") + + +@pytest.fixture +def word(harbour): + select(harbour, NODE) + return harbour + + +def test_dragging_the_opacity_slider_shows_each_value_on_the_page_keeps_the_revision_and_writes_once_on_release(word): + changes = Changes(word) + before = word.site() + start = on_page(word, "opacity") + pointer, x = drag_from(word, slider(word, "Opacity"), 0.8) + pointer.move(*x(0.6), steps=4, held=True) + first = shown_live(word, "opacity", [""]) + pointer.move(*x(0.3), steps=4, held=True) + second = shown_live(word, "opacity", ["", first]) + assert changes.sent == [], "a change was sent while the slider was still held" + assert word.site() == before, "the stored site changed during the drag" + pointer.up() + word.until(lambda site: styles(site).get("opacity") == second, f"opacity {second} to be stored on release") + changes.settled() + sent(changes, 1) + assert word.site()["revision"] == before["revision"] + 1 + page_shows(word, "opacity", css(word, "opacity", second), "after release") + run(word, "edit.undo") + word.restored_to(before["site"]) + page_shows(word, "opacity", start, "one undo after the drag") + + +def test_escape_during_a_slider_drag_puts_the_page_and_the_field_back_and_writes_nothing(word): + typed(word, "opacity", "0.9") + start = on_page(word, "opacity") + changes = Changes(word) + before = word.site() + pointer, x = drag_from(word, slider(word, "Opacity"), 0.85) + pointer.move(*x(0.25), steps=6, held=True) + shown_live(word, "opacity", ["", "0.9"]) + word.page.keyboard.press("Escape") + expect(field(word, "opacity")).to_have_value("0.9") + page_shows(word, "opacity", start, "after Escape during the drag") + pointer.move(*x(0.15), steps=3, held=True) + pointer.up() + changes.settled() + sent(changes, 0) + assert word.site() == before + page_shows(word, "opacity", start, "after the release that followed Escape") + + +def test_a_drag_in_the_color_square_colors_the_element_on_the_page_before_release_and_release_writes_once(word): + typed(word, "color", "#336699") + changes = Changes(word) + before = word.site() + open_picker(word, "Color") + pointer, at = drag_in(word, square(word, "Color"), (0.5, 0.5), (0.8, 0.25)) + first = shown_live(word, "color", ["", "#336699"]) + pointer.move(*at(0.9, 0.1), steps=4, held=True) + second = shown_live(word, "color", ["", "#336699", first]) + assert changes.sent == [] and word.site() == before, "a change was stored during the drag" + pointer.up() + word.until(lambda site: styles(site).get("color") == second, f"color {second} to be stored on release") + changes.settled() + sent(changes, 1) + assert word.site()["revision"] == before["revision"] + 1 + page_shows(word, "color", css(word, "color", second), "after release") + + +@pytest.mark.parametrize("bar", ["Hue", "Opacity"]) +def test_a_drag_on_the_hue_or_opacity_bar_of_the_picker_colors_the_element_on_the_page_before_release_and_writes_once(word, bar): + typed(word, "color", "#336699") + changes = Changes(word) + before = word.site() + open_picker(word, "Color") + pointer, x = drag_from(word, slider(word, f"{bar} of Color"), 0.9) + pointer.move(*x(0.5), steps=4, held=True) + first = shown_live(word, "color", ["", "#336699"]) + pointer.move(*x(0.2), steps=4, held=True) + second = shown_live(word, "color", ["", "#336699", first]) + assert changes.sent == [] and word.site() == before, "a change was stored during the drag" + pointer.up() + word.until(lambda site: styles(site).get("color") == second, f"color {second} to be stored on release") + changes.settled() + sent(changes, 1) + assert word.site()["revision"] == before["revision"] + 1 + page_shows(word, "color", css(word, "color", second), "after release") + + +def test_dragging_a_gradient_stop_changes_the_background_on_the_page_before_release_and_writes_once(word): + typed(word, "background", THREE) + changes = Changes(word) + before = word.site() + dialog = open_picker(word, "Background") + expect(dialog.get_by_role("tab", name="Gradient", exact=True)).to_have_attribute("aria-selected", "true") + bar = dialog.get_by_role("group", name="Gradient stops", exact=True).bounding_box() + stop = dialog.get_by_role("slider", name="Gradient stop 2", exact=True).bounding_box() + pointer = word.canvas_pointer() + y = stop["y"] + stop["height"] / 2 + pointer.move(stop["x"] + stop["width"] / 2, y) + pointer.down() + pointer.move(bar["x"] + bar["width"] * 0.35, y, steps=6, held=True) + first = shown_live(word, "background", ["", THREE]) + pointer.move(bar["x"] + bar["width"] * 0.2, y, steps=6, held=True) + second = shown_live(word, "background", ["", THREE, first]) + assert changes.sent == [] and word.site() == before, "a change was stored during the drag" + pointer.up() + word.until(lambda site: styles(site).get("background") == second, "the dragged gradient to be stored on release") + changes.settled() + sent(changes, 1) + assert word.site()["revision"] == before["revision"] + 1 + page_shows(word, "background", css(word, "background", second), "after release") + + +def test_a_held_arrow_key_on_a_slider_changes_the_page_at_each_step_and_writes_once_on_release(word): + changes = Changes(word) + before = word.site() + slider(word, "Opacity").focus() + values = [] + for _ in range(4): + word.page.keyboard.down("ArrowLeft") + values.append(step_shown(word, values[-1] if values else "")) + assert [float(v) for v in values] == sorted((float(v) for v in values), reverse=True) and len(set(values)) == 4, values + assert changes.sent == [], "a change was sent while the key was held" + assert word.site()["revision"] == before["revision"] + word.page.keyboard.up("ArrowLeft") + word.until(lambda site: styles(site).get("opacity") == values[-1], f"opacity {values[-1]} to be stored on key release") + changes.settled() + sent(changes, 1) + assert word.site()["revision"] == before["revision"] + 1 + page_shows(word, "opacity", css(word, "opacity", values[-1]), "after the key release") + + +def test_with_a_slow_engine_the_page_keeps_the_released_slider_value_and_never_shows_the_old_one_before_the_answer(word): + typed(word, "opacity", "0.9") + old = on_page(word, "opacity") + before = word.site() + held = hold_changes(word) + pointer, x = drag_from(word, slider(word, "Opacity"), 0.85) + pointer.move(*x(0.3), steps=6, held=True) + value = shown_live(word, "opacity", ["", "0.9"]) + sample(word, "opacity") + pointer.up() + word.eventually(lambda: held, "the release to send its change") + word.page.evaluate(FRAMES, 10) + assert word.site()["revision"] == before["revision"] + held.pop(0).continue_() + word.page.unroute(OWN_CHANGE) + word.until(lambda site: styles(site).get("opacity") == value, f"opacity {value} to be stored") + seen = samples(word) + assert seen and all(page != old for page, _ in seen), f"the page showed the old opacity {old} between release and answer: {story(seen)}" + assert seen[0][0] == css(word, "opacity", value) and seen[-1][0] == css(word, "opacity", value), f"the page did not show the released opacity {value} from release to answer: {story(seen)}" + assert revisions(seen) == {before["revision"], before["revision"] + 1}, f"the frames did not cover the release and the answer: {story(seen)}" + + +def test_with_a_slow_engine_the_page_keeps_the_released_square_color_and_never_shows_the_old_one_before_the_answer(word): + typed(word, "color", "#336699") + old = on_page(word, "color") + before = word.site() + open_picker(word, "Color") + held = hold_changes(word) + pointer, at = drag_in(word, square(word, "Color"), (0.5, 0.5), (0.85, 0.15)) + value = shown_live(word, "color", ["", "#336699"]) + sample(word, "color") + pointer.up() + word.eventually(lambda: held, "the release to send its change") + word.page.evaluate(FRAMES, 10) + assert word.site()["revision"] == before["revision"] + held.pop(0).continue_() + word.page.unroute(OWN_CHANGE) + word.until(lambda site: styles(site).get("color") == value, f"color {value} to be stored") + seen = samples(word) + assert seen and all(page != old for page, _ in seen), f"the page showed the old color {old} between release and answer: {story(seen)}" + assert seen[0][0] == css(word, "color", value) and seen[-1][0] == css(word, "color", value), f"the page did not show the released color {value} from release to answer: {story(seen)}" + assert revisions(seen) == {before["revision"], before["revision"] + 1}, f"the frames did not cover the release and the answer: {story(seen)}" + + +def test_a_slider_drag_cut_off_by_select_parent_leaves_both_elements_on_the_page_as_stored_and_writes_nothing(word): + start = on_page(word, "opacity") + parent = on_page(word, "opacity", PARENT) + changes = Changes(word) + before = word.site() + pointer, x = drag_from(word, slider(word, "Opacity"), 0.75) + pointer.move(*x(0.3), steps=6, held=True) + shown_live(word, "opacity", [""]) + run(word, "edit.select-parent") + expect(word.page.locator(".inspector-tag")).to_have_text(re.compile(rf"· {PARENT}$")) + page_shows(word, "opacity", start, "the element the drag began on, after Select parent") + page_shows(word, "opacity", parent, "the parent, after Select parent", PARENT) + pointer.move(*x(0.1), steps=4, held=True) + pointer.up() + changes.settled() + sent(changes, 0) + assert word.site() == before + expect(field(word, "opacity")).to_have_value("") + page_shows(word, "opacity", start, "the element the drag began on, after the release") + page_shows(word, "opacity", parent, "the parent, after the release", PARENT) + + +def test_a_color_square_drag_cut_off_by_select_parent_leaves_both_elements_on_the_page_as_stored_and_writes_nothing(word): + typed(word, "color", "#336699") + start = on_page(word, "color") + parent = on_page(word, "color", PARENT) + changes = Changes(word) + before = word.site() + open_picker(word, "Color") + pointer, at = drag_in(word, square(word, "Color"), (0.5, 0.5), (0.9, 0.1)) + shown_live(word, "color", ["", "#336699"]) + run(word, "edit.select-parent") + expect(word.page.locator(".inspector-tag")).to_have_text(re.compile(rf"· {PARENT}$")) + page_shows(word, "color", start, "the element the drag began on, after Select parent") + page_shows(word, "color", parent, "the parent, after Select parent", PARENT) + pointer.move(*at(0.7, 0.3), steps=3, held=True) + pointer.up() + changes.settled() + sent(changes, 0) + assert word.site() == before + page_shows(word, "color", start, "the element the drag began on, after the release") + page_shows(word, "color", parent, "the parent, after the release", PARENT) + + +def test_escape_during_a_drag_in_the_color_square_puts_the_stored_color_back_on_the_page_and_writes_nothing(word): + typed(word, "color", "#336699") + start = on_page(word, "color") + changes = Changes(word) + before = word.site() + open_picker(word, "Color") + pointer, at = drag_in(word, square(word, "Color"), (0.5, 0.5), (0.1, 0.9)) + shown_live(word, "color", ["", "#336699"]) + word.page.keyboard.press("Escape") + expect(field(word, "color")).to_have_value("#336699") + page_shows(word, "color", start, "after Escape during the drag") + pointer.move(*at(0.2, 0.8), steps=3, held=True) + pointer.up() + changes.settled() + sent(changes, 0) + assert word.site() == before + page_shows(word, "color", start, "after the release that followed Escape") + + +def test_a_slider_drag_cut_off_by_a_breakpoint_change_puts_the_page_back_and_writes_nothing(word): + start = on_page(word, "opacity") + changes = Changes(word) + before = word.site() + pointer, x = drag_from(word, slider(word, "Opacity"), 0.75) + pointer.move(*x(0.3), steps=6, held=True) + shown_live(word, "opacity", [""]) + run(word, "view.tablet") + expect(breakpoint_choice(word)).to_have_value("tablet") + page_shows(word, "opacity", start, "at tablet, after the breakpoint change during the drag") + pointer.move(*x(0.1), steps=4, held=True) + pointer.up() + changes.settled() + sent(changes, 0) + assert word.site() == before + page_shows(word, "opacity", start, "at tablet, after the release") + run(word, "view.desktop") + expect(breakpoint_choice(word)).to_have_value("desktop") + page_shows(word, "opacity", start, "back at desktop") + + +def test_another_writer_during_a_slider_drag_is_drawn_while_the_page_keeps_the_dragged_value_and_release_stores_it(word): + changes = Changes(word) + before = word.site() + pointer, x = drag_from(word, slider(word, "Opacity"), 0.75) + pointer.move(*x(0.3), steps=6, held=True) + value = shown_live(word, "opacity", [""]) + word.command("node.update", {"id": NODE, "patch": {"styles": {"opacity": "0.77", "background": "#00aa00"}}}) + word.until(lambda site: styles(site).get("background") == "#00aa00", "the other writer's change") + page_shows(word, "background-color", "rgb(0, 170, 0)", "the other writer's background") + page_shows(word, "opacity", css(word, "opacity", value), "the dragged opacity over the other writer's change") + pointer.up() + word.until(lambda site: styles(site).get("opacity") == value, f"the dragged opacity {value} to be stored on release") + changes.settled() + sent(changes, 1) + assert word.site()["revision"] == before["revision"] + 2 + page_shows(word, "opacity", css(word, "opacity", value), "after release") + expect(field(word, "opacity")).to_have_value(value) + + +def test_a_slider_drag_that_ends_on_its_start_value_writes_nothing_and_the_page_shows_the_stored_value(word): + pointer, x = drag_from(word, slider(word, "Opacity"), 0.5) + pointer.up() + word.until(lambda site: styles(site).get("opacity") == "0.5", "opacity 0.5 from one click at the middle") + stored_look = css(word, "opacity", "0.5") + page_shows(word, "opacity", stored_look, "after the click") + changes = Changes(word) + before = word.site() + pointer.down() + pointer.move(*x(0.15), steps=6, held=True) + shown_live(word, "opacity", ["", "0.5"]) + pointer.move(*x(0.5), steps=6, held=True) + expect(field(word, "opacity")).to_have_value("0.5") + pointer.up() + changes.settled() + sent(changes, 0) + assert word.site() == before + page_shows(word, "opacity", stored_look, "after the release on the start value") + + +def test_a_release_the_engine_refuses_puts_the_page_and_the_field_back_and_shows_the_reason(word): + start = on_page(word, "opacity") + before = word.site() + refused = [] + + def refuse(route): + refused.append(route.request.post_data) + route.fulfill(status=400, content_type="application/json", body=json.dumps({"detail": "Refused by the drag test."})) + + word.page.route(OWN_CHANGE, refuse) + pointer, x = drag_from(word, slider(word, "Opacity"), 0.8) + pointer.move(*x(0.3), steps=6, held=True) + shown_live(word, "opacity", [""]) + pointer.up() + expect(word.status).to_contain_text("Refused by the drag test.") + assert len(refused) == 1 + page_shows(word, "opacity", start, "after the refused release") + expect(field(word, "opacity")).to_have_value("") + assert word.site() == before + + +def test_the_brand_restriction_coming_on_during_a_square_drag_drops_it_and_the_page_shows_the_stored_color_never_black(word): + typed(word, "color", "#405980") + stored_look = css(word, "color", "#405980") + black = css(word, "color", "#000000") + page_shows(word, "color", stored_look, "the typed color") + changes = Changes(word) + before = word.site() + open_picker(word, "Color") + pointer, at = drag_in(word, square(word, "Color"), (0.5, 0.5), (0.85, 0.2)) + shown_live(word, "color", ["", "#405980"]) + sample(word, "color") + word.command("site.update", {"patch": {"settings": {"brandRestrict": "true"}}}) + word.until(lambda site: site["settings"].get("brandRestrict") == "true", "the brand restriction") + expect(square(word, "Color")).to_be_hidden() + page_shows(word, "color", stored_look, "once the restriction is on, with the button still down") + pointer.move(*at(0.6, 0.6), steps=6, held=True) + pointer.move(*at(0.3, 0.8), steps=6, held=True) + pointer.up() + changes.settled() + seen = samples(word) + assert black not in [page for page, _ in seen], f"the page showed black during the dropped drag: {story(seen)}" + sent(changes, 0) + after = word.site() + assert after["revision"] == before["revision"] + 1 + assert styles(after["site"]).get("color") == "#405980" + page_shows(word, "color", stored_look, "after the release") + expect(field(word, "color")).to_have_value("#405980") + + +def test_resting_the_pointer_on_the_slider_the_square_the_bars_and_the_swatches_changes_nothing_on_the_page(word): + typed(word, "color", "#336699") + changes = Changes(word) + before = word.site() + start = on_page(word, "opacity") + sample(word, "opacity") + pointer = word.canvas_pointer() + rest = lambda box, fx, fy: pointer.move(box["x"] + box["width"] * fx, box["y"] + box["height"] * fy, steps=5) + for fx in (0.1, 0.5, 0.9): + rest(slider(word, "Opacity").bounding_box(), fx, 0.5) + word.page.evaluate(FRAMES, 20) + opacity_seen = samples(word) + dialog = open_picker(word, "Color") + color_start = on_page(word, "color") + sample(word, "color") + for name in ("Saturation and brightness of Color", "Hue of Color", "Opacity of Color"): + for fx, fy in ((0.2, 0.3), (0.8, 0.7)): + rest(slider(word, name).bounding_box(), fx, fy) + word.page.evaluate(FRAMES, 20) + for button in dialog.get_by_role("button").filter(visible=True).all()[:6]: + rest(button.bounding_box(), 0.5, 0.5) + word.page.evaluate(FRAMES, 20) + color_seen = samples(word) + assert {page for page, _ in opacity_seen} == {start}, f"resting on the slider changed the page: {story(opacity_seen)}" + assert {page for page, _ in color_seen} == {color_start}, f"resting on the picker changed the page: {story(color_seen)}" + sent(changes, 0) + assert word.site() == before + rest(square(word, "Color").bounding_box(), 0.5, 0.5) + pointer.down() + pointer.move(*(lambda b: (b["x"] + b["width"] * 0.9, b["y"] + b["height"] * 0.1))(square(word, "Color").bounding_box()), steps=4, held=True) + shown_live(word, "color", ["", "#336699"]) + word.page.keyboard.press("Escape") + pointer.up() + page_shows(word, "color", color_start, "after Escape") + + +def test_with_trying_switched_off_a_slider_drag_still_shows_on_the_page_and_writes_once_on_release(word): + word.page.locator('[data-menu="View"]').click() + item = word.page.locator('[role="menu"]:visible [data-command="view.try-choices"]') + expect(item).to_have_attribute("aria-checked", "true") + item.click() + word.page.locator('[data-menu="View"]').click() + expect(item).to_have_attribute("aria-checked", "false") + word.page.keyboard.press("Escape") + expect(item).to_be_hidden() + changes = Changes(word) + before = word.site() + pointer, x = drag_from(word, slider(word, "Opacity"), 0.8) + pointer.move(*x(0.3), steps=6, held=True) + value = shown_live(word, "opacity", [""]) + assert changes.sent == [] and word.site() == before, "a change was stored during the drag" + pointer.up() + word.until(lambda site: styles(site).get("opacity") == value, f"opacity {value} to be stored on release") + changes.settled() + sent(changes, 1) + assert word.site()["revision"] == before["revision"] + 1 + page_shows(word, "opacity", css(word, "opacity", value), "after release") + + +def test_under_tablet_the_page_shows_the_dragged_value_and_release_writes_tablet_only(word): + breakpoint_choice(word).select_option("tablet") + expect(breakpoint_choice(word)).to_have_value("tablet") + desktop_look = on_page(word, "opacity") + changes = Changes(word) + before = word.site() + pointer, x = drag_from(word, slider(word, "Opacity"), 0.8) + pointer.move(*x(0.35), steps=6, held=True) + value = shown_live(word, "opacity", [""]) + assert changes.sent == [] and word.site() == before, "a change was stored during the drag" + pointer.up() + after = word.until(lambda site: styles(site, breakpoint="tablet").get("opacity") == value, f"tablet opacity {value}") + changes.settled() + sent(changes, 1) + assert styles(after).get("opacity") == styles(before["site"]).get("opacity") + page_shows(word, "opacity", css(word, "opacity", value), "at tablet after release") + run(word, "view.desktop") + expect(breakpoint_choice(word)).to_have_value("desktop") + page_shows(word, "opacity", desktop_look, "back at desktop") + + +def test_a_value_being_typed_into_the_field_is_not_shown_on_the_page_until_enter_writes_it(word): + start = on_page(word, "opacity") + changes = Changes(word) + before = word.site() + box = field(word, "opacity") + box.click() + sample(word, "opacity") + for text in ("0", "0.", "0.3"): + box.fill(text) + word.page.evaluate(FRAMES, 10) + seen = samples(word) + assert {page for page, _ in seen} == {start}, f"text being typed reached the page: {story(seen)}" + assert changes.sent == [] and word.site() == before + box.press("Enter") + word.until(lambda site: styles(site).get("opacity") == "0.3", "opacity 0.3 on Enter") + changes.settled() + sent(changes, 1) + page_shows(word, "opacity", css(word, "opacity", "0.3"), "after Enter") + + +def test_the_hover_outline_stays_off_while_a_held_key_shows_a_slider_value_and_comes_back_after(word): + marked = word.canvas.locator("[data-fw-hover]") + row = word.layer_row("h-tools") + row.scroll_into_view_if_needed() + box = row.bounding_box() + footer = word.page.locator("footer.statusbar").bounding_box() + pointer = word.canvas_pointer() + point = lambda fx: pointer.move(box["x"] + box["width"] * fx, box["y"] + box["height"] / 2, steps=3) + away = lambda: pointer.move(footer["x"] + footer["width"] / 2, footer["y"] + footer["height"] / 2, steps=3) + point(0.4) + expect(marked).to_have_count(1) + away() + expect(marked).to_have_count(0) + changes = Changes(word) + held = hold_changes(word) + slider(word, "Opacity").focus() + word.page.keyboard.down("ArrowLeft") + shown_live(word, "opacity", [""]) + for fx in (0.3, 0.5, 0.7): + word.page.keyboard.down("ArrowLeft") + point(fx) + word.page.evaluate(FRAMES, 3) + assert marked.count() == 0, "a hover outline was drawn while the held key showed its value on the page" + word.page.keyboard.up("ArrowLeft") + word.eventually(lambda: held and len(held) == len(changes.sent), "the key release to send its change") + point(0.4) + word.page.evaluate(FRAMES, 3) + assert marked.count() == 0, "a hover outline was drawn while the released value waited for its answer" + word.eventually(lambda: len(held) == len(changes.sent), "every change of the held key to be held") + for route in held: + route.continue_() + word.page.unroute(OWN_CHANGE) + changes.settled() + away() + point(0.6) + expect(marked).to_have_count(1) diff --git a/frontend/tests/window/test_try_lists.py b/frontend/tests/window/test_try_lists.py new file mode 100644 index 00000000..88b285f8 --- /dev/null +++ b/frontend/tests/window/test_try_lists.py @@ -0,0 +1,584 @@ +import re + +import pytest +from playwright.sync_api import expect + +OWN_CHANGE = re.compile(r"/api/(command|batch)$") +NODE = "h-logo-word" +LIST_FIELDS = (("align-self", "Align self"), ("justify-self", "Justify self"), ("object-fit", "Object fit"), ("font-weight", "Weight"), ("font-variant-caps", "Capitals"), ("font-kerning", "Kerning"), ("position", "Position"), ("overflow", "Overflow")) +FRAMES = "n => new Promise(done => { const step = left => left ? requestAnimationFrame(() => step(left - 1)) : done(); step(n); })" +BOXES = """() => [...document.querySelectorAll('.inspector [data-style]')].map(node => { + const scroller = node.closest('.inspector-scroll'); + const origin = scroller.getBoundingClientRect(); + const box = node.closest('.field').getBoundingClientRect(); + return [node.dataset.style, box.x - origin.x, box.y - origin.y + scroller.scrollTop, box.width, box.height]; +})""" +WATCH_BODY = """() => { + window.__bodyFocused = 0; + const tick = () => { if (document.activeElement === document.body || !document.activeElement) window.__bodyFocused++; requestAnimationFrame(tick); }; + document.addEventListener('focusin', () => { if (document.activeElement === document.body) window.__bodyFocused++; }, true); + requestAnimationFrame(tick); +}""" +FOCUSED = "() => { const a = document.activeElement; return a === document.body ? 'body' : (a.dataset.style || a.getAttribute('role') || a.textContent.trim().slice(0, 20)); }" + + +class Sent: + def __init__(self, editor): + self.requests = [] + editor.page.on("request", lambda r: self.requests.append(r.post_data) if r.method == "POST" and OWN_CHANGE.search(r.url) else None) + + def __len__(self): + return len(self.requests) + + +def choice(editor, key): + return editor.page.locator(f'select[data-style="{key}"]') + + +def listbox(editor): + return editor.page.get_by_role("listbox") + + +def option(editor, name): + return listbox(editor).get_by_role("option", name=name, exact=True) + + +def bar(editor): + return editor.page.locator("[data-try-bar]") + + +def bar_button(editor, name): + return bar(editor).get_by_role("button", name=re.compile(rf"^{name}")) + + +def computed(editor, prop): + return editor.canvas.locator(f'[data-fw-id="{NODE}"]').evaluate(f"e => getComputedStyle(e).getPropertyValue('{prop}')") + + +def shows(editor, prop, value): + expect(editor.canvas.locator(f'[data-fw-id="{NODE}"]'), f"{prop} of {NODE} on the page").to_have_css(prop, value) + + +def stored(editor, key, site=None): + return (site or editor.site()["site"])["nodes"][NODE]["styles"].get(key) + + +def browser_popup_open(select): + return select.evaluate("s => s.matches(':open')") + + +def focused(editor): + return editor.page.evaluate(FOCUSED) + + +def frames(editor, count): + editor.page.evaluate(FRAMES, count) + + +def run(editor, command): + editor.page.evaluate(f"window.formweb.run('{command}')") + + +def open_list(editor, key): + field = choice(editor, key) + field.scroll_into_view_if_needed() + field.click() + expect(listbox(editor)).to_be_visible() + return field + + +def inside_window(editor, box): + size = editor.page.viewport_size + return box["x"] >= 0 and box["y"] >= 0 and box["x"] + box["width"] <= size["width"] and box["y"] + box["height"] <= size["height"] + + +@pytest.fixture +def logo(harbour): + harbour.layer_row(NODE).click() + expect(harbour.page.locator(".inspector-tag")).to_have_text(re.compile(rf"· {NODE}$")) + assert stored(harbour, "font-weight") == "700" and stored(harbour, "align-self") is None + return harbour + + +def test_a_click_on_a_choice_field_opens_the_editors_own_list_of_the_same_choices_with_the_stored_one_marked(logo): + field = choice(logo, "font-weight") + names = field.locator("option").all_inner_texts() + field.scroll_into_view_if_needed() + field.click() + expect(listbox(logo)).to_be_visible() + assert not browser_popup_open(field), "the browser's own popup opened as well" + expect(field).to_have_attribute("aria-expanded", "true") + expect(listbox(logo)).to_have_accessible_name("Weight") + expect(listbox(logo).get_by_role("option")).to_have_text(names) + expect(listbox(logo).locator('[role="option"][aria-selected="true"]')).to_have_text(["700"]) + expect(option(logo, "700").locator("svg")).to_be_visible() + expect(option(logo, "400").locator("svg")).to_be_hidden() + assert inside_window(logo, listbox(logo).bounding_box()), listbox(logo).bounding_box() + expect(bar(logo)).to_be_hidden() + + +def test_a_click_on_a_list_item_tries_it_on_the_page_keeps_the_list_open_and_writes_nothing(logo): + sent = Sent(logo) + before = logo.site() + field = open_list(logo, "font-weight") + shows(logo, "font-weight", "700") + option(logo, "400").click() + shows(logo, "font-weight", "400") + expect(listbox(logo)).to_be_visible() + expect(bar(logo)).to_be_visible() + expect(bar(logo)).to_contain_text("Trying: 400") + expect(option(logo, "400")).to_have_attribute("aria-selected", "true") + expect(field).to_have_value("700") + frames(logo, 10) + assert len(sent) == 0, sent.requests + assert logo.site() == before + + +def test_arrow_keys_home_and_end_move_through_the_list_and_try_each_item_without_writing(logo): + sent = Sent(logo) + before = logo.site() + open_list(logo, "align-self") + shows(logo, "align-self", "auto") + steps = (("ArrowDown", "auto", "auto"), ("ArrowDown", "stretch", "stretch"), ("ArrowDown", "center", "center"), ("ArrowUp", "stretch", "stretch"), + ("End", "end", "end"), ("Home", "Inherit", "auto"), ("End", "end", "end")) + for key, row, value in steps: + logo.page.keyboard.press(key) + shows(logo, "align-self", value) + expect(listbox(logo).locator('[role="option"][aria-selected="true"]'), f"after {key}").to_have_text([row]) + expect(listbox(logo)).to_be_visible() + expect(choice(logo, "align-self")).to_have_value("") + assert len(sent) == 0, sent.requests + assert logo.site() == before + + +def test_a_typed_letter_in_the_list_goes_to_the_next_item_starting_with_it_and_tries_it(logo): + sent = Sent(logo) + before = logo.site() + open_list(logo, "align-self") + for letter, value in (("s", "stretch"), ("s", "start"), ("S", "stretch"), ("c", "center"), ("e", "end")): + logo.page.keyboard.press(letter) + shows(logo, "align-self", value) + expect(option(logo, value)).to_have_attribute("aria-selected", "true") + assert len(sent) == 0, sent.requests + assert logo.site() == before + + +def test_a_typed_letter_on_the_closed_field_opens_the_list_and_tries_the_matching_item_without_changing_the_field(logo): + sent = Sent(logo) + before = logo.site() + field = choice(logo, "align-self") + field.scroll_into_view_if_needed() + field.focus() + logo.page.keyboard.press("c") + expect(listbox(logo)).to_be_visible() + shows(logo, "align-self", "center") + expect(option(logo, "center")).to_have_attribute("aria-selected", "true") + expect(field).to_have_value("") + frames(logo, 10) + assert len(sent) == 0, sent.requests + assert logo.site() == before + + +def test_keys_on_the_closed_field_open_the_list_and_never_change_the_stored_value_by_themselves(logo): + sent = Sent(logo) + before = logo.site() + field = choice(logo, "align-self") + field.scroll_into_view_if_needed() + for key in ("ArrowDown", "ArrowUp", "ArrowRight", "ArrowLeft", "PageDown", "PageUp", "Home", "End"): + field.focus() + logo.page.keyboard.press(key) + expect(listbox(logo), f"{key} on the closed field did not open the list").to_be_visible() + expect(field, f"{key} on the closed field changed its value").to_have_value("") + logo.page.keyboard.press("Escape") + expect(listbox(logo)).to_be_hidden() + shows(logo, "align-self", "auto") + frames(logo, 10) + assert len(sent) == 0, sent.requests + assert logo.site() == before + + +def test_space_enter_arrow_down_and_alt_arrow_down_on_the_focused_field_open_the_list_and_try_nothing(logo): + sent = Sent(logo) + before = logo.site() + field = choice(logo, "font-weight") + field.scroll_into_view_if_needed() + for key in ("Space", "Enter", "ArrowDown", "ArrowUp", "Alt+ArrowDown"): + field.focus() + logo.page.keyboard.press(key) + expect(listbox(logo), f"{key} did not open the list").to_be_visible() + assert not browser_popup_open(field), f"{key} opened the browser's own popup" + frames(logo, 3) + assert computed(logo, "font-weight") == "700", f"{key} tried something" + expect(bar(logo)).to_be_hidden() + expect(listbox(logo).locator('[role="option"][aria-selected="true"]')).to_have_text(["700"]) + expect(field).to_have_value("700") + logo.page.keyboard.press("Escape") + expect(listbox(logo)).to_be_hidden() + assert focused(logo) == "font-weight", f"after Escape focus is on {focused(logo)!r}, not the field" + assert len(sent) == 0, sent.requests + assert logo.site() == before + + +def test_enter_keeps_the_tried_item_in_one_undo_step_closes_the_list_and_the_field_shows_it(logo): + sent = Sent(logo) + before = logo.site() + field = open_list(logo, "font-weight") + option(logo, "400").click() + shows(logo, "font-weight", "400") + logo.page.keyboard.press("Enter") + after = logo.until(lambda site: stored(logo, "font-weight", site) == "400", "the kept weight") + assert logo.site()["revision"] == before["revision"] + 1 + assert len(sent) == 1, sent.requests + expect(listbox(logo)).to_be_hidden() + expect(bar(logo)).to_be_hidden() + expect(field).to_have_value("400") + shows(logo, "font-weight", "400") + assert focused(logo) == "font-weight" + assert after["nodes"][NODE]["styles"] == {**before["site"]["nodes"][NODE]["styles"], "font-weight": "400"} + run(logo, "edit.undo") + logo.restored_to(before["site"]) + expect(field).to_have_value("700") + shows(logo, "font-weight", "700") + + +def test_the_keep_button_keeps_the_tried_item_and_puts_focus_back_on_the_field(logo): + before = logo.site() + field = open_list(logo, "align-self") + option(logo, "end").click() + shows(logo, "align-self", "end") + bar_button(logo, "Keep").click() + logo.until(lambda site: stored(logo, "align-self", site) == "end", "the kept alignment") + assert logo.site()["revision"] == before["revision"] + 1 + expect(listbox(logo)).to_be_hidden() + expect(field).to_have_value("end") + assert focused(logo) == "align-self" + run(logo, "edit.undo") + logo.restored_to(before["site"]) + + +def test_undo_and_redo_pressed_on_the_focused_field_after_keep_act_and_the_field_shows_the_stored_value_while_focused(logo): + before = logo.site() + field = open_list(logo, "font-weight") + option(logo, "400").click() + logo.page.keyboard.press("Enter") + kept = logo.until(lambda site: stored(logo, "font-weight", site) == "400", "the kept weight") + expect(field).to_have_value("400") + assert focused(logo) == "font-weight" + logo.page.keyboard.press("Control+z") + logo.restored_to(before["site"]) + expect(field).to_have_value("700") + shows(logo, "font-weight", "700") + assert focused(logo) == "font-weight", "focus left the field before the undone value showed" + logo.page.keyboard.press("Control+Shift+z") + logo.until(lambda site: site == kept, "the redo") + expect(field).to_have_value("400") + shows(logo, "font-weight", "400") + assert focused(logo) == "font-weight" + + +def test_cut_pressed_on_a_focused_list_field_does_not_remove_the_element(logo): + logo.page.context.grant_permissions(["clipboard-read", "clipboard-write"], origin=logo.base) + before = logo.site() + logo.layer_row(NODE).click() + logo.page.keyboard.press("Control+x") + logo.until(lambda site: NODE not in site["nodes"], "Cut from the Layers list to remove the element") + run(logo, "edit.undo") + logo.restored_to(before["site"]) + logo.layer_row(NODE).click() + expect(logo.page.locator(".inspector-tag")).to_have_text(re.compile(rf"· {NODE}$")) + field = choice(logo, "font-weight") + field.scroll_into_view_if_needed() + field.focus() + revision = logo.site()["revision"] + logo.page.keyboard.press("Control+x") + open_list(logo, "font-weight") + logo.page.keyboard.press("Escape") + frames(logo, 10) + assert NODE in logo.site()["site"]["nodes"], "Cut on the focused field removed the element" + assert logo.site()["revision"] == revision, "Cut on the focused field changed the site" + expect(logo.canvas.locator(f'[data-fw-id="{NODE}"]')).to_be_attached() + + +def test_escape_closes_the_list_reverts_the_page_and_says_the_field_is_unchanged(logo): + sent = Sent(logo) + before = logo.site() + field = open_list(logo, "font-weight") + option(logo, "900").click() + shows(logo, "font-weight", "900") + logo.page.keyboard.press("Escape") + expect(listbox(logo)).to_be_hidden() + expect(bar(logo)).to_be_hidden() + shows(logo, "font-weight", "700") + expect(field).to_have_value("700") + expect(logo.status).to_have_text("Not kept: Weight is unchanged.") + assert focused(logo) == "font-weight" + frames(logo, 10) + assert len(sent) == 0, sent.requests + assert logo.site() == before + + +def test_the_revert_button_closes_the_list_reverts_the_page_and_puts_focus_back_on_the_field(logo): + sent = Sent(logo) + before = logo.site() + field = open_list(logo, "align-self") + option(logo, "center").click() + shows(logo, "align-self", "center") + bar_button(logo, "Revert").click() + expect(listbox(logo)).to_be_hidden() + shows(logo, "align-self", "auto") + expect(field).to_have_value("") + assert focused(logo) == "align-self" + frames(logo, 10) + assert len(sent) == 0, sent.requests + assert logo.site() == before + + +def test_a_click_outside_the_list_closes_it_and_reverts_the_page_without_dropping_focus_to_the_page(logo): + sent = Sent(logo) + before = logo.site() + field = open_list(logo, "align-self") + option(logo, "center").click() + shows(logo, "align-self", "center") + logo.page.locator(".inspector-tabs").click(position={"x": 2, "y": 2}) + expect(listbox(logo)).to_be_hidden() + expect(bar(logo)).to_be_hidden() + shows(logo, "align-self", "auto") + expect(field).to_have_value("") + frames(logo, 5) + assert focused(logo) == "align-self", f"focus is on {focused(logo)!r}, not the field" + assert len(sent) == 0, sent.requests + assert logo.site() == before + + +def test_a_click_into_another_fields_text_box_reverts_the_trial_and_leaves_focus_there(logo): + before = logo.site() + open_list(logo, "align-self") + option(logo, "center").click() + shows(logo, "align-self", "center") + logo.page.locator('input[data-style="width"]').click() + expect(listbox(logo)).to_be_hidden() + shows(logo, "align-self", "auto") + frames(logo, 5) + assert focused(logo) == "width" + assert logo.site() == before + + +def test_tab_from_revert_goes_on_to_the_next_field_reverts_the_trial_and_never_leaves_focus_on_the_page(logo): + sent = Sent(logo) + before = logo.site() + open_list(logo, "align-self") + logo.page.evaluate(WATCH_BODY) + logo.page.keyboard.press("ArrowDown") + logo.page.keyboard.press("ArrowDown") + shows(logo, "align-self", "stretch") + logo.page.keyboard.press("Tab") + expect(bar_button(logo, "Keep")).to_be_focused() + logo.page.keyboard.press("Tab") + expect(bar_button(logo, "Revert")).to_be_focused() + shows(logo, "align-self", "stretch") + logo.page.keyboard.press("Tab") + expect(choice(logo, "justify-self"), "Tab from Revert did not go on to the next field").to_be_focused() + shows(logo, "align-self", "auto") + expect(listbox(logo)).to_be_hidden() + expect(bar(logo)).to_be_hidden() + frames(logo, 5) + assert logo.page.evaluate("window.__bodyFocused") == 0, "focus was on the page body on the way" + assert len(sent) == 0, sent.requests + assert logo.site() == before + + +def test_turning_trying_off_while_a_list_trial_is_on_closes_the_list_puts_the_page_back_and_keeps_focus_on_the_field(logo): + sent = Sent(logo) + before = logo.site() + field = open_list(logo, "font-weight") + option(logo, "900").click() + shows(logo, "font-weight", "900") + run(logo, "view.try-choices") + expect(listbox(logo)).to_be_hidden() + expect(bar(logo)).to_be_hidden() + shows(logo, "font-weight", "700") + expect(field).to_have_value("700") + frames(logo, 5) + assert focused(logo) == "font-weight" + assert len(sent) == 0, sent.requests + assert logo.site() == before + + +def test_a_click_on_another_element_on_the_canvas_closes_the_list_and_drops_the_trial(logo): + sent = Sent(logo) + before = logo.site() + open_list(logo, "font-weight") + option(logo, "400").click() + shows(logo, "font-weight", "400") + logo.canvas.locator('[data-fw-id="h-tools"]').click() + expect(logo.page.locator(".inspector-tag")).not_to_have_text(re.compile(rf"· {NODE}$")) + expect(listbox(logo)).to_be_hidden() + expect(bar(logo)).to_be_hidden() + shows(logo, "font-weight", "700") + frames(logo, 5) + assert len(sent) == 0, sent.requests + assert logo.site() == before + + +def test_delete_and_backspace_in_the_list_and_on_keep_and_revert_remove_nothing(logo): + before = logo.site() + logo.layer_row(NODE).click() + logo.page.keyboard.press("Delete") + logo.until(lambda site: NODE not in site["nodes"], "Delete from the Layers list to remove the element") + run(logo, "edit.undo") + logo.restored_to(before["site"]) + logo.layer_row(NODE).click() + expect(logo.page.locator(".inspector-tag")).to_have_text(re.compile(rf"· {NODE}$")) + before = logo.site() + sent = Sent(logo) + open_list(logo, "align-self") + option(logo, "center").click() + for target in (listbox(logo), bar_button(logo, "Keep"), bar_button(logo, "Revert")): + target.focus() + for key in ("Delete", "Backspace"): + logo.page.keyboard.press(key) + shows(logo, "align-self", "center") + frames(logo, 10) + assert len(sent) == 0, sent.requests + assert logo.site() == before + expect(logo.canvas.locator(f'[data-fw-id="{NODE}"]')).to_be_attached() + + +def test_while_keep_is_pending_rows_and_keys_do_nothing_and_exactly_the_kept_item_is_written(logo): + page = logo.page + held = [] + page.route(OWN_CHANGE, lambda route: held.append(route)) + sent = Sent(logo) + before = logo.site() + field = open_list(logo, "font-weight") + option(logo, "400").click() + shows(logo, "font-weight", "400") + page.keyboard.press("Enter") + logo.eventually(lambda: held, "Keep to send its command") + expect(listbox(logo)).to_have_attribute("aria-busy", "true") + option(logo, "900").click() + page.keyboard.press("ArrowDown") + page.keyboard.press("Home") + page.keyboard.press("Escape") + page.keyboard.press("Enter") + frames(logo, 10) + shows(logo, "font-weight", "400") + assert len(sent) == 1, f"while Keep was pending the window sent {sent.requests}" + assert logo.site() == before + held.pop(0).continue_() + page.unroute(OWN_CHANGE) + logo.until(lambda site: stored(logo, "font-weight", site) == "400", "the kept weight") + expect(listbox(logo)).to_be_hidden() + expect(field).to_have_value("400") + shows(logo, "font-weight", "400") + frames(logo, 10) + assert len(sent) == 1, sent.requests + assert logo.site()["revision"] == before["revision"] + 1 + + +def test_pointing_at_list_rows_and_at_keep_and_revert_changes_nothing_on_the_page(logo): + sent = Sent(logo) + before = logo.site() + open_list(logo, "align-self") + pointer = logo.canvas_pointer() + for name in ("stretch", "center", "start", "end"): + box = option(logo, name).bounding_box() + pointer.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2, steps=5) + frames(logo, 60) + assert computed(logo, "align-self") == "auto", f"pointing at {name} changed the page" + expect(bar(logo)).to_be_hidden() + expect(listbox(logo).locator('[role="option"][aria-selected="true"]')).to_have_text(["Inherit"]) + option(logo, "center").click() + shows(logo, "align-self", "center") + for name in ("Keep", "Revert"): + box = bar_button(logo, name).bounding_box() + pointer.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2, steps=5) + frames(logo, 60) + assert computed(logo, "align-self") == "center", f"pointing at {name} changed the page" + expect(listbox(logo)).to_be_visible() + assert len(sent) == 0, sent.requests + assert logo.site() == before + + +def test_no_inspector_field_moves_or_changes_size_when_a_list_trial_starts_changes_or_ends(logo): + expect(listbox(logo)).to_be_hidden() + choice(logo, "align-self").scroll_into_view_if_needed() + start = logo.page.evaluate(BOXES) + open_list(logo, "align-self") + assert logo.page.evaluate(BOXES) == start, "a field moved when the list opened" + option(logo, "center").click() + shows(logo, "align-self", "center") + assert logo.page.evaluate(BOXES) == start, "a field moved when the trial started" + logo.page.keyboard.press("End") + shows(logo, "align-self", "end") + assert logo.page.evaluate(BOXES) == start, "a field moved when the trial changed" + logo.page.keyboard.press("Escape") + shows(logo, "align-self", "auto") + expect(listbox(logo)).to_be_hidden() + assert logo.page.evaluate(BOXES) == start, "a field moved when the trial ended" + + +def test_a_program_that_sets_the_field_and_fires_change_still_writes_at_once(logo): + before = logo.site() + field = choice(logo, "align-self") + field.evaluate("s => { s.value = 'center'; s.dispatchEvent(new Event('change', { bubbles: true })); }") + logo.until(lambda site: stored(logo, "align-self", site) == "center", "the program's value to be stored") + assert logo.site()["revision"] == before["revision"] + 1 + shows(logo, "align-self", "center") + expect(listbox(logo)).to_be_hidden() + expect(field).to_have_value("center") + + +def test_with_trying_switched_off_the_field_is_the_browsers_own_select_and_a_pick_writes_at_once(logo): + field = choice(logo, "align-self") + field.scroll_into_view_if_needed() + field.click() + expect(listbox(logo)).to_be_visible() + logo.page.keyboard.press("Escape") + expect(listbox(logo)).to_be_hidden() + run(logo, "view.try-choices") + assert logo.page.evaluate("localStorage.getItem('formweb.try-choices')") == "0" + before = logo.site() + field.click() + logo.eventually(lambda: browser_popup_open(field), "the browser's own popup to open") + expect(listbox(logo)).to_be_hidden() + logo.page.keyboard.press("Escape") + field.select_option("stretch") + logo.until(lambda site: stored(logo, "align-self", site) == "stretch", "the pick to be stored") + assert logo.site()["revision"] == before["revision"] + 1 + shows(logo, "align-self", "stretch") + expect(listbox(logo)).to_be_hidden() + expect(bar(logo)).to_be_hidden() + + +@pytest.mark.parametrize("width", [900, 1440]) +def test_every_list_is_placed_fully_on_screen_next_to_its_field_at_the_bottom_and_the_top_of_the_scrolled_inspector(logo, width): + logo.page.set_viewport_size({"width": width, "height": 900}) + scroller = logo.page.locator(".inspector-scroll") + scroller.evaluate("s => { s.scrollTop = s.scrollHeight; }") + frames(logo, 2) + assert scroller.evaluate("s => s.scrollTop > 0 && s.scrollTop + s.clientHeight >= s.scrollHeight - 1"), "the inspector did not scroll to its end" + edges = scroller.bounding_box() + for key, name in LIST_FIELDS: + for edge in ("end", "start"): + field = choice(logo, key) + field.evaluate(f"s => s.scrollIntoView({{ block: '{edge}' }})") + own = field.bounding_box() + near = own["y"] + own["height"] >= edges["y"] + edges["height"] - 2 if edge == "end" else own["y"] <= edges["y"] + 2 + assert near, f"{name} {own} is not at the {edge} of the inspector {edges}" + field.click() + expect(listbox(logo)).to_be_visible() + expect(listbox(logo)).to_have_accessible_name(name) + frames(logo, 2) + pop = listbox(logo).bounding_box() + own = field.bounding_box() + where = f"{name} at the {edge} of the inspector, {width} px wide" + assert inside_window(logo, pop), f"{where}: the list {pop} is not inside the window" + overlap = pop["y"] < own["y"] + own["height"] and own["y"] < pop["y"] + pop["height"] and pop["x"] < own["x"] + own["width"] and own["x"] < pop["x"] + pop["width"] + assert not overlap, f"{where}: the list {pop} covers the field {own}" + gap = pop["y"] - (own["y"] + own["height"]) if pop["y"] >= own["y"] else own["y"] - (pop["y"] + pop["height"]) + assert 0 <= gap <= own["height"], f"{where}: the list {pop} is not next to the field {own}" + assert pop["x"] < own["x"] + own["width"] and own["x"] < pop["x"] + pop["width"], f"{where}: the list {pop} is not under or over the field {own}" + assert not browser_popup_open(field), f"{where}: the browser's own popup opened" + logo.page.keyboard.press("Escape") + expect(listbox(logo)).to_be_hidden() From 32402358be4715b449d2cbb75c219854682debc0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 08:35:58 -0500 Subject: [PATCH 14/17] docs(hashout): frontend v0.34.0, the canvas layers and their order, the try kit and every way a trial ends, the command intercept and the Undo mark, the bar, the segment groups, the list fields and what the browser does on a closed list, values shown while dragging, the preset player and its bounds, and the keys each part keeps --- frontend/HASHOUT_LOG.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 39efc854..bfa285c1 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -1,5 +1,37 @@ # Frontend context map +## Try a choice before keeping it: the trial layer, the try bar, the editor's own list, values shown while dragging, and motion presets played on the canvas · v0.34.0 (2026-11-27) + +The third of five releases (0.32.0 to 0.36.0) that answer the follow-up on issue #36. No engine, model or service change and no new command in the engine: a trial is canvas-only, so the revision, undo, other windows, agents and the export see nothing until Keep. New: `features/try/` (`types.ts`, the contract the lead wrote and nobody else edits; `index.ts`, the kit; `bar.ts`; `segments.ts`; `choice-list.ts`), `features/motion/play.ts`, `styles/try-bar.css`, `styles/try-list.css`, `styles/motion-play.css`. Changed: `ui/canvas.ts` (`setLayer`), `features/inspector/controls/index.ts` (the `trial` option), `features/motion/presets.ts`, `commands/registry.ts` (`intercept`), `commands/keymap.ts`, and in `main.ts` the `installTry({...})` call, one `tryKit.sync()` in `update()`, the Preferences row, `view.try-choices`, `tryKit.busy()` in `installHoverOutline`'s `busy`, `commandRegistry.intercept`, the `trial` option of `installControls`, `breakpoint` and `editing` on the inspector context, and `data-own-keys` on `.inspector-tabs`. + +The canvas layers (`ui/canvas.ts`): `Canvas.setLayer(name, frame)` with `name` `'play'` or `'trial'` and `frame` `{ [nodeId]: { [cssProperty]: string | null } }`, or `null` to clear. `restyle()` (the style block that `patch()` had, moved out unchanged) draws in this order, later wins: the stored styles with the matching breakpoints applied widest first, the scene scrubber's motion frame (`setMotionFrame`, unchanged, still a full `render()`), `play`, `trial`. A layer key first deletes every own key with the same `cssName`, so a camel and a kebab spelling never both apply. `null` means no own value at the picked breakpoint: on the base breakpoint (maxWidth 100000, or none picked) nothing is put back, on a narrower one the value of the wider matching breakpoints without the picked one is. `safeStyle` applies to layer values as to stored ones. `setLayer` returns at once when the frame's JSON equals the last one, stores a deep copy, and before the first render only stores it (the next render draws it). Otherwise it collects, per node id whose entry changed, the union of the property names in the old and the new entry, and calls `restyle(node, key, site, id, scope, only)` on every mounted node of that id (every repeated CMS copy; `:list` keys skipped): `only` limits the writes and removals to those properties, while `this.styles` for the key is still rebuilt in full, so a later full render or a clear leaves no stale inline value. It never calls `render()`, never creates, reorders or reparents a node. Measured at 4x CPU on Lowlight (298 canvas nodes), median per call: equal frame 0 ms, one node 1.9 ms, 30 nodes 9.1 ms, a full `render()` 29.1 ms. Keep that split if you touch `restyle()`, or motion playback becomes a whole-page render per frame. Trap: an element that had no `style` attribute keeps an empty `style=""` after a layer clears (`removeProperty` leaves the attribute); identical on screen, but an exact-attribute test sees it. + +The kit (`features/try/index.ts`, `installTry(options)` once from `main.ts`, created before `installControls` so the control kit can reach it). Options: `scope()` is `||`, `node()`, `exists(id)` (`!!lastState.site.nodes[id]`), `stored(key)` and `inherited(key)` at the picked breakpoint, `editing()` (not Live preview, not Preview as published, no scrim dialog, no demo preview, no feature studio, Home hidden), `setStyle`, `status`, `fields` (`styleFields`) and `segments` (`segmentFields`). One trial at most (`current`). `begin(owner)` retires any trial and returns a `Trial` for `owner.key` on the element and breakpoint on screen; it shows nothing. `put(value, name)` stores the value, redraws the layer, calls `bar.show(owner, name)` and starts the watcher; `''` is drawn as `null`. `draw()` builds one `trial` frame from three sources, in order: live drag values (`lives`, all on one node, `liveNode`), the `landing` set, and `current`. `keep()`: no value yet ends as reverted; a changed scope or node, or design left, ends as dropped; a value equal to the stored one (trimmed) sends nothing and ends quietly (the value is cleared first, so `end('reverted')` prints no "Not kept", and `unsay()` clears the kit's own earlier sentence; before this it printed "Not kept: ..." right after the person pressed Keep); otherwise `pending` is set, focus is moved off the bar, `bar.pending(true)`, and `await options.setStyle(key, value)`. `setStyle` reads `currentNode()` and the breakpoint synchronously, so the one command carries the element and breakpoint of the moment Keep was pressed. Success ends as kept; a rejection ends as refused with the engine's or the editor's sentence as an error ("The change was refused." only when none came). `keep()` never rejects: its body is guarded, and a throw inside ends the trial as dropped. + +Why the layer is cleared in the continuation after `accept()` drew: in `api.ts`, `settle()` runs `accept()`, which runs `update()` (`tryKit.sync()`, then `canvas.render()` with the new stored value) synchronously, before the command's promise resolves. The `await` continuation in `keep()` (`end('kept')`, `draw()`, `setLayer('trial', null)`) therefore runs in the same task as that render, and no frame shows the old value between Keep and the answer. The 409 path loads the newest state before it rejects, so a refusal shows the stored value at once. If `command()` ever defers `accept`, the layer must instead be cleared in the next `sync()`. + +Every ending goes through `entry.end(how, message)` exactly once: `over` is set, the entry leaves `landing`, the bar hides (focus moved off it first), the layer is redrawn, the status line gets the sentence (refused: the message as an error; a given message, today only "The element was changed elsewhere, so the trial was dropped."; reverted with a value shown: "Not kept: {0} is unchanged." with `[{ t: owner.label }]`, so the field name is translated too; kept: the line is cleared only if it still shows the kit's own last sentence, `said`), and then `owner.ended(how)`, inside try/catch with `console.error`, because `sync()` runs in the middle of `update()` and an owner's throw must never stop the canvas and the inspector from following the new state. Who ends what: Keep and Enter call `trial.keep()`, Revert and Escape `trial.revert()` (the owner or the bar). `sync()` from `update()` (`check(true)`): the element no longer exists, dropped with the sentence; scope changed (selection by any path, breakpoint, page) or design left, dropped silently; this key's stored value at this breakpoint differs from the value at `begin` (`base`), dropped with the sentence; any other outside change leaves the trial drawn over the new state. The watcher (`check(false)`, one `requestAnimationFrame` loop while a trial or a live value exists, stopped when neither does) catches design left without an `update()` (Home, a dialog, the full preview) and an anchor that is no longer rendered (a section folded, the inspector tab changed, the property search filtered the field away), which reverts. A capture `focusin` on the document reverts when focus lands outside `owner.anchor`, `owner.inside()` and the bar (not on the body, not in the command palette `.fw-search-pop`). A capture `pointerdown` on the canvas document, attached once after `loaded()` (the kit reads the Canvas's `frame` and `loaded()` the way `hover-outline.ts` does, since `TryCanvas` declares only `setLayer`), reverts a shown, non-pending trial: a press on the element that is already selected changes no selection and focus moving into the iframe fires no `focusin` here, so before this a double-click into the text edited under the tried value. A wheel is not a pointer press and leaves the trial on. Window blur and a `focusout` with no `relatedTarget` do nothing; for the latter, one macrotask later, if the window still has focus and focus is on the body, the kit puts it back on the element that lost it (if still rendered and enabled) or on the anchor, because a press on panel padding blurs the focused segment and Backspace on the body runs `edit.delete`. `begin()` and `live()` retire the trial in progress; `setEnabled(false)` drops it. `drop()`, `active()` and `TryOptions.inherited` exist and nothing calls them. + +Pending Keep and the landing set: a pending entry is never reverted or dropped. `retire()` moves it to `landing`, sets `current` to null and `detached` (the owner's `Trial.over` then reads true, so the owner takes input again), hides the bar and calls `owner.ended('dropped')` once; its value stays drawn on its node until the answer, so the element the command targets never shows the old value. A new `begin()`, `live()`, the switch, `drop()`, and `check()` when the scope changes or design is left while pending all retire. So a selection change during a pending Keep hides the bar at once and frees the field for the new element, and the command still lands on the first element. This differs from contract row 12 (which said the layer is cleared): the kept value stays drawn on the first element until the answer, on purpose. A Keep with no answer after 30 s (`LANDING_MS`) is retired and removed from `landing`, so `busy()` and the hover outlines recover; a late answer still draws and ends it. + +The intercept hook (`commands/registry.ts`): `Commands.intercept`, a nullable `(id) => boolean` set in `main.ts` as `commandRegistry.intercept = id => tryKit.intercept(id)`. Both `run()` and `call()` ask it right after the command lookup and BEFORE the enabled check: `edit.undo` is enabled only with history, and on a freshly opened demo Mod+Z returned before the kit was asked, so the trial stayed. `run()` (keys, menus, toolbar, palette) returns true without running when the hook returns true. `call()` (the agent bridge `runFromBridge`, which `window.formweb.run` also uses) calls the hook for its side effect only and always goes on to the enabled check and the command: a programmatic call is never swallowed, because an agent that sends `edit.undo` to take back its own wrong change would otherwise be told it ran while its change stayed, and would report it undone. The rule inside the kit: `edit.copy`, `file.save`, `view.search` and `view.try-choices` (`PASS`) never touch a trial. For any other id, with a trial on and not pending, the trial is reverted first; for `edit.undo` the hook then returns true when that trial had a value on the page, so a person's Undo only puts the page back and nothing earlier is undone. With no trial, or a pending one, nothing is reverted, so Undo after a pending Keep queues behind it in `api.ts` and undoes the Keep (if that Keep is then refused, the queued undo removes the previous, unrelated change). The toolbar Undo trap: a pointer press on the toolbar Undo button or the Edit menu focuses it first, the `focusin` rule reverts the trial, and when the command then runs the kit finds no trial, so the undo removed the person's previous real change too. Now, when `focusin` reverts a shown trial and focus landed on a command surface (`.fw-menubar`, `.fw-menu`, `.fw-search-pop`, `[data-cmd]`), the kit stores the time (`aimed`); the next `intercept('edit.undo')` within 15 s (`AIMED_MS`) is used up. `aimed` is cleared by any intercept, by `begin()`, by a pointer press or typed input outside the menus and the palette, and by any key press except Mod+Z and the modifier keys. `edit.undo` has `repeat: true`, so once a Mod+Z is used up its auto-repeats are used up too until the key is released (`swallowing`, `repeat`), or holding the keys walked into real history. + +The bar (`bar.ts`, `mountBar(overlay, actions)`): one `div.fw-try-bar` created once in `#overlay-root` with `data-try-bar`, `data-own-keys`, `role="group"`, `aria-label` "Trial" and `tabindex="-1"`; inside, the text "Trying: {0}" (`aria-live="polite"`), Keep and Revert, each with its key from `formatKeys()` (`data-no-i18n`, as menus show keys). It is shown and hidden, never rebuilt, and takes no layout space, so no field moves. `show(owner, name)` unhides first and writes the text after, in the same task and before placement and paint, and `hide()` empties the text: a live region that changes while hidden and appears with its content is not announced, so the first trial was silent. The name goes as `{ t: name }`, so a language switch during a trial translates it. Two rows: "Trying: {0}" fills the top row, cut with an ellipsis, the full text also in its `title` (through `labelAttr`); Keep and Revert sit whole and right-aligned on the second row. Width rule: the width depends only on the panel that holds the owner, the anchor's nearest scrolling parent, or for an anchor in the overlay (the list popover) the scrolling parent of `owner.inside()` (the inspector): panel width minus 6 px on each side, at most the window width minus 16 px, left edge at the panel's left plus 6 px. It is set when a bar is shown for an owner and again only when the panel's width or left edge changes, never on a name change, so arrow keys never move the bar; at that moment, if the content overflows, `is-tight` hides the key hints (both buttons stay whole; seen in German and Russian at a 900 px window, panel 235 px). The pending ring is centered over the whole Keep button, whose text turns transparent while waiting, so no box changes. Placement (`place()`, before the frame is painted): below the box of the anchor together with `owner.inside()` (6 px gap), above when there is more room there, clamped 8 px inside the window; when the anchor has scrolled out of its scrolling parent, pinned to that parent's visible edge. While shown, passive capture `scroll` and `resize` listeners place it again once per animation frame, and a repeat `show()` for the same owner changes only the text and moves only if the anchor box or the bar's width changed. `pending(true)` moves focus off a button that is about to be disabled (to the bar root; a disabled focused button sends focus to the body), sets `aria-busy`, disables both buttons, and after 300 ms shows the ring over Keep (see the width rule above). Focus fallbacks in `hide()` (`rescue()`, only when focus is in the bar): the anchor if it is focusable, else the owner's tried button, else its pressed one, else its first focusable; only when the owner is not rendered, the active inspector tab button. It never walks the page for "the next focusable", which landed on a Reset link, where Backspace still runs `edit.delete`. Keys: Escape anywhere in the bar reverts, Enter on Keep keeps, Tab on Revert or the root calls `leave(true)`, Shift+Tab on Keep `leave(false)` (back to the owner's anchor). + +Segment groups (`segments.ts`, `installSegments`): every group in `segmentFields` (Display, Direction, Align, Justify, Wrap, Text alignment). A capture-phase `click` listener on the group runs before the button's own target-phase listener; when `kit.enabled()` it calls `stopPropagation()` and `preventDefault()`, which is what keeps the 0.33.0 write from running, and starts or moves the trial; with the switch off it returns and the old write runs unchanged. Space is left to the native button click and so goes through the same listener. A click on the stored value tries `''` named "Inherit" (the word the selects use for their empty option; "None" read as hiding the element in Display); a click on the tried value keeps trying it. Arrows step from the tried choice, else the stored one, without wrapping, Home and End go to the ends, and focus follows; an arrow that lands on the stored value with no trial on tries nothing. Enter keeps, Escape reverts, Tab with a trial focuses Keep, Delete and Backspace are swallowed, and while pending every key and click is ignored. The marks are `data-trying` on the tried button and on the group (`"unset"` while `''` is tried); `is-on`, `is-inherited` and `aria-pressed` keep meaning stored and are never touched, so `update()` never has to know about trials. Each group gets `data-own-keys` and `tabindex="-1"` once at install, whatever the switch: the kit rescues focus with `owner.anchor.focus()`, a div is not focusable, and the group's `focus` handler forwards to the tried, else the pressed, else the first button (without it, Shift+Tab from Keep left focus in the bar and a hide after Keep could drop it on the body). Side effect, also with the switch off: Delete and Backspace on a segment no longer run `edit.delete`, and Escape on it no longer reaches the editor. `ended()` clears the marks and moves focus only when the focused button is no longer rendered: to the pressed or first rendered segment, else the active inspector tab. + +The choice list (`choice-list.ts`, `installChoiceLists`): every `