diff --git a/packages/overlay/src/app.ts b/packages/overlay/src/app.ts index e52a6d9..d441c4c 100644 --- a/packages/overlay/src/app.ts +++ b/packages/overlay/src/app.ts @@ -10,6 +10,7 @@ import { type ImageInput, type JobDiffBundle, type JobHistorySummary, + type JobSnapshot, modeToSurface, type ServerEvent, } from "@airship/protocol"; @@ -198,6 +199,16 @@ export interface Stage { * ignores the slot and it collapses to nothing. */ mount: (tools: HTMLElement) => void; + /** + * The left dock's **view-mode** body — on the canvas, the list of frames. + * + * A third slot rather than a second stage-owned dock, for the same reason the + * two bar slots are slots: the app owns where panels go and how wide they + * are, and the stage owns what is in them. A stage with nothing to list omits + * this and the app never builds the alternate body, so the inline overlay's + * dock is exactly what it was. + */ + mountFramesPanel?: (host: HTMLElement) => void; /** * A second bar slot, for controls that act on the stage's *selected object* * rather than on the stage itself. @@ -216,6 +227,16 @@ export interface Stage { * never fills this and its bar is unchanged. */ mountFrameTools?: (host: HTMLElement) => void; + /** + * The bottom-right corner, for a stage that has somewhere to *be* — on the + * canvas, the minimap. + * + * Gated by mode in `syncMinimap`, the way `mountFrameTools`' host is gated in + * `syncBar`, and by its own visible flag from inside. One element per owner, + * so neither can clobber the `hidden` the other wrote. Inline is the page + * itself and has no world to map, so it omits this. + */ + mountMinimap?: (host: HTMLElement) => void; /** * A pan/zoom gesture settled. The pointer has not moved but the canvas under * it has, so the app re-resolves what is being hovered — without this the @@ -334,12 +355,19 @@ export class AirshipApp { private chipsEl!: HTMLElement; private histEl!: HTMLElement; private sendBtn!: HTMLButtonElement; + private newChatBtn!: HTMLElement; + /** The bar's Apply/Discard pair; hidden while nothing is pending. */ + private applyGroup!: HTMLElement; + private applyBtn!: HTMLButtonElement; + private discardBtn!: HTMLButtonElement; // Right (design) dock private rightDock!: HTMLElement; private rightPill!: HTMLElement; private leftOpen = false; + /** High-water mark for `pendingCount()`; the composer reveals on an increase. */ + private pendingSeen = 0; private rightOpen = false; /** Live dock widths, persisted across reloads and reset from the splitters. */ @@ -394,6 +422,28 @@ export class AirshipApp { private viewOnlyBar: HTMLElement[] = []; /** The stage's slot in `viewOnlyBar` — see `Stage.mountFrameTools`. */ private frameToolsHost: HTMLElement | null = null; + /** View mode's one word about a running job — see `buildJobChip`. */ + private jobChip: HTMLElement | null = null; + /** + * The left dock's two heads and two bodies, swapped by mode. + * + * One dock element with two contents, rather than two docks. The splitter, + * the drag handle, the pill and the four `--__airship-left-*` placement + * properties are all keyed on the *side*, so a second element on the same + * side would mean two dnd entities racing for one id and two pills fighting + * over one corner — while the thing actually being asked for is that the + * panel keep its width and position and change what is inside it. + * + * The frames pair is null on a stage that has no frames to list. + */ + private chatHead!: HTMLElement; + private chatBody!: HTMLElement; + private framesHead: HTMLElement | null = null; + private framesBody!: HTMLElement; + /** The collapsed pill's label — it names whichever body the mode is showing. */ + private leftBrand!: HTMLElement; + /** The bottom-right slot — see `Stage.mountMinimap`. */ + private minimapHost: HTMLElement | null = null; /** * The Hand tool's latch. * @@ -742,6 +792,14 @@ export class AirshipApp { if (this.frameToolsHost) { this.stage.mountFrameTools?.(this.frameToolsHost); } + if (this.stage.mountMinimap) { + // Built only when there is something to put in it, the same way the frame + // tools host is — an empty fixed-position box in the corner is invisible + // but is still a node the pointer has to be reasoned about against. + this.minimapHost = el("div", { class: cls("minimap-host") }); + this.root.append(this.minimapHost); + this.stage.mountMinimap(this.minimapHost); + } this.stage.mount(this.barTools); // Inline fills nothing in, and the bar collapses to just the mode toggle. this.bar.classList.toggle( @@ -815,7 +873,7 @@ export class AirshipApp { private buildSplitter(side: Side): HTMLElement { const handle = el("div", { class: `${cls("splitter")} ${cls(`splitter-${side}`)}`, - "data-tip": "Drag to resize · double-click to reset", + "data-tip": "Drag to resize, double-click to reset", onDblclick: () => this.resetWidth(side), }); this.dockScope.add( @@ -1059,13 +1117,16 @@ export class AirshipApp { // The gutter is the breathing room between a dock's inner edge and the // nearest frame a fit is allowed to place there. const gutter = 8; - const covers = (side: Side, open: boolean): number => - open && this.placement[side].mode === "docked" + // `isVisible`, not the raw open flag: in view mode the inspector is gated + // away, and reserving 360px for a panel that is not on screen would leave + // every fit and every centring quietly off-centre to the left. + const covers = (side: Side): number => + this.isVisible(side) && this.placement[side].mode === "docked" ? clampWidth(this.width[side]) + gutter : 0; this.stage.setSafeInset?.({ - left: covers("left", this.leftOpen), - right: covers("right", this.rightOpen), + left: covers("left"), + right: covers("right"), }); this.stage.relayout?.(); } @@ -1341,6 +1402,13 @@ export class AirshipApp { sep(), inspectGroup, sep(), + // Lands immediately before the surface toggle on purpose: that toggle is + // blocked by exactly this pending state, so the remedy sits beside the + // control it unblocks. Two nested `display: contents` wrappers, one per + // owner — the outer is mode-hidden by `syncBar`, the inner is + // pending-hidden by `syncApplyGroup` — so neither can clobber the + // `hidden` the other wrote (same pattern as the frame-tools slot). + el("div", { class: cls("bar-apply-host") }, [this.buildApplyGroup()]), ]; // Same bargain as `editOnlyBar`, in the opposite direction — and empty // rather than disabled when the stage has no pan surface, so the inline @@ -1360,6 +1428,7 @@ export class AirshipApp { ? [ this.buildHandGroup(), ...(this.frameToolsHost ? [this.frameToolsHost] : []), + this.buildJobChip(), sep(), ] : []; @@ -1384,6 +1453,78 @@ export class AirshipApp { this.syncBar(); } + /** + * Apply and Discard, as bar buttons — the save affordance the reporter went + * looking for. Apply is a second entry point onto `submit()`, not a new + * mechanism: `buildEditRequest` already accepts an empty prompt when visual + * deltas exist, and `turnLabel` already synthesizes "Applied 3 style + * changes". Discard is the same unjournalled bulk clear the composer offers, + * so it goes through the same confirm. + */ + private buildApplyGroup(): HTMLElement { + this.applyBtn = el( + "button", + { + "aria-label": "Apply pending changes", + class: cls("tool"), + "data-tip": "Apply", + onClick: () => this.submit(), + type: "button", + }, + [icon("check", "sm")] + ) as HTMLButtonElement; + this.discardBtn = el( + "button", + { + "aria-label": "Discard pending changes", + class: cls("tool"), + "data-tip": "Discard", + onClick: () => + this.confirmPending( + this.discardBtn, + (n) => `Discard all ${n} pending change${n === 1 ? "" : "s"}`, + () => this.panel.discard(), + "above" + ), + type: "button", + }, + [icon("close", "sm")] + ) as HTMLButtonElement; + this.applyGroup = el( + "div", + { class: `${cls("bar-apply-group")} ${cls("hidden")}` }, + [ + el("div", { class: cls("tool-group") }, [ + this.applyBtn, + this.discardBtn, + ]), + el("div", { class: cls("bar-sep") }), + ] + ); + return this.applyGroup; + } + + /** + * Show the pair only while something is pending, keep the tooltips counting, + * and disable Apply during a live job — `submit()` silently no-ops on + * `awaiting`, and a control that eats clicks without a word is the exact + * shape of complaint this group exists to answer. + */ + private syncApplyGroup(): void { + if (!this.applyGroup) { + return; + } + const pending = this.pendingCount(); + this.applyGroup.classList.toggle(cls("hidden"), pending === 0); + if (pending === 0) { + return; + } + const s = pending === 1 ? "" : "s"; + this.applyBtn.dataset.tip = `Apply ${pending} change${s}`; + this.discardBtn.dataset.tip = `Discard ${pending} pending change${s}`; + this.applyBtn.disabled = this.awaiting; + } + /** * Undo and redo, as buttons. * @@ -1469,6 +1610,88 @@ export class AirshipApp { * "Hand tool H" without either side knowing about the other. Same trick the * undo buttons use. */ + /** + * "Working" — the one thing view mode has to say about a job. + * + * Everything that reports a turn's progress lives inside the assistant bubble: + * the pulsing status dot, the timeline rows, the result. All of it is in the + * chat body, which view mode swaps out — so before this, sending a prompt and + * flipping to view meant the editor gave no sign that anything was happening + * at all, and a turn that carried no inspector deltas finished without a word + * anywhere (`reconcileVisual` and `keepVisual` are both gated on + * `applyingVisual`). + * + * A button, not a badge, because there is an obvious thing to want next: it + * puts you back where the transcript is. In `viewOnlyBar` rather than the + * always-on part of the bar, since in edit mode the transcript is already + * saying this — two live indicators for one job is one more than the fact + * deserves. + * + * The dot is the transcript's own (`.dot`, `@keyframes ap-pulse`), so the + * thing in the bar and the thing in the bubble are visibly the same state. + */ + private buildJobChip(): HTMLElement { + this.jobChip = el( + "button", + { + // The visible "Working" and the dot carry the state; the tip carries + // what pressing it does. Kept apart rather than joined with a dash, + // which is the whole point of the rule `tooltip.copy.test.ts` enforces. + "aria-label": "Working. Show the agent panel", + class: `${cls("bar-job")} ${cls("hidden")}`, + "data-tip": "Show the agent panel", + onClick: () => this.showTranscript(), + type: "button", + }, + [ + el("span", { class: cls("dot") }), + el("span", { class: cls("bar-job-label"), text: "Working" }), + ] + ); + /* + * Two elements, one per owner — the same bargain `bar-frame-tools` and + * `bar-apply-host` make, and for a reason this very nearly shipped without. + * + * Two things gate this chip and they belong to different code: the *mode*, + * which `syncBar` hides the whole `viewOnlyBar` by, and `awaiting`, which + * `syncJobChip` owns. Written to one element they clobber each other — and + * in the direction that matters: start a job in edit mode and + * `syncJobChip` would strip the `hidden` that `syncBar` had put there, + * putting the chip in a bar that is supposed to have swapped it out. + */ + return el("div", { class: cls("bar-job-host") }, [this.jobChip]); + } + + private syncJobChip(): void { + this.jobChip?.classList.toggle(cls("hidden"), !this.awaiting); + } + + /** + * Go to where the transcript is, from wherever you are. + * + * Three things can be hiding it and any of them can be true at once: view + * mode swapped the body out, the dock is collapsed to its pill, and the + * preview pane is over the top of it. The chip and the completion toast both + * land here so neither has to know which one it is fixing. + */ + private showTranscript(): void { + this.setEditing(true); + this.setPreview(false); + if (!this.leftOpen) { + this.setLeft(true); + } + this.repinTranscript(); + } + + /** Is the transcript actually on screen? Not the same as "in edit mode". */ + private transcriptVisible(): boolean { + return ( + this.editing && + this.leftOpen && + !(this.previewOpen || this.chatBody.classList.contains(cls("hidden"))) + ); + } + private buildHandGroup(): HTMLElement { this.handBtn = el( "button", @@ -1543,11 +1766,22 @@ export class AirshipApp { /** Edits that only exist in memory, and so would not survive a navigation. */ private hasPendingEdits(): boolean { - return !( - this.changeSet.isEmpty() && - this.moveSet.isEmpty() && - this.structureSet.isEmpty() && - this.attrSet.isEmpty() + return this.pendingCount() > 0; + } + + /** + * Every pending in-memory edit, as one number — the single spelling of "is + * anything pending". The composer reveal, the surface-toggle block and the + * bar's Apply/Discard group all read it. Structure edits are included on + * purpose: the old reveal predicate forgot them, so a delete rendered a chip + * and blocked the surface toggle without ever revealing the composer. + */ + private pendingCount(): number { + return ( + this.changeSet.count() + + this.moveSet.count() + + this.attrSet.count() + + this.structureSet.count() ); } @@ -1655,9 +1889,21 @@ export class AirshipApp { */ private syncSurfaceToggle(): void { const blocked = this.hasPendingEdits(); - const label = blocked - ? "Apply or discard your changes before switching surface" - : `Surface: ${this.activeSurface().label}`; + /* + * The remedy has to be one you can actually reach. + * + * Apply, Discard and the composer's per-change chips are all edit-mode + * furniture, so in view mode the old wording named three controls that were + * not on screen — and on the canvas the whole chat body is swapped out, so + * there was no route to any of them without first doing the thing the + * message did not mention. + */ + let label = `Surface: ${this.activeSurface().label}`; + if (blocked) { + label = this.editing + ? "Apply or discard your changes before switching surface" + : "Switch to Edit to apply or discard your changes"; + } this.surfaceBtn.disabled = blocked; this.surfaceBtn.setAttribute("data-tip", label); this.surfaceBtn.setAttribute("aria-label", label); @@ -1668,7 +1914,7 @@ export class AirshipApp { "button", { class: `${cls("seg")} ${cls("seg-on")}`, - "data-tip": "Edit mode — hover to auto-select, click to edit", + "data-tip": "Edit mode. Hover to select, click to edit", onClick: () => this.setEditing(true), type: "button", }, @@ -1678,7 +1924,7 @@ export class AirshipApp { "button", { class: cls("seg"), - "data-tip": "View mode — no auto-select, page fully interactive", + "data-tip": "View mode. The page stays interactive", onClick: () => this.setEditing(false), type: "button", }, @@ -1721,11 +1967,61 @@ export class AirshipApp { this.tools.reset(); this.clearSelectionScope(); } + // Both of the left dock's overlays come down, and for the same reason: they + // are drawn over the transcript's slot, so either one left standing would + // survive the swap and sit on top of the frame list — the drawer as a + // full-panel sheet of past chats (`inset: 0`), the preview as the prompt + // pane in the transcript's place. The preview is the one that bites on the + // way *back*, where it hides the turn that just finished. + this.closeHistory(); + this.setPreview(false); this.syncBar(); + this.syncDocks(); + this.syncMinimap(); + this.syncJobChip(); + // Its blocked message names a different remedy per mode, so the mode is now + // one of its inputs — `renderComposerChips` is no longer the only thing + // that can make it stale. + this.syncSurfaceToggle(); + // Republishes the safe inset — which has just changed, because the + // inspector is gated away in view mode — and re-anchors the chrome. + this.afterDockToggle(); this.panel.setEditing(on); this.controller.setEditing(on); - // On the canvas this is what makes the frames inert (edit) or live (view). + // On the canvas this is what makes the frames inert (edit) or live (view), + // and what catches the minimap and the frame list up on everything that + // moved while they were off screen. After `afterDockToggle`, so the inset + // they aim against is the one they will be looking at. this.stage.setEditing?.(on); + if (on) { + this.repinTranscript(); + } + } + + /** + * Put the transcript back at the bottom after it has been off screen. + * + * `.hidden` is `display: none`, and an element with no box reports zero for + * `scrollTop`, `scrollHeight` and `clientHeight` — so while the chat is + * swapped out, `atBottom()` computes `0 - 0 - 0 < 40` and answers *true* to + * everything, and the `scrollTop` writes `scrollTranscript` makes are + * discarded by the CSSOM. The box that comes back is a fresh one at offset 0. + * + * The upshot before this: stream a turn, flip to view mode and back, and the + * transcript was scrolled to the very top showing the oldest bubble — with a + * live turn still writing into the bottom of it. + * + * The frame of delay is load-bearing. `syncDocks` has un-hidden the subtree + * but layout has not run, so `scrollHeight` is still 0 this tick; scrolling + * now would write into the same void that lost the position in the first + * place. + */ + private repinTranscript(): void { + requestAnimationFrame(() => { + if (!this.chatBody.classList.contains(cls("hidden"))) { + this.scrollTranscript(); + } + }); } private buildLeftDock(): void { @@ -1803,7 +2099,7 @@ export class AirshipApp { ]), el("div", { class: cls("head-actions") }, [ this.buildAgentButton(), - this.iconButton("plus", "New chat", () => this.newChat()), + this.buildNewChatButton(), this.iconButton("history", "Past chats", () => this.toggleHistory()), this.iconButton("rotate-ccw", "Reset width", () => this.resetWidth("left") @@ -1831,33 +2127,96 @@ export class AirshipApp { const composer = el("div", { class: cls("composer") }, [field]); this.buildPreviewPane(); + /* + * The chat's four children, wrapped so the mode can hide them as a group. + * + * `display: contents` on the wrapper, not a real box: the dock is a flex + * column and these have to stay its own flex items — the transcript is what + * takes the remaining height, and a wrapper with a box of its own would take + * it instead and leave the composer floating. It also keeps the drawer's + * `inset: 0` resolving against the dock, which is what it is drawn over. + */ + this.chatBody = el("div", { class: cls("dock-body") }, [ + this.transcriptEl, + this.previewEl, + this.histEl, + composer, + ]); + this.chatHead = head; + this.framesHead = this.buildFramesHead(); + this.framesBody = el("div", { + class: `${cls("dock-body")} ${cls("hidden")}`, + }); this.leftDock = el( "div", { class: `${cls("dock")} ${cls("dock-left")} ${cls("hidden")}` }, [ - head, - this.transcriptEl, - this.previewEl, - this.histEl, - composer, + this.chatHead, + ...(this.framesHead ? [this.framesHead] : []), + this.chatBody, + this.framesBody, this.buildSplitter("left"), ] ); + this.leftBrand = el("span", { + class: cls("brand-name"), + text: "Airship", + }); this.leftPill = this.buildPill("left", "chat", [ - el("div", { class: cls("brand") }, [ - icon("logo", "sm"), - el("span", { class: cls("brand-name"), text: "Airship" }), - ]), + el("div", { class: cls("brand") }, [icon("logo", "sm"), this.leftBrand]), this.panelToggle("left", "chat", true), ]); this.heads.left = head; this.armDockDrag("left", head, "head"); + if (this.framesHead) { + // A distinct `part`, or the two would build dnd entities with the same + // id — `armDockDrag` keys on `${type}:${side}:${part}`. + this.armDockDrag("left", this.framesHead, "frames-head"); + } this.armDockDrag("left", this.leftPill, "pill"); this.root.append(this.leftDock, this.leftPill); + this.stage.mountFramesPanel?.(this.framesBody); this.clearTranscript(); this.renderComposerChips(); } + /** + * The left dock's view-mode header. + * + * Its own header rather than a retitled one, because the actions differ all + * the way down: no agent picker, no new chat, no past chats — none of which + * mean anything in a mode with no element selection to scope a prompt to. + * What it keeps is the pair every dock header has, reset-width and collapse, + * so the panel behaves like the panel it replaced. + * + * Null on a stage with no frames to list, and that absence is what leaves the + * inline overlay's dock exactly as it was. + */ + private buildFramesHead(): HTMLElement | null { + if (!this.stage.mountFramesPanel) { + return null; + } + return el( + "div", + { + class: `${cls("head")} ${cls("hidden")}`, + ...dockHeadAttrs("Frames panel"), + }, + [ + el("div", { class: cls("brand") }, [ + icon("layer-frame", "sm"), + el("span", { class: cls("brand-name"), text: "Frames" }), + ]), + el("div", { class: cls("head-actions") }, [ + this.iconButton("rotate-ccw", "Reset width", () => + this.resetWidth("left") + ), + this.panelToggle("left", "frames", false), + ]), + ] + ); + } + /** * Size the composer to its content: one line at rest, growing until it would * eat the transcript, then scrolling. @@ -1866,12 +2225,14 @@ export class AirshipApp { * the content height *of the current box*, so measuring without the reset * only ever ratchets upwards and the field can never shrink again. * - * Bails while the dock is hidden, where every layout metric reads 0 and the - * field would collapse to nothing; `afterDockToggle` re-runs it on the way - * back open. + * Bails while the composer is not on screen, where every layout metric reads + * 0 and the field would collapse to nothing; `afterDockToggle` re-runs it on + * the way back. That is two cases now, not one: the dock can be collapsed to + * its pill, and — since the left dock started carrying the frame list in view + * mode — the dock can be open with the chat swapped out from under it. */ private autoGrow(): void { - if (!this.leftOpen) { + if (!this.leftOpen || this.chatBody.classList.contains(cls("hidden"))) { return; } const max = Math.max(96, Math.round(this.leftDock.clientHeight * 0.4)); @@ -1921,6 +2282,51 @@ export class AirshipApp { return e.scrollHeight - e.scrollTop - e.clientHeight < 40; } + /** + * New chat, behind the confirm. Held as a field because the confirm menu + * anchors on it — and because `newChat` destroys pending edits, comments, + * the draft and the transcript, and doing that silently was how the + * complaint arrived. + */ + private buildNewChatButton(): HTMLElement { + this.newChatBtn = this.iconButton("plus", "New chat", () => + this.confirmPending( + this.newChatBtn, + (n) => + `Discard ${n} pending change${n === 1 ? "" : "s"} and start a new chat`, + () => this.newChat() + ) + ); + return this.newChatBtn; + } + + /** + * Run a destructive action, asking first when there is something to lose. + * + * `panel.discard()` clears four delta sets *and* the journal, so unlike + * everything else in the editor there is no ⌘Z behind it — and the toast + * doctrine reserves an actionable toast for acts the journal can honestly + * reverse, which this is not. The two-step menu is the same shape the + * push-and-open-PR flow uses: it says exactly what will happen and takes a + * second deliberate click. With nothing pending it stays out of the way. + */ + private confirmPending( + anchor: HTMLElement, + verb: (pending: number) => string, + run: () => void, + prefer: "above" | "below" = "below" + ): void { + const pending = this.pendingCount(); + if (pending === 0) { + run(); + return; + } + createMenu([ + { header: "This cannot be undone" }, + { icon: "close", label: verb(pending), run }, + ]).open(anchor, prefer); + } + private newChat(): void { this.parentJobId = null; this.activeThreadRoot = null; @@ -2039,18 +2445,64 @@ export class AirshipApp { private setLeft(open: boolean): void { this.leftOpen = open; - this.leftDock.classList.toggle(cls("hidden"), !open); - this.leftPill.classList.toggle(cls("hidden"), open); + this.syncDocks(); this.afterDockToggle(); } private setRight(open: boolean): void { this.rightOpen = open; - this.rightDock.classList.toggle(cls("hidden"), !open); - this.rightPill.classList.toggle(cls("hidden"), open); + this.syncDocks(); this.afterDockToggle(); } + /** Does this side's panel have a home in the mode we are in? */ + private isVisible(side: Side): boolean { + return dockVisible({ + editing: this.editing, + modeScoped: Boolean(this.stage.mountFramesPanel), + open: this.isOpen(side), + side, + }); + } + + /** + * Publish which panels exist, and which body the left one is showing. + * + * The open flags are the *user's* state and are never written here — the mode + * is a second term laid over them, so a round trip through view mode returns + * the inspector exactly as it was found, open or collapsed. Writing + * `rightOpen = false` on the way in would have been a line shorter and would + * have quietly thrown that away. + * + * A collapsed panel's pill goes with it. The pill means "there is a panel + * here, folded up"; in view mode there is no inspector to unfold, so a pill + * offering to show one would be a control that lies. + */ + private syncDocks(): void { + const leftOn = this.isVisible("left"); + const rightOn = this.isVisible("right"); + const modeScoped = Boolean(this.stage.mountFramesPanel); + const frames = modeScoped && !this.editing; + this.leftDock.classList.toggle(cls("hidden"), !leftOn); + this.leftPill.classList.toggle(cls("hidden"), leftOn); + this.rightDock.classList.toggle(cls("hidden"), !rightOn); + this.rightPill.classList.toggle( + cls("hidden"), + rightOn || (modeScoped && !this.editing) + ); + this.chatHead.classList.toggle(cls("hidden"), frames); + this.chatBody.classList.toggle(cls("hidden"), frames); + this.framesHead?.classList.toggle(cls("hidden"), !frames); + this.framesBody.classList.toggle(cls("hidden"), !frames); + this.leftBrand.textContent = frames ? "Frames" : "Airship"; + this.leftPill.dataset.tip = frames ? "Show frames" : "Show chat"; + } + + /** The bottom-right slot exists only in the mode the minimap belongs to. */ + private syncMinimap(): void { + this.minimapHost?.classList.toggle(cls("hidden"), this.editing); + } + /** * Docks float over the canvas in both stages — nothing under them moves when * one opens. What the canvas is told is how much of itself is now covered, so @@ -2263,16 +2715,20 @@ export class AirshipApp { /** The inspector recorded or discarded a tweak. Surface it in the left * composer and — so direct-manipulation edits visibly "land in the chat" — - * open the left dock whenever changes are pending. */ + * open the left dock when a *new* edit arrives. */ private onVisualChanged(): void { this.renderComposerChips(); - // Reveal the composer the first time a tweak lands (guarded so continuous - // scrub/resize ticks don't re-inset the canvas once it's already open). - const pending = - this.changeSet.count() + this.moveSet.count() + this.attrSet.count() > 0; - if (pending && !this.leftOpen) { + // Reveal on an increase only, never on "non-zero": this fires on every + // panel change including deselect, undo and refresh, and re-opening a dock + // the user deliberately closed on a plain empty-canvas click was a bug. + const pending = this.pendingCount(); + if (pending > this.pendingSeen && !this.leftOpen) { this.setLeft(true); } + // Stored unconditionally — inside the `if`, the watermark would latch high + // after a discard and the reveal would be dead for the rest of the session. + this.pendingSeen = pending; + this.syncApplyGroup(); } /** The composer's context chips: the selected element (scopes the next edit) @@ -2300,8 +2756,13 @@ export class AirshipApp { ]) ); } - renderChangeChips(this.selChipsEl, this.pendingChips(), () => - this.panel.discard() + renderChangeChips(this.selChipsEl, this.pendingChips(), (anchor) => + this.confirmPending( + anchor, + (n) => `Discard all ${n} pending change${n === 1 ? "" : "s"}`, + () => this.panel.discard(), + "above" + ) ); // The single funnel every delta mutation already passes through — selection // set or cleared, a tweak recorded, a chip discarded, `reconcileVisual` @@ -2355,7 +2816,7 @@ export class AirshipApp { scope: c.scope, state: c.state, }), - tip: `${label}${suffix} — ${c.property}: ${c.from} → ${c.to}${ + tip: `${label}${suffix} · ${c.property}: ${c.from} → ${c.to}${ c.token ? ` (token ${c.token.name})` : "" }`, }); @@ -2372,7 +2833,7 @@ export class AirshipApp { icon: "drag", label: `${chipLabel(entry.element)} moved`, onRemove: () => this.panel.discardOneMove(entry.node), - tip: `${chipLabel(entry.element)} — repositioned in the tree`, + tip: `${chipLabel(entry.element)} · moved in the tree`, }); } for (const entry of this.structureSet.entries()) { @@ -2381,7 +2842,7 @@ export class AirshipApp { icon: entry.op === "delete" ? "minus" : "plus", label: `${chipLabel(entry.element)} ${verb}`, onRemove: () => this.panel.discardOneStructure(entry.node), - tip: `${chipLabel(entry.element)} — ${verb}`, + tip: `${chipLabel(entry.element)} · ${verb}`, }); } for (const entry of this.structureSet.textEntries()) { @@ -2390,7 +2851,7 @@ export class AirshipApp { icon: "layer-text", label: `${label} “${shortValue(entry.to)}”`, onRemove: () => this.panel.discardOneText(entry.node), - tip: `${label} — text: ${JSON.stringify(entry.from)} → ${JSON.stringify(entry.to)}`, + tip: `${label} · text: ${JSON.stringify(entry.from)} → ${JSON.stringify(entry.to)}`, }); } return chips; @@ -2406,7 +2867,7 @@ export class AirshipApp { icon: "insert", label: `${label} ${entry.attribute} ${shown}`, onRemove: () => this.panel.discardOneAttr(entry.node, entry.attribute), - tip: `${label} — ${entry.attribute}: ${entry.from ?? "(unset)"} → ${ + tip: `${label} · ${entry.attribute}: ${entry.from ?? "(unset)"} → ${ entry.to ?? "(unset)" }`, }); @@ -2514,6 +2975,24 @@ export class AirshipApp { if (this.awaiting) { return; } + /* + * Refuse rather than send into a closed socket. + * + * `AirshipSocket.send` drops silently when the socket is down, which is the + * right bargain for fire-and-forget traffic and the wrong one here: + * `beginJob` would latch `awaiting` for a job the daemon was never told to + * create, and nothing would ever clear it — Send and Apply disabled for the + * rest of the session, with a "Working" chip pulsing over a turn that does + * not exist. `isOpen` was added for exactly this distinction on the prompt + * preview; see its docstring. + * + * The socket reconnects on a 1.5s timer, so this refuses a keystroke the + * user can repeat rather than one they cannot take back. + */ + if (!this.socket.isOpen()) { + toast("Not connected. Try again in a moment.", { tone: "error" }); + return; + } // Before `buildRequest`, not after. An uncommitted edit is not yet in the // structure set, so the request would ship without the text *and* // `hasVisualDeltas` could answer false, skipping the reconcile that puts the @@ -2635,11 +3114,108 @@ export class AirshipApp { this.awaiting = true; this.activeJobId = null; this.sendBtn.disabled = true; + this.syncApplyGroup(); + this.syncJobChip(); const turn = assistantTurn(); this.activeTurn = turn; this.pushBubble(turn.root); } + /** + * Reconcile a latched `awaiting` against what the daemon actually has. + * + * `awaiting` is cleared in exactly one place — a `job:done` whose id matches + * `activeJobId` — so anything that eats that one broadcast strands the editor + * with Send and Apply disabled and no way back. The daemon sends it once; a + * socket that is down at that moment simply never hears it, and the 1.5s + * reconnect brings back a connection with nothing to say about the turn that + * ended while it was gone. + * + * `hello` is the answer because the server sends it on *every* connection + * carrying `jobs.snapshots()`, and `JobStore` never evicts — so a reconnect + * arrives holding the outcome of the job we stopped hearing about. + * + * Adopting the running job when we have no id of our own is sound rather than + * a guess: the server serialises edits on one chain, so at most one job is + * ever `running`, and having no id means our `job:created` was the thing we + * missed. + */ + private reconcileAwaiting(jobs: JobSnapshot[]): void { + if (!this.awaiting) { + return; + } + const verdict = reconcileJob(this.activeJobId, jobs); + if (verdict.kind === "running") { + // Still going, and we are back in time to hear it land. + this.activeJobId = verdict.jobId; + return; + } + this.releaseAwaiting(verdict.job); + } + + /** + * Let go of a turn whose ending we will never see. + * + * The bundle is what `finalizeAssistant` needs and the one thing a snapshot + * cannot carry, so the turn is closed rather than filled: the pulse comes + * off, the bubble takes the error treatment, and the text points at Past + * chats, which is where the daemon did persist the result. Saying that is + * better than either leaving it pulsing forever or quietly deleting it. + */ + private releaseAwaiting(job?: JobSnapshot): void { + this.awaiting = false; + this.activeJobId = null; + this.applyingVisual = false; + this.sendBtn.disabled = false; + this.syncApplyGroup(); + this.syncJobChip(); + + const turn = this.activeTurn; + this.activeTurn = null; + if (turn) { + turn.status.remove(); + (turn.result.parentElement ?? turn.result).classList.add(cls("msg-err")); + clear(turn.result); + turn.result.append( + el("div", { + class: cls("msg-body"), + text: job + ? `Lost the connection while this ran. It ${job.status}; open Past chats for the result.` + : "Lost the connection before this was sent. Nothing ran.", + }) + ); + } + // Pending visual deltas are deliberately left alone: the turn may well have + // landed, and discarding a user's unsaved changes on a socket blip would be + // a far worse trade than leaving them to re-apply. + toast("Connection dropped. The turn was released.", { tone: "error" }); + } + + /** + * Say a turn finished, when nothing on screen otherwise would. + * + * A finished turn reports itself by *becoming* the assistant bubble — which + * is the right design and says nothing at all if the transcript is not on + * screen. That is now three ordinary states, not an edge case: view mode, a + * dock collapsed to its pill, and the preview pane open over the top. + * + * Gated on visibility rather than on the mode, so all three are covered by + * one condition; and gated on that rather than firing always, because a toast + * duplicating a bubble the user is already looking at is noise. The action is + * the same door the bar chip opens — see `showTranscript`. + */ + private reportOffscreenTurn(bundle: JobDiffBundle): void { + if (this.transcriptVisible()) { + return; + } + const ok = bundle.status === "done"; + toast(ok ? "Change applied" : `Change ${bundle.status}`, { + action: { label: "Show", run: () => this.showTranscript() }, + icon: ok ? "check" : "attention", + tone: ok ? "neutral" : "error", + }); + } + // -- Socket events --------------------------------------------------------- private onEvent(ev: ServerEvent): void { @@ -2648,6 +3224,9 @@ export class AirshipApp { // The daemon's `--agent` is the resting default; the picker only ever // departs from it deliberately. this.setAgent(ev.defaultAgent); + // The snapshot is the only thing that can tell us a turn ended while we + // were not listening — see `reconcileAwaiting`. + this.reconcileAwaiting(ev.jobs); // A reconnect drops whatever request was in flight. Reset the key // first, or the dedupe decides nothing changed and the pane never // repaints. @@ -2767,6 +3346,9 @@ export class AirshipApp { private onDone(bundle: JobDiffBundle): void { this.awaiting = false; this.sendBtn.disabled = false; + this.syncApplyGroup(); + this.syncJobChip(); + this.reportOffscreenTurn(bundle); this.parentJobId = bundle.jobId; if (!this.activeThreadRoot) { this.activeThreadRoot = bundle.jobId; @@ -2815,7 +3397,7 @@ export class AirshipApp { } const what = status === "cancelled" ? "Cancelled" : "Edit failed"; toast( - `${what} — your ${pending === 1 ? "change is" : "changes are"} still pending`, + `${what}. Your ${pending === 1 ? "change is" : "changes are"} still pending`, { icon: "rotate-ccw", } @@ -2881,7 +3463,7 @@ export class AirshipApp { this.clearSelectionScope(); this.stage.afterApply?.(); if (bundle.status === "done") { - toast("Applied — reload if it doesn't update", { icon: "check" }); + toast("Applied. Reload if it doesn't update", { icon: "check" }); } } @@ -2897,7 +3479,7 @@ export class AirshipApp { this.parentJobId = jobId; this.forkNext = true; this.setLeft(true); - toast("Branching — type a new instruction", { icon: "version-branch" }); + toast("Branching. Type a new instruction", { icon: "version-branch" }); this.input.focus(); } @@ -2940,7 +3522,7 @@ export class AirshipApp { }); this.setLeft(true); this.renderComposerChips(); - toast("Comment added — send to apply", { icon: "tool-comment" }); + toast("Comment added. Send to apply", { icon: "tool-comment" }); } ); } @@ -3077,7 +3659,7 @@ export class AirshipApp { } this.previewBodyEl.append( emptyState({ - body: "Select an element, tweak it in the inspector, or type an instruction — the prompt the agent receives appears here.", + body: "Select an element, tweak it in the inspector, or type an instruction. The prompt the agent receives appears here.", title: "Nothing to send yet", }) ); @@ -3188,10 +3770,67 @@ function clamp(v: number, lo: number, hi: number): number { * `closest("[data-tip]")`, so each button in the row keeps its own tip and only * the bare header shows this one. */ +/** + * What a reconnect's job snapshot says about the turn we think is in flight. + * + * Free and exported so the rule can be asserted directly. Standing up an + * `AirshipApp` to check three cases would mean a socket, a dnd-kit manager, a + * `DesignPanel` and a live document — and this is the part that has to be + * right: answering "running" for a job that ended leaves the editor latched, + * and answering "release" for one that is still going throws away a live turn's + * transcript while the agent is still writing to it. + */ +export type AwaitingVerdict = + | { jobId: string; kind: "running" } + | { job?: JobSnapshot; kind: "release" }; + +export function reconcileJob( + activeJobId: string | null, + jobs: JobSnapshot[] +): AwaitingVerdict { + // With no id of our own, `job:created` is precisely what we missed — and the + // server runs edits on one chain, so at most one job is ever `running`. + const mine = activeJobId + ? jobs.find((job) => job.jobId === activeJobId) + : jobs.find((job) => job.status === "running"); + return mine?.status === "running" + ? { jobId: mine.jobId, kind: "running" } + : { job: mine, kind: "release" }; +} + +/** + * Is a dock on screen, given what the user asked for and which mode we are in? + * + * Free and exported so the rule can be asserted without standing up an + * `AirshipApp` — which means a socket, a dnd-kit manager, a `DesignPanel` and a + * live document — to check three booleans. `AirshipApp.isVisible` is the only + * caller in the product. + * + * `modeScoped` is what keeps the inline overlay out of this. Edit and view mean + * different things on the two stages: on the canvas, view mode is *about* the + * frames and has a panel and a map of its own to put in their place, so giving + * up the two element-scoped panels is a trade. Inline has neither, so the same + * rule would just take the inspector away and put nothing there — the gate is + * therefore the stage's ability to fill the gap, which is exactly what + * `Stage.mountFramesPanel` reports. + */ +export function dockVisible(opts: { + editing: boolean; + modeScoped: boolean; + open: boolean; + side: Side; +}): boolean { + if (!(opts.open && opts.modeScoped)) { + return opts.open; + } + // The left dock stays: it is the one that has something else to show. + return opts.side === "left" || opts.editing; +} + function dockHeadAttrs(name: string): Record { return { "aria-label": name, - "data-tip": "Drag to move · double-click to dock", + "data-tip": "Drag to move, double-click to dock", }; } @@ -3287,5 +3926,5 @@ function applyLabel( attrCount = 0 ): string { const base = `Applied ${changeSummary(styleCount, moveCount, structureCount, attrCount)}`; - return note ? `${base} — ${note}` : base; + return note ? `${base}. ${note}` : base; } diff --git a/packages/overlay/src/awaiting.test.ts b/packages/overlay/src/awaiting.test.ts new file mode 100644 index 0000000..f75768c --- /dev/null +++ b/packages/overlay/src/awaiting.test.ts @@ -0,0 +1,83 @@ +/** + * What a reconnect makes of a turn we think is still running. + * + * `awaiting` is cleared in exactly one place — a `job:done` whose id matches the + * one we latched — so anything that eats that single broadcast strands the + * editor with Send and Apply disabled and no way back. Two ordinary things do: + * + * - **The socket was down when Send was pressed.** `AirshipSocket.send` drops + * silently on a closed socket, so `beginJob` latched `awaiting` for a job the + * daemon was never asked to create. `submit` now refuses up front, but a + * session that latched before the refusal existed still has to be able to get + * out. + * - **The socket was down when the job landed.** The daemon broadcasts + * `job:done` once; the 1.5s reconnect comes back with no memory of it. + * + * `hello` carries `jobs.snapshots()` on every connection and `JobStore` never + * evicts, so the reconnect is holding the answer. The risk runs both ways, + * which is why this is tested rather than eyeballed: answering "running" for a + * job that ended re-latches the editor, and answering "release" for one that is + * genuinely still going tears down a live turn's transcript while the agent is + * still writing into it. + */ + +import { describe, expect, it } from "vitest"; +import { reconcileJob } from "./app"; + +const job = ( + jobId: string, + status: "running" | "done" | "failed" | "cancelled" +) => ({ createdAt: 0, jobId, status }); + +describe("reconcileJob", () => { + it("keeps waiting when our job is still running", () => { + const verdict = reconcileJob("a", [job("a", "running")]); + expect(verdict).toEqual({ jobId: "a", kind: "running" }); + }); + + it("releases when our job finished while we were away", () => { + for (const status of ["done", "failed", "cancelled"] as const) { + const verdict = reconcileJob("a", [job("a", status)]); + expect(verdict.kind).toBe("release"); + expect(verdict.kind === "release" && verdict.job?.status).toBe(status); + } + }); + + it("releases when the daemon has never heard of our job", () => { + // The Send-into-a-closed-socket case: `beginJob` latched, the edit was + // dropped, and nothing was ever created. + const verdict = reconcileJob("a", []); + expect(verdict).toEqual({ job: undefined, kind: "release" }); + }); + + it("adopts the running job when we never learned an id", () => { + // `job:created` was the message we missed. Edits run on one chain, so the + // single running job is necessarily ours. + const verdict = reconcileJob(null, [ + job("old", "done"), + job("live", "running"), + ]); + expect(verdict).toEqual({ jobId: "live", kind: "running" }); + }); + + it("releases when there is no id and nothing is running", () => { + const verdict = reconcileJob(null, [job("old", "done")]); + expect(verdict.kind).toBe("release"); + }); + + it("does not adopt someone else's finished job as ours", () => { + // Matching by id first is what keeps a stale snapshot from being read as + // our turn's outcome. + const verdict = reconcileJob("mine", [job("theirs", "done")]); + expect(verdict).toEqual({ job: undefined, kind: "release" }); + }); + + it("ignores a finished job that shares the store with ours", () => { + const verdict = reconcileJob("mine", [ + job("older", "done"), + job("mine", "running"), + job("oldest", "failed"), + ]); + expect(verdict).toEqual({ jobId: "mine", kind: "running" }); + }); +}); diff --git a/packages/overlay/src/bar-job.test.ts b/packages/overlay/src/bar-job.test.ts new file mode 100644 index 0000000..cba6d23 --- /dev/null +++ b/packages/overlay/src/bar-job.test.ts @@ -0,0 +1,38 @@ +/** + * The job chip's two gates. + * + * The chip is hidden by two different owners — the *mode* (`syncBar`, over the + * whole `viewOnlyBar`) and `awaiting` (`syncJobChip`) — and written to one + * element they clobber each other. The direction that matters is the one that + * nearly shipped: starting a job in edit mode would have stripped the `hidden` + * that the mode had just written, putting a view-mode control into the edit + * bar. + * + * Asserted structurally rather than through `AirshipApp`, which would want a + * socket, a dnd-kit manager and a `DesignPanel` to check where a class lands. + * The invariant is "one element per owner", and that is a shape. + */ + +import { describe, expect, it } from "vitest"; +import { PREFIX } from "./dom"; +import { overlayCss } from "./styles/index"; + +/** Top-level, so it is not recompiled on every assertion. */ +const CONTENTS = /display:\s*contents/; + +describe("bar hosts", () => { + it("gives every double-gated bar control a host of its own", () => { + // `display: contents` is what lets the wrapper exist without earning a flex + // gap of its own — and `.hidden`'s `display: none !important` still beats + // it, which is the whole mechanism. + const css = overlayCss(); + for (const host of ["bar-frame-tools", "bar-apply-host", "bar-job-host"]) { + expect(css).toContain(`.${PREFIX}-${host}`); + } + const rule = css + .split("\n") + .find((line) => line.includes(`${PREFIX}-bar-job-host`)); + expect(rule).toBeDefined(); + expect(css.slice(css.indexOf(`${PREFIX}-bar-job-host`))).toMatch(CONTENTS); + }); +}); diff --git a/packages/overlay/src/canvas/frames-panel.stories.ts b/packages/overlay/src/canvas/frames-panel.stories.ts new file mode 100644 index 0000000..605133f --- /dev/null +++ b/packages/overlay/src/canvas/frames-panel.stories.ts @@ -0,0 +1,150 @@ +import type { Meta, StoryObj } from "@storybook/html-vite"; +import { el } from "../dom"; +import { dock, plainStage } from "../stories/chrome"; +import { onStoryTeardown } from "../stories/lifecycle"; +import { FrameManager, MAX_FRAMES } from "./frames"; +import { FramesPanel } from "./frames-panel"; +import { CanvasViewport } from "./viewport"; + +/* + * The frame list — the left dock's view-mode body. + * + * Rendered inside a real `dock` at a real width, because the whole design of + * the row is about width: it is a three-column grid, and the only interesting + * question is what happens to a long device name when the size readout beside + * it will not shrink. A story at 1200px is a picture of a panel that does not + * exist. `Narrow` is the same list at `MIN_DOCK_W`, which is as small as the + * splitter will let a user make it. + * + * The `FrameManager` here is real and so are its frames — they are real + * same-origin iframes, appended to a world element that is never put on screen. + * `mount()` is never called, so no `src` is ever set and nothing loads; this + * file only ever asks the manager about names, sizes and order, which is all + * the panel reads. `viewport` is real too and is genuinely driven: clicking a + * row centres it, and with no canvas on screen that is invisible but harmless, + * which is why the caption points at the rename and the menu instead. + * + * Every key is prefixed `__airship-story:` and nothing calls `restore()` or + * `save()`, so the catalogue leaves no state behind. + */ + +const meta: Meta = { + title: "Canvas/Frames panel", +}; + +export default meta; + +interface Rig { + frames: FrameManager; + panel: FramesPanel; +} + +function rig(): Rig { + const world = el("div"); + const viewport = new CanvasViewport({ + getContentRects: () => frames.worldRects(), + getSelectionRect: () => null, + onChange: () => undefined, + storageKey: "__airship-story:viewport", + }); + const frames: FrameManager = new FrameManager({ + onChanged: () => panel.render(), + pathname: "/", + storageKey: "__airship-story:frames", + world, + }); + // No `addFrame` shim any more, which is the point: the `+` used to delegate to + // the bottom bar's menu, so this rig substituted a straight `add` and the + // story never showed what the button actually did. It owns its own device + // menu now, anchored to itself — press `+` here and you get the real one. + const panel = new FramesPanel({ frames, viewport }); + + onStoryTeardown(() => { + panel.destroy(); + frames.destroy(); + viewport.destroy(); + }); + + return { frames, panel }; +} + +/** A board worth looking at: two devices, a duplicate, and a custom size. */ +function fill(frames: FrameManager): void { + frames.add({ presetId: "desktop" }); + frames.add({ presetId: "iphone-16" }); + frames.add({ presetId: "ipad-pro-12-9" }); + frames.add({ height: 720, name: "Checkout kiosk", width: 1280 }); +} + +export const Default: StoryObj = { + render: () => { + const { frames, panel } = rig(); + fill(frames); + frames.setActive("f2"); + return plainStage([dock(panel.element, { label: "Frames" })], { + try: "Double-click a name to rename it. The ⋯ menu carries the device list, rotate, reload, duplicate and delete — and delete offers itself back.", + what: "The list in its ordinary state, with one frame selected. Rows are paint order, so dragging the grip restacks overlapping frames.", + }); + }, +}; + +/** + * The empty state, which is also the first thing a new project sees before + * `CanvasStage.mount` adds its two starting frames. + */ +export const Empty: StoryObj = { + render: () => { + const { panel } = rig(); + return plainStage([dock(panel.element, { label: "Frames" })], { + what: "No frames. The count still reads, which is the one place the cap of eight is stated before you hit it.", + }); + }, +}; + +/** + * At the cap. + * + * The add button goes disabled here rather than letting you press it and taking + * a toast for an answer — the refusal is spoken only where there is no control + * to disable, which is the row menu's Duplicate. + */ +export const AtTheCap: StoryObj = { + render: () => { + const { frames, panel } = rig(); + for (let i = 0; i < MAX_FRAMES; i += 1) { + frames.add({ presetId: i % 2 ? "iphone-16" : "desktop" }); + } + return plainStage([dock(panel.element, { label: "Frames" })], { + what: `All ${MAX_FRAMES} frames. The + is disabled and says why; the list scrolls inside the dock rather than growing it.`, + }); + }, +}; + +/** + * Long names at the narrowest the panel can be. + * + * The row is a grid with `minmax(0, 1fr)` on the name, so the name is the + * column that gives — the size readout is the one thing on the row that must + * never be ambiguous, and a truncated `1440 × 10…` is worse than no readout. + */ +export const Narrow: StoryObj = { + render: () => { + const { frames, panel } = rig(); + frames.add({ + name: "Marketing site — pricing page, wide", + presetId: "desktop", + }); + frames.add({ presetId: "iphone-16-pro-max" }); + frames.add({ + height: 720, + name: "Checkout kiosk (landscape)", + width: 1280, + }); + return plainStage( + [dock(panel.element, { label: "Frames", narrow: true })], + { + what: "The same rows at MIN_DOCK_W with names that do not fit. The name truncates; the size never does.", + } + ); + }, +}; diff --git a/packages/overlay/src/canvas/frames-panel.test.ts b/packages/overlay/src/canvas/frames-panel.test.ts new file mode 100644 index 0000000..886daaa --- /dev/null +++ b/packages/overlay/src/canvas/frames-panel.test.ts @@ -0,0 +1,640 @@ +/** + * The frame list — its rows, its rename, and the one thing about it that is a + * trap. + * + * The trap is `delete`. `FrameManager.remove` is one call and looks like the + * whole job, and a panel that reached for it directly would ship a delete with + * no way back: the undo for a frame is not in the model, it rides on the toast + * that `frame-verbs.ts` raises (see that file's header). Nothing about the + * manager's API would have refused, and nothing afterwards would have said so — + * hence `routes delete through the shared verb`, which asserts on the toast + * rather than on the frame being gone, because the frame being gone is the part + * that was never in doubt. + * + * The rest is the render contract. `render` runs on every frame of a canvas pan + * (it is driven from `CanvasStage.notify`), so the tests that matter are the + * ones about what it does *not* do: rebuild rows that already exist, and + * overwrite a name the user is in the middle of typing. + * + * No geometry here. happy-dom does no layout, so the reorder drag — which + * resolves its target by hit-testing row rects — is covered at the model layer + * in `frames.test.ts` instead, where the invariant it exists to protect (no + * iframe is re-parented) actually lives. + */ + +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { cls } from "../dom"; +import { closeOpenPopover, mountPopoverHost } from "../popover-host"; +import { mountToastHost } from "../toast"; +import { FrameManager, MAX_FRAMES } from "./frames"; +import { dropStackIndex, FramesPanel } from "./frames-panel"; +import { CanvasViewport } from "./viewport"; + +let world: HTMLElement; +let frames: FrameManager; +let viewport: CanvasViewport; +let panel: FramesPanel; + +function rows(): HTMLElement[] { + return [...panel.element.querySelectorAll(`.${cls("fp-row")}`)]; +} + +function names(): string[] { + return rows().map( + (row) => row.querySelector(`.${cls("fp-name")}`)?.textContent ?? "?" + ); +} + +function labelOf(id: string): HTMLElement { + const node = panel.element.querySelector( + `[data-frame="${id}"] .${cls("fp-name")}` + ); + if (!node) { + throw new Error(`no row for ${id}`); + } + return node; +} + +function type(label: HTMLElement, text: string): void { + label.textContent = text; +} + +function key(label: HTMLElement, name: string): void { + label.dispatchEvent( + new KeyboardEvent("keydown", { bubbles: true, cancelable: true, key: name }) + ); +} + +/** The live toasts, by their text. */ +function toasts(): string[] { + return [...document.querySelectorAll(`.${cls("toast")}`)].map( + (node) => node.textContent ?? "" + ); +} + +beforeEach(() => { + document.body.replaceChildren(); + mountToastHost(document.body); + /* + * Re-mounted per test, not once. + * + * `popover-host` caches its mount in a module variable, so the + * `replaceChildren` above detaches the host while the host still believes it + * is mounted — and every menu opened afterwards is appended to a node that is + * not in the document, where nothing can find it. `mountPopoverHost` + * re-appends the cached node, so this is both idempotent and the repair. Same + * trap `popover-host.test.ts` and `token-field.test.ts` document. + */ + mountPopoverHost(document.body); + world = document.createElement("div"); + document.body.append(world); + viewport = new CanvasViewport({ + getContentRects: () => frames.worldRects(), + getSelectionRect: () => null, + onChange: () => undefined, + storageKey: "__airship-test:viewport", + }); + frames = new FrameManager({ + onChanged: () => panel?.render(), + pathname: "/", + storageKey: "__airship-test:frames", + world, + }); + panel = new FramesPanel({ frames, viewport }); + document.body.append(panel.element); + panel.render(); +}); + +afterEach(() => { + closeOpenPopover("programmatic"); + panel.destroy(); + frames.destroy(); + viewport.destroy(); + world.remove(); +}); + +describe("FramesPanel rows", () => { + it("lists the frames front-most first", () => { + // The reverse of `frames.all`, which is paint order: `applyOrder` writes the + // array index out as `z-index`, so the *last* frame is the one on top. A + // layers panel puts that one at the top of the list, and until it did the + // restack verbs pointed the wrong way. A frame added later is in front, so + // it lands above the ones already there. + frames.add({ name: "Desktop" }); + frames.add({ name: "iPhone" }); + + expect(names()).toEqual(["iPhone", "Desktop"]); + expect(rows().map((r) => r.dataset.frame)).toEqual(["f2", "f1"]); + }); + + it("follows a reorder", () => { + frames.add({ name: "one" }); + frames.add({ name: "two" }); + frames.add({ name: "three" }); + + // Stack index 0 is the back, so "three" goes to the *bottom* of the list. + frames.reorder("f3", 0); + + expect(names()).toEqual(["two", "one", "three"]); + }); + + it("shows the size and keeps it current", () => { + frames.add({ height: 900, name: "Kiosk", width: 1200 }); + const dims = (): string => + panel.element.querySelector(`.${cls("fp-dims")}`)?.textContent ?? ""; + expect(dims()).toBe("1200 × 900"); + + frames.resize("f1", 800, 600); + expect(dims()).toBe("800 × 600"); + }); + + it("marks the selected frame, and only that one", () => { + frames.add({ name: "one" }); + frames.add({ name: "two" }); + frames.setActive("f2"); + + const on = panel.element.querySelectorAll(`.${cls("fp-row-on")}`); + expect(on).toHaveLength(1); + expect((on[0] as HTMLElement).dataset.frame).toBe("f2"); + }); + + it("counts against the cap and stops offering to add past it", () => { + const count = (): string => + panel.element.querySelector(`.${cls("fp-count")}`)?.textContent ?? ""; + const add = panel.element.querySelector( + `.${cls("fp-add")}` + ); + expect(count()).toBe(`0 of ${MAX_FRAMES} frames`); + expect(add?.disabled).toBe(false); + + for (let i = 0; i < MAX_FRAMES; i += 1) { + frames.add({ name: `f${i}` }); + } + + expect(count()).toBe(`${MAX_FRAMES} of ${MAX_FRAMES} frames`); + expect(add?.disabled).toBe(true); + }); + + it("opens its own device menu against its own button", () => { + // Not the stage's. The `+` used to call `FrameChrome.openAddMenu`, which + // places its menu against the bottom bar — so a press in the left dock + // popped the device list open in the middle of the window. Picking the size + // up front rather than guessing one is still the rule; where the menu + // appears is what changed. + panel.element.querySelector(`.${cls("fp-add")}`)?.click(); + + const menu = document.querySelector(`.${cls("pop-menu")}`); + expect(menu).not.toBeNull(); + expect( + menu?.querySelectorAll(`.${cls("pop-group")}`).length + ).toBeGreaterThan(1); + // Opening the menu is not adding a frame; choosing a device is. + expect(frames.all).toHaveLength(0); + + menu?.querySelector(`.${cls("pop-item")}`)?.click(); + expect(frames.all).toHaveLength(1); + }); + + it("reuses rows when nothing about the set has changed", () => { + // `render` is driven from the stage's `notify`, which fires on every frame + // of a pan. Rebuilding there would destroy and recreate a dnd entity per + // row sixty times a second. + frames.add({ name: "one" }); + const [first] = rows(); + panel.render(); + panel.render(); + + expect(rows()[0]).toBe(first); + }); +}); + +describe("FramesPanel accessibility", () => { + it("names the drag handle instead of hiding it", () => { + // The bug: a drag handle looks like decoration, so it was `aria-hidden`. + // dnd-kit then stamps `tabindex="0"` and `role="button"` onto it as a + // handle — a focusable node inside a hidden subtree, which is axe's + // `aria-hidden-focus`, and a tab stop announcing nothing. + frames.add({ name: "Desktop" }); + const grip = panel.element.querySelector(`.${cls("fp-grip")}`); + + expect(grip?.hasAttribute("aria-hidden")).toBe(false); + expect(grip?.getAttribute("aria-label")).toBe("Reorder Desktop"); + }); + + it("declines the attributes dnd-kit would put on the row", () => { + /* + * The row is the drag handle now, so it is what the Accessibility plugin + * writes to — and every one of its writes is skipped when the attribute is + * already there. Two of the three would be wrong here: a second tab stop per + * row on top of the grip's, and a description telling a screen-reader user + * to press the space bar, which `POINTER_ONLY` guarantees does nothing. + */ + frames.add({ name: "Desktop" }); + const [row] = rows(); + + expect(row.getAttribute("tabindex")).toBe("-1"); + expect(row.getAttribute("role")).toBe("listitem"); + // Pointed at the grip, which is the control that actually restacks. + const describedBy = row.getAttribute("aria-describedby"); + expect(describedBy).toBeTruthy(); + expect(document.getElementById(describedBy ?? "")).toBe( + row.querySelector(`.${cls("fp-grip")}`) + ); + }); + + it("keeps every derived name current through a rename", () => { + frames.add({ name: "Desktop" }); + frames.rename("f1", "Marketing"); + + const row = panel.element.querySelector(`.${cls("fp-row")}`); + expect( + row?.querySelector(`.${cls("fp-grip")}`)?.getAttribute("aria-label") + ).toBe("Reorder Marketing"); + expect( + row?.querySelector(`.${cls("fp-more")}`)?.getAttribute("aria-label") + ).toBe("Options for Marketing"); + expect( + row?.querySelector(`.${cls("fp-pick")}`)?.getAttribute("aria-label") + ).toContain("Marketing"); + }); + + it("keeps the rows a real list", () => { + // dnd-kit stamps its role onto the *handle*, not the element — so the row + // stays a `listitem`. Asserted rather than assumed: if that ever moves to + // the element, `role="list"` would be left with non-listitem children. + frames.add({ name: "one" }); + frames.add({ name: "two" }); + + const list = panel.element.querySelector(`.${cls("fp-list")}`); + expect(list?.getAttribute("role")).toBe("list"); + expect(rows().map((n) => n.getAttribute("role"))).toEqual([ + "listitem", + "listitem", + ]); + // The drop line is a child of the list too — it has to be, or its offsets + // are measured against one box and drawn against another. It must not be + // announced as a row, and `dropIndexAt` must not count it as one. + const line = list?.querySelector(`.${cls("fp-drop")}`); + expect(line?.parentElement).toBe(list); + expect(line?.hasAttribute("role")).toBe(false); + }); + + it("does not count the drop line as a row", () => { + // The bug this guards: `dropIndexAt` used to walk `list.children`, so + // moving the line inside the list would have silently added a phantom row + // at the end and shifted every drop by one. + frames.add({ name: "one" }); + frames.add({ name: "two" }); + frames.add({ name: "three" }); + + expect(rows()).toHaveLength(3); + // happy-dom gives every rect zeroes, so every midpoint test is false and + // the answer is 0 — what matters is that it is bounded by the row count + // and not the child count. + const index = ( + panel as unknown as { dropIndexAt: (y: number) => number } + ).dropIndexAt(1e6); + expect(index).toBe(3); + }); +}); + +describe("FramesPanel keyboard restack", () => { + function arrow(id: string, name: string): void { + panel.element + .querySelector(`[data-frame="${id}"] .${cls("fp-grip")}`) + ?.dispatchEvent( + new KeyboardEvent("keydown", { + bubbles: true, + cancelable: true, + key: name, + }) + ); + } + + it("moves a row with the arrow keys", () => { + frames.add({ name: "one" }); + frames.add({ name: "two" }); + frames.add({ name: "three" }); + // Front-first, so the newest is on top: three, two, one. + + arrow("f1", "ArrowUp"); + expect(names()).toEqual(["three", "one", "two"]); + + arrow("f1", "ArrowDown"); + expect(names()).toEqual(["three", "two", "one"]); + }); + + it("moves the frame forward when the row moves up", () => { + /* + * The direction, asserted where it actually lives. + * + * Every other test here reads row order, which cannot tell a correct + * restack from an inverted one — the row moves either way. `applyOrder` + * writes the array index straight out as `z-index`, so this is the only + * assertion that says the frame ended up in *front*. It is the regression + * the whole reversal exists for: "Bring forward" used to run `moveBy(-1)` + * against a back-first list and send the frame behind its neighbour. + */ + frames.add({ name: "one" }); + frames.add({ name: "two" }); + const z = (id: string) => Number(frames.byId(id)?.el.style.zIndex); + expect(z("f1")).toBeLessThan(z("f2")); + + // "one" is the bottom row, because it is the back-most frame. + arrow("f1", "ArrowUp"); + + expect(z("f1")).toBeGreaterThan(z("f2")); + expect(names()).toEqual(["one", "two"]); + }); + + it("keeps focus on the handle across the rebuild", () => { + // `reorder` fires `onChanged`, which rebuilds every row — so the element + // the keypress arrived on is gone by the time the handler returns. Without + // re-taking focus the second press lands on the body and does nothing. + frames.add({ name: "one" }); + frames.add({ name: "two" }); + + arrow("f1", "ArrowUp"); + expect(names()).toEqual(["one", "two"]); + expect(document.activeElement).toBe( + panel.element.querySelector(`[data-frame="f1"] .${cls("fp-grip")}`) + ); + }); + + it("refuses to move past either end", () => { + frames.add({ name: "one" }); + frames.add({ name: "two" }); + // "two" is the top row and "one" the bottom, so these are the two ends. + + arrow("f2", "ArrowUp"); + expect(names()).toEqual(["two", "one"]); + + arrow("f1", "ArrowDown"); + expect(names()).toEqual(["two", "one"]); + }); + + it("swallows the arrow even when the move is refused", () => { + // Otherwise the panel scrolls under a keypress that changed nothing, which + // reads as the row having moved. + frames.add({ name: "one" }); + const grip = panel.element.querySelector(`.${cls("fp-grip")}`); + const e = new KeyboardEvent("keydown", { + bubbles: true, + cancelable: true, + key: "ArrowUp", + }); + grip?.dispatchEvent(e); + + expect(e.defaultPrevented).toBe(true); + }); + + it("leaves other keys alone", () => { + frames.add({ name: "one" }); + const grip = panel.element.querySelector(`.${cls("fp-grip")}`); + const e = new KeyboardEvent("keydown", { + bubbles: true, + cancelable: true, + key: "Tab", + }); + grip?.dispatchEvent(e); + + // The Tab that dnd-kit's keyboard sensor used to eat. Nothing here may + // claim it — see `POINTER_ONLY`. + expect(e.defaultPrevented).toBe(false); + }); + + it("registers rows pointer-only, so no keyboard drag can latch", () => { + // The bug: a `FEEDBACK.none` draggable can start a keyboard drag it can + // never move and cannot be tabbed out of. The row must carry its own + // sensor list rather than inheriting the manager's. + frames.add({ name: "one" }); + const [entity] = ( + panel as unknown as { scope: { entities: { sensors?: unknown[] }[] } } + ).scope.entities; + + expect(entity.sensors).toHaveLength(1); + }); +}); + +describe("FramesPanel navigation", () => { + it("selects and centres on a click, without changing the zoom", () => { + frames.add({ height: 1000, name: "one", width: 1000, x: 0, y: 0 }); + viewport.set({ scale: 2, x: 0, y: 0 }); + + panel.element.querySelector(`.${cls("fp-pick")}`)?.click(); + + expect(frames.active?.id).toBe("f1"); + // The whole point of centre-over-fit: a list you can step through while + // staying at the scale you were working at. + expect(viewport.scale).toBe(2); + }); +}); + +describe("FramesPanel rename", () => { + it("commits on Enter", () => { + frames.add({ name: "Desktop" }); + const label = labelOf("f1"); + label.dispatchEvent(new MouseEvent("dblclick", { bubbles: true })); + type(label, "Marketing"); + key(label, "Enter"); + + expect(frames.byId("f1")?.name).toBe("Marketing"); + expect(label.isContentEditable).toBe(false); + }); + + it("restores the old name on Escape", () => { + frames.add({ name: "Desktop" }); + const label = labelOf("f1"); + label.dispatchEvent(new MouseEvent("dblclick", { bubbles: true })); + type(label, "Nope"); + key(label, "Escape"); + + expect(frames.byId("f1")?.name).toBe("Desktop"); + expect(label.textContent).toBe("Desktop"); + }); + + it("refuses an empty name instead of leaving an unreadable row", () => { + frames.add({ name: "Desktop" }); + const label = labelOf("f1"); + label.dispatchEvent(new MouseEvent("dblclick", { bubbles: true })); + type(label, " "); + key(label, "Enter"); + + expect(frames.byId("f1")?.name).toBe("Desktop"); + expect(label.textContent).toBe("Desktop"); + }); + + it("restores the right name when the same row is renamed twice", () => { + /* + * The bug: the label is reused rather than rebuilt, and every `beginRename` + * added a `keydown` listener that was never removed while `finish` guarded + * on the shared `this.renaming`. On a second rename both listeners matched + * and the *older* one ran first — so Escape restored the name from before + * the first rename, over a model holding the second, and it stayed wrong + * until something else happened to re-render. + */ + frames.add({ name: "Desktop" }); + const label = labelOf("f1"); + + label.dispatchEvent(new MouseEvent("dblclick", { bubbles: true })); + type(label, "Marketing"); + key(label, "Enter"); + expect(frames.byId("f1")?.name).toBe("Marketing"); + + label.dispatchEvent(new MouseEvent("dblclick", { bubbles: true })); + type(label, "Scratch"); + key(label, "Escape"); + + // Back to what the model actually holds, not to the original name. + expect(frames.byId("f1")?.name).toBe("Marketing"); + expect(label.textContent).toBe("Marketing"); + }); + + it("does not leave a listener behind per rename", () => { + frames.add({ name: "Desktop" }); + const label = labelOf("f1"); + for (let i = 0; i < 3; i += 1) { + label.dispatchEvent(new MouseEvent("dblclick", { bubbles: true })); + key(label, "Escape"); + } + + // A fourth session must see exactly one live handler: if the previous three + // were still attached, the oldest would win `finish` and revert to its own + // stale `before`. + label.dispatchEvent(new MouseEvent("dblclick", { bubbles: true })); + type(label, "Final"); + key(label, "Enter"); + expect(frames.byId("f1")?.name).toBe("Final"); + }); + + it("does not let a render overwrite what is being typed", () => { + // The bug this prevents: `render` runs on every frame of a canvas pan, and + // an unguarded `sync` would rewrite the label from the model on each one — + // so renaming a frame while the canvas drifted would silently erase itself. + frames.add({ name: "Desktop" }); + const label = labelOf("f1"); + label.dispatchEvent(new MouseEvent("dblclick", { bubbles: true })); + type(label, "Half-typ"); + + panel.render(); + + expect(label.textContent).toBe("Half-typ"); + }); + + it("keeps the keystrokes away from the canvas bindings", () => { + // ⌫ deletes the selected *frame* in view mode (`FrameChrome`'s binding), so + // a backspace that escaped the rename would delete the thing being renamed. + frames.add({ name: "Desktop" }); + const label = labelOf("f1"); + label.dispatchEvent(new MouseEvent("dblclick", { bubbles: true })); + + let reached = false; + document.addEventListener("keydown", () => { + reached = true; + }); + key(label, "Backspace"); + + expect(reached).toBe(false); + }); +}); + +describe("FramesPanel dragging", () => { + it("stops the options button from arming a drag", () => { + /* + * The whole row is the drag target, and dnd-kit's pointer sensor listens on + * it — so without this guard a press on `⋯` starts a drag. The 4px threshold + * means the click still lands and the menu still opens, which is what makes + * the bug quiet: the row fades and a drop line appears under a pointer that + * was only reaching for a menu. + */ + frames.add({ name: "Desktop" }); + const more = panel.element.querySelector(`.${cls("fp-more")}`); + const press = new MouseEvent("pointerdown", { + bubbles: true, + cancelable: true, + }); + let reachedRow = false; + rows()[0].addEventListener("pointerdown", () => { + reachedRow = true; + }); + more?.dispatchEvent(press); + + expect(reachedRow).toBe(false); + }); + + it("leaves the rest of the row free to start one", () => { + // The complement, and the point of the change: a press on the row's body + // must reach the row, because that is what the sensor is listening on. + frames.add({ name: "Desktop" }); + let reachedRow = false; + rows()[0].addEventListener("pointerdown", () => { + reachedRow = true; + }); + panel.element + .querySelector(`.${cls("fp-pick")}`) + ?.dispatchEvent( + new MouseEvent("pointerdown", { bubbles: true, cancelable: true }) + ); + + expect(reachedRow).toBe(true); + }); +}); + +describe("FramesPanel verbs", () => { + it("routes delete through the shared verb, so it still offers Undo", () => { + frames.add({ name: "Desktop" }); + const before = frames.all.length; + + panel.element.querySelector(`.${cls("fp-more")}`)?.click(); + const del = [ + ...document.querySelectorAll("[data-pop-item]"), + ].find((node) => node.textContent?.includes("Delete")); + del?.click(); + + expect(frames.all).toHaveLength(before - 1); + // The assertion that matters. A panel calling `frames.remove` directly + // would pass every other test in this file and lose the undo. + expect(toasts().join(" ")).toContain("Undo"); + }); +}); + +/* + * The drop's arithmetic, on its own. + * + * Driving a real drag needs dnd-kit's manager and a DOM that lays out, and this + * one has neither — but the part of a drop that can be wrong is not the plumbing, + * it is these two corrections. Both are off-by-one shaped, and both move the + * frame one place from where the drop line promised, which reads as a sloppy + * drop rather than as a bug. + */ +describe("dropStackIndex", () => { + // Three rows, front-first: list 0,1,2 ↔ stack 2,1,0. + const TOTAL = 3; + + it("puts a row dropped at the top at the front of the stack", () => { + // Dragged from the bottom row to slot 0 — nothing was lifted from above it, + // so the slot is the landing position. + expect(dropStackIndex(0, 2, TOTAL)).toBe(2); + }); + + it("puts a row dropped past the end at the back of the stack", () => { + // Slot 3 is past the last row; lifting the top row out shifts it to 2. + expect(dropStackIndex(3, 0, TOTAL)).toBe(0); + }); + + it("discounts the row's own slot when it travelled downward", () => { + // Top row to slot 2: the two rows it passed have moved up, so it lands at 1. + expect(dropStackIndex(2, 0, TOTAL)).toBe(1); + }); + + it("does not discount when it travelled upward", () => { + // Bottom row to slot 1: nothing between it and the slot moved. + expect(dropStackIndex(1, 2, TOTAL)).toBe(1); + }); + + it("is a no-op for a drop onto the row's own slot", () => { + for (const at of [0, 1, 2]) { + expect(dropStackIndex(at, at, TOTAL)).toBe(TOTAL - 1 - at); + } + }); +}); diff --git a/packages/overlay/src/canvas/frames-panel.ts b/packages/overlay/src/canvas/frames-panel.ts new file mode 100644 index 0000000..cf1b556 --- /dev/null +++ b/packages/overlay/src/canvas/frames-panel.ts @@ -0,0 +1,834 @@ +/** + * The frame list — what the left dock shows in view mode. + * + * Until now the only handle on a frame was the frame: its title on the canvas + * was the sole entry point to selecting one, so a frame parked off-screen was + * effectively lost, and there was nowhere at all that answered "what have I + * got?". Eight is a small number, but it is more than enough to lose one in. + * + * It sits opposite the agent panel deliberately, in the mode where a frame is + * the thing you are working on. Edit mode is about an element inside a frame, + * and it already has two panels scoped to that; view mode is about the frames + * themselves — `frame-chrome.ts` has restricted frame selection to view mode + * since before this existed — so the list and the minimap take that slot rather + * than leaving two element-scoped panels open over a mode with no element + * selection. + * + * The verbs are not implemented here. They live in `frame-verbs.ts`, shared + * with the canvas furniture and the bar, so a frame deleted from this list is + * the same act with the same receipt and the same undo as one deleted with ⌫. + * That file's header has the argument. + */ + +import { + DND, + DndScope, + DragDelta, + Draggable, + FEEDBACK, + manager, + POINTER_ONLY, +} from "../dnd/manager"; +import { clear, cls, el, PREFIX } from "../dom"; +import { type IconName, icon } from "../icons"; +import { createMenu, type MenuEntry, type MenuHandle } from "../popover-host"; +import { customSizeRow, deviceGroups } from "./device-menu"; +import { deleteFrame, duplicateFrame, reloadFrame } from "./frame-verbs"; +import { + type Frame, + type FrameManager, + groupOfPreset, + MAX_FRAMES, +} from "./frames"; +import type { CanvasViewport } from "./viewport"; + +/** A frame's glyph, by the device family it belongs to. */ +function glyphFor(frame: Frame): IconName { + switch (groupOfPreset(frame.presetId)?.id) { + case "phone": + return "device-mobile"; + case "tablet": + return "device-tablet"; + default: + return "layer-frame"; + } +} + +export interface FramesPanelDeps { + frames: FrameManager; + viewport: CanvasViewport; +} + +export class FramesPanel { + readonly element: HTMLElement; + + private readonly list: HTMLElement; + private readonly count: HTMLElement; + private readonly addBtn: HTMLButtonElement; + private readonly dropLine: HTMLElement; + private readonly scope = new DndScope(); + private readonly delta = new DragDelta(); + private readonly unsubscribe: (() => void)[] = []; + private readonly deps: FramesPanelDeps; + + /** + * The ids the current rows were built from, in order. + * + * Structure is rebuilt only when this changes; renaming, resizing or + * selecting takes the update path. Rebuilding on every render would be + * cheap enough in DOM terms and wrong in two others: it destroys and + * recreates a dnd-kit entity per row on every frame of a canvas pan, and it + * throws away an in-progress inline rename the moment anything else moves. + */ + private shape = ""; + /** The row being dragged, and where it would land. Null when not dragging. */ + private drag: { id: string; to: number } | null = null; + /** The row whose name is being edited, so a render leaves it alone. */ + private renaming: string | null = null; + + constructor(deps: FramesPanelDeps) { + this.deps = deps; + this.count = el("span", { class: cls("fp-count") }); + this.addBtn = el( + "button", + { + "aria-label": "Add a frame", + class: cls("fp-add"), + "data-tip": "Add a frame", + onClick: () => this.openAddMenu(), + type: "button", + }, + [icon("plus", "sm")] + ) as HTMLButtonElement; + this.dropLine = el("div", { + class: `${cls("fp-drop")} ${cls("hidden")}`, + }); + this.list = el("div", { class: cls("fp-list"), role: "list" }); + this.element = el("div", { class: cls("fp") }, [ + el("div", { class: cls("fp-bar") }, [this.count, this.addBtn]), + // The drop line goes *inside* the list, which is what makes its `top` + // 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]), + ]); + this.list.append(this.dropLine); + this.watchDrag(); + } + + /** + * Redraw. Driven from the stage's `notify`, so it runs on every frame of a + * pan as well as on every frame mutation — see `shape`. + */ + render(): void { + const { frames } = this.deps; + const shape = frames.all.map((f) => f.id).join(","); + if (shape !== this.shape) { + this.shape = shape; + this.rebuild(); + } + this.sync(); + } + + destroy(): void { + this.scope.clear(); + for (const off of this.unsubscribe) { + off(); + } + this.unsubscribe.length = 0; + this.element.remove(); + } + + // -- Structure --------------------------------------------------------------- + + private rebuild(): void { + // Every row owns a dnd entity; clearing before the DOM goes is what keeps + // the registry from filling with detached elements that still answer + // collision queries. See `DndScope`. + this.scope.clear(); + clear(this.list); + this.renaming = null; + for (const frame of this.stackOrder()) { + this.list.append(this.buildRow(frame)); + } + // The line lives in the list so its offsets are the list's — which means + // `clear` above takes it too. `rows()` is a class query rather than + // `children` precisely so this sibling cannot be mistaken for a row. + this.list.append(this.dropLine); + } + + /** + * The frames as the list shows them: front-most first. + * + * `frames.all` is paint order, and paint order runs the other way — + * `FrameManager.applyOrder` writes each frame's array index straight out as + * its `z-index`, so index 0 is the *back* of the stack and the last entry is + * the front. Rendered in that order the panel read bottom-up, which is the + * reverse of every layers panel there has ever been, and it made the restack + * verbs incoherent: "Bring forward" moved a row *up* the list while moving the + * frame *down* the stack, so the two halves of one gesture disagreed. + * + * Reversing the view rather than the model is what fixes it without touching + * z-order: `reorder` and `applyOrder` still speak in stack indices, this panel + * speaks in list positions, and {@link stackIndexAt} is the only place the two + * meet. It also puts a newly added frame at the top, where a new layer goes. + */ + private stackOrder(): Frame[] { + return [...this.deps.frames.all].reverse(); + } + + /** The row elements, and only those — the drop line is a sibling of them. */ + private rows(): HTMLElement[] { + return [...this.list.querySelectorAll(`.${cls("fp-row")}`)]; + } + + private buildRow(frame: Frame): HTMLElement { + const gripId = `${PREFIX}-fp-grip-${frame.id}`; + /* + * Named, and deliberately not `aria-hidden`. + * + * The obvious reading of a drag handle is that it is decoration for the row + * it sits on — which is what it was, until the restack arrived. It is no + * longer dnd-kit's *handle* (the row is), but it is still a real tab stop + * that this file gives a `tabindex` to, so an `aria-hidden` grip would be a + * focusable element inside a hidden subtree: the exact shape of axe's + * `aria-hidden-focus`, and a tab stop with no accessible name at all. + * + * The label is the same bargain `dockHeadAttrs` makes for the dock headers, + * and for the same reason written there — a control with no name of its own + * borrows the concatenated text of everything near it. `sync` keeps it + * current, because a rename changes what this handle moves. + */ + const grip = el( + "span", + { + "aria-keyshortcuts": "ArrowUp ArrowDown", + "aria-label": `Reorder ${frame.name}`, + class: cls("fp-grip"), + "data-tip": "Drag to restack", + id: gripId, + // 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, + * 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, + * which is when it is needed. + */ + tabindex: "0", + }, + [icon("drag", "sm")] + ); + const name = el("span", { class: cls("fp-name"), text: frame.name }); + const dims = el("span", { class: cls("fp-dims") }); + const pick = el( + "button", + { + class: cls("fp-pick"), + onClick: () => this.goTo(frame.id), + onDblClick: () => this.zoomTo(frame.id), + type: "button", + }, + [icon(glyphFor(frame), "sm"), name, dims] + ); + // The rename is armed on the label rather than the row: a double-click + // anywhere else is zoom-to-frame, and one gesture cannot mean both. + name.addEventListener("dblclick", (e) => { + e.stopPropagation(); + this.beginRename(frame, name); + }); + const more = el( + "button", + { + "aria-haspopup": "menu", + "aria-label": `Options for ${frame.name}`, + class: cls("fp-more"), + "data-tip": "Frame options", + onClick: (e: Event) => { + e.stopPropagation(); + this.openRowMenu(frame, more as HTMLElement); + }, + // The whole row is the drag handle now, and dnd-kit's pointer sensor + // listens on it — so without this a press on `⋯` arms a drag. The 4px + // threshold means the click still lands, but the row fades and a drop + // line appears under a pointer that was only opening a menu. + onPointerdown: (e: Event) => e.stopPropagation(), + type: "button", + }, + [icon("more", "sm")] + ); + /* + * Three attributes written here to *stop* dnd-kit writing them. + * + * The Accessibility plugin stamps its markup on `handle ?? element`, and + * every one of its writes is guarded by "if the attribute is absent" — so + * pre-setting one is how you decline it. With the row as the handle + * (see the `Draggable` below) all three would otherwise land here: + * + * - **`tabindex="0"`**, making every row a tab stop. The grip beside it is + * already one and is the real keyboard route, so this would be a second + * stop per row that does nothing the first does not. + * - **`aria-describedby`** pointing at dnd-kit's hidden "to pick up a + * draggable item, press the space bar" text. That instruction cannot be + * followed: `POINTER_ONLY` unregisters the keyboard sensor precisely + * because a `FEEDBACK.none` draggable latches on Space and cannot be moved + * by any arrow key (see the note in `dnd/manager.ts`). Pointed at the grip + * instead, the description is the one control that *can* do the job. + * - `role`, which is skipped anyway because `listitem` is already here — but + * only by that guard, so the attribute is load-bearing rather than + * decorative. + * + * `aria-roledescription="draggable"` is left to the plugin: unlike the + * others it is simply true, and now true of the whole row. + */ + const row = el( + "div", + { + "aria-describedby": gripId, + class: cls("fp-row"), + "data-frame": frame.id, + role: "listitem", + tabindex: "-1", + }, + [grip, pick, more] + ); + this.scope.add( + new Draggable( + { + element: row, + /* + * No `handle`, so the element *is* the handle — the whole row drags. + * + * It used to be the grip, which is a 16px strip at the far left that + * is `opacity: 0` until the row is hovered: an invisible target the + * width of a scrollbar, when every list of this shape lets you drag a + * row by picking it up anywhere. + * + * Safe because the sensor has a 4px activation distance + * (`DRAG_THRESHOLD`, restated in `POINTER_ONLY`), so a press that does + * not travel still falls through to `pick`'s click and its + * double-click. The one child that must not arm a drag is `⋯`, which + * stops the press itself. + */ + id: `${DND.frameRow}:${frame.id}`, + // Nothing is translated: the row stays put and the drop line does the + // reporting, so the list never reflows under the pointer. + 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. + sensors: POINTER_ONLY, + type: DND.frameRow, + }, + manager + ) + ); + return row; + } + + /** Everything that changes without the set of frames changing. */ + private sync(): void { + const { frames } = this.deps; + const total = frames.all.length; + this.count.textContent = `${total} of ${MAX_FRAMES} frames`; + this.addBtn.disabled = total >= MAX_FRAMES; + this.addBtn.dataset.tip = + total >= MAX_FRAMES + ? `Frame limit reached (${MAX_FRAMES})` + : "Add a frame"; + const activeId = frames.active?.id ?? null; + for (const frame of frames.all) { + const row = this.rowOf(frame.id); + if (!row) { + continue; + } + row.classList.toggle(cls("fp-row-on"), frame.id === activeId); + const name = row.querySelector(`.${cls("fp-name")}`); + // Skipped mid-rename, or every keystroke would be overwritten by the + // model value the edit has not committed yet. + if (name && this.renaming !== frame.id) { + name.textContent = frame.name; + } + const dims = row.querySelector(`.${cls("fp-dims")}`); + if (dims) { + dims.textContent = `${Math.round(frame.width)} × ${Math.round(frame.height)}`; + } + // Three names derived from the frame's own, so a rename does not leave + // the row announcing itself by the name it used to have. + row + .querySelector(`.${cls("fp-pick")}`) + ?.setAttribute( + "aria-label", + `${frame.name}, ${Math.round(frame.width)} by ${Math.round(frame.height)}` + ); + row + .querySelector(`.${cls("fp-grip")}`) + ?.setAttribute("aria-label", `Reorder ${frame.name}`); + row + .querySelector(`.${cls("fp-more")}`) + ?.setAttribute("aria-label", `Options for ${frame.name}`); + } + } + + private rowOf(id: string): HTMLElement | null { + return this.list.querySelector(`[data-frame="${id}"]`); + } + + // -- Navigation -------------------------------------------------------------- + + /** + * Select a frame and move the camera onto it, *without* changing the zoom. + * + * A list whose every click re-zoomed you would be unusable for the thing a + * list is for — stepping between frames while working at one scale. Getting + * closer is the double-click, and ⇧2 already exists for the selection. + */ + private goTo(id: string): void { + const frame = this.deps.frames.byId(id); + if (!frame) { + return; + } + this.deps.frames.setActive(id); + this.deps.viewport.centerOn({ + x: frame.x + frame.width / 2, + y: frame.y + frame.height / 2, + }); + this.deps.viewport.save(); + } + + private zoomTo(id: string): void { + const frame = this.deps.frames.byId(id); + if (!frame) { + return; + } + this.deps.frames.setActive(id); + this.deps.viewport.fitToRect({ + height: frame.height, + left: frame.x, + top: frame.y, + width: frame.width, + }); + this.deps.viewport.save(); + } + + // -- Rename ------------------------------------------------------------------ + + /** + * Edit a frame's name in place. + * + * `contenteditable` on the label already in the row, rather than swapping in + * an `input`: the row is a grid and a field with its own metrics would resize + * it under the pointer at the moment of the double-click. Enter commits, + * Escape restores, blur commits — the same bargain the canvas title makes. + */ + private beginRename(frame: Frame, label: HTMLElement): void { + if (this.renaming === frame.id) { + return; + } + this.renaming = frame.id; + const before = frame.name; + label.contentEditable = "plaintext-only"; + label.classList.add(cls("fp-name-edit")); + label.focus(); + getSelection()?.selectAllChildren(label); + + /* + * Local, not `this.renaming`. + * + * The shared field cannot tell two *sessions* apart, only two frames — and + * the label is reused rather than rebuilt, so a second rename of the same + * row left the first session's listener attached and still matching. Both + * fired, and the older one ran first: Escape restored the name from before + * the *first* rename, over a model holding the second, and it stayed wrong + * until something else happened to re-render. + * + * `FrameChrome.renameFrame` never had this because it swaps in a fresh + * `input` and drops it again — the listeners die with the element. This + * takes the other half of the same bargain: a flag that belongs to the + * session, and listeners that are taken down with it. + */ + let done = false; + const finish = (commit: boolean): void => { + if (done) { + return; + } + done = true; + this.renaming = null; + label.removeEventListener("keydown", onKey); + label.removeEventListener("blur", onBlur); + label.contentEditable = "false"; + label.classList.remove(cls("fp-name-edit")); + const next = (label.textContent ?? "").trim(); + // An empty name would leave a row with nothing to click and nothing to + // read; the previous one is the only sensible thing to fall back to. + if (commit && next && next !== before) { + this.deps.frames.rename(frame.id, next); + } else { + label.textContent = before; + } + }; + + function onKey(e: KeyboardEvent): void { + if (e.key === "Enter") { + e.preventDefault(); + finish(true); + } else if (e.key === "Escape") { + e.preventDefault(); + finish(false); + } + // Every other key is the user typing a name, and must not reach the + // canvas bindings underneath — ⌫ deletes the selected frame in this mode. + e.stopPropagation(); + } + function onBlur(): void { + finish(true); + } + + label.addEventListener("keydown", onKey); + label.addEventListener("blur", onBlur); + } + + // -- Menus ------------------------------------------------------------------- + + /** + * The panel's `+` — pick a device, get a frame. + * + * Its own menu, against its own button. It used to call the stage's + * `openAddMenu`, which opens a menu parented to the bottom bar and placed + * against it: pressing `+` in the left dock popped the device list open above + * the middle of the window, nowhere near the control that was clicked. It + * could not be dismissed by pressing `+` again either — `FrameChrome`'s + * outside-press guard spares `.fc-menu, .fc-size, .fbar-btn` and the panel's + * button is none of them, so the press closed the menu and the click reopened + * it. + * + * The bar's own `+` and the `F` shortcut still go to `FrameChrome`, which is + * right: that menu is anchored to *that* button. + */ + private openAddMenu(): void { + // Declared before the menu that owns it: the form has to be able to close + // the menu it is standing in, and it is built as one of that menu's entries. + let handle: MenuHandle | null = null; + const custom = customSizeRow( + (width, height) => + this.deps.frames.add({ height, name: `${width} × ${height}`, width }), + () => handle?.close() + ); + handle = createMenu([ + ...deviceGroups((preset) => + this.deps.frames.add({ presetId: preset.id }) + ), + { separator: true }, + { node: custom }, + ]); + handle.open(this.addBtn, "below"); + } + + /** + * The row's `⋯` — the verbs, then the device list. + * + * **Verbs first, and that ordering is not taste.** Even grouped, the device + * list is four more lines; built the other way round the verbs start below the + * fold on a row near the bottom of the panel, which puts Delete out of sight in + * a menu you opened to reach it. Leading with the verbs means everything that + * acts on the frame is in view on open and the devices are the tail you open + * deliberately. + * + * The device half is `device-menu.ts`'s, shared with the panel's `+` and built + * from `PRESET_GROUPS` — so this list cannot drift out of step with the one on + * the canvas. + */ + private openRowMenu(frame: Frame, anchor: HTMLElement): void { + const at = this.indexOf(frame.id); + const last = this.deps.frames.all.length - 1; + const entries: MenuEntry[] = [ + /* + * The discoverable half of the restack. The grip's arrows are the fast + * route and are announced on the handle itself; a menu row is what tells + * anyone the operation exists at all. + * + * `at` is a *list* position, so forward is `-1` and the guards read off + * the ends of the list — which is the same thing as the ends of the stack + * now that the list is front-first. This pair used to say `-1` for forward + * against a back-first list and therefore did the opposite of its label: + * `applyOrder` writes the array index straight out as `z-index`, so + * lowering the index sends a frame *back*. See `stackOrder`. + */ + { + disabled: at <= 0, + hint: "↑", + icon: "chev-up", + label: "Bring forward", + run: () => this.moveBy(frame.id, -1), + }, + { + disabled: at < 0 || at >= last, + hint: "↓", + icon: "chev-down", + label: "Send backward", + run: () => this.moveBy(frame.id, 1), + }, + { separator: true }, + { + icon: "rotation", + label: "Rotate", + run: () => this.deps.frames.rotate(frame.id), + }, + { + icon: "rotate-ccw", + label: "Reload", + run: () => reloadFrame(this.deps.frames, frame), + }, + { + // The one door onto Duplicate that has a control to grey out, so the + // refusal does not have to be spoken here — see `duplicateFrame`. + disabled: this.deps.frames.all.length >= MAX_FRAMES, + icon: "doc-plus", + label: "Duplicate", + run: () => duplicateFrame(this.deps.frames, frame), + }, + { + // The bin, matching the bar's Delete frame button. These two are one + // verb and drew two different glyphs — a `✕` here and a `−` there — + // because the imported set publishes no trash and both call sites + // improvised. See `trash` in the icon set's ICONS.md. + icon: "trash", + label: "Delete", + run: () => deleteFrame(this.deps.frames, frame), + }, + { separator: true }, + ...deviceGroups( + (preset) => this.deps.frames.applyPreset(frame.id, preset.id), + frame + ), + ]; + createMenu(entries).open(anchor, "below"); + } + + // -- Reorder ----------------------------------------------------------------- + + /** + * Move a frame one row through the list. + * + * `delta` is in *list* terms — `-1` is one row up, which is one place toward + * the front of the stack. Everything the panel does is stated that way, and + * {@link stackIndexAt} turns the answer back into the index `reorder` wants. + * + * The keyboard and menu route to the same thing the drag does, so there is one + * definition of what "restack" means. The precedent is `num-field.ts`, whose + * `FEEDBACK.none` scrub has `stepBy` beside it on the arrow keys for the same + * reason: the drag is a pointer gesture, and a pointer gesture is not an + * interaction — it is one way to reach one. + * + * Returns whether anything moved, which is what lets the menu grey out its + * ends and the key handler decide whether to swallow the press. + */ + private moveBy(id: string, delta: number): boolean { + const from = this.indexOf(id); + const to = from + delta; + if (from === -1 || to < 0 || to >= this.deps.frames.all.length) { + return false; + } + this.deps.frames.reorder(id, this.stackIndexAt(to)); + return true; + } + + /** + * ↑/↓ on a focused grip. + * + * Focus is re-taken after the move because `reorder` fires `onChanged`, which + * re-renders, which rebuilds every row — so the element the key arrived on is + * gone by the time this returns and the next press would land on the body. + * Looked up by frame id rather than held as a node, for the same reason. + * + * 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(`.${cls("fp-grip")}`) + ?.focus(); + } + } + + /** + * Drag a row to restack the frames. + * + * The list is the stack seen from the front, which is what makes this worth + * having at all: frames may overlap on the canvas, and until now nothing could + * change which one was on top. Dragging a row up moves its frame toward you, + * because up the list *is* toward the front — see `stackOrder`. + * `FrameManager.reorder` publishes the result as `z-index` rather than moving + * anything in the DOM — moving an `iframe` reloads it, and a drag that + * rebooted the app you were looking at would be a strange price for raising it + * one place. + * + * The pointer is read from `DragDelta`, not from the operation's own + * `position.current`, for the reason that class documents: the manager + * assigns that in a microtask *after* `dragmove` is dispatched, so a target + * resolved here from it would be one move behind. + */ + private watchDrag(): void { + this.unsubscribe.push( + manager.monitor.addEventListener("dragstart", () => { + const id = rowIdOf(manager.dragOperation.source); + if (!id) { + return; + } + this.delta.start(); + this.drag = { id, to: this.indexOf(id) }; + this.rowOf(id)?.classList.add(cls("fp-row-drag")); + }), + manager.monitor.addEventListener("dragmove", (e) => { + if (!this.drag) { + return; + } + this.delta.update(e); + this.drag.to = this.dropIndexAt(this.delta.pointer.y); + this.showDropLine(this.drag.to); + }), + manager.monitor.addEventListener("dragend", (e) => { + const { drag } = this; + if (!drag) { + return; + } + this.drag = null; + this.rowOf(drag.id)?.classList.remove(cls("fp-row-drag")); + this.dropLine.classList.add(cls("hidden")); + if (e.canceled) { + return; + } + this.deps.frames.reorder( + drag.id, + dropStackIndex( + drag.to, + this.indexOf(drag.id), + this.deps.frames.all.length + ) + ); + }) + ); + } + + /** A frame's row position, counting from the top. -1 if it has no row. */ + private indexOf(id: string): number { + const at = this.deps.frames.all.findIndex((f) => f.id === id); + return at === -1 ? -1 : this.stackIndexAt(at); + } + + /** + * List position ↔ stack index, in one function because it is one fact. + * + * The list runs front-to-back and the model runs back-to-front, so the two are + * mirror images: `last - n`. That makes this its own inverse, which is why one + * name serves both directions — `stackIndexAt(listPosition)` and + * `stackIndexAt(stackIndex)` are the same arithmetic read the other way round. + * See {@link stackOrder} for why the view is the half that got reversed. + */ + private stackIndexAt(n: number): number { + return this.deps.frames.all.length - 1 - n; + } + + /** How many rows the pointer has passed the midpoint of — the insertion slot. */ + private dropIndexAt(y: number): number { + let index = 0; + for (const row of this.rows()) { + const r = row.getBoundingClientRect(); + if (y > r.top + r.height / 2) { + index += 1; + } + } + return index; + } + + /** + * Draw the line at an insertion slot. + * + * Slot `n` is the *top* of row `n`, except for the one past the end, which is + * the bottom of the last row — so the line can be shown below everything + * without a phantom row to hang it on. Positioned against the list rather + * than the scroller so it travels with the rows when the list is scrolled + * mid-drag. + */ + private showDropLine(index: number): void { + const rows = this.rows(); + const past = index >= rows.length; + const edge = past ? rows.at(-1) : rows[index]; + if (!edge) { + return; + } + const host = this.list.getBoundingClientRect(); + const r = edge.getBoundingClientRect(); + this.dropLine.style.top = `${(past ? r.bottom : r.top) - host.top}px`; + this.dropLine.classList.remove(cls("hidden")); + } +} + +/** + * Where a dropped row lands, as a stack index. + * + * Two corrections, and getting either wrong moves the frame one place from + * where the line promised — which is the kind of bug that reads as the drop + * being imprecise rather than as arithmetic. + * + * First, `to` is an *insertion slot* in the list as it currently stands, with + * the dragged row still in it. Lifting the row out shifts everything below it up + * by one, so a row that travelled downward lands one place earlier than its slot + * number says. A row that travelled up is unaffected: nothing between it and the + * slot has moved. + * + * Second, the result is still a list position, and the list runs front-to-back + * while `FrameManager` runs back-to-front. See `FramesPanel.stackOrder`. + * + * Exported to the test rather than left inline because it is the whole of the + * drop's correctness and the only part of the drag that can be checked without + * standing up dnd-kit's manager in a DOM that does no layout. + */ +export function dropStackIndex( + to: number, + from: number, + total: number +): number { + 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 +): string | null { + if (!source || source.type !== DND.frameRow) { + return null; + } + const id = String(source.id); + return id.slice(id.indexOf(":", DND.frameRow.length) + 1) || null; +} diff --git a/packages/overlay/src/canvas/minimap.stories.ts b/packages/overlay/src/canvas/minimap.stories.ts new file mode 100644 index 0000000..3b9971e --- /dev/null +++ b/packages/overlay/src/canvas/minimap.stories.ts @@ -0,0 +1,238 @@ +import type { Meta, StoryObj } from "@storybook/html-vite"; +import { el } from "../dom"; +import { type Caption, plainStage } from "../stories/chrome"; +import { onStoryTeardown } from "../stories/lifecycle"; +import { FrameManager } from "./frames"; +import { Minimap } from "./minimap"; +import { CanvasViewport } from "./viewport"; + +/* + * The minimap, over a real canvas. + * + * This one genuinely needs a browser and is close to useless without one. The + * card is nothing but arithmetic turned into `left`/`top`/`width`/`height`, and + * happy-dom answers every rect with zero — so `minimap.test.ts` asserts the + * projection directly and leaves the rendered result untested by construction. + * Here it is rendered, over a viewport with a real size, and you can drag it. + * + * The frames are real iframes with no `src`, appended to a real world element + * under a real `CanvasViewport`. `mount()` is never called (under Storybook + * `/?__airship=frame` is Storybook's own index, recursively — see the note at + * the top of `canvas.stories.ts`), so they stay blank white rectangles. That is + * the right fidelity for this story: the minimap draws *rectangles*, and what + * is inside a frame is the one thing it can never show. + * + * The pairing is the point of the first story. The card and the canvas above it + * are the same world twice, so a drag in one has to move the other — and the + * indicator has to keep reporting where you are once you leave the frames + * behind, which is what `FarField` is for. + */ + +const meta: Meta = { + title: "Canvas/Minimap", +}; + +export default meta; + +const CANVAS_H = "60vh"; + +interface Rig { + element: HTMLElement; + frames: FrameManager; + minimap: Minimap; + viewport: CanvasViewport; +} + +/** + * A canvas with a minimap over it, wired the way `CanvasStage` wires them. + * + * `frames` is referred to inside `viewport`'s deps and vice versa; both + * closures are lazy and nothing fires until a frame is added — the same knot + * `frame-chrome.test.ts` and `canvas.stories.ts` both tie. + */ +function rig(): Rig { + let frames: FrameManager; + let minimap: Minimap; + + const viewport = new CanvasViewport({ + getContentRects: () => frames.worldRects(), + getSelectionRect: () => null, + onChange: () => minimap.render(), + storageKey: "__airship-story:viewport", + }); + frames = new FrameManager({ + onChanged: () => minimap.render(), + pathname: "/", + storageKey: "__airship-story:frames", + world: viewport.world, + }); + minimap = new Minimap({ frames, viewport }); + + // The card is `position: fixed` in the product. Pinned to the demo's own box + // here instead, so two stories on one page do not stack in the same corner. + minimap.element.style.position = "absolute"; + minimap.element.style.right = "12px"; + minimap.element.style.bottom = "12px"; + + const element = el( + "div", + { + style: `position: relative; width: 100%; height: ${CANVAS_H}; + overflow: hidden; border-radius: 6px;`, + }, + [viewport.element, minimap.element] + ); + + onStoryTeardown(() => { + minimap.destroy(); + frames.destroy(); + viewport.destroy(); + }); + + return { element, frames, minimap, viewport }; +} + +/** + * Build a board and let the layout settle before anything is measured. + * + * `viewport.rect` reads the element's own `getBoundingClientRect`, which is + * zero until Storybook has appended the story — so a minimap rendered + * synchronously would project against a zero-sized viewport and draw an + * indicator covering the whole card. + */ +function board( + build: (r: Rig) => void, + caption: Caption, + fit = true +): HTMLElement { + const r = rig(); + requestAnimationFrame(() => { + build(r); + if (fit) { + r.viewport.zoomToFit(); + } + r.minimap.render(); + }); + return plainStage([r.element], caption); +} + +/** The two frames a new project starts with, plus room to get lost in. */ +function starter(frames: FrameManager): void { + frames.add({ presetId: "desktop", x: 0, y: 0 }); + frames.add({ presetId: "iphone-16", x: 1560, y: 0 }); + frames.add({ presetId: "ipad-pro-12-9", x: 2080, y: 0 }); +} + +export const Default: StoryObj = { + render: () => + board(({ frames }) => starter(frames), { + try: "Press anywhere on the map — the canvas jumps there and keeps following until you let go. Wheel or ⌘-wheel over the canvas and watch the indicator track it.", + what: "Three frames, fitted. The blue box is the part of the world the canvas is showing; the grey ones are the frames.", + }), +}; + +/** + * Zoomed in on one frame. + * + * The state the map is actually for: the indicator is small, most of the board + * is off screen, and the card is the only thing on screen that says so. + */ +export const ZoomedIn: StoryObj = { + render: () => + board( + ({ frames, viewport }) => { + starter(frames); + viewport.set({ scale: 1.6, x: -180, y: -120 }); + }, + { + what: "At 160%, showing a corner of the first frame. The indicator shrinks to match what is visible.", + }, + false + ), +}; + +/** + * Panned off the end of the world. + * + * The bug this design exists to avoid: projecting the frames alone puts the + * indicator off the card exactly here, at the moment a map is the only thing + * that could help. The bounds include where you are looking, so the frames + * shrink into a corner and the map keeps pointing back at them. + */ +export const FarField: StoryObj = { + render: () => + board( + ({ frames, viewport }) => { + starter(frames); + viewport.set({ scale: 0.4, x: -9000, y: -3400 }); + }, + { + what: "Panned far past every frame. The frames collapse into a corner rather than the indicator sliding off the card — the projection covers the union of both.", + }, + false + ), +}; + +/** One frame, and nothing to get lost among. The map is honest about that. */ +export const SingleFrame: StoryObj = { + render: () => + board( + ({ frames }) => { + frames.add({ presetId: "desktop" }); + }, + { + what: "A single frame at fit. The indicator is larger than the frame because a fit leaves padding around it — which is what the padding on the card is echoing.", + } + ), +}; + +/** + * The selected frame. + * + * Selection is a *view-mode* idea — `frame-chrome.ts` restricts it to that + * mode, which is the same mode this card only appears in — so the map marks it + * in the accent rather than leaving eight identical grey boxes. + */ +export const WithSelection: StoryObj = { + render: () => + board( + ({ frames }) => { + starter(frames); + frames.setActive("f2"); + }, + { + try: "Press the highlighted chip on the map: it selects that frame. Double-click it to zoom to it.", + what: "The selected frame in the accent colour. Everything else is the same neutral fill.", + } + ), +}; + +/** The card at its widest content: a wall of frames at the cap. */ +export const FullBoard: StoryObj = { + render: () => + board( + ({ frames }) => { + for (let i = 0; i < 8; i += 1) { + frames.add({ + presetId: i % 3 === 0 ? "desktop" : "iphone-16", + x: i * 700, + y: (i % 2) * 400, + }); + } + }, + { + what: "Eight frames — the cap. At this width the projection is well under MIN_SCALE, which is the reason the minimap does not use `fitTo`.", + } + ), +}; + +/* + * Dragging is deliberately not a story. + * + * The two gestures the card carries — grab the indicator and it travels with + * the pointer, press outside it and the view goes there — are a *sequence* of + * pointer events, and a story is one picture. They are fenced in + * `minimap.test.ts` under `Minimap dragging`, which stubs the card's rect and + * drives the events directly; the stories here are for the projection, which is + * the half you have to look at to judge. + */ diff --git a/packages/overlay/src/canvas/minimap.test.ts b/packages/overlay/src/canvas/minimap.test.ts new file mode 100644 index 0000000..85d7364 --- /dev/null +++ b/packages/overlay/src/canvas/minimap.test.ts @@ -0,0 +1,416 @@ +/** + * The minimap's geometry, and the one behaviour that is not geometry. + * + * Two bugs are being fenced off here and both are silent — a wrong minimap + * looks like a minimap. + * + * The first is the bounds. Projecting the frames alone is the obvious reading + * of "show me my canvas", and it means the indicator slides off the card the + * moment you pan past your content — which is precisely when a map is the only + * thing that could help. `minimapProjection` unions the visible rect in for + * that reason, and `stays on the card` is the assertion that says so. + * + * The second is `MIN_SCALE`. `projectInto` exists because `fitTo` clamps, and + * the reason it clamps is that its result is a *zoom level* — reusing it here + * would floor a wide canvas at 0.1 and draw the frames several times wider than + * the box holding them. `space.test.ts` proves the helper; this proves the + * minimap reaches for the right one. + * + * Geometry is asserted through the pure projection rather than through the + * rendered card, because happy-dom does no layout: the card's own rect reads + * zero, so a conversion through it would be dividing by nothing. Everything that + * needs the browser's answer is `getBoundingClientRect`, and it is stubbed where + * a test needs it — which is what lets `Minimap dragging` exercise the pointer + * path for real rather than leaving the whole gesture unverified. + */ + +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { cls } from "../dom"; +import { MINIMAP_H, MINIMAP_PAD, MINIMAP_W } from "../styles/const"; +import { FrameManager } from "./frames"; +import { Minimap, minimapProjection } from "./minimap"; +import { MIN_SCALE, type Rect, worldRectToScreen } from "./space"; +import { CanvasViewport } from "./viewport"; + +const BOX: Rect = { height: MINIMAP_H, left: 0, top: 0, width: MINIMAP_W }; + +let world: HTMLElement; +let frames: FrameManager; +let viewport: CanvasViewport; +let minimap: Minimap; +/** What the open docks are covering. Mutable, so one test can open one. */ +let inset: { left: number; right: number }; + +/** The canvas viewport's own screen rect, which happy-dom will not compute. */ +function sizeCanvas(width: number, height: number): void { + viewport.element.getBoundingClientRect = () => + ({ + bottom: height, + height, + left: 0, + right: width, + top: 0, + width, + }) as DOMRect; +} + +function chips(): string[] { + return [...minimap.element.querySelectorAll(`.${cls("minimap-frame")}`)].map( + (node) => node.getAttribute("data-frame") ?? "?" + ); +} + +/** Is a rect entirely inside the projection box? */ +function inside(rect: Rect): boolean { + return ( + rect.left >= -0.001 && + rect.top >= -0.001 && + rect.left + rect.width <= MINIMAP_W + 0.001 && + rect.top + rect.height <= MINIMAP_H + 0.001 + ); +} + +beforeEach(() => { + document.body.replaceChildren(); + world = document.createElement("div"); + document.body.append(world); + inset = { left: 0, right: 0 }; + viewport = new CanvasViewport({ + getContentRects: () => frames.worldRects(), + getSafeInset: () => inset, + getSelectionRect: () => null, + onChange: () => undefined, + storageKey: "__airship-test:viewport", + }); + sizeCanvas(1200, 800); + frames = new FrameManager({ + pathname: "/", + storageKey: "__airship-test:frames", + world, + }); + minimap = new Minimap({ frames, viewport }); + minimap.mount(document.body); +}); + +afterEach(() => { + minimap.destroy(); + frames.destroy(); + viewport.destroy(); + world.remove(); +}); + +describe("minimapProjection", () => { + const FRAME: Rect = { height: 1024, left: 0, top: 0, width: 1440 }; + + it("fits the frames inside the box", () => { + const seen: Rect = { height: 800, left: 0, top: 0, width: 1200 }; + const projection = minimapProjection([FRAME], seen); + + expect(inside(worldRectToScreen(projection.map, BOX, FRAME))).toBe(true); + }); + + it("scales below MIN_SCALE for a wide canvas", () => { + // Eight desktop frames in a row is well inside what the canvas allows, and + // it is already an order of magnitude past what a zoom level may be. + const wide: Rect = { height: 1024, left: 0, top: 0, width: 12_000 }; + const projection = minimapProjection([wide], wide); + + expect(projection.map.scale).toBeLessThan(MIN_SCALE); + }); + + it("keeps the viewport indicator on the card when it leaves the frames", () => { + // Panned far off to the right of everything, which is the case that made + // the frames-only version useless. + const seen: Rect = { height: 800, left: 40_000, top: 9000, width: 1200 }; + const projection = minimapProjection([FRAME], seen); + + expect(inside(worldRectToScreen(projection.map, BOX, seen))).toBe(true); + // …and the frames are still on it, so the map says which way to go back. + expect(inside(worldRectToScreen(projection.map, BOX, FRAME))).toBe(true); + }); + + it("holds still while the viewport is inside the frames' bounds", () => { + // The cost of unioning the visible rect in is that the projection can + // rescale as you pan. It must not do that over your own content, or the + // map would shift under the pointer on every gesture. + const wall: Rect = { height: 1024, left: 0, top: 0, width: 6000 }; + const a = minimapProjection([wall], { + height: 400, + left: 500, + top: 100, + width: 600, + }); + const b = minimapProjection([wall], { + height: 400, + left: 3200, + top: 300, + width: 600, + }); + + expect(a.map.scale).toBe(b.map.scale); + expect(a.map.x).toBe(b.map.x); + }); + + it("leaves a margin, so the indicator never merges with the card's edge", () => { + const seen: Rect = { height: 1024, left: 0, top: 0, width: 1440 }; + const rect = worldRectToScreen( + minimapProjection([FRAME], seen).map, + BOX, + FRAME + ); + + expect(rect.left).toBeGreaterThanOrEqual(MINIMAP_PAD - 0.001); + expect(rect.top).toBeGreaterThanOrEqual(MINIMAP_PAD - 0.001); + }); + + it("answers for an empty canvas rather than refusing to", () => { + // No frames at all, and a viewport that has not been laid out — the state + // the very first render runs in. `projectInto` gives back the identity for + // a degenerate box, so nothing downstream has to defend against a zero or + // negative scale. + const map = minimapProjection([], { height: 0, left: 0, top: 0, width: 0 }); + expect(map.map.scale).toBe(1); + expect(Number.isFinite(map.bounds.width)).toBe(true); + }); +}); + +describe("Minimap rendering", () => { + it("tracks the set of frames", () => { + frames.add({ name: "one" }); + frames.add({ name: "two" }); + minimap.render(); + expect(chips()).toEqual(["f1", "f2"]); + + frames.remove("f1"); + minimap.render(); + expect(chips()).toEqual(["f2"]); + }); + + it("marks the selected frame", () => { + frames.add({ name: "one" }); + frames.add({ name: "two" }); + frames.setActive("f2"); + minimap.render(); + + const on = minimap.element.querySelectorAll(`.${cls("minimap-frame-on")}`); + expect(on).toHaveLength(1); + expect(on[0].getAttribute("data-frame")).toBe("f2"); + }); + + it("reuses chips rather than rebuilding them on every render", () => { + // The render path runs on every frame of a pan. Rebuilding would throw away + // and recreate a node per frame sixty times a second, and is the reason + // `syncChips` is a diff rather than a `clear`. + frames.add({ name: "one" }); + minimap.render(); + const first = minimap.element.querySelector(`[data-frame="f1"]`); + minimap.render(); + minimap.render(); + + expect(minimap.element.querySelector(`[data-frame="f1"]`)).toBe(first); + }); + + it("keeps the indicator painting over the frames", () => { + // `syncChips` inserts before the indicator specifically so a frame added + // later cannot end up on top of the box that says where you are looking. + frames.add({ name: "one" }); + minimap.render(); + frames.add({ name: "two" }); + minimap.render(); + + const body = minimap.element.querySelector(`.${cls("minimap-body")}`); + const classes = [...(body?.children ?? [])].map((n) => n.className); + expect(classes.at(-1)).toContain(cls("minimap-view")); + }); +}); + +describe("Minimap accessibility", () => { + it("hides the graphic and puts nothing focusable inside it", () => { + // The card is a pointer-only enhancement: everything it does is reachable + // through ⇧1, ⇧2 and the frame list. That is only honest while the drawing + // itself stays out of the tree *and* contains no tab stop — an + // `aria-hidden` subtree with a focusable node in it is axe's + // `aria-hidden-focus`, which is the trap the frame list's drag handle fell + // into. + frames.add({ name: "one" }); + frames.add({ name: "two" }); + minimap.render(); + + const body = minimap.element.querySelector(`.${cls("minimap-body")}`); + expect(body?.getAttribute("aria-hidden")).toBe("true"); + expect(body?.querySelectorAll("button, a, input, [tabindex]")).toHaveLength( + 0 + ); + }); + + it("names the card, and offers no way to dismiss it", () => { + expect(minimap.element.getAttribute("role")).toBe("group"); + expect(minimap.element.getAttribute("aria-label")).toBe("Canvas minimap"); + // The card used to carry a close button whose only counterpart was a + // checkbox under the zoom readout. Nothing hides the map now, so nothing + // has to be found to bring it back. + expect(minimap.element.querySelectorAll("button")).toHaveLength(0); + }); +}); + +/* + * The pointer path. + * + * happy-dom does no layout, so the card's own rect reads zero and every + * conversion through it collapses. `sizeMap` is what makes these tests possible + * at all: it gives the body the rect the stylesheet would have given it, which + * is the one number the geometry cannot derive for itself. + */ +describe("Minimap dragging", () => { + /** The card's body rect, which happy-dom will not compute. */ + function sizeMap(): void { + const body = minimap.element.querySelector( + `.${cls("minimap-body")}` + ); + if (!body) { + throw new Error("no minimap body"); + } + body.getBoundingClientRect = () => + ({ + bottom: MINIMAP_H, + height: MINIMAP_H, + left: 0, + right: MINIMAP_W, + top: 0, + width: MINIMAP_W, + }) as DOMRect; + } + + function press(x: number, y: number): void { + minimap.element + .querySelector(`.${cls("minimap-body")}`) + ?.dispatchEvent( + new MouseEvent("pointerdown", { bubbles: true, clientX: x, clientY: y }) + ); + } + + function move(x: number, y: number): void { + minimap.element + .querySelector(`.${cls("minimap-body")}`) + ?.dispatchEvent( + new MouseEvent("pointermove", { bubbles: true, clientX: x, clientY: y }) + ); + } + + /** The indicator's box in card px, as `render` last drew it. */ + function indicator(): Rect { + const node = minimap.element.querySelector( + `.${cls("minimap-view")}` + ); + return { + height: Number.parseFloat(node?.style.height ?? "0"), + left: Number.parseFloat(node?.style.left ?? "0"), + top: Number.parseFloat(node?.style.top ?? "0"), + width: Number.parseFloat(node?.style.width ?? "0"), + }; + } + + beforeEach(() => { + // A wall of frames, so the map has a real scale rather than projecting the + // viewport onto itself. + frames.add({ height: 1024, name: "one", width: 1440 }); + frames.add({ height: 1024, name: "two", width: 1440 }); + sizeMap(); + minimap.render(); + }); + + it("keeps the grab offset instead of snapping the box to the cursor", () => { + // The whole of the reported over-sensitivity: pressing inside the indicator + // used to centre it on the pointer, so taking hold near an edge jumped the + // camera by half a box before the pointer had travelled at all. + const before = indicator(); + press(before.left + 1, before.top + 1); + minimap.render(); + + const after = indicator(); + expect(after.left).toBeCloseTo(before.left, 1); + expect(after.top).toBeCloseTo(before.top, 1); + }); + + it("carries the box with the pointer, one for one", () => { + const before = indicator(); + press(before.left + 1, before.top + 1); + move(before.left + 21, before.top + 1); + minimap.render(); + + expect(indicator().left).toBeCloseTo(before.left + 20, 0); + }); + + it("jumps to a press outside the box, then tracks from there", () => { + const before = indicator(); + // Well clear of the indicator, along the row of frames. + const target = before.left + before.width + 20; + press(target, before.top + before.height / 2); + minimap.render(); + + const jumped = indicator(); + expect(jumped.left + jumped.width / 2).toBeCloseTo(target, 0); + + move(target + 10, before.top + before.height / 2); + minimap.render(); + const tracked = indicator(); + expect(tracked.left + tracked.width / 2).toBeCloseTo(target + 10, 0); + }); + + it("holds the projection still for the length of a drag", () => { + // `minimapProjection` folds the visible rect into its bounds, so panning + // past the frames rescales the map. Recomputed mid-gesture that changes how + // far the next pointer move travels — the rubber-banding this snapshot + // exists to stop. The chips are the projection made visible: if they move, + // the map rescaled under the pointer. + const chip = () => + minimap.element.querySelector(`[data-frame="f1"]`)?.style + .width; + const before = indicator(); + press(before.left + before.width / 2, before.top + before.height / 2); + const width = chip(); + + // Drag hard against the edge, which is far outside the frames' union. + move(MINIMAP_W - 1, MINIMAP_H - 1); + minimap.render(); + expect(chip()).toBe(width); + }); + + it("recomputes the projection once the drag is over", () => { + const chip = () => + minimap.element.querySelector(`[data-frame="f1"]`)?.style + .width; + const before = indicator(); + press(before.left + before.width / 2, before.top + before.height / 2); + move(MINIMAP_W - 1, MINIMAP_H - 1); + minimap.render(); + const frozen = chip(); + + minimap.element + .querySelector(`.${cls("minimap-body")}`) + ?.dispatchEvent(new MouseEvent("pointerup", { bubbles: true })); + minimap.render(); + + // The camera is now well outside the frames, so the union — and with it the + // scale — has to have moved on. + expect(chip()).not.toBe(frozen); + }); + + it("centres on the rect it draws, docks and all", () => { + // The indicator is drawn from `visibleSafeRect` and `centerOn` aims at the + // same box. Drawn from the full canvas rect instead, the two disagreed by + // half the open docks' width — a constant drift between where you pressed + // and where the camera landed. + inset = { left: 280, right: 0 }; + minimap.render(); + const before = indicator(); + // Outside the box, so this is a jump rather than a grab — a jump is the + // gesture that has to land exactly where it was aimed. + const target = before.left + before.width + 20; + press(target, before.top + before.height / 2); + minimap.render(); + + const after = indicator(); + expect(after.left + after.width / 2).toBeCloseTo(target, 0); + }); +}); diff --git a/packages/overlay/src/canvas/minimap.ts b/packages/overlay/src/canvas/minimap.ts new file mode 100644 index 0000000..e4444b7 --- /dev/null +++ b/packages/overlay/src/canvas/minimap.ts @@ -0,0 +1,381 @@ +/** + * A small map of the whole canvas, and a way to move around it. + * + * The canvas is infinite and until now nothing on screen said where on it you + * were. Pan away from your frames and there was no affordance pointing back — + * only ⇧1, which answers the question by throwing away the zoom level you were + * working at. This is the cheap continuous answer: everything you have, at a + * glance, with a box showing the part you are looking at, draggable. + * + * **Rectangles, not thumbnails.** Every frame is a live same-origin `iframe` + * running a full instance of the user's app. There is no paint capture anywhere + * in the overlay and no way to add one cheaply — `FrameAgent` exposes DOM, not + * pixels — an `iframe` cannot be duplicated, and cloning one would boot a ninth + * app against a cap of eight. So a frame is drawn the way `ChromeLayer` draws + * everything else: a positioned `div` with the numbers written into it. + * + * **The bounds include where you are looking**, not just where the frames are, + * and that is the difference between a map and a decoration. Projecting the + * frames alone means the indicator slides off the card the moment you pan past + * them — exactly when a map is the only thing that could help. The cost is that + * the projection rescales while you are outside your content; inside it, which + * is the common case, the frames' union dominates and the map holds still. + * + * **The card cannot be dismissed.** It used to carry a close button, with the + * only way back a checkbox under the zoom readout — no shortcut, no palette, + * and a README that documented the hiding and not the restoring. A control + * whose off state is discoverable and whose on state is not is a trap, and the + * map is small enough that nothing was bought by allowing it. It is furniture + * now: always on the canvas stage, still stood down under 900px where it would + * collide with the bar, and still skipped in edit mode by its host. + * + * **Accessibility.** The projection is `aria-hidden` and nothing in it takes + * focus. It is a pointer-only enhancement, and everything it does is reachable + * without it: ⇧1 fits, ⇧2 zooms to the selection, and the frame list beside it + * is a real keyboard-navigable list of the same frames. A draggable + * `role="application"` region here would be a worse answer pretending to be a + * better one. + */ + +import { cls, el } from "../dom"; +import { clamp } from "../num"; +import { MINIMAP_H, MINIMAP_PAD, MINIMAP_W } from "../styles/const"; +import type { FrameManager } from "./frames"; +import { + type Point, + projectInto, + type Rect, + screenToWorld, + unionRects, + type Viewport, + worldRectToScreen, +} from "./space"; +import type { CanvasViewport } from "./viewport"; + +/** The projection box, as a rect — the origin every placement is measured from. */ +const BOX: Rect = { height: MINIMAP_H, left: 0, top: 0, width: MINIMAP_W }; + +/** + * How the world maps into the card. + * + * Split out as a pure function because it is the whole of the geometry and none + * of the DOM: everything that can be wrong about a minimap is wrong in here, + * and this way it can be asserted directly rather than through a rendered card + * under a DOM implementation that does no layout. + * + * Total, with no failure case. `seen` is always in the union, so the bounds can + * never be empty the way `unionRects` alone can be — an empty canvas projects + * the viewport by itself, and a viewport that has not been laid out yet is a + * zero box, which `projectInto` answers with the identity rather than a + * division by nothing. + */ +export function minimapProjection( + frameRects: Rect[], + seen: Rect +): { bounds: Rect; map: Viewport } { + // biome-ignore lint/style/noNonNullAssertion: the list always has `seen` in it. + const bounds = unionRects([...frameRects, seen])!; + return { bounds, map: projectInto(bounds, BOX, MINIMAP_PAD) }; +} + +export interface MinimapDeps { + frames: FrameManager; + viewport: CanvasViewport; +} + +/** + * A drag in flight. + * + * Both fields exist to stop the gesture changing shape underneath itself. + * + * `map` is a *snapshot*. The live projection is recomputed on every rendered + * frame from bounds that include where you are looking, so panning changes the + * scale, which changes how far the next pointer move travels — a stationary + * pointer on a rescaling map is the rubber-banding this fixes. Frozen for the + * length of the gesture, one pixel of pointer means the same distance from + * press to release. + * + * `grab` is where inside the indicator you took hold of it, in card pixels. + * Without it every move re-centres the box on the cursor, so grabbing an edge + * snaps the view by half a box before you have moved at all. Holding the offset + * is what makes the indicator track the pointer instead of jumping to it — the + * behaviour Photoshop's Navigator has always had, and the one VS Code's minimap + * grew in microsoft/vscode#64459. A press *outside* the indicator has no offset + * to keep: it means "go there", so it centres and then tracks from zero. + */ +interface MinimapDrag { + grab: Point; + map: Viewport; +} + +export class Minimap { + readonly element: HTMLElement; + + private readonly body: HTMLElement; + private readonly view: HTMLElement; + /** One chip per frame, keyed by id — see `render`. */ + private readonly chips = new Map(); + private readonly deps: MinimapDeps; + + /** The live projection, kept so a pointer can be mapped back through it. */ + private map: Viewport | null = null; + /** Where the indicator was last drawn, in card px — what `onPress` hit-tests. */ + private viewRect: Rect | null = null; + private drag: MinimapDrag | null = null; + + constructor(deps: MinimapDeps) { + this.deps = deps; + this.view = el("div", { class: cls("minimap-view") }); + this.body = el( + "div", + { "aria-hidden": "true", class: cls("minimap-body") }, + [this.view] + ); + this.element = el( + "div", + { + "aria-label": "Canvas minimap", + class: cls("minimap"), + role: "group", + }, + [this.body] + ); + this.bind(); + } + + mount(host: HTMLElement): void { + host.append(this.element); + } + + /** + * Redraw. Called from the stage's `notify`, which the viewport already + * coalesces to one call per animation frame — so this is the per-frame budget + * and does no scheduling of its own. The stage skips it entirely in edit + * mode, where the host is hidden. + * + * Structure is rebuilt only when the *set* of frames changes; a pan or a zoom, + * many times a second, takes the placement path alone. Same bargain + * `FrameChrome.render` makes, and for the same reason. + */ + render(): void { + const { frames, viewport } = this.deps; + /* + * The *uncovered* canvas, not the whole of it. + * + * This is what `centerOn` aims at, and the indicator has to be drawn from + * the same rect or pressing the map moves the camera somewhere other than + * where the box says you asked for — a constant drift the width of whichever + * docks are open. See `CanvasViewport.visibleSafeRect`. + */ + const seen = viewport.visibleSafeRect; + // Frozen mid-drag. `minimapProjection` folds `seen` into its bounds, so + // recomputing here would rescale the map as the gesture moved it. + const map = + this.drag?.map ?? minimapProjection(frames.worldRects(), seen).map; + this.map = map; + this.syncChips(); + const activeId = frames.active?.id ?? null; + for (const frame of frames.all) { + const chip = this.chips.get(frame.id); + if (!chip) { + continue; + } + place( + chip, + worldRectToScreen(map, BOX, { + height: frame.height, + left: frame.x, + top: frame.y, + width: frame.width, + }) + ); + chip.classList.toggle(cls("minimap-frame-on"), frame.id === activeId); + } + this.viewRect = worldRectToScreen(map, BOX, seen); + place(this.view, this.viewRect); + } + + destroy(): void { + this.element.remove(); + this.chips.clear(); + } + + // -- Internals --------------------------------------------------------------- + + /** Add and remove chips so the map's set matches the canvas's. */ + private syncChips(): void { + const wanted = new Set(this.deps.frames.all.map((f) => f.id)); + for (const [id, chip] of this.chips) { + if (!wanted.has(id)) { + chip.remove(); + this.chips.delete(id); + } + } + for (const frame of this.deps.frames.all) { + if (this.chips.has(frame.id)) { + continue; + } + const chip = el("div", { + class: cls("minimap-frame"), + "data-frame": frame.id, + }); + this.chips.set(frame.id, chip); + // Before the indicator, so the box showing where you are always paints + // over the frames it is standing on rather than under whichever one was + // added last. + this.view.before(chip); + } + } + + private bind(): void { + this.body.addEventListener("pointerdown", (e) => this.onPress(e)); + this.body.addEventListener("pointermove", (e) => this.onMove(e)); + this.body.addEventListener("pointerup", (e) => this.onRelease(e)); + this.body.addEventListener("pointercancel", (e) => this.onRelease(e)); + this.body.addEventListener("dblclick", (e) => this.onDoublePress(e)); + } + + /** + * Take hold of the map. + * + * Two gestures share one press, decided here and then not revisited: + * + * - **Inside the indicator** — a grab. The offset from the box's centre to + * the cursor is kept, so the box travels with the pointer rather than + * snapping its middle to it. Re-centring on every move is what made this + * feel over-sensitive: it turned a grab near the edge into an instant jump + * of half a box before the pointer had travelled at all. + * - **Anywhere else** — "go there". No offset to keep, so the press centres + * the view on that point and the drag continues from zero. This is what + * keeps the map usable at a wide zoom-out, where the indicator is a few + * pixels across and demanding a hit on it would be hostile. + * + * Pressing on a frame also selects it, which is the same rule a press inside + * a live frame already follows (see `__airshipOnFramePress` in + * `shell-app.ts`) — but a press on open canvas leaves the selection alone, + * because it is not a deselect gesture, it is a pan. + */ + private onPress(e: PointerEvent): void { + if (e.button !== 0 || !this.map) { + return; + } + // Otherwise the press begins a text selection that survives the drag. + e.preventDefault(); + const id = frameIdOf(e.target); + if (id) { + this.deps.frames.setActive(id); + } + const at = this.cardPoint(e); + const box = this.viewRect; + const inside = + box !== null && + at.x >= box.left && + at.x <= box.left + box.width && + at.y >= box.top && + at.y <= box.top + box.height; + this.drag = { + grab: + inside && box + ? { + x: at.x - (box.left + box.width / 2), + y: at.y - (box.top + box.height / 2), + } + : { x: 0, y: 0 }, + map: this.map, + }; + this.body.setPointerCapture(e.pointerId); + this.goTo(e); + } + + private onMove(e: PointerEvent): void { + if (this.drag) { + this.goTo(e); + } + } + + private onRelease(e: PointerEvent): void { + if (!this.drag) { + return; + } + this.drag = null; + if (this.body.hasPointerCapture(e.pointerId)) { + this.body.releasePointerCapture(e.pointerId); + } + // Every other pan persists on settle; this one is no different. + this.deps.viewport.save(); + } + + /** Double-click a frame to zoom to it — the map's one magnifying gesture. */ + private onDoublePress(e: PointerEvent | MouseEvent): void { + const id = frameIdOf(e.target); + const frame = id ? this.deps.frames.byId(id) : null; + if (!frame) { + return; + } + this.deps.viewport.fitToRect({ + height: frame.height, + left: frame.x, + top: frame.y, + width: frame.width, + }); + this.deps.viewport.save(); + } + + /** + * Put the indicator where the pointer has carried it. + * + * The target is the cursor less the grab offset — the point the box's *centre* + * should land on — clamped to the card. Clamping is what bounds the gesture: + * pointer capture means a drag continues past the card's edge, and without it + * a flick off the side would pan into empty space with nothing left on the map + * to steer back by. Inside the card the clamp never fires, so it costs the + * common case nothing. + */ + private goTo(e: PointerEvent): void { + const { drag } = this; + if (!drag) { + return; + } + const r = this.body.getBoundingClientRect(); + const at = this.cardPoint(e); + const target = { + x: clamp(at.x - drag.grab.x, 0, r.width), + y: clamp(at.y - drag.grab.y, 0, r.height), + }; + this.deps.viewport.centerOn( + screenToWorld( + drag.map, + { height: r.height, left: 0, top: 0, width: r.width }, + target + ) + ); + } + + /** + * A pointer event in the card's own pixels. + * + * The card's rect is read from the browser rather than derived, for the reason + * `frameScreenRect` gives: it already carries wherever the element happens to + * sit, including any future ancestor transform, and cannot drift out of step + * with the CSS the way a re-derived offset would. + */ + private cardPoint(e: PointerEvent): Point { + const r = this.body.getBoundingClientRect(); + return { x: e.clientX - r.left, y: e.clientY - r.top }; + } +} + +/** Which frame a node in the map belongs to, if any. */ +function frameIdOf(target: EventTarget | null): string | null { + return target instanceof Element + ? (target.closest(`.${cls("minimap-frame")}`)?.getAttribute("data-frame") ?? + null) + : null; +} + +function place(node: HTMLElement, rect: Rect): void { + node.style.left = `${rect.left}px`; + node.style.top = `${rect.top}px`; + node.style.width = `${Math.max(1, rect.width)}px`; + node.style.height = `${Math.max(1, rect.height)}px`; +} diff --git a/packages/overlay/src/chat/change-chips.ts b/packages/overlay/src/chat/change-chips.ts index e0f0c9f..cdf161c 100644 --- a/packages/overlay/src/chat/change-chips.ts +++ b/packages/overlay/src/chat/change-chips.ts @@ -36,7 +36,9 @@ export interface ChangeChip { export function renderChangeChips( host: HTMLElement, chips: ChangeChip[], - onDiscardAll?: () => void + // Handed its own button so the caller can anchor a confirm menu on it — + // this is the bulk path with no journal entry behind it. + onDiscardAll?: (anchor: HTMLElement) => void ): void { for (const chip of chips) { host.append( @@ -63,18 +65,17 @@ export function renderChangeChips( } if (onDiscardAll && chips.length > 1) { - host.append( - el( - "button", - { - class: `${cls("sel-chip")} ${cls("chip-all")}`, - "data-tip": "Discard every pending change", - onClick: onDiscardAll, - type: "button", - }, - [icon("close", "sm"), el("span", { text: "Discard all" })] - ) + const all = el( + "button", + { + class: `${cls("sel-chip")} ${cls("chip-all")}`, + "data-tip": "Discard every pending change", + type: "button", + }, + [icon("close", "sm"), el("span", { text: "Discard all" })] ); + all.addEventListener("click", () => onDiscardAll(all)); + host.append(all); } } diff --git a/packages/overlay/src/dnd/manager.ts b/packages/overlay/src/dnd/manager.ts index 47ea680..a9a44ab 100644 --- a/packages/overlay/src/dnd/manager.ts +++ b/packages/overlay/src/dnd/manager.ts @@ -46,6 +46,8 @@ export const DND = { frameGrip: "airship:frame-grip", /** Dragging a frame's title bar to reposition it on the canvas. */ frameMove: "airship:frame-move", + /** Dragging a row of the frame list to restack the frames. */ + frameRow: "airship:frame-row", resizeHandle: "airship:resize-handle", scrub: "airship:scrub", splitter: "airship:splitter", @@ -89,6 +91,38 @@ export const FEEDBACK = { none: [Feedback.configure({ feedback: "none" })] as Plugins, }; +/** + * Sensors for a draggable that must not offer a keyboard drag. + * + * A `feedback: "none"` draggable **cannot** be dragged by keyboard, and the + * failure is silent and hostile. `KeyboardSensor.handleMove` returns early on + * `!shape`, and the only thing that ever sets `dragOperation.shape` is the + * Feedback plugin — which returns before that line for `feedback: "none"`. So + * the sensor still *starts* a drag on Space and still ends one on Space, Enter + * or Tab, but every arrow key in between does nothing at all. + * + * What the user gets is worse than "nothing happens": the row latches into its + * dragging state, the Accessibility plugin has already announced the handle as + * `aria-roledescription="draggable"`, and the sensor's document-capture listener + * calls `preventDefault` on Tab — so the one key that should let you leave ends + * the phantom drag *and* eats the focus move. Unregistering the sensor for these + * draggables is what stops a promise being made that nothing can keep; the + * keyboard route is then a real one, next to the drag rather than pretending to + * be it (see `FramesPanel.moveBy`, and `num-field.ts`'s `stepBy` beside its + * scrub). + * + * The pointer constraint has to be restated because a per-draggable `sensors` + * array *replaces* the manager's list rather than extending it — omitted, every + * press on a handle would begin a drag with no threshold at all. + */ +export const POINTER_ONLY = [ + PointerSensor.configure({ + activationConstraints: [ + new PointerActivationConstraints.Distance({ value: DRAG_THRESHOLD }), + ], + }), +]; + /** * Cumulative pointer delta for a transform-only drag (resize grip, scrub, dock * splitter). diff --git a/packages/overlay/src/dock-gate.test.ts b/packages/overlay/src/dock-gate.test.ts new file mode 100644 index 0000000..d570d24 --- /dev/null +++ b/packages/overlay/src/dock-gate.test.ts @@ -0,0 +1,82 @@ +/** + * Which docks exist in which mode. + * + * Three booleans, and every one of them was a bug waiting to happen. + * + * `open` is the *user's* state and the mode is laid over it, never written into + * it. Collapsing the inspector on the way into view mode would have been a line + * shorter and would have quietly discarded whether it had been open — so a + * round trip through view mode is asserted directly, because that is the part + * that is easy to get wrong and impossible to notice until someone complains + * that their panel keeps closing. + * + * `modeScoped` is what keeps the inline overlay out of it. Edit and view mean + * different things on the two stages: on the canvas, view mode has a frame list + * and a map to put in the place of the two element-scoped panels, so giving + * them up is a trade. Inline has neither, so the same rule would take the + * inspector away and put nothing there. + * + * Tested as a free function rather than through `AirshipApp`, which would mean + * a socket, a dnd-kit manager, a `DesignPanel` and a live document to check + * three booleans. + */ + +import { describe, expect, it } from "vitest"; +import { dockVisible } from "./app"; + +/** The canvas: view mode swaps the panels, so the gate is live. */ +function canvas(side: "left" | "right", open: boolean, editing: boolean) { + return dockVisible({ editing, modeScoped: true, open, side }); +} + +/** Inline: nothing to swap in, so the gate must never fire. */ +function inline(side: "left" | "right", open: boolean, editing: boolean) { + return dockVisible({ editing, modeScoped: false, open, side }); +} + +describe("dockVisible on the canvas", () => { + it("shows both panels while editing", () => { + expect(canvas("left", true, true)).toBe(true); + expect(canvas("right", true, true)).toBe(true); + }); + + it("takes the inspector away in view mode", () => { + // It is scoped to an element selection, and view mode has none by + // construction — so it was offering controls that could not do anything. + expect(canvas("right", true, false)).toBe(false); + }); + + it("keeps the left dock in view mode, because it has something else to show", () => { + expect(canvas("left", true, false)).toBe(true); + }); + + it("never overrides a panel the user closed", () => { + for (const editing of [true, false]) { + expect(canvas("left", false, editing)).toBe(false); + expect(canvas("right", false, editing)).toBe(false); + } + }); + + it("gives the inspector back exactly as it was found", () => { + // The round trip, both ways. The mode is a second term over `open`, never a + // write to it, so this holds without the app remembering anything. + const wasOpen = true; + expect(canvas("right", wasOpen, false)).toBe(false); + expect(canvas("right", wasOpen, true)).toBe(wasOpen); + + const wasClosed = false; + expect(canvas("right", wasClosed, false)).toBe(false); + expect(canvas("right", wasClosed, true)).toBe(wasClosed); + }); +}); + +describe("dockVisible inline", () => { + it("is the open flag and nothing else, in either mode", () => { + for (const side of ["left", "right"] as const) { + for (const editing of [true, false]) { + expect(inline(side, true, editing)).toBe(true); + expect(inline(side, false, editing)).toBe(false); + } + } + }); +}); diff --git a/packages/overlay/src/shell-app.ts b/packages/overlay/src/shell-app.ts index 00ea3bd..764b8e8 100644 --- a/packages/overlay/src/shell-app.ts +++ b/packages/overlay/src/shell-app.ts @@ -2,6 +2,8 @@ import type { AirshipWindowConfig } from "@airship/protocol"; import { AirshipApp, type Stage } from "./app"; import { FrameChrome } from "./canvas/frame-chrome"; import { type Frame, FrameManager } from "./canvas/frames"; +import { FramesPanel } from "./canvas/frames-panel"; +import { Minimap } from "./canvas/minimap"; import { frameScreenRect, type Point, type Rect } from "./canvas/space"; import { CanvasViewport, type SafeInset } from "./canvas/viewport"; import { @@ -38,6 +40,8 @@ class CanvasStage implements Stage { private readonly canvas: CanvasViewport; private readonly frames: FrameManager; private readonly chrome: FrameChrome; + private readonly minimap: Minimap; + private readonly framesPanel: FramesPanel; private readonly listeners: (() => void)[] = []; /** Subscribers to the trailing edge of a pan/zoom — see `isGesturing`. */ private readonly gestureEndListeners: (() => void)[] = []; @@ -79,6 +83,14 @@ class CanvasStage implements Stage { storageKey: `${key}:frames`, world: this.canvas.world, }); + this.minimap = new Minimap({ + frames: this.frames, + viewport: this.canvas, + }); + this.framesPanel = new FramesPanel({ + frames: this.frames, + viewport: this.canvas, + }); this.chrome = new FrameChrome({ frames: this.frames, inCanvas: (point) => this.canvas.contains(point), @@ -306,6 +318,17 @@ class CanvasStage implements Stage { this.chrome.mountFrameTools(host); } + /** The left dock's view-mode body. */ + mountFramesPanel(host: HTMLElement): void { + host.append(this.framesPanel.element); + this.framesPanel.render(); + } + + /** The bottom-right corner. */ + mountMinimap(host: HTMLElement): void { + this.minimap.mount(host); + } + bindFramePress(report: (at: Point, mods: Mods, dbl: boolean) => void): void { this.reportFramePress = report; } @@ -429,6 +452,12 @@ class CanvasStage implements Stage { // visible but inert in edit. See the note above `FrameChrome.setEditing`. this.frames.setEditing(on); this.chrome.setEditing(on); + if (!on) { + // Coming into view mode, both have been ignoring every change since the + // last time they were on screen and are showing a stale canvas. + this.minimap.render(); + this.framesPanel.render(); + } } relayout(): void { @@ -461,12 +490,38 @@ class CanvasStage implements Stage { } private onFramesChanged(): void { + this.pruneFrameUnsubs(); this.frames.updateMounts(this.canvas.rect); this.chrome.render(); this.notify(); this.save(); } + /** + * Drop the layout subscriptions of frames that are gone. + * + * `onFrameReady` writes one entry per frame and nothing ever removed them, so + * a deleted frame left its unsubscriber in the map — and that closure holds + * the frame's `FrameAgent`, which holds that frame's `window`. The realm the + * delete was supposed to destroy stayed reachable for the rest of the + * session, and with a cap of eight frames you can churn through a lot of + * them. + * + * Calling the disposer rather than only forgetting it: the agent's own + * listener list is in the frame's realm, and while that realm is being torn + * down anyway it costs nothing to leave it tidy — and this same path runs for + * a frame that was merely *replaced*, where the realm is very much alive. + */ + private pruneFrameUnsubs(): void { + const live = new Set(this.frames.all.map((f) => f.id)); + for (const [id, off] of this.frameUnsubs) { + if (!live.has(id)) { + off(); + this.frameUnsubs.delete(id); + } + } + } + /** * A frame published its agent — on first load, and again after every HMR full * reload, which rebuilds the frame's realm from scratch. @@ -484,7 +539,21 @@ class CanvasStage implements Stage { this.notify(); } + /** + * Everything that has to be re-read after the canvas moved or its frames + * changed. + * + * The two view-mode surfaces are redrawn from here rather than subscribing + * through `onLayoutChange` like the app's own chrome does, because the gate + * belongs here: they are hidden in edit mode, this fires on every frame of + * every pan, and a subscriber cannot see the mode. `setEditing` catches them + * up on the way back. + */ private notify(): void { + if (!this.editing) { + this.minimap.render(); + this.framesPanel.render(); + } for (const cb of this.listeners) { cb(); } diff --git a/packages/overlay/src/styles/const.ts b/packages/overlay/src/styles/const.ts index adb278e..31830e8 100644 --- a/packages/overlay/src/styles/const.ts +++ b/packages/overlay/src/styles/const.ts @@ -40,3 +40,45 @@ export const ROOT = `#${PREFIX}-root`; * application in the dependency graph of every control story. */ export const MIN_DOCK_W = 280; + +/** + * The minimap's projection box, in CSS px, and the margin held inside it. + * + * Here for the same reason `MIN_DOCK_W` is, one clause stronger. The dock width + * is a number the stylesheet and the clamp merely have to *agree* on; this one + * is a number the stylesheet and the arithmetic have to be the *same* on. The + * minimap projects the world into this box with `projectInto` and then writes + * the results as inline `left`/`top`/`width`/`height`, so a stylesheet that + * disagreed by a pixel would not misalign the card — it would draw every frame + * in the wrong place inside it, and nothing would report it. + * + * Fixed rather than measured, which also buys the tests: the projection is + * pure arithmetic over these constants, so it can be asserted under happy-dom + * without stubbing a layout that happy-dom does not do. + */ +export const MINIMAP_W = 208; +export const MINIMAP_H = 136; + +/** + * Breathing room between the projected content and the card's edge. + * + * Not cosmetic: the viewport indicator is drawn as a 1px-bordered box, and at + * the exact fit it would land flush against the card's own border and read as + * part of it. + */ +export const MINIMAP_PAD = 10; + +/** + * The widest a tooltip may be. + * + * Narrow enough to fit inside the narrowest dock, which is the constraint that + * picks the number. `Tooltips.bounds()` clamps to the enclosing dock with a 6px + * margin either side, and `clamp` resolves a min above its max to the *max* — so + * a tip as wide as `MIN_DOCK_W` gets shoved off the panel's left edge by the very + * clamp that exists to contain it. 260 + 12 keeps that impossible. + * + * It is also the right measure. At `--ap-font-size-body` (11px Inter) the 242px + * of content inside the padding and border runs about 43 characters — the bottom + * of the 45-75 band, which is where micro-copy shown for half a second belongs. + */ +export const TIP_MAX_W = 260; diff --git a/packages/overlay/src/styles/docks.css.ts b/packages/overlay/src/styles/docks.css.ts index 8908ad8..9fa0db0 100644 --- a/packages/overlay/src/styles/docks.css.ts +++ b/packages/overlay/src/styles/docks.css.ts @@ -30,6 +30,14 @@ export const css = ` \`.hidden\`'s \`display: none !important\` still outranks it when the mode hides the host. */ .${PREFIX}-bar-frame-tools { display: contents; } +/* Same bargain for the Apply/Discard pair: the outer host is mode-hidden by + syncBar, the inner group is pending-hidden by syncApplyGroup — one element + per owner, so neither clobbers the \`hidden\` the other wrote. */ +.${PREFIX}-bar-apply-host, +.${PREFIX}-bar-apply-group { display: contents; } +/* And once more for the job chip: the host is mode-hidden by \`syncBar\`, the + chip inside is state-hidden by \`syncJobChip\`. */ +.${PREFIX}-bar-job-host { display: contents; } /* Inline has no stage controls, and a separator with nothing after it is just a stub of hairline hanging off the mode toggle. Scoped to \`bar-sep-tools\` — the one that divides the mode toggle from the stage slot — rather than to every @@ -38,6 +46,22 @@ export const css = ` .${PREFIX}-bar-bare .${PREFIX}-bar-sep-tools, .${PREFIX}-bar-bare .${PREFIX}-bar-tools { display: none; } +/* "Working" — view mode's one word about a running job. + + Borrows \`.dot\` and its pulse from the transcript rather than restating them, + so the thing in the bar and the status inside the assistant bubble are + visibly one state rather than two things that happen to agree. Sized against + \`.tool\` so it sits in the row without changing the bar's height. */ +.${PREFIX}-bar-job { + display: inline-flex; align-items: center; gap: 6px; + height: 26px; padding: 0 9px; margin-left: 2px; + border: none; border-radius: var(--ap-radius-xs); + background: var(--ap-surface-active); color: var(--ap-text-secondary); + font-size: var(--ap-font-size-label); cursor: pointer; + transition: background var(--ap-motion-dur-micro) var(--ap-motion-ease); +} +.${PREFIX}-bar-job:hover { background: var(--ap-surface-selected); color: var(--ap-text-primary); } + /* Edit/View mode segmented toggle — compact, restrained, border over shadow. */ .${PREFIX}-seg-group { display: inline-flex; align-items: center; gap: 2px; padding: 2px; @@ -73,6 +97,25 @@ export const css = ` .${PREFIX}-dock-left { left: var(--ap-space-md); width: var(--${PREFIX}-left-w, 340px); } .${PREFIX}-dock-right { right: var(--ap-space-md); width: var(--${PREFIX}-right-w, 360px); } +/* A swappable dock body — the chat and the frame list share the left dock, one + per mode (see \`AirshipApp.syncDocks\`). + + \`display: contents\` and not a box of its own, which is load-bearing twice + over. The dock is a flex column whose transcript takes the remaining height; + a real wrapper would take that height instead and leave the composer + floating in the middle. And the past-chats drawer is \`inset: 0\` against the + dock, so a wrapper with a box would become its containing block and shrink it + to whatever the chat happened to measure. \`.hidden\`'s + \`display: none !important\` still outranks this, which is the whole point — + same bargain \`.bar-frame-tools\` makes in the bar. */ +.${PREFIX}-dock-body { display: contents; } + +/* The minimap's slot. Nothing but a mode gate: the card inside is + \`position: fixed\` and places itself, so this element has no geometry to + contribute and only exists so the app can hide the stage's content without + writing to a class the stage also writes to. */ +.${PREFIX}-minimap-host { display: contents; } + /* Torn off its edge and floating. Position and height come from three more custom properties written by \`applyPlacement\`, and the collapsed pill reads the same three — which is what @@ -203,18 +246,4 @@ ${ROOT} .${PREFIX}-tool-on .${PREFIX}-ic { --${PREFIX}-ic-tone: var(--ap-text-pr twin, and the mark is symmetric about its vertical axis, so the flip is exact rather than approximate — cheaper and more honest than hand-authoring a near-copy into \`icons.ts\`'s \`LEGACY\` block. */ -.${PREFIX}-bar-redo .${PREFIX}-ic { transform: scaleX(-1); } - -/* Tooltip. Sits above everything, carries its own shortcut hint. */ -.${PREFIX}-tip { - position: absolute; z-index: ${Z}; pointer-events: none; - display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; - max-width: 280px; padding: 4px 8px; - background: var(--ap-surface-selected); color: var(--ap-text-primary); - border: 1px solid var(--ap-border-default); border-radius: var(--ap-radius-xs); - box-shadow: var(--ap-elevation-floating); - font-family: var(--ap-font-sans); font-size: var(--ap-font-size-body); line-height: 1.5; -} -.${PREFIX}-tip-key { - font-family: var(--ap-font-mono); color: var(--ap-text-tertiary); -}`; +.${PREFIX}-bar-redo .${PREFIX}-ic { transform: scaleX(-1); }`; diff --git a/packages/overlay/src/styles/frames-panel.css.ts b/packages/overlay/src/styles/frames-panel.css.ts new file mode 100644 index 0000000..f03565f --- /dev/null +++ b/packages/overlay/src/styles/frames-panel.css.ts @@ -0,0 +1,151 @@ +import { PREFIX } from "../dom"; + +/** + * The frame list — the left dock's view-mode body. + * + * Written against the same measures as the chat panel it shares a dock with, so + * switching modes does not move the panel's edges or change its rhythm: the bar + * across the top matches the composer's padding, and a row is the same height + * as an inspector control. + * + * The row is a three-column grid rather than a flex row, and that is what makes + * a long device name shorten instead of pushing the size readout out of the + * panel — \`minmax(0, 1fr)\` on the middle column is the whole mechanism. + */ +export const css = ` +.${PREFIX}-fp { display: flex; flex-direction: column; min-height: 0; flex: 1; } + +/* Count and add, across the top. The count is not decoration: the cap is eight + and nothing else on screen says so until you hit it and get a toast. */ +.${PREFIX}-fp-bar { + display: flex; align-items: center; justify-content: space-between; + gap: var(--ap-space-sm); + padding: var(--ap-space-sm) var(--ap-space-md); + border-bottom: 1px solid var(--ap-border-subtle); +} +.${PREFIX}-fp-count { + font-size: var(--ap-font-size-label); color: var(--ap-text-tertiary); + letter-spacing: .02em; +} +.${PREFIX}-fp-add { + display: inline-flex; align-items: center; justify-content: center; + width: 22px; height: 22px; padding: 0; + border: none; border-radius: var(--ap-radius-xs); + background: transparent; color: var(--ap-text-secondary); cursor: pointer; + transition: background var(--ap-motion-dur-micro) var(--ap-motion-ease); +} +.${PREFIX}-fp-add:hover:not(:disabled) { + background: var(--ap-surface-hover); color: var(--ap-text-primary); +} +.${PREFIX}-fp-add:disabled { opacity: .4; cursor: default; } + +.${PREFIX}-fp-scroll { + flex: 1; min-height: 0; overflow-y: auto; + padding: var(--ap-space-xs) var(--ap-space-sm); +} + +/* The list is the drop line's containing block, and it has to be: an absolutely + positioned box is placed against its containing block's *padding* box, so with + the scroller in that role the line was offset by the scroller's own + \`padding-top\` — measured from the list, drawn from the padding edge, one + \`--ap-space-xs\` too high on every row. Being the list also means the line's + left and right edges are the rows' own, with nothing to restate. */ +.${PREFIX}-fp-list { position: relative; } + +/* The whole row is the drag target (see \`buildRow\`), but the cursor stays what + each part of it does: \`fp-pick\` selects and shows a pointer, \`fp-more\` opens + a menu. A \`grab\` here would be painted only in the gaps between those two — + \`fp-pick\` covers most of the row and sets its own — so it would read as a + rendering fault rather than as an affordance. The grip is the visual signal, + the way it is in every list of this shape. */ +.${PREFIX}-fp-row { + display: grid; grid-template-columns: auto minmax(0, 1fr) auto; + align-items: center; gap: 2px; + border-radius: var(--ap-radius-xs); + transition: background var(--ap-motion-dur-micro) var(--ap-motion-ease); +} +.${PREFIX}-fp-row:hover { background: var(--ap-surface-hover); } +/* Blue, matching the canvas. + + The active frame is outlined in \`--ap-primary\` and its title goes blue with + it (\`canvas.css.ts\`'s \`.fc-active\`), while this row was \`--ap-surface-selected\` + — a flat grey. Two surfaces showing the same fact in two colours, and the + panel's was the one that did not look like a selection at all: grey is also + what \`:hover\` gives, one token apart. \`--ap-primary-bg\` is the established + "this is the active one" fill (\`controls.css.ts\`'s pad modes, + \`inspector.css.ts\`), which keeps the grammar \`guide-overlay.ts\` states — + blue is what you are pointing at. */ +.${PREFIX}-fp-row-on { background: var(--ap-primary-bg); } +/* Faded rather than moved: the row stays where it is for the whole drag and the + drop line does the reporting, so the list cannot reflow under the pointer. */ +.${PREFIX}-fp-row-drag { opacity: .4; } + +/* Revealed on hover — and on focus, which is not symmetry for its own sake. + dnd-kit makes this a real tab stop (see \`buildRow\`), so a hover-only reveal + would leave a keyboard user landing on a control that is not painted. + + No longer the drag *target* — the whole row is — but still the drag + affordance: it is what says the row can be picked up at all, and it is the + only keyboard route to a restack, because \`POINTER_ONLY\` unregisters the + keyboard sensor and \`onGripKey\` takes its place. */ +.${PREFIX}-fp-grip { + display: inline-flex; align-items: center; justify-content: center; + width: 16px; color: var(--ap-text-tertiary); + cursor: grab; opacity: 0; + transition: opacity var(--ap-motion-dur-micro) var(--ap-motion-ease); +} +.${PREFIX}-fp-row:active .${PREFIX}-fp-grip { cursor: grabbing; } +.${PREFIX}-fp-row:hover .${PREFIX}-fp-grip, +.${PREFIX}-fp-grip:focus-visible { opacity: 1; } + +/* The row's own hit target. Transparent and borderless because the row behind + it carries the surface — a nested button with its own background would paint + a second rectangle inside the first. */ +.${PREFIX}-fp-pick { + display: grid; grid-template-columns: auto minmax(0, 1fr) auto; + align-items: center; gap: var(--ap-space-sm); + min-width: 0; padding: 6px 4px; + border: none; background: transparent; cursor: pointer; text-align: left; + color: var(--ap-text-secondary); font: inherit; +} +.${PREFIX}-fp-row-on .${PREFIX}-fp-pick { color: var(--ap-text-primary); } +/* The name carries the blue, mirroring \`.fc-active .fc-name\` on the canvas. The + size stays tertiary: it is a readout, and colouring it too would make the row + read as one blue block rather than as a name that is selected. */ +.${PREFIX}-fp-row-on .${PREFIX}-fp-name { color: var(--ap-primary); } + +.${PREFIX}-fp-name { + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; + font-size: var(--ap-font-size-body); +} +/* The editing affordance has to be visible or a double-click looks like it did + nothing — the caret alone is not enough on a one-line label. */ +.${PREFIX}-fp-name-edit { + outline: 1px solid var(--ap-primary); outline-offset: 2px; + border-radius: 2px; cursor: text; +} +.${PREFIX}-fp-dims { + font-family: var(--ap-font-mono); font-size: var(--ap-font-size-label); + color: var(--ap-text-tertiary); white-space: nowrap; +} + +.${PREFIX}-fp-more { + display: inline-flex; align-items: center; justify-content: center; + width: 22px; height: 22px; padding: 0; + border: none; border-radius: var(--ap-radius-xs); + background: transparent; color: var(--ap-text-tertiary); + cursor: pointer; opacity: 0; + transition: opacity var(--ap-motion-dur-micro) var(--ap-motion-ease); +} +.${PREFIX}-fp-row:hover .${PREFIX}-fp-more, +.${PREFIX}-fp-more:focus-visible { opacity: 1; } +.${PREFIX}-fp-more:hover { color: var(--ap-text-primary); } + +/* Where the dragged row would land. \`pointer-events: none\` because it tracks + the cursor and would otherwise sit under it, eating the moves that place it. */ +.${PREFIX}-fp-drop { + position: absolute; left: 0; right: 0; + height: 2px; border-radius: 1px; + background: var(--ap-primary); pointer-events: none; +} +`; diff --git a/packages/overlay/src/styles/index.ts b/packages/overlay/src/styles/index.ts index a763e15..9cf169e 100644 --- a/packages/overlay/src/styles/index.ts +++ b/packages/overlay/src/styles/index.ts @@ -9,7 +9,9 @@ import { css as controls } from "./controls.css"; 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 inspector } from "./inspector.css"; +import { css as minimap } from "./minimap.css"; import { css as motion } from "./motion.css"; import { css as pop } from "./pop.css"; import { css as portable } from "./portable.css"; @@ -93,8 +95,15 @@ const CSS = [ base, portable, canvas, + // Canvas furniture, so it sits with the substrate it reports on rather than + // with the docks it borrows its surface recipe from. + minimap, docks, chat, + // The left dock's other body. Beside `chat` because it is the same kind of + // thing — the contents of a panel, not the panel — and the two are never on + // screen together, so the order between them is documentation, not cascade. + framesPanel, inspector, cssPane, // Empty states are surface-agnostic — the same block renders in the chat diff --git a/packages/overlay/src/styles/minimap.css.ts b/packages/overlay/src/styles/minimap.css.ts new file mode 100644 index 0000000..ce49d86 --- /dev/null +++ b/packages/overlay/src/styles/minimap.css.ts @@ -0,0 +1,84 @@ +import { PREFIX } from "../dom"; +import { MINIMAP_H, MINIMAP_W, Z } from "./const"; + +/** + * The canvas minimap — a small card in the bottom-right corner. + * + * The surface recipe is the dock's, not a new one: same panel fill, hairline + * border and card elevation, so the map reads as another piece of the editor's + * furniture rather than something painted onto the canvas. + * + * The box's dimensions come from \`const.ts\` rather than being written here, + * and that is load-bearing. \`minimap.ts\` projects the world into exactly these + * numbers and then writes the results as inline geometry — a stylesheet that + * disagreed by a pixel would not misalign the card, it would misplace every + * frame drawn inside it, silently. + * + * Note the absent \`transition\` on the two positioned children. Everything else + * here may animate; those two are rewritten on every frame of a pan, and an + * eased \`left\` would leave the indicator trailing the canvas it is supposed to + * be reporting. Same rule \`chrome.css.ts\` is held to by \`check-css.mjs\`, for + * the same reason — it is simply not enforceable from here, because the rest of + * this file is legitimately allowed to move. + * + * There is no close button and so no rule for one. The card is furniture: see + * the header of \`minimap.ts\` for why being able to dismiss it was worth less + * than the trap it set. + */ +export const css = ` +.${PREFIX}-minimap { + position: fixed; + right: var(--ap-space-md); bottom: var(--ap-space-md); + z-index: ${Z}; pointer-events: auto; + padding: 4px; border-radius: var(--ap-radius-md); + background: var(--ap-surface-panel); + border: 1px solid var(--ap-border-default); + box-shadow: var(--ap-elevation-card); +} + +/* The projection box. \`cursor: grab\` says the whole surface is draggable, which + it is — pressing anywhere jumps there rather than requiring a hit on an + indicator that is only a few pixels wide when zoomed out. */ +.${PREFIX}-minimap-body { + position: relative; overflow: hidden; + width: ${MINIMAP_W}px; height: ${MINIMAP_H}px; + border-radius: var(--ap-radius-xs); + /* The same fill the canvas itself uses, so the map reads as a scaled copy of + the surface rather than as a panel that happens to have shapes on it. */ + background: var(--ap-surface-canvas); + cursor: grab; touch-action: none; +} +.${PREFIX}-minimap-body:active { cursor: grabbing; } + +/* A frame. Filled rather than outlined: at this scale a 1px border on a 12px + box is most of the box, and the fill is what makes a wall of frames legible + as a shape. */ +.${PREFIX}-minimap-frame { + position: absolute; + background: var(--ap-text-tertiary); + border-radius: 1px; + opacity: .55; +} +.${PREFIX}-minimap-frame-on { + background: var(--ap-primary); + opacity: 1; +} + +/* Where you are looking. Outline over fill, so it reads as a window onto the + frames rather than another one of them — and it sits above them all, which is + why \`syncChips\` inserts new chips *before* it. */ +.${PREFIX}-minimap-view { + position: absolute; + border: 1px solid var(--ap-primary); + border-radius: 1px; + background: var(--ap-primary-bg); + pointer-events: none; +} + +/* The bar is centred at \`bottom: 16px\` and grows with the mode it is in; below + this the two would overlap. The map is the one that gives way — it is the + enhancement, and every one of its functions has a keyboard route. */ +@media (max-width: 900px) { + .${PREFIX}-minimap { display: none; } +} +`; diff --git a/packages/overlay/src/styles/pop.css.ts b/packages/overlay/src/styles/pop.css.ts index 17d3729..ae63d44 100644 --- a/packages/overlay/src/styles/pop.css.ts +++ b/packages/overlay/src/styles/pop.css.ts @@ -1,5 +1,5 @@ import { PREFIX } from "../dom"; -import { Z_POP } from "./const"; +import { TIP_MAX_W, Z_POP } from "./const"; /** * The popover layer: the host, the shared shell, and the menu shape. @@ -15,6 +15,63 @@ export const css = ` .${PREFIX}-pop-host { position: absolute; inset: 0; z-index: ${Z_POP}; pointer-events: none; } +/* The tooltip. Here rather than beside the docks it mostly labels, because + \`Tooltips\` mounts it into the host above and its neighbours are the shells + below it. + + \`z-index: 1\`, and not the global \`Z\`: the host is a stacking context of its + own, so the global scale means nothing inside it. What this orders is the tip + against its *siblings* — the \`.pop\` shells, which carry no z-index and are all + appended after the tip, which is created once when the overlay mounts. Drop + the number and DOM order takes over: the tip paints under every popover ever + opened, which is how it reads on a control inside the colour picker. + + It wraps, and that is the shape of the whole rule. Most tips are one short + line, but a handful carry values the editor did not author — a font stack, a + stylesheet URL, a review comment body — and for those the tip *is* the + untruncated view of a field that already truncated. Ellipsing them throws + away the only thing they were opened for. + + This used to say \`white-space: nowrap\` alongside the same width cap and no + overflow rule at all. Those cannot both hold: the text laid out at its full + intrinsic width while the border, background and shadow painted at the cap, so + from about 45 characters up the label sat outside its own box. It also made + \`offsetWidth\` report the cap rather than the painted width, so the centring in + \`Tooltips.place\` and its dock clamp were both computed from a number that was + never true of anything on screen. */ +.${PREFIX}-tip { + position: absolute; z-index: 1; pointer-events: none; + display: flex; align-items: baseline; gap: 6px; + width: max-content; max-width: ${TIP_MAX_W}px; padding: 4px 8px; + background: var(--ap-surface-selected); color: var(--ap-text-primary); + border: 1px solid var(--ap-border-default); border-radius: var(--ap-radius-xs); + box-shadow: var(--ap-elevation-floating); + font-family: var(--ap-font-sans); font-size: var(--ap-font-size-body); line-height: 1.5; +} +/* Three lines, then an ellipsis. A tip is a label and not a document, and the + interpolated ones have no length bound at all — a comment body is whatever + somebody typed into it. + + \`overflow-wrap: anywhere\` rather than \`break-word\` is for the values with no + spaces to break at, a stylesheet URL being the one that actually turns up: + only \`anywhere\` lowers the min-content width, so the box settles at + \`max-width\` instead of being pushed past it by a single unbreakable token. */ +.${PREFIX}-tip-text { + min-width: 0; + display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; + overflow: hidden; overflow-wrap: anywhere; +} +/* The chord never wraps and never shrinks. It is the one part of a tooltip that + is unreadable if it breaks, so the \`min-width: 0\` above makes the *text* the + item that gives way — the container stays \`flex-wrap: nowrap\`, which is what + keeps the chip on the first line beside a wrapped tip instead of orphaning it + onto a line of its own. \`baseline\` on the container is what sits it on that + first line rather than halfway down the block, and it is also what lines + JetBrains Mono up with Inter at the same size, which \`center\` never did. */ +.${PREFIX}-tip-key { + flex: 0 0 auto; white-space: nowrap; + font-family: var(--ap-font-mono); color: var(--ap-text-tertiary); +} /* The shell is the scroller, because the shell is what carries the cap. \`placePopover\` measures the content and writes a \`max-height\` *here* — and a @@ -83,6 +140,38 @@ export const css = ` padding: 6px 8px 2px; font-family: var(--ap-font-mono); text-transform: uppercase; font-size: var(--ap-font-size-micro); letter-spacing: .6px; color: var(--ap-text-tertiary); } +/* ---- Collapsible group -------------------------------------------------- */ + +/* The long-list answer, next to \`pop-head\`'s short-list one. Written to the same + measures as \`fc-dgroup\` in \`canvas.css.ts\` on purpose: the device list appears + in both menu systems, and two accordions over the same twenty-two rows must + not be visibly different objects. */ +.${PREFIX}-pop-group { display: flex; flex-direction: column; } +.${PREFIX}-pop-group + .${PREFIX}-pop-group { + margin-top: 4px; padding-top: 4px; + border-top: 1px solid var(--ap-border-default); +} +/* Sentence case and body type, not \`pop-head\`'s uppercase mono: these are + section headers in a list you are reading, not the menu's own title. */ +.${PREFIX}-pop-group-head { + display: flex; align-items: center; gap: 6px; width: 100%; + padding: 5px 8px; border: 0; border-radius: var(--ap-radius-xs); + background: transparent; cursor: pointer; text-align: left; + font-family: var(--ap-font-sans); font-size: var(--ap-font-size-label); + color: var(--ap-text-primary); +} +.${PREFIX}-pop-group-head:hover { background: var(--ap-surface-active); } +/* 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); } +/* 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 + a tree. */ +.${PREFIX}-pop-group-body .${PREFIX}-pop-item { padding-left: 30px; } + .${PREFIX}-pop-item-main { display: inline-flex; align-items: center; gap: var(--ap-space-xs); min-width: 0; } .${PREFIX}-pop-item-main { --${PREFIX}-ic-tone: var(--ap-icon-secondary); } .${PREFIX}-pop-item-main .${PREFIX}-ic { flex: 0 0 auto; }