feat(overlay): move a popover off what it covers, and answer for every edge

A popover with a title gets a bar you can drag it by, because the ones that edit
what they sit over — stroke settings, advanced type — hid the rows they were
changing. Once moved it stays moved, since `place()` is wired to scroll and
resize and re-anchoring a surface somebody deliberately put somewhere is what
makes a movable thing feel broken rather than absent.

That bar is a pointer affordance and says so. It is a `POINTER_ONLY` draggable,
and dnd-kit stamps a tab stop and `aria-roledescription="draggable"` onto any
handle unless the attribute is already there — which would leave a control that
announces itself as movable and answers no key. It carries its own `tabindex`
to stop that, is hidden from assistive tech, and the title moves onto the shell
so nothing is lost. Unlike the frame-list grips there is no keyboard verb to
offer beside it, because a popover that never moves is fully usable.

The Stroke section answers for all four edges rather than writing the shorthand,
and the advanced form hands its controls back when it closes. Skipping that was
justified by `renderBody` closing every popover as it destroys the registry,
which is true of the render path and not of the user path — Escape or an outside
press closes it without re-rendering anything, so its rows stayed registered and
`reseed` wrote into detached fields on every refresh afterwards.

Right-click works. `contextmenu` was on the swallowed list, so it did nothing
anywhere in the editor and nothing was ever put in its place; it moves to the
picker rather than simply coming off, because the browser's own menu over an
element you are editing is not the right answer either.

`styles/index.test.ts` gains the check that would have caught two class names
applied with no rule anywhere. Both silently took their box from `.pop-modal` —
right for the palette and wrong for a sixty-row reference that got a container
sized for ten results and a query.
This commit is contained in:
Nayan
2026-08-15 10:24:52 +05:30
parent f6477a74ce
commit bab7a47117
29 changed files with 1544 additions and 219 deletions
+28 -16
View File
@@ -10,7 +10,7 @@ import {
} from "../dnd/manager";
import { clear, cls, el, PREFIX } from "../dom";
import { type IconName, icon } from "../icons";
import { keys } from "../keys";
import { keys } from "../keys/registry";
import { placePopover } from "../popover";
import { createMenu, type MenuEntry } from "../popover-host";
import { isElement } from "../realm";
@@ -229,7 +229,10 @@ export class FrameChrome {
// Registration order is *not* the guarantee and must not become one.
// `keys.bind` unshifts and `CanvasStage` is built before `AirshipApp`, so
// the element delete actually sits ahead of this one; it is the guards
// that keep them apart.
// that keep them apart. `catalog.test.ts` now checks that pairing rather
// than trusting this paragraph: two commands may share a chord only if
// their modes are disjoint, which `element.delete` (edit) and
// `frame.delete` (view) are.
//
// Bound here rather than through `Stage`. `Keys` evaluates `when` before
// `run` and consumes the event on any match, so an honest guard needs a
@@ -246,12 +249,8 @@ export class FrameChrome {
// menu's W/H boxes. `isTypingTarget` skips every binding without
// `allowWhileTyping` for exactly those, and this one does not carry it.
//
// The label is "Delete frame", not "Delete": `keys.hintFor` matches on
// label and `bindEditorKeys` already registers a "Delete", so a shared one
// would put the wrong chord on one of the two buttons.
keys.bind({
keys: "backspace, delete",
label: "Delete frame",
id: "frame.delete",
run: () => this.deleteActiveFrame(),
when: () => !this.editing && this.deps.frames.active !== null,
})
@@ -398,21 +397,29 @@ export class FrameChrome {
* neither the row nor the deps behind it exist. See `minimap.ts`.
*/
private zoomEntries(): MenuEntry[] {
// `command`, not `hint`. These five used to spell their own chords: "⌘+"
// where the binding is `mod+=`, "⌘−" with a U+2212 minus where it is an
// ASCII hyphen, and all five rendered as Mac glyphs on Windows and Linux.
// The registry renders them now, in the reader's own platform's spelling.
const entries: MenuEntry[] = [
{ hint: "⌘+", label: "Zoom in", run: () => this.zoomBy(1) },
{ hint: "⌘−", label: "Zoom out", run: () => this.zoomBy(-1) },
{ command: "view.zoomIn", label: "Zoom in", run: () => this.zoomBy(1) },
{
hint: "⇧1",
command: "view.zoomOut",
label: "Zoom out",
run: () => this.zoomBy(-1),
},
{
command: "view.zoomToFit",
label: "Zoom to fit",
run: () => this.runZoom(() => this.deps.viewport.zoomToFit()),
},
{
hint: "⇧2",
command: "view.zoomToSelection",
label: "Zoom to selection",
run: () => this.runZoom(() => this.deps.viewport.zoomToSelection()),
},
{
hint: "⌘0",
command: "view.zoom100",
label: "Zoom to 100%",
run: () => this.runZoom(() => this.deps.viewport.zoomTo100()),
},
@@ -669,7 +676,7 @@ export class FrameChrome {
return el(
"div",
{
class: `${cls("fc-menu")} ${cls("fbar-menu")} ${cls("hidden")}`,
class: `${cls("fc-menu")} ${cls("fbar-menu")} ${cls("scroll-y")} ${cls("hidden")}`,
onClick: (e: Event) => e.stopPropagation(),
},
[
@@ -760,7 +767,7 @@ export class FrameChrome {
return el(
"div",
{
class: `${cls("fc-menu")} ${cls("fbar-menu")} ${cls("hidden")}`,
class: `${cls("fc-menu")} ${cls("fbar-menu")} ${cls("scroll-y")} ${cls("hidden")}`,
onClick: (e: Event) => e.stopPropagation(),
},
[
@@ -989,9 +996,14 @@ export class FrameChrome {
if (!this.menuFor) {
return;
}
// Unscoped, and `priority: "modal"` in the catalog rather than a `within`.
// The menu is opened by a click, so focus is still on `document.body` and a
// scoped binding would never match its own keystroke — while the menu is
// up, Escape belongs to it, and saying so as a priority is the honest way
// to outrank the picker's Deselect without depending on which constructor
// ran first.
this.unbindMenuKeys = keys.bind({
keys: "escape",
label: "Close",
id: "frameMenu.close",
run: () => this.closeMenu(),
});
}
+52 -37
View File
@@ -31,6 +31,7 @@ import {
} from "../dnd/manager";
import { clear, cls, el, PREFIX } from "../dom";
import { type IconName, icon } from "../icons";
import { keys, tip } from "../keys/registry";
import { createMenu, type MenuEntry, type MenuHandle } from "../popover-host";
import { customSizeRow, deviceGroups } from "./device-menu";
import { deleteFrame, duplicateFrame, reloadFrame } from "./frame-verbs";
@@ -94,7 +95,7 @@ export class FramesPanel {
{
"aria-label": "Add a frame",
class: cls("fp-add"),
"data-tip": "Add a frame",
...tip("Add a frame", "frame.add"),
onClick: () => this.openAddMenu(),
type: "button",
},
@@ -110,10 +111,54 @@ export class FramesPanel {
// mean what `showDropLine` computes. Parked in the scroller it was
// positioned against that element's padding box while being measured from
// the list's top edge, so every line drew one `--ap-space-xs` too high.
el("div", { class: cls("fp-scroll") }, [this.list]),
el("div", { class: `${cls("fp-scroll")} ${cls("scroll-y")}` }, [
this.list,
]),
]);
this.list.append(this.dropLine);
this.watchDrag();
this.bindGripKeys();
}
/**
* ↑ and ↓ on a focused grip, as real commands.
*
* These were a raw `onKeydown` on each grip, with the two menu rows that
* describe them spelling `"↑"` and `"↓"` by hand — so the restack existed in
* three places that agreed only by inspection, and in none that the shortcuts
* panel or `CONTROLS.md` could see.
*
* Scoped to the list rather than to a grip: rows are rebuilt whenever the
* frame set changes, and a binding per grip would be registered and disposed
* on every rebuild. The list outlives them, and `within` is checked before
* the chord, so ↑/↓ elsewhere still belong to whatever owns them there.
*/
private bindGripKeys(): void {
// The row comes from the keystroke's own origin, not from
// `document.activeElement`: the binding only fired because the key was
// pressed inside this list, so the event already says which row, and asking
// the document instead would answer differently the moment anything else
// took focus between the press and the handler.
const move = (delta: number) => (e: KeyboardEvent) => {
const from = e.target as HTMLElement | null;
const id = from?.closest?.<HTMLElement>("[data-frame]")?.dataset.frame;
if (!id) {
return;
}
if (this.moveBy(id, delta)) {
// The row this grip lived on has been rebuilt; take focus to the new one
// so a run of presses keeps moving the same frame.
this.rowOf(id)
?.querySelector<HTMLElement>(`.${cls("fp-grip")}`)
?.focus();
}
};
this.unsubscribe.push(
keys.bindAll([
{ id: "frame.bringForward", run: move(-1), within: this.list },
{ id: "frame.sendBackward", run: move(1), within: this.list },
])
);
}
/**
@@ -210,13 +255,12 @@ export class FramesPanel {
// The keyboard half of the same job. Bound here rather than through
// `keys` because it is only meaningful while this handle has focus,
// and the registry's `when` predicates are for global chords.
onKeydown: (e: KeyboardEvent) => this.onGripKey(e, frame.id),
/*
* Ours, not dnd-kit's.
*
* The Accessibility plugin does stamp `tabindex="0"` on a handle — but
* it does it from an effect, a tick after the entity is constructed.
* `onGripKey` re-takes focus on a row that `reorder` has just rebuilt,
* `bindGripKeys` re-takes focus on a row that `reorder` has just rebuilt,
* and in that window the fresh `span` is not focusable yet, so the
* `focus()` silently did nothing and the second arrow press went to the
* body. Setting it here makes the row focusable the moment it exists,
@@ -323,8 +367,8 @@ export class FramesPanel {
plugins: FEEDBACK.none,
// …which is exactly why the keyboard sensor must go. See
// `POINTER_ONLY`: left on, Space would latch a drag that no arrow key
// can move and that eats the Tab out of it. `onGripKey` is the real
// keyboard route.
// can move and that eats the Tab out of it. The `frame.bringForward` and
// `frame.sendBackward` commands are the real keyboard route.
sensors: POINTER_ONLY,
type: DND.frameRow,
},
@@ -563,15 +607,15 @@ export class FramesPanel {
* lowering the index sends a frame *back*. See `stackOrder`.
*/
{
command: "frame.bringForward",
disabled: at <= 0,
hint: "↑",
icon: "chev-up",
label: "Bring forward",
run: () => this.moveBy(frame.id, -1),
},
{
command: "frame.sendBackward",
disabled: at < 0 || at >= last,
hint: "↓",
icon: "chev-down",
label: "Send backward",
run: () => this.moveBy(frame.id, 1),
@@ -652,21 +696,6 @@ export class FramesPanel {
* Plain arrows are safe without a guard: the global Nudge binding is gated on
* `editing && selection`, and this panel exists only in view mode.
*/
private onGripKey(e: KeyboardEvent, id: string): void {
const delta = arrowDelta(e.key);
if (delta === 0) {
return;
}
// Before the move, or a refused one at either end would still scroll the
// panel — which reads as the row having moved.
e.preventDefault();
if (this.moveBy(id, delta)) {
this.rowOf(id)
?.querySelector<HTMLElement>(`.${cls("fp-grip")}`)
?.focus();
}
}
/**
* Drag a row to restack the frames.
*
@@ -808,20 +837,6 @@ export function dropStackIndex(
return total - 1 - (to > from ? to - 1 : to);
}
/**
* Which way an arrow key moves a row, or 0 for any other key.
*
* In list terms, so ↑ is one row up — and because the list is front-first, one
* row up is one place toward the front. The two readings of "up" agree, which is
* the whole point of `stackOrder`.
*/
function arrowDelta(key: string): number {
if (key === "ArrowUp") {
return -1;
}
return key === "ArrowDown" ? 1 : 0;
}
/** The frame id carried by a drag source, or null if it is not one of ours. */
function rowIdOf(
source: { id?: unknown; type?: unknown } | null
+23 -11
View File
@@ -1,6 +1,6 @@
import { cls, el } from "../dom";
import { isOwn } from "../edit-guard";
import { isInsidePopover, isTypingTarget, keys } from "../keys";
import { isInsidePopover, isTypingTarget, keys } from "../keys/registry";
import { isFrameChrome } from "./frame-chrome";
import {
centerAt,
@@ -451,6 +451,18 @@ export class CanvasViewport {
off();
}
this.unbind.length = 0;
// Both in flight at the moment a wheel gesture is interrupted by a teardown,
// and both close over this viewport: the frame would paint a transform onto
// a detached stage, and the gesture timer would clear `gesturing` on it long
// after the canvas it belonged to had gone.
if (this.frameRequest) {
cancelAnimationFrame(this.frameRequest);
this.frameRequest = 0;
}
if (this.gestureTimer) {
clearTimeout(this.gestureTimer);
this.gestureTimer = 0;
}
this.setHandTool(false);
}
@@ -676,29 +688,29 @@ export class CanvasViewport {
};
return keys.bindAll([
{
keys: "mod+=",
label: "Zoom in",
id: "view.zoomIn",
run: zoom(() => this.zoomStep(1)),
},
{
keys: "mod+-",
label: "Zoom out",
id: "view.zoomOut",
run: zoom(() => this.zoomStep(-1)),
},
{
keys: "mod+0, shift+0",
label: "Zoom to 100%",
id: "view.zoom100",
run: zoom(() => this.zoomTo100()),
},
{
keys: "shift+1",
label: "Zoom to fit",
id: "view.zoomToFit",
run: zoom(() => this.zoomToFit()),
},
{
keys: "shift+2",
label: "Zoom to selection",
id: "view.zoomToSelection",
run: zoom(() => this.zoomToSelection()),
// Was unguarded, so ⇧2 with nothing selected consumed the keystroke and
// did nothing visible. `zoomToSelection` already declines internally;
// saying so here is what keeps the palette and the panel from offering
// it when there is nothing to zoom to.
when: () => this.deps.getSelectionRect() !== null,
},
]);
}
+2
View File
@@ -48,6 +48,8 @@ export const DND = {
frameMove: "airship:frame-move",
/** Dragging a row of the frame list to restack the frames. */
frameRow: "airship:frame-row",
/** Dragging a popover's title bar to move it away from its anchor. */
popMove: "airship:pop-move",
resizeHandle: "airship:resize-handle",
scrub: "airship:scrub",
splitter: "airship:splitter",
+7 -5
View File
@@ -74,17 +74,19 @@ describe("pressVerdict", () => {
});
describe("SWALLOWED", () => {
it("leaves click and dblclick to the picker", () => {
// Both are the picker's outright — one selects, the other enters in-place
// text editing. Putting either back here gives the event two owners and
// silently breaks double-click entry, since `onPress` runs first.
it("leaves click, dblclick and contextmenu to the picker", () => {
// All three are the picker's outright — one selects, one enters in-place
// text editing, one opens the editor's menu on the selection. Putting any
// back here gives the event two owners and silently breaks the picker's,
// since `onPress` runs first.
expect(SWALLOWED).not.toContain("click");
expect(SWALLOWED).not.toContain("dblclick");
expect(SWALLOWED).not.toContain("contextmenu");
});
it("still covers the presses that would wake the app", () => {
expect(SWALLOWED).toContain("pointerdown");
expect(SWALLOWED).toContain("mousedown");
expect(SWALLOWED).toContain("contextmenu");
expect(SWALLOWED).toContain("auxclick");
});
});
+11 -5
View File
@@ -73,14 +73,21 @@ export function isEditorNode(node: Element): boolean {
* be allowed through on the drag source so dnd-kit's PointerSensor — which binds
* element-level listeners, i.e. after document capture — can still see it.
*
* `click` and `dblclick` are both absent because the picker owns them outright:
* one selects, the other enters in-place text editing, and it swallows each
* itself in capture before the app can act. Two owners of one event type is an
* ordering hazard worth avoiding — `onPress` uses `stopPropagation`, not
* `click`, `dblclick` and `contextmenu` are all absent because the picker owns
* them outright: one selects, one enters in-place text editing, one opens the
* editor's own menu on the selection, and it swallows each itself in capture
* before the app can act. Two owners of one event type is an ordering hazard
* worth avoiding — `onPress` uses `stopPropagation`, not
* `stopImmediatePropagation`, so a picker listener on the same node *would*
* still fire, but only by accident of `SelectionController.setEditing` calling
* `guard.setEditing` before registering its own.
*
* `contextmenu` was on this list for a long time, which is why right-clicking
* anywhere in the editor did nothing whatsoever: it was swallowed and nothing
* was ever put in its place. It moves to the picker rather than simply coming
* off, because the browser's own menu over an element you are editing is not
* the right answer either.
*
* Exported for the frame agent, which runs this same list one realm down while a
* frame is live for a text edit.
*/
@@ -89,7 +96,6 @@ export const SWALLOWED = [
"mousedown",
"mouseup",
"pointerup",
"contextmenu",
"auxclick",
"dragstart",
] as const;
@@ -302,9 +302,15 @@ export function createColorRow(opts: ColorRowOptions): ColorRowHandle {
reflect(current);
// On the wrapper, matching what `num-field` does for a field whose glyph is a
// letter or absent: this one has no glyph at all, so without a tip the only
// thing naming it was a six-character value that could be any colour channel.
const hexWrap = el(
"div",
{ class: `${cls("ctl-num")} ${cls("paint-hex")}` },
{
class: `${cls("ctl-num")} ${cls("paint-hex")}`,
"data-tip": "Hex value",
},
[hex]
);
const row = el("div", { class: cls("paint-row") }, [
@@ -437,11 +443,17 @@ export function openColorPicker(opts: PickerOptions): PickerHandle {
*/
// -- saturation / value ----------------------------------------------------
const svKnob = el("i", { class: cls("pop-sv-knob") });
// A tip as well as the name. These three surfaces are bare gradients: unlike
// a select or a labelled field there is nothing on them that says what they
// do, so the accessible name was the only description and only a screen
// reader could reach it. The tips name the axis and the keyboard route,
// which is the part that is genuinely undiscoverable.
const sv = el(
"div",
{
"aria-label": "Saturation and brightness",
class: cls("pop-sv"),
"data-tip": "Saturation and brightness",
role: "application",
tabindex: "0",
},
@@ -457,6 +469,7 @@ export function openColorPicker(opts: PickerOptions): PickerHandle {
"aria-valuemax": "360",
"aria-valuemin": "0",
class: `${cls("pop-slider")} ${cls("pop-slider-hue")}`,
"data-tip": "Hue. Arrow keys to step",
role: "slider",
tabindex: "0",
},
@@ -471,6 +484,7 @@ export function openColorPicker(opts: PickerOptions): PickerHandle {
"aria-valuemax": "100",
"aria-valuemin": "0",
class: `${cls("pop-slider")} ${cls("pop-slider-alpha")}`,
"data-tip": "Opacity. Arrow keys to step",
role: "slider",
tabindex: "0",
},
@@ -665,8 +679,12 @@ export function openColorPicker(opts: PickerOptions): PickerHandle {
svKnob.style.left = `${state.s * 100}%`;
svKnob.style.top = `${(1 - state.v) * 100}%`;
svKnob.style.background = solid;
hueKnob.style.left = `${(state.h / 360) * 100}%`;
alphaKnob.style.left = `${state.a * 100}%`;
// A 0-1 fraction, not a percentage: the stylesheet turns it into a `left`
// across `100% - <knob>` so the dial stays inside its track at both ends.
// The SV knob above keeps its percentages — it marks a point in an area
// whose corners are real values, so centring it on one is correct.
hueKnob.style.setProperty(`--${cls("knob")}`, String(state.h / 360));
alphaKnob.style.setProperty(`--${cls("knob")}`, String(state.a));
alphaFill.style.backgroundImage = `linear-gradient(to right, transparent, ${solid})`;
// The announced value, kept in step with the knob it describes.
hue.setAttribute("aria-valuenow", String(Math.round(state.h)));
@@ -267,7 +267,12 @@ function stopBar(
selected: number,
handlers: BarHandlers
): HTMLElement {
const wrap = el("div", { class: cls("grad-bar-wrap") });
// The one surface in the editor with no name of any kind. Both of its
// gestures are invisible until tried, and one of them creates a stop.
const wrap = el("div", {
class: cls("grad-bar-wrap"),
"data-tip": "Drag a stop. Double-click to add",
});
const bar = el("div", { class: cls("grad-bar") });
bar.style.backgroundImage = barCss(gradient);
wrap.append(bar);
@@ -39,6 +39,7 @@ import {
} from "../../dnd/manager";
import { cls, el } from "../../dom";
import { hasIcon, type IconName, icon } from "../../icons";
import { isTypingTarget } from "../../keys/registry";
import { clamp, round } from "../../num";
import {
formatLength,
@@ -144,7 +145,15 @@ function trackModifiers(): {
state.shift = e.shiftKey;
};
const onPointer = (e: Event): void => from(e as PointerEvent);
const onKey = (e: Event): void => from(e as KeyboardEvent);
const onKey = (e: Event): void => {
// Same question the registry asks, asked by hand because this is a raw
// listener: ⇧ typed into a field is a capital letter, not a coarse-step
// modifier for a scrub that happens to be live in another panel.
if (isTypingTarget((e as KeyboardEvent).target, e as KeyboardEvent)) {
return;
}
from(e as KeyboardEvent);
};
document.addEventListener("pointermove", onPointer, true);
document.addEventListener("keydown", onKey, true);
document.addEventListener("keyup", onKey, true);
@@ -550,6 +559,25 @@ export function createNumField(
if (spec.fieldKey) {
wrap.dataset.field = spec.fieldKey;
}
/*
* The whole field is still the click target.
*
* A suffixed input sizes to its content now (see `controls.css.ts`), so it no
* longer stretches under the empty half of the field the way a `width: 100%`
* input did — and clicking there landed on this div and focused nothing. On
* Rotation that is most of the control.
*
* Guarded on the target being this element: the glyph is a scrub handle and
* the input takes its own clicks, and stealing either would break the caret
* position a click inside the text is asking for.
*/
wrap.addEventListener("pointerdown", (ev) => {
if (ev.target === wrap) {
ev.preventDefault();
input.focus();
input.select();
}
});
// On the whole field, not just the glyph, whenever the glyph is a letter or
// absent: a one-character mark like "W" or "Z" is the only thing naming this
// control, and hitting a 20px target to find out what it does is not an
@@ -156,7 +156,10 @@ function openTokenPicker(anchor: HTMLElement, opts: TokenBadgeOptions): void {
// real menus on none of it, so a token picker opened beside a select read as
// a different product.
const list = el("div", {
class: `${cls("pop-menu")} ${cls("token-list")}`,
// `scroll-y` here as well as on the shell: `.pop-menu`'s own `overflow-y`
// is what a token list actually scrolls in (see pop.css), so the shell's
// treatment never reaches it.
class: `${cls("pop-menu")} ${cls("token-list")} ${cls("scroll-y")}`,
role: "menu",
});
+33 -7
View File
@@ -92,7 +92,13 @@ const LAYOUT: Descriptor[] = [
// rows in a 320px dock, and a control that reflows as you resize the dock
// reads as a bug — the rule `select.ts` already states, applied here too.
key: "display",
label: "Display",
// "Layout", not "Display", and the section renders this rather than a
// literal of its own. The two disagreed: the rail said Layout while the
// descriptor said Display, so the row was invisible to anything sweeping
// `descriptors.ts` for copy. Layout is also the word the rest of the
// section already uses — the headings are "Auto layout" and "Layout grid",
// and a design tool has no `display`.
label: "Layout",
span: "full",
},
{
@@ -560,9 +566,12 @@ export const VERTICAL_ALIGN: Descriptor = {
* different properties on different elements, is worse than a shorter word.
* `CONSTRAIN_V` calls the same axis "Vertical" already.
*
* Not "Vertical align" because the 68px label rail neither ellipsises nor
* clips: fourteen characters wrap to two lines and take the row's height with
* them. "Blend mode" at ten is the longest label the panel ships.
* Not "Vertical align" because the label rail neither ellipsises nor clips:
* past `LABEL_MAX_CHARS` a label wraps to two lines and takes the row's
* height with it. That constant is the budget, and `tooltip.copy.test.ts`
* holds every rail label to it — this comment used to name the longest label
* shipped, which stopped being true the moment somebody added a longer one
* and nothing said so.
*/
label: "Vertical",
};
@@ -631,7 +640,14 @@ export const FONT_OPTICAL_SIZING: Descriptor = {
],
group: "typography",
key: "fontOpticalSizing",
label: "Optical sizing",
/*
* "Optical", not "Optical sizing", which sat exactly on the budget — one
* character from wrapping, and wrapping anyway inside Advanced type while
* that section paid its inset twice. A label at the limit is a label waiting
* for a wider word next to it; the noun is redundant in a group where every
* row is a sizing control.
*/
label: "Optical",
span: "full",
};
@@ -764,7 +780,16 @@ export const JUSTIFY_ITEMS: Descriptor = {
],
group: "layout",
key: "justifyItems",
label: "Align items horizontally",
/*
* "Horizontal", not "Align items horizontally".
*
* Twenty-four characters in a fourteen-character rail wrapped to three lines
* and pushed a four-cell segmented group onto its own line beneath them. The
* axis is the only thing the label has to carry: the four icons already say
* *align*, the section heading already says *grid*, and `CONSTRAIN_H` names
* the same axis with the same word one section up.
*/
label: "Horizontal",
span: "full",
};
@@ -780,7 +805,8 @@ export const ALIGN_ITEMS_GRID: Descriptor = {
],
group: "layout",
key: "alignItemsGrid",
label: "Align items vertically",
/** The vertical half of `JUSTIFY_ITEMS` above, named the same way. */
label: "Vertical",
span: "full",
};
@@ -276,6 +276,76 @@ export const Empty: StoryObj = {
/** The whole panel at `MIN_DOCK_W`, which is the real stress test. */
export const Narrow: StoryObj = {
/*
* The two measurements the unit tier cannot take.
*
* `LABEL_MAX_CHARS` is an estimate standing in for this: happy-dom does no
* layout, so `rail-label.test.ts` can only count characters and hope the
* arithmetic behind the constant still holds. Here the rail is really 68px of
* really-rendered 12px Inter, at the narrowest dock the splitter allows —
* which is the width that decides it. A label that wraps is two lines tall,
* so the height is the assertion.
*
* The gap is the other half. `.sect-body` owns its children's separation now
* rather than each child bringing a margin, and the failure mode if that
* regresses is not a thrown error anywhere — it is a section that looks
* slightly wrong, which is exactly the class of bug this catalogue exists to
* catch and the class a test suite usually cannot.
*/
play: async ({ canvasElement }) => {
// Measured in the real face or not at all: a fallback metric wraps at a
// different word, so this would report on a font nobody sees.
await document.fonts.ready;
// `build` swaps the panel in on a frame, so at `play` time the story is
// still the placeholder slot. Two frames: one for that swap, one for the
// layout it causes.
await new Promise((resolve) => requestAnimationFrame(resolve));
await new Promise((resolve) => requestAnimationFrame(resolve));
// `canvasElement` is inside the decorator's `#__airship-root` rather than
// around it — same reason `foundations.stories.ts` reaches for `closest`
// before `querySelector` — so the panel is not always beneath it.
const scope =
canvasElement.closest("#__airship-root") ??
document.getElementById("__airship-root") ??
canvasElement;
const labels = [
...scope.querySelectorAll<HTMLElement>(".__airship-row-label"),
];
if (labels.length === 0) {
throw new Error("No rail labels rendered — the panel did not build.");
}
/*
* Counted as line boxes, not measured against a line height.
*
* The obvious version — `offsetHeight > lineHeight * 1.5` — is worse than
* wrong, it is vacuous: `.row-label` declares no `line-height`, so the
* computed value is the keyword `normal`, `parseFloat` gives `NaN`, and a
* guard against that skips every label and reports a clean sweep. A range
* over the text node yields one rect per line box, which needs no constant
* and cannot silently stop testing anything.
*/
const range = document.createRange();
const wrapped = labels.filter((label) => {
range.selectNodeContents(label);
return range.getClientRects().length > 1;
});
if (wrapped.length > 0) {
throw new Error(
`Rail labels wrap at MIN_DOCK_W: ${wrapped.map((l) => l.textContent).join(", ")}`
);
}
const body = scope.querySelector<HTMLElement>(".__airship-sect-body");
if (!body) {
throw new Error("No section body to measure.");
}
const gap = getComputedStyle(body).rowGap;
if (gap !== "6px") {
throw new Error(
`A section body should space its children by the row pitch, got ${gap}.`
);
}
},
render: () =>
panelStory("card", {
caption: {
+3 -1
View File
@@ -527,7 +527,9 @@ export class DesignPanel {
deps.controller.guard.allowPressOn(() => this.reorder.proxyElement);
this.headEl = el("div", { class: cls("insp-head") });
this.tabsEl = el("div", { class: cls("insp-tabs") });
this.bodyEl = el("div", { class: cls("insp-body") });
this.bodyEl = el("div", {
class: `${cls("insp-body")} ${cls("scroll-y")}`,
});
// Tree drag-to-reparent indicators. These track *tree rows*, which are the
// panel's own chrome and therefore already in screen space — no surface
@@ -0,0 +1,167 @@
import { beforeEach, describe, expect, it } from "vitest";
import { cls } from "../dom";
import { closeOpenPopover } from "../popover-host";
import { LABEL_MAX_CHARS } from "../styles/const";
import { DesignPanel } from "./panel";
import {
harness,
mount,
resetDocument,
selectionOf,
sizeOf,
} from "./test-support";
/*
* Every rail label the panel actually renders, held to the rail's budget.
*
* `tooltip.copy.test.ts` reads the two places a label is *written* — a
* descriptor's `label`, and the literal at a `labelled()` call site. Between
* them they miss the third: the sections that build rows from a local table and
* pass the label through as a variable. `sections/media.ts`, `sections/fill.ts`
* and `sections/vector.ts` all do this, and so did Advanced type, which is
* where "Feature settings" — sixteen characters into a fourteen-character
* rail — lived without either scanner being able to see it.
*
* Reading the rendered DOM catches all three at once and cannot drift from
* `fieldCell`'s routing, because it *is* that routing: whatever ends up in a
* `.row-label` is on the rail by definition, however it got there.
*
* happy-dom does no layout, so this asserts the character budget rather than a
* measured width. That is the same trade `LABEL_MAX_CHARS` itself makes, and
* the reason the constant is derived once and written down: the real check —
* that nothing wraps at `MIN_DOCK_W` — needs a browser, and lives in Storybook.
*/
/**
* The element kinds that between them reach every section.
*
* A section renders only for a node it applies to — `gates.ts` hides a Fill row
* on an unstyled div, the vector sections need an SVG shape, and the grid
* branch of Layout needs `display: grid`. One div would exercise about half the
* rails in the panel and report a clean pass for the rest.
*/
const SUBJECTS: { style?: string; tag: string; text?: string }[] = [
{ style: "position: absolute; top: 4px; left: 8px", tag: "div" },
{ style: "display: flex; gap: 8px; padding: 4px", tag: "div" },
{ style: "display: grid; grid-template-columns: 1fr 1fr", tag: "div" },
{
style:
"background: #ff0000; border: 1px solid #00ff00; border-radius: 4px; box-shadow: 0 1px 2px #000; filter: blur(1px); opacity: .5",
tag: "div",
},
{ style: "font: 700 14px/1.4 Inter; color: #123456", tag: "p", text: "Hi" },
{ style: "min-width: 10px; max-width: 90px", tag: "span", text: "Hi" },
{ tag: "img" },
{ tag: "video" },
{ tag: "svg" },
{ tag: "button", text: "Go" },
];
/**
* Every `.row-label` one subject can produce, popovers included.
*
* Read off `document` rather than `panel.element`, and after every header
* action has been pressed. The advanced clusters — Advanced type, stroke
* settings — are `.pop-form` popovers now, mounted on the popover host rather
* than inside the panel, so a panel-only query would have quietly stopped
* seeing exactly the labels that were worst.
*
* Pressing every action is blunt, and deliberately so: some open a popover,
* some add a row, one opens a menu. None of that matters to a label sweep, and
* a list of which buttons are worth pressing is a list that goes stale.
*/
function railLabels(subject: (typeof SUBJECTS)[number]): string[] {
const h = harness();
const panel = new DesignPanel(h.deps);
const node = mount(subject.tag, {
style: subject.style,
text: subject.text,
});
sizeOf(node, { height: 40, width: 100 });
panel.setSelection(selectionOf(node));
// Both roots: the harness never attaches `panel.element` to the document,
// and the popover host mounts on `document.body` — so neither query alone
// sees the whole panel.
const read = (): string[] =>
[
...panel.element.querySelectorAll(`.${cls("row-label")}`),
...document.querySelectorAll(`.${cls("row-label")}`),
]
.map((el) => el.textContent?.trim() ?? "")
.filter(Boolean);
const found = read();
// One at a time, reading between each. Opening a second popover closes the
// first — `openPopover` closes everything above its anchor's level — so
// clicking every action and then reading once would only ever see the last
// popover's rows, and would report a clean sweep for all the others.
for (const action of panel.element.querySelectorAll<HTMLElement>(
`.${cls("sect-act")}`
)) {
action.click();
found.push(...read());
closeOpenPopover();
}
return found;
}
/*
* Swept once, asserted twice.
*
* Ten panels, each rebuilt and then had every header action pressed, is real
* work — around ten seconds of it. Running the sweep per `it` doubled that and
* put the file over vitest's five-second default, which is a slow test
* masquerading as a broken one. The two cases ask different questions of the
* same evidence, so the evidence is gathered once.
*
* `beforeEach(resetDocument)` still runs between them; only the collected
* strings outlive it, and strings are all either case reads.
*/
/**
* Longer than the default, because the sweep is genuinely long.
*
* Ten `DesignPanel` builds and every header action on each — around sixty
* popover opens, each with its own mount and teardown. It runs in about a
* second and a half alone and closer to seven alongside the other sixty-nine
* files, which is over vitest's five-second default and reports as a timeout
* rather than as the slow-but-working case it is. Raised deliberately, and
* sized to leave room on a loaded machine rather than to just clear the bar.
*/
const SWEEP_TIMEOUT = 30_000;
let swept: string[] | null = null;
function allRailLabels(): string[] {
if (!swept) {
resetDocument();
swept = SUBJECTS.flatMap(railLabels);
}
return swept;
}
describe("rail labels", () => {
beforeEach(resetDocument);
it(
"renders enough rails to be worth checking",
() => {
// A harness that threw and swallowed it, or a selector that stopped
// matching, would make the budget case below pass on an empty list.
expect(new Set(allRailLabels()).size).toBeGreaterThan(15);
},
SWEEP_TIMEOUT
);
it(
"keeps every rendered label inside the rail",
() => {
const tooLong = new Set<string>();
for (const label of allRailLabels()) {
if (label.length > LABEL_MAX_CHARS) {
tooLong.add(`${label} (${label.length})`);
}
}
expect([...tooLong].sort((a, b) => a.localeCompare(b))).toEqual([]);
},
SWEEP_TIMEOUT
);
});
@@ -27,6 +27,7 @@ import {
import { declaredValue } from "../sizing";
import { readValue } from "../style-model";
import type { SectionContext } from "./context";
import { labelled } from "./row";
/**
* Auto Layout, which is very nearly flexbox with better naming.
@@ -58,12 +59,14 @@ export function renderAutoLayout(
const displayDesc = LAYOUT_GROUP.descriptors.find((d) => d.key === "display");
if (displayDesc) {
const control = ctx.buildControl(displayDesc, node, () => ctx.rerender());
body.append(
el("div", { class: cls("row") }, [
el("span", { class: cls("row-label"), text: "Layout" }),
control.element,
])
);
// `labelled()` rather than the same markup written out again, and the
// descriptor's own label rather than a literal: this row said "Layout"
// while its descriptor said something else, so a sweep driven off
// `descriptors.ts` could not see it. `group` because the switch is its own
// decision — everything below it describes the layout it just chose.
const row = labelled(displayDesc.label, control.element);
row.classList.add(cls("group"));
body.append(row);
}
if (isGrid) {
@@ -76,18 +79,24 @@ export function renderAutoLayout(
* no `grid-auto-flow`, and one `gap` field carrying a horizontal glyph for both of
* its independent axes.
*/
const gaps = el("div", { class: cls("grid") });
const gaps = el("div", { class: `${cls("grid")} ${cls("group")}` });
for (const axis of ["row", "column"] as const) {
gaps.append(ctx.fieldCell(GRID_GAP(axis), node));
}
body.append(gaps);
// The three of them are one decision — how the items sit in the tracks —
// so they are grouped rather than appended loose. Before the section body
// owned its spacing these landed as bare siblings of the gap grid, which
// no adjacency rule named, and the two blocks touched.
const placement = el("div", { class: cls("group") });
for (const descriptor of [
JUSTIFY_ITEMS,
ALIGN_ITEMS_GRID,
GRID_AUTO_FLOW,
]) {
body.append(ctx.fieldCell(descriptor, node));
placement.append(ctx.fieldCell(descriptor, node));
}
body.append(placement);
return ctx.section("auto-layout", "Layout grid", body);
}
@@ -228,9 +237,15 @@ export function renderAutoLayout(
ctx.register(dirSeg);
dirRow.append(dirSeg.element);
// `group` on the pad cluster, not a margin under the direction row: the two
// are separate decisions, and saying so in the shared vocabulary lets the
// section body space them like every other pair.
body.append(
dirRow,
el("div", { class: cls("al-main") }, [pad.element, fields])
el("div", { class: `${cls("al-main")} ${cls("group")}` }, [
pad.element,
fields,
])
);
// No "Remove auto layout" header action either — same reasoning as the
@@ -347,11 +362,13 @@ function renderGridTracks(ctx: SectionContext, node: Element): HTMLElement {
wrap.append(row);
}
// Gutter and margin, which is what a design tool calls gap and padding.
const grid = el("div", { class: cls("grid") });
grid.append(ctx.fieldCell(LAYOUT_GAP(false), node));
wrap.append(grid);
// Margin, which is what a design tool calls padding. The gutter is not here:
// this runs for grid containers only, and the caller already gives them
// `row-gap` and `column-gap` as separate fields. A `gap` shorthand beside
// them is a third control writing the same declaration as the other two, so
// whichever was touched last silently overwrote the pair — and the shorthand
// is the one carrying a horizontal glyph for both of a grid's independent
// axes, which is the confusion the axis fields were added to end.
const padding = ctx.spacingControl(node, "padding");
ctx.register(padding);
wrap.append(padding.element);
@@ -420,6 +420,9 @@ function openStrokeSettings(
style.destroy?.();
},
prefer: "below",
// Movable: this one opens directly over the stroke rows it edits, so
// watching a dashed border take effect meant closing the form that set it.
title: "Stroke settings",
});
}
+89 -24
View File
@@ -1,6 +1,6 @@
import { cls, el } from "../../dom";
import { type IconName, icon } from "../../icons";
import { createMenu, type MenuEntry } from "../../popover-host";
import { createMenu, type MenuEntry, openPopover } from "../../popover-host";
import { computedStyle, ownerDocument } from "../../realm";
import { tokensFor, tokensForPicker } from "../../tokens/match";
import { tokenValue } from "../../tokens/registry";
@@ -29,7 +29,9 @@ const RUN_OF_WHITESPACE = /\s+/;
* "more" popover for case, decoration and truncation.
*/
function renderTextExtras(ctx: SectionContext, node: Element): HTMLElement {
const wrap = el("div", { class: cls("text-extras") });
const wrap = el("div", {
class: `${cls("text-extras")} ${cls("group")}`,
});
/*
* Font family: free text over the stack, with a picker beside it.
@@ -187,7 +189,16 @@ function renderTextExtras(ctx: SectionContext, node: Element): HTMLElement {
slot: familySlot,
stack,
})
).open(pick, "below");
// Anchored to the field, not to the caret that opens it.
//
// `placePopover` aligns a menu's left edge to its anchor's, and the
// caret is a 20px glyph at the field's right edge — so the list hung off
// that glyph and out past the dock until the viewport clamp pushed it
// back, which reads as a kebab menu rather than as this field's list.
// `matchAnchorWidth` then floors the menu at the field's width, so it
// opens as wide as the control it belongs to. `select.ts` has always
// done both; this was the one dropdown that did neither.
).open(familyField, "below", { matchAnchorWidth: true });
});
const familyField = el(
@@ -535,38 +546,92 @@ export function renderText(
if (group.id === "typography") {
body.append(renderTextExtras(ctx, node));
}
body.append(renderAdvancedType(ctx, node));
return ctx.section(group.id, group.label, body);
return ctx.section(group.id, group.label, body, {
actions: [advancedTypeAction(ctx, node)],
});
}
/**
* The axes a variable font is chosen *for*, behind a collapsed sub-section.
* The header button that opens Advanced type.
*
* Built here rather than through a bare `ctx.headerAction` call for the reason
* `filters.ts` gives about its own `+`: the popover has to anchor to the button,
* and the callback is handed no anchor to open against.
*/
function advancedTypeAction(ctx: SectionContext, node: Element): HTMLElement {
const button = ctx.headerAction("var-settings", "Advanced type", () =>
openAdvancedType(ctx, node, button)
);
return button;
}
/**
* The axes a variable font is chosen *for*, in a movable popover.
*
* The section had a weight select and nothing else — no width, no optical sizing, no
* numeral variants, and no way to reach a font's own axes at all except by typing into
* the CSS pane. Collapsed by default because most type is not variable, and a section
* that opens onto six rows nobody needs is how a panel stops being scannable.
* the CSS pane.
*
* It arrived as a collapsed sub-section, which was the wrong shape twice over. A
* nested `.sect` paid the body inset a second time, so its heading sat 48px in
* while the rows it headed sat at 24 — and the 48px it cost every row was
* exactly what pushed them past their wrap threshold, so each label broke onto
* its own line and each control went full-bleed under it. That much is now
* fixed in the stylesheet. What is not fixable there is the rest of it: six
* rows nobody needs most of the time, in the middle of the section, pushing
* everything below them down whenever they were open.
*
* A popover answers both. It is out of the section's everyday height, and being
* movable it can sit beside the text it is tuning rather than on top of it —
* which is the whole point of a variable-axis control you are watching the page
* respond to. Same `.pop-form` shape as the stroke settings.
*
* The two `*-settings` properties stay free text: their grammar is `"wght" 450, "opsz" 32`,
* the axis tags are per-font, and a closed control would have to either guess a font's axes
* or refuse the ones it does not know.
*/
function renderAdvancedType(ctx: SectionContext, node: Element): HTMLElement {
const body = el("div", { class: cls("sect-body") });
const grid = el("div", { class: cls("grid") });
grid.append(ctx.fieldCell(FONT_STRETCH, node));
body.append(grid);
for (const descriptor of [FONT_OPTICAL_SIZING, FONT_VARIANT]) {
body.append(ctx.fieldCell(descriptor, node));
}
for (const [property, label, placeholder] of [
["font-variation-settings", "Variation axes", '"wght" 450, "opsz" 32'],
["font-feature-settings", "Feature settings", '"ss01" 1, "liga" 0'],
] as const) {
body.append(freeformType(ctx, node, property, label, placeholder));
}
return ctx.section("text:advanced", "Advanced type", body, {
startCollapsed: true,
function openAdvancedType(
ctx: SectionContext,
node: Element,
anchor: HTMLElement
): void {
const body = el("div", { class: cls("pop-form") });
// Everything below registers into the panel's own control registry, and a
// scope is what lets this popover hand its share of that registry back.
//
// The teardown used to be skipped entirely, on the grounds that `renderBody`
// closes every popover in the same breath as it destroys the registry. That
// is true of the *render* path and not of the *user* path: Escape, an outside
// press or a drag away closes this without re-rendering anything, so its rows
// stayed registered. `reseed` then wrote into detached fields on every
// refresh, and each open/close cycle added another set.
const scope = ctx.repaintScope();
scope(() => {
const grid = el("div", { class: cls("grid") });
grid.append(ctx.fieldCell(FONT_STRETCH, node));
body.append(grid);
for (const descriptor of [FONT_OPTICAL_SIZING, FONT_VARIANT]) {
body.append(ctx.fieldCell(descriptor, node));
}
// "Axes" and "Features", not "Variation axes" and "Feature settings": both
// sat over the rail's budget, and the qualifier is carried by the group they
// are in — every row in here is about the variable font already.
for (const [property, label, placeholder] of [
["font-variation-settings", "Axes", '"wght" 450, "opsz" 32'],
["font-feature-settings", "Features", '"ss01" 1, "liga" 0'],
] as const) {
body.append(freeformType(ctx, node, property, label, placeholder));
}
});
openPopover({
anchor,
content: body,
// Re-running the scope with an empty paint is what disposes and unregisters
// what the paint above adopted. Safe on the render path too: the second run
// finds the same set and drops it once.
onClose: () => scope(() => undefined),
prefer: "below",
title: "Advanced type",
});
}
@@ -44,7 +44,7 @@ const PAINT_NOTE = "Paint server or keyword, edit in CSS";
* colour the illustration does not have. `planVector` already refuses to route
* a truncated scan through `color`; this is the same refusal made visible.
*/
const TRUNCATED_NOTE = "Too many shapes to edit here — edit in CSS";
const TRUNCATED_NOTE = "Too many shapes to edit here. Edit in CSS";
/** The row a truncated plan gets in place of a control. */
function truncatedNote(owners: number): HTMLElement {
+57 -4
View File
@@ -39,7 +39,7 @@ import {
snapAxis,
} from "./inspector/snap";
import { isEditableText } from "./inspector/text-edit";
import { keys } from "./keys";
import { isInsidePopover, isTypingTarget, keys } from "./keys/registry";
import {
clipToSurface,
localRect,
@@ -176,6 +176,14 @@ export interface SelectionDeps {
isGesturing?: () => boolean;
/** Where chrome is drawn. */
layer: ChromeLayer;
/**
* A right-click landed on a selectable element, which is now selected.
*
* The picker does not build the menu: it knows about nodes and surfaces and
* nothing about commands. The app owns what a right-click offers, the same
* way it owns what ⌘Z does.
*/
onContextMenu?: (at: Point, node: Element) => void;
/** Resolves screen points and nodes to the surface they belong to. */
resolver: SurfaceResolver;
/** See `EditGuardOptions.swallowPresses` — true inline, false on the canvas. */
@@ -518,6 +526,7 @@ export class SelectionController {
document.addEventListener("mousemove", this.onMove, true);
document.addEventListener("click", this.onClick, true);
document.addEventListener("dblclick", this.onDblClick, true);
document.addEventListener("contextmenu", this.onContextMenu, true);
window.addEventListener("pointerdown", this.onMarqueeDown, true);
window.addEventListener("pointermove", this.onMarqueeMove);
// Capture, like the down handler — and not only for symmetry. In the
@@ -527,8 +536,7 @@ export class SelectionController {
// inline: the band stayed painted and the selection never landed.
window.addEventListener("pointerup", this.onMarqueeUp, true);
this.unbindKeys = keys.bind({
keys: "escape",
label: "Deselect",
id: "selection.deselect",
run: () => this.deselect(),
// Escape belongs to the drag while one is in flight — it cancels the
// operation, and deselecting on the same keypress would tear down the
@@ -548,6 +556,7 @@ export class SelectionController {
document.removeEventListener("mousemove", this.onMove, true);
document.removeEventListener("click", this.onClick, true);
document.removeEventListener("dblclick", this.onDblClick, true);
document.removeEventListener("contextmenu", this.onContextMenu, true);
window.removeEventListener("pointerdown", this.onMarqueeDown, true);
window.removeEventListener("pointermove", this.onMarqueeMove);
window.removeEventListener("pointerup", this.onMarqueeUp, true);
@@ -792,7 +801,17 @@ export class SelectionController {
// A modifier pressed while typing is a character, not a gesture. Option-E
// for an accented `e` would otherwise flip `altKey` and paint a spacing
// measurement across the text you are in the middle of editing.
if (this.textOwner) {
//
// `textOwner` alone only covered the *in-place* case, so holding ⌥ over the
// composer or a CSS value field still repainted measurements over whatever
// the pointer happened to be resting on. This is a raw listener rather than
// a binding, so it has to ask the registry's questions for itself — the
// same pair `CanvasViewport.onSpaceDown` asks, and for the same reason.
if (
this.textOwner ||
isTypingTarget(e.target, e) ||
isInsidePopover(e.target)
) {
return;
}
if (e.key === "Alt" && this.altKey !== e.altKey) {
@@ -1146,6 +1165,40 @@ export class SelectionController {
this.select(found.node, found.surface, modeOf(e));
};
/**
* A right-click on the page, while editing.
*
* Right-click did nothing anywhere in this editor: `contextmenu` was on
* `EditGuard`'s `SWALLOWED` list and nothing was ever put in its place, so
* the single most conventional mouse affordance in any design tool was a dead
* gesture. It belongs to the picker for the same reason `dblclick` does —
* this is the layer that can turn a screen point into a node — and the picker
* hands the *menu* to the app, which is the layer that knows what commands
* exist.
*
* Declining is as important as answering. Over the editor's own chrome, over
* empty canvas, and in view mode where the page is the user's, the browser's
* own menu is the right answer and this must not `preventDefault`. That is
* also why it selects first: a menu of verbs about "the selection" is a lie
* if the thing you right-clicked is not it.
*/
private readonly onContextMenu = (e: MouseEvent): void => {
if (this.inspecting || isOwn(e.target) || this.textOwner) {
return;
}
const at = { x: e.clientX, y: e.clientY };
const found = this.pick(at);
if (!found) {
return;
}
e.preventDefault();
e.stopPropagation();
// Replace, never extend: a right-click that quietly added to a multi-select
// would change what the menu's verbs apply to as it opened.
this.select(found.node, found.surface, "replace");
this.deps.onContextMenu?.(at, found.node);
};
/**
* A click that arrived while an in-place text edit was live.
*
+107 -3
View File
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cls, el } from "./dom";
import { keys } from "./keys";
import { keys } from "./keys/registry";
import {
closeOpenPopover,
createMenu,
@@ -282,7 +282,7 @@ describe("a popover's own keys", () => {
// The guard's purpose, from the other side: the canvas nudge must not run
// under an open menu.
const nudge = vi.fn();
const off = keys.bind({ keys: "arrowdown", label: "Nudge", run: nudge });
const off = keys.bind({ id: "element.nudge", run: nudge });
try {
const { content } = menu();
press(rows(content)[0], "ArrowDown");
@@ -295,7 +295,7 @@ describe("a popover's own keys", () => {
it("hands the keys back when it closes", () => {
const nudge = vi.fn();
const off = keys.bind({ keys: "arrowdown", label: "Nudge", run: nudge });
const off = keys.bind({ id: "element.nudge", run: nudge });
try {
const { content } = menu();
press(rows(content)[0], "Escape");
@@ -512,3 +512,107 @@ describe("a menu with collapsible groups", () => {
expect(shells()[0].querySelector(".custom-form")).toBe(custom);
});
});
/*
* The modal shape, the title bar, and the parts of both that no case reached.
*
* `popover-host.ts` grew by a third when the palette, the shortcuts sheet and
* the movable title bar landed, and this file's diff for all of it was an import
* path and two renamed literals. What follows covers the behaviour that has a
* user-visible failure mode: a scrim that must take the press meant for the page
* behind it, focus that must come back to whatever opened the modal, and a title
* bar that must be a pointer affordance without pretending to be a keyboard one.
*/
describe("a modal popover", () => {
it("puts a scrim behind it", () => {
openPopover({ content: el("div"), modal: true });
expect(popoverHost()?.querySelector(`.${cls("pop-scrim")}`)).not.toBeNull();
});
it("takes the scrim away again when it closes", () => {
const handle = openPopover({ content: el("div"), modal: true });
handle.close("programmatic");
expect(popoverHost()?.querySelector(`.${cls("pop-scrim")}`)).toBeNull();
});
it("gives focus back to whatever opened it", () => {
// Without this, dismissing the palette drops focus on the body and the next
// keystroke goes nowhere — the composer the user was in is no longer live.
const trigger = anchor();
trigger.focus();
expect(document.activeElement).toBe(trigger);
// No option for it: the shell remembers whatever had focus when it opened,
// and a modal passes no anchor, so this is the only thing it can go back to.
const handle = openPopover({ content: el("div"), modal: true });
// Focus has to actually leave, or the case proves nothing about restoring it.
const [shell] = shells();
(shell as HTMLElement).focus();
expect(document.activeElement).not.toBe(trigger);
handle.close("programmatic");
expect(document.activeElement).toBe(trigger);
});
it("carries the class it was asked for", () => {
// The palette and the shortcuts sheet size themselves through these, and
// both were applied for a long time with no rule anywhere to receive them.
openPopover({ className: "pop-palette", content: el("div"), modal: true });
expect(
popoverHost()?.querySelector(`.${cls("pop-palette")}`)
).not.toBeNull();
});
});
describe("a popover with a title", () => {
it("wears a draggable bar", () => {
openPopover({ anchor: anchor(), content: el("div"), title: "Stroke" });
const bar = popoverHost()?.querySelector(`.${cls("pop-bar")}`);
expect(bar?.textContent).toContain("Stroke");
});
it("hides the bar from assistive tech and names the shell instead", () => {
/*
* The bar is a `POINTER_ONLY` draggable, and dnd-kit stamps
* `aria-roledescription="draggable"` and a tab stop onto any handle. With no
* keyboard sensor that is a control which announces itself as movable and
* answers no key — the promise `POINTER_ONLY`'s own docstring says not to
* make. The title moves to the shell so nothing is lost.
*/
openPopover({ anchor: anchor(), content: el("div"), title: "Stroke" });
const bar = popoverHost()?.querySelector(`.${cls("pop-bar")}`);
const shell = popoverHost()?.querySelector(`.${cls("pop")}`);
expect(bar?.getAttribute("aria-hidden")).toBe("true");
expect(shell?.getAttribute("aria-label")).toBe("Stroke");
expect(shell?.getAttribute("role")).toBe("group");
});
it("keeps the hidden bar out of the tab order", () => {
/*
* The half that makes `aria-hidden` honest, and the half a browser decides
* rather than this test's DOM: dnd-kit's Accessibility plugin writes
* `tabindex="0"` onto any drag handle, guarded only by
* `!activator.hasAttribute("tabindex")`. Writing one first is what stops it,
* and without it the bar would be hidden from screen readers *and* reachable
* by Tab — which is a worse trap than the one being fixed.
*/
openPopover({ anchor: anchor(), content: el("div"), title: "Stroke" });
const bar = popoverHost()?.querySelector(`.${cls("pop-bar")}`);
expect(bar?.getAttribute("tabindex")).toBe("-1");
expect((bar as HTMLElement).tabIndex).toBe(-1);
});
it("builds no bar at all without one", () => {
openPopover({ anchor: anchor(), content: el("div") });
expect(popoverHost()?.querySelector(`.${cls("pop-bar")}`)).toBeNull();
});
});
+323 -41
View File
@@ -30,9 +30,19 @@
* together, and a singleton makes outside-press, Escape and "the panel just
* rebuilt" one code path each instead of a registry to keep in step.
*/
import {
DND,
DndScope,
DragDelta,
Draggable,
FEEDBACK,
manager,
POINTER_ONLY,
} from "./dnd/manager";
import { cls, el } from "./dom";
import { type IconName, icon } from "./icons";
import { type Binding, keys } from "./keys";
import type { CommandId } from "./keys/catalog";
import { type Binding, keys } from "./keys/registry";
import { type PlaceOptions, placePopover, type Side } from "./popover";
export type CloseReason =
@@ -44,16 +54,55 @@ export type CloseReason =
| "select";
export interface PopoverOptions extends PlaceOptions {
anchor: HTMLElement;
/**
* The control this popover belongs to, and the box it is placed against.
*
* Omitted only by a `modal` popover, which belongs to no control: the command
* palette and the shortcuts panel are opened by a chord from anywhere and
* have nowhere to point at.
*/
anchor?: HTMLElement;
/** Extra class on the shell — `pop-menu`, `pop-color`. */
className?: string;
content: HTMLElement;
/** Match the shell's width to the anchor's. For selects. */
matchAnchorWidth?: boolean;
/**
* A centred sheet over a scrim, rather than a box beside a control.
*
* Turns off everything that is about an anchor — the placement, the
* reposition-on-scroll and the frame-by-frame "is my anchor still there"
* watchdog — and adds a scrim that takes the press meant for the page behind
* it. Focus returns to wherever it was when the popover opened, since there
* is no anchor to return it to.
*
* Still a `.pop` shell in the same host, which is the point of putting it
* here rather than in a second layer: it inherits the token scope, membership
* of `edit-guard`'s `CHROME` list, and — the load-bearing one — the
* registry's rule that an unscoped binding never fires while focus is inside
* a popover. Without that, arrowing through the palette would nudge the
* selected element at the same time.
*/
modal?: boolean;
onClose?: (reason: CloseReason) => void;
prefer?: Side;
/** Arrow/Home/End roving over `[data-pop-item]` inside `content`. */
roving?: boolean;
/**
* Give the popover a title bar you can drag it by.
*
* For the "advanced settings" shape, and not for menus. A menu is a
* click-once surface that should be gone before you could want it elsewhere;
* a settings form is one you hold open *against* the thing it edits, and the
* one place it is guaranteed to be in the way is directly over its own
* anchor. Every one of these was fixed to that spot, which is what made them
* read as half-finished.
*
* The string is the bar's label. There is no untitled variant: a bar with
* nothing in it is a grab handle nobody can identify, and every surface that
* wants one has a name already.
*/
title?: string;
}
export interface PopoverHandle {
@@ -66,6 +115,132 @@ const ITEM = "[data-pop-item]";
let host: HTMLElement | null = null;
/** Distinguishes one open popover's drag from another's on the shared monitor. */
let dragSeq = 0;
/** Kept off the viewport edge by this much when dragged. */
const DRAG_MARGIN = 8;
/**
* A title bar, and the drag that moves the shell by it.
*
* `element`, never dnd-kit's `handle` — the same call `armDockDrag` documents
* in `app.ts`: `preventActivation` tests `handle.contains(target)` first and
* returns early, which would turn any button placed in this bar into a drag
* origin instead of a button.
*
* `POINTER_ONLY` because this is a `feedback: "none"` draggable, and those
* cannot be dragged by keyboard — the sensor starts and ends a drag but every
* arrow between does nothing, latching the handle into a dragging state it
* cannot leave. Declining the keyboard route is better than pretending to it;
* the popover is dismissible with Escape either way.
*
* Returns the bar and a teardown, because the monitor is global: a listener
* left behind would go on moving a shell that had closed.
*/
function draggableBar(
shell: HTMLElement,
title: string,
onMoved: () => void
): { bar: HTMLElement; destroy: () => void } {
const bar = el(
"div",
{
/*
* Hidden from assistive tech, and the title moved onto the shell instead.
*
* This is a `POINTER_ONLY` draggable, and dnd-kit's Accessibility plugin
* stamps `tabindex="0"` and `aria-roledescription="draggable"` on any
* handle regardless — so left alone this is a tab stop that announces
* itself as movable and answers no key, which is the exact promise
* `POINTER_ONLY`'s own docstring says not to make. Unlike the frame-list
* grips there is no keyboard verb to offer beside it, because there is
* nothing to offer: a popover that never moves is fully usable, and the
* drag is a convenience for people pushing it off what it covers.
*
* The name is not lost — `openPopover` puts `title` on the shell.
*
* `tabindex` is set here, and its value matters less than its presence:
* the plugin's guard is `!activator.hasAttribute("tabindex")`, so writing
* one ourselves is what stops it writing `0`. Without that the bar would
* be `aria-hidden` *and* focusable — a worse thing than what this fixes,
* because a keyboard user could tab onto something no screen reader can
* see. `aria-hidden` is only honest on a node nothing can reach.
*/
"aria-hidden": "true",
class: cls("pop-bar"),
tabindex: "-1",
},
[el("span", { class: cls("pop-bar-title"), text: title })]
);
bar.dataset.tip = "Drag to move";
dragSeq += 1;
const id = `${DND.popMove}:${dragSeq}`;
const scope = new DndScope();
scope.add(
new Draggable(
{
element: bar,
id,
// The shell is positioned by `left`/`top`; a translate on top of that
// would double every pixel of the drag.
plugins: FEEDBACK.none,
sensors: POINTER_ONLY,
type: DND.popMove,
},
manager
)
);
const delta = new DragDelta();
let from: { x: number; y: number } | null = null;
const offs = [
manager.monitor.addEventListener("dragstart", () => {
if (manager.dragOperation.source?.id !== id) {
return;
}
// Measured live rather than read back off the style, so the first drag
// starts from wherever `placePopover` last put it.
const rect = shell.getBoundingClientRect();
from = { x: rect.left, y: rect.top };
delta.start();
// Before the first move, not after: `place()` runs on scroll and resize,
// and one of those landing mid-drag would snap the shell back under the
// pointer it is being dragged away from.
onMoved();
}),
manager.monitor.addEventListener("dragmove", (e) => {
if (!from) {
return;
}
const d = delta.update(e);
const max = {
x: window.innerWidth - shell.offsetWidth - DRAG_MARGIN,
y: window.innerHeight - shell.offsetHeight - DRAG_MARGIN,
};
// Clamped, or a popover can be pushed under the viewport edge and left
// there — it has no chrome of its own to drag it back by.
shell.style.left = `${Math.round(Math.min(Math.max(DRAG_MARGIN, from.x + d.x), Math.max(DRAG_MARGIN, max.x)))}px`;
shell.style.top = `${Math.round(Math.min(Math.max(DRAG_MARGIN, from.y + d.y), Math.max(DRAG_MARGIN, max.y)))}px`;
}),
manager.monitor.addEventListener("dragend", () => {
from = null;
}),
];
return {
bar,
destroy: () => {
for (const off of offs) {
off();
}
scope.clear();
},
};
}
/*
* Popovers nest, shallowly.
*
@@ -86,7 +261,8 @@ let host: HTMLElement | null = null;
const stack: OpenPopover[] = [];
interface OpenPopover {
anchor: HTMLElement;
/** Null for a modal popover, which belongs to no control. */
anchor: HTMLElement | null;
dispose: () => void;
handle: PopoverHandle;
onClose?: (reason: CloseReason) => void;
@@ -163,17 +339,70 @@ export function openPopover(opts: PopoverOptions): PopoverHandle {
* it go. Anything else is a hand-off, which is the old unconditional close and
* still the common case.
*/
const mine = stack.findIndex((entry) => entry.anchor === opts.anchor);
const { anchor } = opts;
// The toggle only applies to an anchored popover. Two modal ones both have a
// null anchor, so without this guard opening the palette while the shortcuts
// panel was up would read as re-clicking the panel's trigger: it would close
// the panel and open nothing.
const mine = anchor
? stack.findIndex((entry) => entry.anchor === anchor)
: -1;
if (mine !== -1) {
closeAbove(mine - 1, "reopen");
return DEAD;
}
closeAbove(levelOf(opts.anchor), "reopen");
// `levelOf(null)` is -1, so a modal closes every open popover before it opens
// — which is what you want from a sheet that covers the editor.
closeAbove(levelOf(anchor ?? null), "reopen");
const mount = host ?? mountPopoverHost(document.body);
// `isConnected`, not a null check. `mountPopoverHost` keeps the host in a
// module variable and re-appends it, so a host that was detached — by a teardown,
// or by anything that replaced the body's children — stayed non-null and
// kept being used. Popovers then mounted into a node that was in no
// document: no error, no popover, and nothing to see in the DOM you were
// inspecting. Re-mounting on demand makes the reference a cache rather than
// a claim about the tree.
const mount = host?.isConnected ? host : mountPopoverHost(document.body);
// Whatever had focus when this opened, so a modal can hand it back. An
// anchored popover returns focus to its anchor instead and ignores this.
const restoreFocus = document.activeElement as HTMLElement | null;
const scrim = opts.modal ? el("div", { class: cls("pop-scrim") }) : null;
if (scrim) {
mount.append(scrim);
}
// `scroll-y` on every shell: a popover is the overlay's own surface and had
// been the largest family still painting a platform scrollbar — a font list
// or a token picker sat beside an inspector that hides its own, which is
// where "the submenus look nothing like the panel" came from.
const shell = el("div", {
class: opts.className ? `${cls("pop")} ${cls(opts.className)}` : cls("pop"),
class: [
cls("pop"),
cls("scroll-y"),
opts.className ? cls(opts.className) : "",
opts.modal ? cls("pop-modal") : "",
]
.filter(Boolean)
.join(" "),
});
// Once the user has put the popover somewhere, it stays there. `place()` is
// wired to scroll and resize, and re-anchoring a shell that was deliberately
// moved would drag it back the moment the panel behind it scrolled — the
// thing that makes a movable surface feel broken rather than absent.
let moved = false;
const dragging = opts.title
? draggableBar(shell, opts.title, () => {
moved = true;
})
: null;
if (dragging) {
// The name the bar can no longer carry — see `draggableBar`. `group` rather
// than `dialog`: these are anchored, non-modal, and do not trap focus; the
// two that *are* modal set `role="dialog"` on their own content and pass no
// title, so neither branch reaches this.
shell.setAttribute("role", "group");
shell.setAttribute("aria-label", opts.title as string);
shell.prepend(dragging.bar);
}
shell.append(opts.content);
// Appended after its parent and left at `z-index: auto` like every other
// shell, inside the host's single stacking context — so DOM order alone paints
@@ -181,9 +410,16 @@ export function openPopover(opts: PopoverOptions): PopoverHandle {
mount.append(shell);
const place = (): void => {
// A modal is centred by CSS. There is no anchor to measure against, and
// running the placement would write a `left`/`top` over the centring.
// A popover the user has dragged is in the same position for a different
// reason: its coordinates are now an answer, not a derivation.
if (!anchor || moved) {
return;
}
placePopover(
shell,
opts.anchor.getBoundingClientRect(),
anchor.getBoundingClientRect(),
opts.prefer ?? "below",
{
align: opts.align,
@@ -199,9 +435,7 @@ export function openPopover(opts: PopoverOptions): PopoverHandle {
* difference. As a floor it does the one thing a select wants (never
* narrower than its trigger) and lets the content have the rest.
*/
minWidth: opts.matchAnchorWidth
? opts.anchor.offsetWidth
: opts.minWidth,
minWidth: opts.matchAnchorWidth ? anchor.offsetWidth : opts.minWidth,
scroll: opts.scroll,
}
);
@@ -240,8 +474,13 @@ export function openPopover(opts: PopoverOptions): PopoverHandle {
const active = shell.ownerDocument.activeElement;
const hadFocus = active instanceof Node && shell.contains(active);
shell.remove();
if (hadFocus && opts.anchor.isConnected) {
opts.anchor.focus?.();
scrim?.remove();
// A modal has no anchor to go back to, so it goes back to whatever the
// user was on when they hit ⌘K — otherwise focus lands on `<body>` and
// the next Tab restarts at the top of the document.
const back = anchor ?? restoreFocus;
if (hadFocus && back?.isConnected) {
back.focus?.();
}
// Out of the stack before `onClose` runs, as before — a parent's `onClose`
// may destroy a control that owns a child popover, and every path has to
@@ -252,9 +491,16 @@ export function openPopover(opts: PopoverOptions): PopoverHandle {
reposition: place,
};
const dispose = install(opts, handle);
const installed = install(opts, handle);
// The drag's listeners live on the shared monitor rather than on the shell,
// so removing the element does not remove them — a closed popover would go
// on answering a drag it can no longer show.
const dispose = (): void => {
installed();
dragging?.destroy();
};
stack.push({
anchor: opts.anchor,
anchor: anchor ?? null,
dispose,
handle,
onClose: opts.onClose,
@@ -281,7 +527,7 @@ function install(opts: PopoverOptions, handle: PopoverHandle): () => void {
// Inside *any* open shell counts as inside. `shell.contains` — all this used
// to test — cannot see a child, because children are siblings in the host,
// so a press in a menu opened from this popover read as a press outside it.
if (levelOf(target) !== -1 || opts.anchor.contains(target)) {
if (levelOf(target) !== -1 || opts.anchor?.contains(target)) {
return;
}
handle.close("outside");
@@ -316,18 +562,23 @@ function install(opts: PopoverOptions, handle: PopoverHandle): () => void {
* parent's body: when that parent scrolls, the child's anchor really has
* moved, and the child really does have to follow it.
*/
const watched = opts.anchor;
const onReflow = (e: Event): void => {
if (e.type === "scroll" && handle.element.contains(e.target as Node)) {
return;
}
if (!opts.anchor.isConnected) {
if (!watched?.isConnected) {
handle.close("anchor-gone");
return;
}
handle.reposition();
};
window.addEventListener("scroll", onReflow, true);
window.addEventListener("resize", onReflow);
// A modal is centred and belongs to no control, so there is nothing for a
// scroll or a resize to move it away from and nothing to watch for removal.
if (watched) {
window.addEventListener("scroll", onReflow, true);
window.addEventListener("resize", onReflow);
}
/*
* A frame-by-frame check that the anchor still exists.
@@ -339,13 +590,15 @@ function install(opts: PopoverOptions, handle: PopoverHandle): () => void {
* work is one property read per frame while a popover is open — and nothing at
* all when none is.
*/
let frame = requestAnimationFrame(function watch() {
if (!opts.anchor.isConnected) {
handle.close("anchor-gone");
return;
}
frame = requestAnimationFrame(watch);
});
let frame = watched
? requestAnimationFrame(function watch() {
if (!watched.isConnected) {
handle.close("anchor-gone");
return;
}
frame = requestAnimationFrame(watch);
})
: 0;
/*
* Through the registry, not a raw listener, and every one of them scoped to
@@ -362,33 +615,29 @@ function install(opts: PopoverOptions, handle: PopoverHandle): () => void {
* which is correct for the arrows (they should move the caret inside the
* picker's hex field) but means a focused field swallows Escape too. Fields
* inside a popover therefore keep their own Escape handler, which is what
* `keys.ts` prescribes for field-local commit/cancel anyway.
* `keys/registry.ts` prescribes for field-local commit/cancel anyway.
*/
const bindings: Binding[] = [
{
keys: "escape",
label: "Close",
id: "popover.close",
run: () => handle.close("escape"),
},
];
if (opts.roving) {
const step = (delta: number) => () => moveItem(opts.content, delta);
bindings.push(
{ keys: "arrowdown", label: "Next option", run: step(1) },
{ keys: "arrowup", label: "Previous option", run: step(-1) },
{ id: "popover.next", run: step(1) },
{ id: "popover.prev", run: step(-1) },
{
keys: "home",
label: "First option",
id: "popover.first",
run: () => focusItem(opts.content, 0),
},
{
keys: "end",
label: "Last option",
id: "popover.last",
run: () => focusItem(opts.content, -1),
},
{
keys: "enter",
label: "Choose option",
id: "popover.choose",
run: () => activeItem(opts.content)?.click(),
}
);
@@ -475,9 +724,25 @@ const DEAD: PopoverHandle = {
// -- Menus --------------------------------------------------------------------
export interface MenuItem {
/**
* The command this row runs, so its chord is rendered from the registry.
*
* Prefer this over spelling a chord into `hint`. Five rows in
* `canvas/frame-chrome.ts` used to carry hand-written Mac glyphs — `"⌘+"`
* where the binding was `mod+=`, `"⌘−"` with a U+2212 minus, all of them
* shown unchanged to Windows and Linux — and one row in `chat/transcript.ts`
* advertised `⌘Z` for the server-side revert, which ⌘Z has never run.
*/
command?: CommandId;
/** Present but unusable — greyed, and skipped by the keyboard cursor. */
disabled?: boolean;
/** Rendered right-aligned in a dimmed mono — a shortcut, a size, a unit. */
/**
* Rendered right-aligned in a dimmed mono.
*
* For a size or a unit. If it is a *shortcut*, use `command` instead — a
* chord typed in here is a copy of the registry that nothing keeps honest,
* and `keys/catalog.test.ts` will reject one that looks like a chord.
*/
hint?: string;
/** Leading glyph. Optional: a menu of plain verbs is better without one. */
icon?: IconName;
@@ -501,6 +766,16 @@ export interface MenuItem {
export interface MenuGroup {
/** Stable id, written to `data-group`. What `open` is matched against. */
group: string;
/**
* Glyph on the header, after the disclosure chevron.
*
* For a group whose identity is a mark rather than a word — the agent
* picker's three backends are known by their logos, and a shut accordion
* that reads "Claude / Codex / OpenCode" in plain text throws away the
* fastest thing about it. Optional, because a group of *sizes* has no glyph
* worth showing and the device menus are right not to carry one.
*/
icon?: IconName;
items: MenuItem[];
label: string;
open?: boolean;
@@ -588,7 +863,11 @@ function buildGroup(
},
type: "button",
},
[icon("chev-right", "xs"), el("span", { text: entry.label })]
[
icon("chev-right", "xs"),
...(entry.icon ? [icon(entry.icon, "sm")] : []),
el("span", { text: entry.label }),
]
);
return el("div", { class: cls("pop-group"), "data-group": entry.group }, [
head,
@@ -719,8 +998,11 @@ export function createMenu(entries: MenuEntry[]): MenuHandle {
]),
]
);
if (entry.hint) {
row.append(el("span", { class: cls("pop-item-hint"), text: entry.hint }));
// The command's own chord wins over a hand-written `hint`, so a row that
// names a command can never disagree with the key that runs it.
const hint = entry.command ? keys.hint(entry.command) : entry.hint;
if (hint) {
row.append(el("span", { class: cls("pop-item-hint"), text: hint }));
}
return row;
};
+71
View File
@@ -39,6 +39,77 @@ ${ROOT} [disabled] .${PREFIX}-ic { --${PREFIX}-ic-tone: var(--ap-icon-disabled);
.${PREFIX}-hidden { display: none !important; }
/* Scrollbars. One definition, applied by class, for every scroll container the
overlay owns.
These were \`scrollbar-width: none\` plus \`::-webkit-scrollbar { display: none }\`
— a deliberate-looking choice that quietly broke the mouse. A trackpad can
swipe a horizontal rail sideways and a hidden scrollbar costs it nothing; a
mouse wheel produces vertical delta only, so with no scrollbar, no wheel
handler and no visible edge, the chips past the fold were simply unreachable.
The people who built it were on trackpads, which is exactly why it survived.
Transparent at rest so the chrome stays quiet, tinted once the surface is
under the pointer or holds focus. \`scrollbar-width: thin\` reserves its gutter
whether or not the thumb is painted, so revealing it shifts nothing — and the
rails are \`:empty { display: none }\`, so the ~6px is only spent when there is
something to scroll, which is when you want the affordance anyway.
Both syntaxes: \`scrollbar-color\` is the standard one (Firefox, Chrome 121+),
\`::-webkit-scrollbar\` covers Safari and older WebKit. An engine that honours
the first ignores the second, so they do not fight.
The \`--ap-scrollbar-*\` ramp has been shipping from @airship/editor-tokens
since the token set was written and had no reader until now. */
.${PREFIX}-scroll-x, .${PREFIX}-scroll-y {
scrollbar-width: thin; scrollbar-color: transparent transparent;
}
/* \`overflow-y: hidden\` on the rail is deliberate: the thin scrollbar takes 6px
off the content box, and without it a chip that exactly fills the row can
provoke a vertical scrollbar on a one-row strip. \`.scroll-y\` sets no
cross-axis value at all — the panels it dresses hold rows that are
occasionally wider than the dock, and \`overflow-x: hidden\` would clip them
where today they scroll. */
.${PREFIX}-scroll-x { overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; }
.${PREFIX}-scroll-y { overflow-y: auto; overscroll-behavior-y: contain; }
.${PREFIX}-scroll-x:hover, .${PREFIX}-scroll-x:focus-within,
.${PREFIX}-scroll-y:hover, .${PREFIX}-scroll-y:focus-within {
scrollbar-color: var(--ap-scrollbar-thumb) var(--ap-scrollbar-track);
}
.${PREFIX}-scroll-x::-webkit-scrollbar, .${PREFIX}-scroll-y::-webkit-scrollbar {
width: 6px; height: 6px;
}
.${PREFIX}-scroll-x::-webkit-scrollbar-track, .${PREFIX}-scroll-y::-webkit-scrollbar-track {
background: var(--ap-scrollbar-track);
}
.${PREFIX}-scroll-x::-webkit-scrollbar-thumb, .${PREFIX}-scroll-y::-webkit-scrollbar-thumb {
background: transparent; border-radius: var(--ap-radius-pill);
}
.${PREFIX}-scroll-x:hover::-webkit-scrollbar-thumb, .${PREFIX}-scroll-x:focus-within::-webkit-scrollbar-thumb,
.${PREFIX}-scroll-y:hover::-webkit-scrollbar-thumb, .${PREFIX}-scroll-y:focus-within::-webkit-scrollbar-thumb {
background: var(--ap-scrollbar-thumb);
}
.${PREFIX}-scroll-x::-webkit-scrollbar-thumb:hover, .${PREFIX}-scroll-y::-webkit-scrollbar-thumb:hover {
background: var(--ap-scrollbar-thumb-hover);
}
.${PREFIX}-scroll-x::-webkit-scrollbar-thumb:active, .${PREFIX}-scroll-y::-webkit-scrollbar-thumb:active {
background: var(--ap-scrollbar-thumb-active);
}
/* Fade the edge a rail can still scroll toward, so the overflow is visible
before you hover it — the affordance a mouse user actually notices. The
attribute is written by \`attachRailWheel\` from the rail's own scroll position;
absent means it fits and nothing is masked. */
.${PREFIX}-scroll-x[data-overflow="right"] {
mask-image: linear-gradient(to right, #000 calc(100% - 24px), transparent 100%);
}
.${PREFIX}-scroll-x[data-overflow="left"] {
mask-image: linear-gradient(to right, transparent 0, #000 24px);
}
.${PREFIX}-scroll-x[data-overflow="both"] {
mask-image: linear-gradient(to right, transparent 0, #000 24px, #000 calc(100% - 24px), transparent 100%);
}
/* Edit mode: the page is a canvas, not an app. Element-level cursors (a link's
pointer, an input's text caret) beat \`document.body.style.cursor\`, so the
arrow has to be forced from here — and text selection has to be off, or
+29
View File
@@ -82,3 +82,32 @@ export const MINIMAP_PAD = 10;
* of the 45-75 band, which is where micro-copy shown for half a second belongs.
*/
export const TIP_MAX_W = 260;
/**
* The label rail on a `labelled()` row, in CSS px.
*
* Here for the reason `MIN_DOCK_W` is: comments in `inspector.css.ts` and
* `controls.css.ts` reason about "the 68px label rail" in five places while the
* number itself lived in exactly one of them, as a literal. Anything that has
* to be quoted to be explained belongs where it can be imported.
*
* It is one half of a wrap threshold rather than a free choice. A `.row` breaks
* when the rail, a gutter and `--ap-row-ctl-min` stop fitting the dock, so this
* number and that one decide together whether a row is one line or two.
*/
export const LABEL_RAIL_W = 68;
/**
* The most characters a rail label may run to.
*
* Derived the way `TIP_MAX_W` derives its own: at `--ap-font-size-label` (12px
* Inter) the rail holds about fourteen characters. The rail neither ellipsises
* nor clips — there is nowhere for a fifteenth to go, so it wraps to a second
* line and takes the row's height with it.
*
* The rule was written down in `descriptors.ts` long before this constant, and
* drifted anyway: it claimed "Blend mode" at ten was the longest label shipped,
* by which time three labels were past fourteen and one was twenty-four. Prose
* cannot hold a budget. `tooltip.copy.test.ts` asserts against this.
*/
export const LABEL_MAX_CHARS = 14;
+41 -16
View File
@@ -145,16 +145,36 @@ ${[
font-family: var(--ap-font-mono); font-size: var(--ap-font-size-body);
color: var(--ap-text-tertiary);
}
/* A unit belongs to the number it follows, so the number goes to meet it.
/* A unit belongs to the number it follows, so the suffix goes to meet it.
The input is \`flex: 1 1 auto\` and its text is left-aligned, so it absorbed
every pixel between the digits and the rigid suffix: the fill row's alpha
field rendered "25" and its "%" about 29px apart, at two different sizes and
two different tones, which read as two controls rather than one value. Only
where there is a suffix — a field without one has nothing to meet, and its
digits belong on the left beside the glyph that names them. */
The goal has not changed. The input is \`flex: 1 1 auto\`, so it absorbed every
pixel between the digits and the rigid suffix: the fill row's alpha field
rendered "25" and its "%" about 29px apart, at two different sizes and two
different tones, which read as two controls rather than one value.
What changed is which half moves. Sending the *number* right closed that gap
but bought a second one: Rotation right-aligned while X, Y and Z beside it —
same row, same field, no suffix — stayed left, so four numbers that belong to
one element sat on two different margins. Nothing about a degree sign should
move the digits it qualifies.
So the input sizes to its content and the suffix follows it. Both stay on the
left margin, the unit still touches its number, and alignment stops depending
on whether a field happens to carry a unit.
\`field-sizing\` is the only way to content-size a replaced element in CSS, and
it is Chromium-and-Safari for now. The old rule is the fallback rather than
nothing: without it Firefox would render the 29px gap this rule exists to
close, which is worse than an alignment that varies by unit. */
.${PREFIX}-ctl-num:has(> .${PREFIX}-ctl-suffix) > .${PREFIX}-ctl-input {
text-align: right;
field-sizing: content;
flex: 0 1 auto; width: auto; min-width: 2ch; max-width: 100%;
}
@supports not (field-sizing: content) {
.${PREFIX}-ctl-num:has(> .${PREFIX}-ctl-suffix) > .${PREFIX}-ctl-input {
flex: 1 1 auto; width: 100%; min-width: 0; max-width: none;
text-align: right;
}
}
/* Segmented group. Text options stay pills; an all-icon group becomes square
@@ -190,7 +210,9 @@ ${ROOT} .${PREFIX}-ctl-seg-on .${PREFIX}-ic { --${PREFIX}-ic-tone: var(--ap-text
/* ---- Auto layout ------------------------------------------------------- */
/* Direction row, then the 3x3 pad beside a stack of fields — the design-tool layout. */
.${PREFIX}-al-dir { margin-bottom: var(--ap-control-group-gap); }
/* No margin under the direction row: \`.al-main\` carries \`group\`, so the
section body puts a group-gap between them the same way it does everywhere
else. A margin here would be added to that gap, not instead of it. */
.${PREFIX}-al-main { display: flex; align-items: flex-start; gap: var(--ap-control-gutter); }
.${PREFIX}-al-fields { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: var(--ap-control-row-gap); }
@@ -539,13 +561,16 @@ ${ROOT} .${PREFIX}-select[aria-expanded="true"] .${PREFIX}-ic { --${PREFIX}-ic-t
with \`margin: 6px 0\` (see inspector.css.ts) and margins do not collapse
between flex items, so a 6px column gap put 18px between two rows and 12px
above the first — one pitch reading as three. Block flow is the model those
margins were written for, the one .sect-body already gives every other
section, and the one where :first-child and :last-child mean what they say.
What is left here is the group gap above, which is all this wrapper was ever
for. The font-family field is still full width under it: a \`display: flex\`
box in block flow is block-level and fills the line exactly as a stretching
column made it. */
.${PREFIX}-text-extras { margin-top: var(--ap-control-group-gap); }
margins were written for, and the one where :first-child and :last-child mean
what they say. That still holds *inside* this wrapper, which is why it stays
a block: \`.sect-body\` is a flex column now, but it zeroes the margin on its
own direct children only, so rows nested one level down keep collapsing.
The gap above comes from \`group\` on the element rather than a margin here —
a margin would be added to the body's gap, not instead of it. The
font-family field is still full width under it: a \`display: flex\` box in
block flow is block-level and fills the line exactly as a stretching column
made it. */
/* An icon group is not three word pills, and {row-ctl-min} is a measurement of
words — "Inside / Centre / Outside", per the note where it is defined. Three
icon cells are legible from 24px, so 3x40 plus the group's 8px of chrome is
+92
View File
@@ -1,3 +1,5 @@
import { existsSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { buildCss, design } from "@airship/editor-tokens";
import { describe, expect, it } from "vitest";
import { overlayCss } from "./index";
@@ -112,3 +114,93 @@ describe("overlay stylesheet", () => {
expect(css.slice(at)).not.toContain("transition:");
});
});
/*
* A class the product applies must be a class the stylesheet defines.
*
* `.pop-palette` and `.pop-shortcuts` were passed as `className` by the palette
* and the shortcuts sheet, and neither had a rule anywhere. Both silently took
* their whole box from `.pop-modal` — right for the palette, and wrong for a
* sixty-row two-column reference that got a container sized for ten results.
*
* `scripts/check-css.mjs` cannot see this: it checks backtick escaping and the
* no-transition rule against the stylesheet alone, and an applied-but-undefined
* class is only visible by comparing the sheet with the call sites.
*
* Scoped to `className:` popover options rather than every `cls()` call in the
* product. Those are the ones whose entire purpose is to carry styling — a
* `cls()` used as a query hook legitimately has no rule.
*/
const POPOVER_CLASS = /className:\s*"([a-z][\w-]*)"/g;
/**
* The overlay's own sources, found from the working directory.
*
* `import.meta.url` is an http URL under happy-dom, and vitest's root is the
* package while turbo can run from the repo root — the same two facts
* `tooltip.copy.test.ts` resolves the same way.
*/
const SRC = [
join(process.cwd(), "src"),
join(process.cwd(), "packages/overlay/src"),
process.cwd(),
].find((dir) => existsSync(join(dir, "tooltip.ts"))) as string;
function sourceFiles(dir: string, found: string[] = []): string[] {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const path = join(dir, entry.name);
if (entry.isDirectory()) {
sourceFiles(path, found);
} else if (
entry.name.endsWith(".ts") &&
!(entry.name.includes(".test.") || entry.name.includes(".stories."))
) {
found.push(path);
}
}
return found;
}
describe("popover classNames", () => {
const css = overlayCss().replace(CSS_COMMENT, "");
const files = sourceFiles(SRC);
it("finds the sources to scan", () => {
// A scan that matched nothing would make the case below pass forever.
expect(files.length).toBeGreaterThan(20);
});
/**
* Whether the stylesheet has a rule for `.${PREFIX}-<name>`.
*
* The boundary matters in both directions. A bare `includes` would accept
* `.ap-pop-menu-hint` as a definition of `pop-menu`, and would *reject* a real
* rule written `.ap-pop-foo:hover` or `.ap-pop-foo{`. So: the name, then
* anything that can legally end a class in a selector.
*/
const defines = (name: string): boolean =>
new RegExp(`\\.[\\w-]*-${name}(?![\\w-])`).test(css);
it("agrees with itself about what counts as defined", () => {
// The matcher is the whole case below; a broken one passes silently.
expect(defines("pop-modal")).toBe(true);
expect(defines("pop-menu")).toBe(true);
expect(defines("definitely-not-a-class")).toBe(false);
// A prefix of a real class is not that class.
expect(defines("pop-mod")).toBe(false);
});
it("defines every class a popover asks for", () => {
const undefinedClasses: string[] = [];
for (const path of files) {
const src = readFileSync(path, "utf8");
for (const [, name] of src.matchAll(POPOVER_CLASS)) {
if (!defines(name)) {
undefinedClasses.push(`${path.slice(SRC.length)} "${name}"`);
}
}
}
expect(undefinedClasses.sort((a, b) => a.localeCompare(b))).toEqual([]);
});
});
+5
View File
@@ -10,6 +10,7 @@ import { css as cssPane } from "./css-pane.css";
import { css as docks } from "./docks.css";
import { css as empty } from "./empty.css";
import { css as framesPanel } from "./frames-panel.css";
import { css as help } from "./help.css";
import { css as inspector } from "./inspector.css";
import { css as minimap } from "./minimap.css";
import { css as motion } from "./motion.css";
@@ -112,6 +113,10 @@ const CSS = [
empty,
controls,
pop,
// After `pop`, because both discovery surfaces are `.pop` shells and this is
// what fills them — the shell's recipe has to land first for these to be
// overrides of it rather than a parallel definition.
help,
chrome,
toast,
// Last, and it has to be: it overrides the motion every module above declares,
+57 -14
View File
@@ -1,5 +1,5 @@
import { PREFIX } from "../dom";
import { Z } from "./const";
import { LABEL_RAIL_W, Z } from "./const";
/** Right dock: tabs, the DOM tree, sections, the field grid, the CSS tab. */
export const css = `
@@ -149,13 +149,33 @@ export const css = `
panel's empty state pinned itself to the top while the transcript's (already
a flex column) centred correctly. Same block, two different results, which is
the bug. Both hosts are columns now. */
/* The overflow and the scrollbar come from \`.scroll-y\` in base.css. This panel
is the tallest scroll surface in the editor and it had no scrollbar at all, so
nothing said how far down the sections went. */
.${PREFIX}-insp-body {
flex: 1 1 auto; overflow-y: auto; scrollbar-width: none;
flex: 1 1 auto;
display: flex; flex-direction: column;
}
.${PREFIX}-insp-body::-webkit-scrollbar { display: none; }
.${PREFIX}-insp-hint { font-size: var(--ap-font-size-label); opacity: .5; padding: var(--ap-space-md) var(--ap-space-lg); }
.${PREFIX}-sect { border-bottom: 1px solid var(--ap-border-default); }
/* A sub-section does not pay the inset twice.
\`section()\` builds one shape, and four callers nest it inside a body that has
already spent \`--ap-space-lg\` on each side — Advanced type, Filters, Matched
CSS rules and Source. The head and body then add their own, so the heading
sat 48px in while the rows it headed sat at 24, and it drew a divider through
the middle of the section containing it.
The width mattered more than the alignment did. A labelled row wraps when the
rail, the gutter and \`--ap-row-ctl-min\` stop fitting, so at the narrowest
dock the doubled padding was the 48px that decided it: every row inside
Advanced type broke its label onto its own line and went full-bleed, while
the identical rows one level up did not. Un-inset, they wrap together or not
at all. */
.${PREFIX}-sect-body > .${PREFIX}-sect { border-bottom: 0; }
.${PREFIX}-sect-body > .${PREFIX}-sect > .${PREFIX}-sect-head,
.${PREFIX}-sect-body > .${PREFIX}-sect > .${PREFIX}-sect-body {
padding-left: 0; padding-right: 0;
}
/* Symmetric inset, matching \`sect-body\` and the field grid: with the chevron
moved to the right (see \`section()\`) the heading starts on the same margin
as the rows it heads, and no arrow is pressed against the dock edge. */
@@ -187,9 +207,26 @@ export const css = `
divider — the heading crowded its own body and floated away from the section
above it. A heading is now exactly one group-gap from its content, which is
the same distance two groups inside it are from each other. */
/* A column with one pitch, rather than every child arguing its own case.
The separation used to come from \`.row\`'s own margin plus five \`+\` pairs
naming which neighbours earned a group-gap. Between them they covered
\`.group\`/\`.grid\`/\`.rows\` and missed \`.row\`+\`.grid\`, \`.grid\`+\`.grid\` and
\`.grid-tracks\`+\`.grid\` — and \`.grid\` carries no margin, so those pairs
touched. Layout's grid branch stacked a track editor, a gap grid and three
rows at three different distances, none of them chosen.
Stated as a gap, the default is the row pitch and every child gets it
whatever it is; \`.group\` then adds the difference to reach a group-gap. Two
rules instead of six, and a new block shape cannot arrive unspaced. */
.${PREFIX}-sect-body {
display: flex; flex-direction: column;
gap: var(--ap-control-row-gap);
padding: var(--ap-control-group-gap) var(--ap-space-lg);
}
/* The body owns the separation now. Rows outside one — \`.pop-form\`'s, and the
source kv list — keep the margin below, because those containers have no gap
of their own to fall back on. */
.${PREFIX}-sect-body > .${PREFIX}-row { margin: 0; }
/* The field grid.
A design tool's rail is two columns of glyph-fielded controls, not a label rail with
@@ -228,9 +265,10 @@ export const css = `
}
.${PREFIX}-grid > .${PREFIX}-span2 { grid-column: 1 / -1; }
.${PREFIX}-grid > .${PREFIX}-cell { min-width: 0; }
/* Margin, not gap: a .row is a sibling of grids and lists rather than a child
of one, so it owns its own separation. Collapsed against the section's own
padding at the edges. */
/* The margin is the fallback, not the rule. Inside a \`.sect-body\` the parent's
gap owns the separation and this is zeroed above; it survives for the rows
that live somewhere else — \`.pop-form\`'s and the source kv list — whose
containers have no gap to inherit. */
/* Wraps, so the 68px label rail gives up its line before the control gives up
its legibility. The rail is \`flex: 0 0 68px\` and never yielded, so at the
narrowest dock Padding, Margin and Stroke position were working in 154px —
@@ -249,16 +287,21 @@ export const css = `
/* A group: the level between a row and a section. Everything inside it is one
decision — the alignment pad and the fields beside it, a stroke's colour and
its weight — and the gap above says where the previous decision ended. */
.${PREFIX}-group + .${PREFIX}-group,
.${PREFIX}-group + .${PREFIX}-grid,
.${PREFIX}-grid + .${PREFIX}-group,
.${PREFIX}-group + .${PREFIX}-rows,
.${PREFIX}-rows + .${PREFIX}-group {
margin-top: var(--ap-control-group-gap);
its weight — and the gap above says where the previous decision ended.
A marker, never a box: \`.group\` is composed onto four different shapes
(\`row group\`, \`grid group\`, \`size-wrap group\`, and a bare div), so it must
not declare \`display\` — giving it a column direction would lay every
\`row group\` out vertically. It only ever adds the distance above itself.
The difference, not the whole gap, because the parent already spent one
row-gap on this child. \`:not(:first-child)\` so a group opening a section
does not push itself off its own heading. */
.${PREFIX}-group:not(:first-child) {
margin-top: calc(var(--ap-control-group-gap) - var(--ap-control-row-gap));
}
.${PREFIX}-row-label {
flex: 0 0 68px; font-size: var(--ap-font-size-label); color: var(--ap-text-tertiary);
flex: 0 0 ${LABEL_RAIL_W}px; font-size: var(--ap-font-size-label); color: var(--ap-text-tertiary);
}
/* Opt out of the row's centring, for a one-line control standing beside a
control that stacks. A .row centres because almost everything in it is one
+170 -5
View File
@@ -96,8 +96,103 @@ export const css = `
border: 1px solid var(--ap-border-default);
border-radius: var(--ap-radius-md);
box-shadow: var(--ap-elevation-floating);
overflow-x: hidden; overflow-y: auto;
overscroll-behavior: contain;
/* Vertical overflow and the scrollbar itself come from \`.scroll-y\`, which
every shell carries. \`overflow-x\` stays here: it is a clipping decision
rather than a scrolling one, and the note above depends on it. */
overflow-x: hidden;
}
/* A popover's title bar, and the only part of it you can drag by.
Reads as the section heading it sits under — same mono uppercase eyebrow as
\`.sect-head\` — because a settings popover is a section that happens to
float, and giving it a second visual language would make it a dialog.
\`sticky\` rather than static: the shell is the scroller (\`.scroll-y\`), and a
bar that scrolled away would take the grab handle with it, stranding a
popover you had scrolled to the bottom of. */
.${PREFIX}-pop-bar {
position: sticky; top: 0; z-index: 1;
display: flex; align-items: center; gap: var(--ap-control-row-gap);
padding: var(--ap-space-xs) var(--ap-space-sm);
margin-bottom: var(--ap-control-row-gap);
background: var(--ap-surface-panel);
border-bottom: 1px solid var(--ap-border-default);
cursor: grab; user-select: none; touch-action: none;
}
.${PREFIX}-pop-bar:active { cursor: grabbing; }
.${PREFIX}-pop-bar-title {
flex: 1 1 auto; min-width: 0;
font-family: var(--ap-font-mono); text-transform: uppercase;
font-size: var(--ap-font-size-caption); letter-spacing: .6px; opacity: .6;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
/* A modal popover: the command palette and the shortcuts panel.
Centred by CSS rather than placed, which is why \`openPopover\` skips
\`placePopover\` entirely for one of these — the placement writes a \`left\` and
a \`top\`, and either would fight the transform below.
Above centre, not at it: a sheet pinned to the exact middle of the window
reads as lower than centre, and this one grows downward as you type, so
anchoring it high keeps the first result where the eye already is. The same
trick every command palette uses.
\`overflow: hidden\` overrides \`.pop\`'s \`auto\`: a palette scrolls its
*results*, not its shell, or the search field scrolls away from the query
being typed into it. The rows below own the scrolling; this only clips them
to the rounded corner. */
.${PREFIX}-pop-modal {
position: fixed; left: 50%; top: 18vh; transform: translateX(-50%);
width: min(560px, calc(100vw - 2 * var(--ap-space-xl)));
max-height: min(60vh, 520px);
display: flex; flex-direction: column;
overflow: hidden;
}
/* The palette, at the modal's own size. Declared rather than left to the
fallback so the class \`openPalette\` passes has a rule to find: an applied
class with no rule anywhere is indistinguishable from a missing stylesheet,
and \`styles/index.test.ts\` now fails one. */
.${PREFIX}-pop-palette {
width: min(560px, calc(100vw - 2 * var(--ap-space-xl)));
}
/* The shortcuts sheet is a reference, not a search box, and wants a different
box from the palette it shares \`.pop-modal\` with.
\`.sc-body\` sets \`columns: 2\`, so at the modal's 560px each column is about
250px — and the sheet renders every command, every gesture and the closing
notes, roughly sixty rows, into that. Both classes were applied with no rule
of their own, so this inherited a box sized for ten results and a query.
Higher, too: a taller box anchored at 18vh would push its own tail off the
bottom of the window. */
.${PREFIX}-pop-shortcuts {
top: 10vh;
width: min(880px, calc(100vw - 2 * var(--ap-space-xl)));
max-height: min(80vh, 720px);
}
/* The scrim. Takes the press meant for the page behind it — without one, a
click beside the palette lands on the app and selects an element on the way
to closing the palette. \`pointer-events: auto\` because \`.pop-host\` is
\`none\`, and the host's own outside-press handler is what closes it.
A literal rather than a token: the set has no scrim colour, and inventing an
\`--ap-\` name here would put a value in the stylesheet that
\`packages/editor-tokens/EDITOR.md\` has never heard of. */
.${PREFIX}-pop-scrim {
position: fixed; inset: 0; pointer-events: auto;
background: rgba(0, 0, 0, 0.4);
}
/* A stand-in for the pointer, so a context menu can be anchored at a *point*.
\`openPopover\` places against an element's rect and watches that element for
removal, so a bare coordinate needs a box; this is the smallest honest one.
Removed when the menu closes. */
.${PREFIX}-point-anchor {
position: fixed; width: 1px; height: 1px; pointer-events: none;
}
/* Menu. Mirrors \`.fc-menu-item\` rather than sharing it: the canvas keeps its
@@ -164,8 +259,13 @@ export const css = `
/* Rotating \`chev-right\` a quarter turn reproduces \`chev-down\` exactly — the set
draws them as one path at two rotations — so one glyph serves both states.
Driven from \`aria-expanded\`, which is where the state already lives. */
.${PREFIX}-pop-group-head .${PREFIX}-ic { flex: 0 0 16px; opacity: .5; }
.${PREFIX}-pop-group-head[aria-expanded="true"] .${PREFIX}-ic { transform: rotate(90deg); }
/* \`:first-child\` because a group may now carry a second glyph — its own mark,
after the chevron. Both of these are about the *disclosure*: an unscoped
selector dimmed the mark to half and, worse, spun it a quarter turn every
time the group opened. */
.${PREFIX}-pop-group-head > .${PREFIX}-ic { flex: 0 0 16px; }
.${PREFIX}-pop-group-head > .${PREFIX}-ic:first-child { opacity: .5; }
.${PREFIX}-pop-group-head[aria-expanded="true"] > .${PREFIX}-ic:first-child { transform: rotate(90deg); }
/* 8px padding + 16px glyph + 6px gap, so a group's name and every row under it
share one left edge and the triangle hangs in a gutter of its own. Getting
this wrong is what makes an accordion read as two unrelated lists rather than
@@ -204,11 +304,35 @@ export const css = `
/* The "advanced settings" shape: the two or three properties you set once
and then forget, kept out of the section's everyday height. Same labelled
rows as the panel, so it reads as the same system rather than a dialog. */
/* A gap, and the rows give up their margins to it — the same correction
\`.sect-body\` takes, and for a sharper reason: this is a flex column, and
margins do not collapse between flex items, so two rows each asking for 6px
were sitting 12px apart. The form read a pitch looser than the panel it is
supposed to look like. */
.${PREFIX}-pop-form {
display: flex; flex-direction: column;
gap: var(--ap-control-row-gap);
padding: var(--ap-space-sm); min-width: 236px;
}
.${PREFIX}-pop-form > .${PREFIX}-row { margin: 0; }
.${PREFIX}-pop-form .${PREFIX}-row-label { flex: 0 0 60px; }
/* The control's floor, restated for this shell rather than inherited.
\`--ap-row-ctl-min\` is 192px, measured against a dock: 60 + 8 + 192 is 260,
and a 236px form minus its padding leaves 212 — so every labelled row in
here wrapped its label onto its own line, in a popover with no dock edge
forcing it to. 144 is what actually fits, and it is arrived at rather than
guessed: the content box less the rail and the gutter.
Not by widening the shell instead: 236 is shared with the token picker
deliberately, after this panel had grown three popover widths for three
popovers. A number that exists to be the same everywhere is the wrong one to
change for one caller. */
.${PREFIX}-pop-form > .${PREFIX}-row > .${PREFIX}-ctl-seg,
.${PREFIX}-pop-form > .${PREFIX}-row > .${PREFIX}-select-wrap,
.${PREFIX}-pop-form > .${PREFIX}-row > .${PREFIX}-pad-row {
--${PREFIX}-row-ctl-min: 144px;
}
/* The honest footnote. Quiet, and wrapped rather than truncated — it is the
only place the panel explains what CSS cannot express, so it has to be
readable rather than tidy. */
@@ -253,6 +377,34 @@ export const css = `
display: flex; flex-direction: column; min-width: 0; min-height: 0;
}
/* ---- A typed value at the end of a list --------------------------------- */
/* The escape hatch a menu of presets needs: the list can only offer what was
known when it was built, and a model shipped this morning is not on it.
Its own classes rather than the canvas's \`.fc-menu-custom\` trio, which is
the same idea one shape away — that row holds two 62px number fields for a
width and a height, and an identifier wants the whole width. Sharing them
would mean one of the two callers overriding most of what it inherited. */
.${PREFIX}-pop-custom {
display: flex; align-items: center; gap: 4px; padding: 4px 8px 6px;
}
.${PREFIX}-pop-custom-input {
flex: 1 1 auto; min-width: 0; padding: 3px 6px;
border-radius: var(--ap-radius-xs);
background: var(--ap-input-bg); color: var(--ap-text-primary);
border: 1px solid var(--ap-input-border);
font-family: var(--ap-font-mono); font-size: var(--ap-font-size-caption);
}
.${PREFIX}-pop-custom-input:focus {
outline: none; border-color: var(--ap-input-focus-border);
}
.${PREFIX}-pop-custom-go {
flex: 0 0 auto; padding: 3px 8px; border: 0; cursor: pointer;
border-radius: var(--ap-radius-xs);
background: var(--ap-primary); color: var(--ap-text-primary);
font-family: var(--ap-font-sans); font-size: var(--ap-font-size-caption);
}
/* ---- Colour picker ------------------------------------------------------ */
.${PREFIX}-pop-color { width: 232px; }
@@ -293,8 +445,21 @@ export const css = `
.${PREFIX}-pop-slider-fill {
position: absolute; inset: 0; border-radius: inherit; pointer-events: none;
}
/* The knob travels inside the track, not across it.
\`left\` used to be the raw percentage against a \`-7px\` margin, which put the
knob's centre on the track's end at both extremes — so half of a 14px dial
hung outside a 12px track, into the 8px of \`.pop-color-body\` padding, and
came to rest one pixel from the shell's border. At 0% and 100%, which is
where an alpha slider spends most of its life, it read as falling off.
Travelling the *box* from 0 to \`100% - 14px\` keeps both ends flush with the
track instead: the knob still marks the value it always did, because the
track's own ends are what moved under it. The 14px is stated twice here and
has to stay in step with \`width\`; there is no third place it appears.
\`--knob\` is a 0-1 number written by \`color-picker.ts\`. */
.${PREFIX}-pop-slider-knob {
position: absolute; top: 50%; width: 14px; height: 14px; margin: -7px 0 0 -7px;
position: absolute; top: 50%; width: 14px; height: 14px; margin: -7px 0 0 0;
left: calc((100% - 14px) * var(--${PREFIX}-knob, 0));
background: #fff; border-radius: var(--ap-radius-full);
box-shadow: 0 0 0 1px rgba(0,0,0,.35); pointer-events: none;
}
+12 -9
View File
@@ -24,8 +24,11 @@
* the other mode. These three are what a click means *while editing*; the Hand
* is what a drag means while the page is **live**, which is precisely when the
* space-drag modifier stops working — the frames are real iframes in view
* mode, and once the pointer takes focus into one, no keydown reaches the
* shell. Joining this group would have meant inventing a "no tool" member for
* mode, and once the pointer takes focus into one, a keydown reaches the shell
* only for the handful of commands the catalog marks `inFrame`. Space-to-pan
* is not one: it is a raw listener rather than a binding, and routing it would
* mean swallowing a bare Space typed into somebody's own form.
* Joining this group would have meant inventing a "no tool" member for
* a radio that has never needed one. It also stops at the frame boundary: a
* press the iframe consumes never reaches the canvas, so the Hand moves the
* surface without ever reaching into the app on it.
@@ -47,19 +50,20 @@
* furniture: `enabled` gates their shortcuts so pressing V or I over a live app
* in view mode does nothing, matching a bar that no longer shows them.
*/
import { keys } from "./keys";
import type { CommandId } from "./keys/catalog";
import { keys } from "./keys/registry";
export type Tool = "inspect" | "move";
export interface ToolBinding {
key: string;
label: string;
/** The command this tool is. Its chord and its name come from the catalog. */
id: CommandId;
tool: Tool;
}
export const TOOLS: ToolBinding[] = [
{ key: "v", label: "Move", tool: "move" },
{ key: "i", label: "Inspect", tool: "inspect" },
{ id: "tool.move", tool: "move" },
{ id: "tool.inspect", tool: "inspect" },
];
type Listener = (tool: Tool) => void;
@@ -81,8 +85,7 @@ export class ToolController {
this.unbind.push(
keys.bindAll(
TOOLS.map((t) => ({
keys: t.key,
label: t.label,
id: t.id,
run: () => this.set(t.tool),
when: () => this.enabled(),
}))