From cd2dbed31f14c5764470922d8f2a492735d41365 Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:54:03 +0700 Subject: [PATCH] feat(doop): ledger caption, read-only Finished canvas, phone column (CHE-9470) L8 of CHE-9398 plan r5. - canEditActivePage gates every frame-edit entry point on a Finished page. - Lock and Restore keep their own rule. - A 409 page_finished shows the read-only notice. - The ledger page shows its caption: a bar on desktop, a box in the phone Layers sheet. - The landing line stays with CHE-9448. --- .context/TECHSTACK.md | 6 + docs/ux/CHE-9470.yml | 43 +++++ src/components/FrameContextMenu.tsx | 16 +- src/components/FrameHistoryModal.tsx | 6 +- src/components/FrameView.tsx | 10 +- src/components/LayersPanel.tsx | 18 +- src/components/LedgerCaption.tsx | 41 ++++ src/lib/actions/edits.ts | 5 +- src/lib/actions/registry.ts | 9 +- src/lib/api.ts | 10 +- src/lib/i18n/en/panels.ts | 3 + src/lib/i18n/pt-BR/panels.ts | 3 + src/lib/layerEdits.ts | 4 +- src/lib/store.ts | 15 ++ src/pages/CanvasPage.tsx | 29 +-- tests/ledgerCanvasUi.test.tsx | 267 +++++++++++++++++++++++++++ 16 files changed, 448 insertions(+), 37 deletions(-) create mode 100644 docs/ux/CHE-9470.yml create mode 100644 src/components/LedgerCaption.tsx create mode 100644 tests/ledgerCanvasUi.test.tsx diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index 48858ad24..d91f0454a 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -748,6 +748,12 @@ data-doop-webfonts>` for the roster families the frame names and does not load i 400 `ledger_page`, the Archive 400 `archive_page`, unknown page 404, view role 403. A page-list save (REST and `set_canvas_pages`, MCP and resident) that renames or drops a Finished page is refused 400 `page_finished`; a plain `{ id, name }` save keeps the flags. Tests: `pageFinished.test.ts` (including the restore-race cases FP-01 and FP-03). + The client side (CHE-9470, L8): a Finished page opens read only. `canEditActivePage` (`src/lib/store.ts`) is + `canEditOpenCanvas` and the active page not Finished, and every frame-edit entry point reads it (frame press and drag, + Layers rows and menus, delete, paste, drop, rename, ⌘K and shortcut actions, version restore, and the Inspector, element + and Page panels). Lock and Unlock and Restore keep `canEditOpenCanvas` (the server leaves them open). `req()` shows the + notice "Finished pages are read only. Restore the page to edit it." on a 409 `page_finished`. The ledger page shows + `LedgerCaption` (a floating bar on desktop, a box at the top of the phone Layers sheet). Tests: `ledgerCanvasUi.test.tsx`. - Frame write keys (`frame_write_keys`, migration 0045; `actions.writeFrameHtmlOnce`): MCP `set_frame_html` / `edit_frame_html` / `append_frame_html` and REST `PATCH /api/frames/:id` (html only) and `POST /api/frames/:id/append` take `idempotency_key` and an optional `version_name`. The key row, diff --git a/docs/ux/CHE-9470.yml b/docs/ux/CHE-9470.yml new file mode 100644 index 000000000..9bc915ca0 --- /dev/null +++ b/docs/ux/CHE-9470.yml @@ -0,0 +1,43 @@ +issue: CHE-9470 +design: design/lifecycle-ui/approved/A5-project-ledger.html @ 572cc77 +# L8 (CHE-9398 plan r5): the ledger caption, the read-only Finished canvas and the phone 390 A5 +# column. Every row of "What the lock asks for" that is not marked CHE-9448 is named once below: +# under `keep` when this slice leaves it as it is (it belongs to L5 or L7), under `change` when +# this slice draws it. The two landing rows are delivered by CHE-9448 and are not drawn here. +# The phone state rows cite U0 (CHE-9390, docs/ux/CHE-9390.yml), the shared PanelState, which L7 +# already mounts in the Pages list: this slice draws the same four states inside the phone sheet. +pages: + - id: a5-ledger-canvas-desktop + design: design/lifecycle-ui/approved/A5-project-ledger.html @ 572cc77 + url: doop page che-5478, the canvas stage with the ledger page and a Finished page open (reference frame), 1440 and 390 + keep: + - pages-list: 'the Pages list, its Ledger tag, Finished group, row menus and Restore button are L7 (CHE-9469) and are not touched here' + - activity-row-finished: '"CHE-5162 · checkout moved to Finished" is written by the server (L5); the Activity feed is not touched here' + - lock-toggle: 'Lock and Unlock on a frame stay allowed on a Finished page; the server keeps them open and the client keeps its own rule (canEditOpenCanvas)' + - restore-page: 'Restore on a Finished page works from the Pages list; the canvas read-only rule does not cover it' + - copy-frame: 'Copy stays in the frame menu on a Finished page; it reads the frame and writes nothing' + - viewer-rules: 'a view-role visitor is read only as before; the guest and role rules are unchanged' + change: + - ledger-caption: 'a white pill under the top bar, left of the stage, with a brand book icon and the line "Ledger page. The latest approved designs. It changes only when a locked proposal lands."; the lead "Ledger page." is bold; shown on the ledger page only' + - finished-read-only: 'a Finished page opens read only: frame press and drag, the move gesture, delete, paste, drop, rename, hide, duplicate, mark ready and version restore are off, on the canvas, in the Layers panel and in the ⌘K and shortcut actions; the Inspector, the element panel and the Page panel are not offered' + - finished-layers: 'on a Finished page the Layers panel drops the New frame button, the Hide eye and the edit items of the frame menu; the Lock button and Copy stay' + - finished-notice: 'a 409 page_finished refusal shows the notice "Finished pages are read only. Restore the page to edit it." once, then the call still fails as before' + - activity-row-landing: 'delivered by CHE-9448' + - phone-landing-line: 'delivered by CHE-9448' + remove: + - finished-frame-edits: 'every frame edit entry point on a Finished page (listed under finished-read-only); the server already refuses them, the client no longer offers them' + - id: a5-ledger-phone-390 + design: design/lifecycle-ui/approved/A-phone-390-all-five.html @ 572cc77 + url: doop page che-5478, the Layers sheet on a phone (reference frame), 390 + keep: + - phone-tabs: 'the Layers, Tokens, Components and Comments tabs of the sheet are not touched' + - pages-list-phone: 'the Pages list inside the sheet is L7; its rows, Finished group and menus are as shipped there' + - state-loading: 'PanelState loading, "Reading pages…" (U0 state-loading), drawn by L7 and shown here in the phone sheet' + - state-empty: 'PanelState empty, "No ledger page", the hint and its action (U0 state-empty), drawn by L7' + - state-error: 'PanelState error with one retry, "Could not move to Finished (409). The page changed." and Reload pages (U0 state-error), drawn by L7' + - state-offline: 'PanelState offline banner, "Offline. Pages are read only until it reconnects." (U0 state-offline), drawn by L7' + change: + - phone-ledger-caption: 'a grey box at the top of the Layers sheet, above Pages, with the same line as the desktop pill; shown only while the ledger page is open' + - phone-finished-read-only: 'the sheet lists a Finished page read only, as on the desktop' + - phone-landing-line: 'delivered by CHE-9448' + remove: [] diff --git a/src/components/FrameContextMenu.tsx b/src/components/FrameContextMenu.tsx index 8ad660ed3..7879225fc 100644 --- a/src/components/FrameContextMenu.tsx +++ b/src/components/FrameContextMenu.tsx @@ -6,7 +6,7 @@ import { writeCanvasClipboard } from '../lib/canvasClipboard' import { copyFramePng } from '../lib/frameExport' import { deleteFramesTracked } from '../lib/history' import { isStackLocked, setFramesHidden, setFramesLocked } from '../lib/layerEdits' -import { canEditOpenCanvas, useStore } from '../lib/store' +import { canEditActivePage, canEditOpenCanvas, useStore } from '../lib/store' import { setFramesApproval } from '../lib/frameApproval' import { useFrameSaves } from '../lib/frameSaves' import { MOD_KEY } from '../lib/keys' @@ -46,8 +46,10 @@ export function FrameContextMenu({ const [savingApproval, setSavingApproval] = useState(false) /* a right-click inside a multi-selection acts on the whole group */ const selectedIds = useStore((s) => s.selectedIds) - /* a view or comment link keeps the items that only read the frame */ - const readOnly = useStore((s) => !canEditOpenCanvas(s)) + /* a view or comment link keeps the items that only read the frame; so does a Finished page, which + also keeps Lock (the server lets a lock through) */ + const readOnly = useStore((s) => !canEditActivePage(s)) + const canLock = useStore(canEditOpenCanvas) const groupIds = selectedIds.includes(frame.id) ? selectedIds : [frame.id] const groupSize = groupIds.length const pendingSave = useFrameSaves((s) => groupIds.some((id) => !!s.pending[id])) @@ -162,6 +164,10 @@ export function FrameContextMenu({ {allReady ? t('stage.moveToDraft') : t('stage.markReadyForDev')} {groupSize > 1 && {t('stage.framesCount', { count: groupSize })}} + + )} + {canLock && ( + <> setFramesLocked(groupFrames(), !allLocked)}> {groupSize > 1 @@ -169,6 +175,10 @@ export function FrameContextMenu({ : t(allLocked ? 'stage.unlock' : 'stage.lock')} {MOD_KEY}⇧L + + )} + {!readOnly && ( + <> {groupSize > 1 ? t('stage.deleteFrames', { count: groupSize }) : t('stage.deleteFrame')} diff --git a/src/components/FrameHistoryModal.tsx b/src/components/FrameHistoryModal.tsx index 3226fd115..c46f07e4a 100644 --- a/src/components/FrameHistoryModal.tsx +++ b/src/components/FrameHistoryModal.tsx @@ -2,7 +2,7 @@ import { useEffect, useState } from 'react' import type { Frame, FrameVersion, FrameVersionInfo } from '../../shared/types' import { api, errorMessage } from '../lib/api' import { recordUpdate } from '../lib/history' -import { canEditOpenCanvas, useStore } from '../lib/store' +import { canEditActivePage, useStore } from '../lib/store' import { timeAgo } from '../lib/time' import { AgentIcon } from './AgentIcon' import { Badge } from './ui/badge' @@ -25,8 +25,8 @@ type Shown = Pick export function FrameHistoryModal({ frame, onClose }: { frame: Frame; onClose: () => void }) { /* the live frame: the prop is a snapshot from the menu that opened us */ const live = useStore((s) => s.canvas?.frames.find((f) => f.id === frame.id)) ?? frame - /* a view or comment link may browse the history, not restore from it */ - const readOnly = useStore((s) => !canEditOpenCanvas(s)) + /* a view or comment link, or a Finished page, may browse the history, not restore from it */ + const readOnly = useStore((s) => !canEditActivePage(s)) const [versions, setVersions] = useState(null) const [selected, setSelected] = useState(null) const [loaded, setLoaded] = useState(null) diff --git a/src/components/FrameView.tsx b/src/components/FrameView.tsx index 3a2f5c111..cab1ae1f5 100644 --- a/src/components/FrameView.tsx +++ b/src/components/FrameView.tsx @@ -1,7 +1,7 @@ import { memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { createPortal } from 'react-dom' import type { ElementComment, Frame } from '../../shared/types' -import { canEditOpenCanvas, pickedSelectors, useStore } from '../lib/store' +import { canEditActivePage, pickedSelectors, useStore } from '../lib/store' import { isCanvasElement } from '../lib/drawing' import { isLayerLocked, standaloneSelector } from '../lib/layerEdits' import { documentRect } from '../lib/frameBleed' @@ -291,9 +291,9 @@ export const FrameView = memo(function FrameView({ /* the canvas tool: Hand lets presses fall through to the Stage, Comment turns a click on the surface into a comment on the element under it */ const tool = useStore((s) => s.tool) - /* a view or comment link: the frame can be selected and looked at, never + /* a view or comment link, or a Finished page: the frame can be selected and looked at, never moved, resized or edited — the server refuses those writes anyway */ - const readOnly = useStore((s) => !canEditOpenCanvas(s)) + const readOnly = useStore((s) => !canEditActivePage(s)) const select = useStore((s) => s.select) const flash = useStore((s) => s.flashes[frame.id]) const stream = useStore((s) => s.streams[frame.id]) @@ -389,7 +389,7 @@ export const FrameView = memo(function FrameView({ /* a locked frame is not the stage's to select, move or resize: the press falls through to the Stage, which treats it as empty canvas */ if (action !== 'frame-drag' || frame.locked) return - if (!canEditOpenCanvas(s)) { + if (!canEditActivePage(s)) { e.stopPropagation() if (!s.selectedIds.includes(frame.id)) select(frame.id) return @@ -723,7 +723,7 @@ export const FrameView = memo(function FrameView({ pointerType: e.pointerType, spaceHeld: s.panMode, }) - if (action !== 'frame-drag' || frame.locked || !canEditOpenCanvas(s)) return + if (action !== 'frame-drag' || frame.locked || !canEditActivePage(s)) return e.stopPropagation() e.preventDefault() if (!s.selectedIds.includes(frame.id)) select(frame.id) diff --git a/src/components/LayersPanel.tsx b/src/components/LayersPanel.tsx index 5e55c5284..f3636aa70 100644 --- a/src/components/LayersPanel.tsx +++ b/src/components/LayersPanel.tsx @@ -11,10 +11,11 @@ import { } from 'react' import type { Frame } from '../../shared/types' import type { ComponentDef } from '../../shared/components' -import { canEditOpenCanvas, pickedSelectors, useStore } from '../lib/store' +import { canEditActivePage, canEditOpenCanvas, pickedSelectors, useStore } from '../lib/store' import { layerPlacement } from '../lib/frameBridge' import { currentPageCanvas, usePageCanvas } from '../lib/pages' import { PagesPanel, sectionHeading } from './PagesPanel' +import { LedgerCaption } from './LedgerCaption' import { getIdentity } from '../lib/identity' import { deleteFramesTracked } from '../lib/history' import { renameComponent, rootPartKey } from '../lib/components' @@ -242,7 +243,7 @@ export function LayersPanel({ const tab = useStore((s) => s.layersTab) const setTab = useStore((s) => s.setLayersTab) /* view and comment links browse the tree; nothing in it moves or changes */ - const readOnly = useStore((s) => !canEditOpenCanvas(s)) + const readOnly = useStore((s) => !canEditActivePage(s)) /* the Components tab wears a dot while its library waits on someone: changes not yet published, or published updates not yet taken */ const libraryStatus = useLibraryStatus(useStore((s) => s.canvas?.id)) @@ -603,6 +604,7 @@ export function LayersPanel({ <> {/* Figma's order: the pages at the top, the frames of the active page under them, the search at the bottom within thumb's reach */} + {surface === 'inline' && }
@@ -830,7 +832,9 @@ function FrameRow({ onPointerDown: (e: ReactPointerEvent) => void }) { const { frame } = row - const readOnly = useStore((s) => !canEditOpenCanvas(s)) + const readOnly = useStore((s) => !canEditActivePage(s)) + /* a Finished page keeps the lock: the server lets it through, and so does its menu */ + const canLock = useStore(canEditOpenCanvas) const { label, startRename } = useItemRename(frame.name, !readOnly && !frame.locked, (value) => renameFrame(frame.id, value), ) @@ -846,8 +850,8 @@ function FrameRow({ return ( <> - {/* every item in the frame menu is an edit */} - + {/* a viewer has no item in the frame menu worth opening; a Finished page keeps the reading items and Lock */} + setFrameHidden(frame, !frame.hidden)} locked={!!frame.locked} - onToggleLocked={readOnly ? undefined : () => setFramesLocked([frame], !frame.locked)} + onToggleLocked={canLock ? () => setFramesLocked([frame], !frame.locked) : undefined} onClick={onActivate} onDoubleClick={startRename} onContextMenu={() => { @@ -935,7 +939,7 @@ function NodeRow({ onPointerDown: (e: ReactPointerEvent) => void }) { const { frame, node } = row - const readOnly = useStore((s) => !canEditOpenCanvas(s)) + const readOnly = useStore((s) => !canEditActivePage(s)) const hasChildren = node.children.length > 0 const component = useStore((s) => node.componentId ? s.canvas?.components?.find((def) => def.id === node.componentId) : undefined, diff --git a/src/components/LedgerCaption.tsx b/src/components/LedgerCaption.tsx new file mode 100644 index 000000000..d60ae48fb --- /dev/null +++ b/src/components/LedgerCaption.tsx @@ -0,0 +1,41 @@ +import type { CSSProperties } from 'react' +import { activePageOf, useStore } from '../lib/store' +import { useT } from '../lib/i18n' +import { cn } from '../lib/utils' +import { BookOpenIcon } from './ui/icons' + +/** What the ledger page is and when it changes (CHE-9398 L8, A5). Shown only while the ledger page is the + * active page. `bar` is the desktop chip floating over the stage, `box` the note on top of the phone sheet. */ +export function LedgerCaption({ + variant = 'bar', + className, + style, +}: { + variant?: 'bar' | 'box' + className?: string + style?: CSSProperties +}) { + const t = useT() + const ledger = useStore((s) => !!activePageOf(s)?.ledger) + if (!ledger) return null + return ( +

+ {variant === 'bar' && } + + {t('panels.ledgerCaptionLead')}{' '} + {t('panels.ledgerCaptionRest')} + +

+ ) +} diff --git a/src/lib/actions/edits.ts b/src/lib/actions/edits.ts index ce33e65aa..06255d48b 100644 --- a/src/lib/actions/edits.ts +++ b/src/lib/actions/edits.ts @@ -10,7 +10,7 @@ import { readingOrder } from '../../../shared/frameOrder' import { normalizeRotation } from '../../../shared/frameRotation' import { api } from '../api' import { t } from '../i18n' -import { canEditOpenCanvas, pickedSelectors, useStore } from '../store' +import { canEditActivePage, pickedSelectors, useStore } from '../store' import { currentPageCanvas } from '../pages' import { LAYER_TEXT_PROPERTIES } from '../richText' import { recordUpdates, trackSave } from '../history' @@ -86,7 +86,8 @@ export function selectedFrames(): Frame[] { return frames.filter((f) => s.selectedIds.includes(f.id)) } -export const canEdit = () => canEditOpenCanvas(useStore.getState()) +/** Frame edits on the page in view: false for a viewer and on a Finished page. */ +export const canEdit = () => canEditActivePage(useStore.getState()) const notice = (text: string) => useStore.getState().pushNotice(text) /* ---- frames: moved, turned, rounded as one undo step ---- */ diff --git a/src/lib/actions/registry.ts b/src/lib/actions/registry.ts index 9bbe3cc67..b0720d504 100644 --- a/src/lib/actions/registry.ts +++ b/src/lib/actions/registry.ts @@ -4,7 +4,7 @@ the registry what only it holds (its modals and panels) as the host. */ import type { PlainMessageKey } from '../i18n' -import { useStore } from '../store' +import { canEditOpenCanvas, useStore } from '../store' import { currentMe, offersUpgrade } from '../me' import { openUpgrade } from '../upgrade' import { currentPageCanvas } from '../pages' @@ -125,8 +125,10 @@ export interface CanvasAction { section: number /** the first chord bound on this platform is the one menus show */ keys?: readonly Chord[] - /** changes the canvas: only an editor may run it */ + /** changes the canvas: only an editor may run it, and not on a Finished page */ edit?: boolean + /** with `edit`: still runs on a Finished page, whose frames the server lets an editor lock */ + onFinished?: boolean /** the chords are shown, but another handler owns them (⌫ and Esc, which * the canvas page claims with rules of their own) */ hintOnly?: boolean @@ -749,6 +751,7 @@ export const ACTIONS: readonly CanvasAction[] = [ section: 4, keys: [mod('l', { shift: true })], edit: true, + onFinished: true, enabled: hasSelection, run: () => toggleLockSelection(), }, @@ -1085,7 +1088,7 @@ export const ACTIONS: readonly CanvasAction[] = [ * needs to be, and its own test passes. */ export function isEnabled(action: CanvasAction): boolean { if (!host) return false - if (action.edit && !canEdit()) return false + if (action.edit && !(action.onFinished ? canEditOpenCanvas(useStore.getState()) : canEdit())) return false return action.enabled ? action.enabled() : true } diff --git a/src/lib/api.ts b/src/lib/api.ts index 5e3cb6b0b..e7096f234 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -1,4 +1,5 @@ import { useStore } from './store' +import { t } from './i18n' import type { InstanceSettings, InstanceSettingsPatch } from '../../shared/instanceSettings' import { beginFrameSave } from './frameSaves' import type { StackWrite } from '../../shared/frameStack' @@ -433,7 +434,14 @@ export async function req(url: string, init?: RequestInit): Promise { headers: { 'Content-Type': 'application/json' }, ...init, }) - if (!res.ok) throw new ApiError(res.status, await res.text()) + if (!res.ok) { + const error = new ApiError(res.status, await res.text()) + /* a write on a Finished page (CHE-9398 L8): every surface that sent one says why it did not land */ + if (error.status === 409 && error.body.code === 'page_finished') { + useStore.getState().pushNotice(t('panels.pageFinishedReadOnly')) + } + throw error + } return res.json() } diff --git a/src/lib/i18n/en/panels.ts b/src/lib/i18n/en/panels.ts index 56fe5a114..b043bfb10 100644 --- a/src/lib/i18n/en/panels.ts +++ b/src/lib/i18n/en/panels.ts @@ -47,6 +47,9 @@ export const panels = { pagesFinishedGroup: 'Finished', pagesFinishedHint: 'Read only. Restore to move one back.', pagesRestore: 'Restore', + ledgerCaptionLead: 'Ledger page.', + ledgerCaptionRest: 'The latest approved designs. It changes only when a locked proposal lands.', + pageFinishedReadOnly: 'Finished pages are read only. Restore the page to edit it.', pagesLoading: 'Reading pages…', pagesNoLedger: 'No ledger page', pagesNoLedgerHint: 'Mark one page as the ledger. Approved designs land there.', diff --git a/src/lib/i18n/pt-BR/panels.ts b/src/lib/i18n/pt-BR/panels.ts index 3ddf75bf1..d46afff1d 100644 --- a/src/lib/i18n/pt-BR/panels.ts +++ b/src/lib/i18n/pt-BR/panels.ts @@ -47,6 +47,9 @@ export const panels: Catalog['panels'] = { pagesFinishedGroup: 'Concluídas', pagesFinishedHint: 'Somente leitura. Restaure para trazer uma de volta.', pagesRestore: 'Restaurar', + ledgerCaptionLead: 'Página do registro.', + ledgerCaptionRest: 'Os designs aprovados mais recentes. Só muda quando uma proposta travada entra.', + pageFinishedReadOnly: 'Páginas concluídas são somente leitura. Restaure a página para editá-la.', pagesLoading: 'Lendo as páginas…', pagesNoLedger: 'Nenhuma página de registro', pagesNoLedgerHint: 'Marque uma página como o registro. Os designs aprovados entram nela.', diff --git a/src/lib/layerEdits.ts b/src/lib/layerEdits.ts index 325231ae6..70d21bad6 100644 --- a/src/lib/layerEdits.ts +++ b/src/lib/layerEdits.ts @@ -3,7 +3,7 @@ import type { Frame } from '../../shared/types' import { ELEMENT_ID_ATTR } from '../../shared/elementId' import type { ReorderMove } from './keys' import { restack, roomAt, stackOf, type StackWrite } from '../../shared/frameStack' -import { canEditOpenCanvas, pickedSelectors, useStore } from './store' +import { canEditActivePage, pickedSelectors, useStore } from './store' import { t } from './i18n' import { api, ApiError, errorMessage } from './api' import { formatElementText, inspectElement, nudgeElements, requestFrame } from './frameBridge' @@ -61,7 +61,7 @@ function queueRename(frameId: string, edit: (frame: Frame) => Promise) { const started = historyEpoch() const run = async () => { const s = useStore.getState() - if (s.canvas?.id !== canvasId || historyEpoch() !== started || !canEditOpenCanvas(s)) return + if (s.canvas?.id !== canvasId || historyEpoch() !== started || !canEditActivePage(s)) return const frame = s.canvas?.frames.find((f) => f.id === frameId) if (frame) await edit(frame) } diff --git a/src/lib/store.ts b/src/lib/store.ts index 581476db2..ae1c355fb 100644 --- a/src/lib/store.ts +++ b/src/lib/store.ts @@ -10,6 +10,7 @@ import type { AgentTask, Canvas, CanvasGuide, + CanvasPageInfo, DesignDecision, ElementComment, Frame, @@ -835,6 +836,20 @@ export function canEditOpenCanvas(s: Pick): boolean { return roleAllows(roleOf(s), 'edit') } +/** The page the caller is on: the saved one, else the first. */ +export function activePageOf(s: Pick): CanvasPageInfo | undefined { + if (!s.canvas) return undefined + const pages = canvasPages(s.canvas) + return pages.find((page) => page.id === s.activePageId) ?? pages[0] +} + +/** May the caller edit the frames on the page they are on? A Finished page is read only (CHE-9398 L8): + * the server refuses every frame write on it (409 `page_finished`), so the editor never offers one. + * Locking, Restore and the page-agnostic panels keep `canEditOpenCanvas`. */ +export function canEditActivePage(s: Pick): boolean { + return canEditOpenCanvas(s) && !activePageOf(s)?.finished +} + /** May the caller comment on the open canvas? */ export function canCommentOpenCanvas(s: Pick): boolean { return roleAllows(roleOf(s), 'comment') diff --git a/src/pages/CanvasPage.tsx b/src/pages/CanvasPage.tsx index c758a7ef8..a08774e50 100644 --- a/src/pages/CanvasPage.tsx +++ b/src/pages/CanvasPage.tsx @@ -1,6 +1,6 @@ import { CAPTURE_PREFIX, pasteWebCapture } from '../lib/webCapture' import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react' -import { canEditOpenCanvas, pickedSelectors, roleOf, useStore } from '../lib/store' +import { canEditActivePage, canEditOpenCanvas, pickedSelectors, roleOf, useStore } from '../lib/store' import { followPageInUrl } from '../lib/pageUrl' import { MOD_KEY, PRESENT_SHORTCUT_HINT, isControlTarget, isTypingTarget } from '../lib/keys' import { enterSelection, exitSelection, selectSibling } from '../lib/selectionKeys' @@ -128,6 +128,7 @@ import { Note } from '../components/ui/note' import { Textarea } from '../components/ui/textarea' import { Modal, ModalActions, ModalEyebrow, ModalLede, ModalTitle } from '../components/ui/modal' import { createCenteredFrame } from '../lib/framePlacement' +import { LedgerCaption } from '../components/LedgerCaption' import { RULER_PX } from '../components/Rulers' import { NO_CANVAS, onViewCommand, syncViewMenu } from '../lib/viewMenu' import { AGENTS_MIN, LAYERS_MIN, fitPanelWidths } from '../lib/panelWidths' @@ -260,6 +261,9 @@ export function CanvasPage({ /* a guest is read-only from the first paint; anyone else until their role arrives with the canvas (roleOf reads a missing canvas as edit) */ const readOnly = useStore((s) => guest || !canEditOpenCanvas(s)) + /* a Finished page opens read only: no Inspector, element panel or Page panel to edit it with (the server + refuses those writes too) */ + const pageEditable = useStore((s) => !guest && canEditActivePage(s)) const editorReady = useStore((s) => !guest && s.canvas?.id === canvasId && canEditOpenCanvas(s)) const isMobile = useIsMobile() const prototypeMode = useStore((s) => s.prototypeMode) @@ -415,7 +419,7 @@ export function CanvasPage({ always claimed, deleted something or not: an unhandled Backspace is "back" to some engines (WebKitGTK, the Linux desktop app), and a canvas must never leave the page for it. */ - const canEdit = canEditOpenCanvas(useStore.getState()) + const canEdit = canEditActivePage(useStore.getState()) if (e.key === 'Delete' || e.key === 'Backspace') { e.preventDefault() if (canEdit && !e.repeat) deleteSelection() @@ -472,7 +476,7 @@ export function CanvasPage({ function onPaste(e: ClipboardEvent) { if (isTypingTarget(e.target)) return /* every paste lands a frame or a layer */ - if (!canEditOpenCanvas(useStore.getState())) return + if (!canEditActivePage(useStore.getState())) return const captureText = e.clipboardData?.getData('text/plain') ?? '' if (captureText.startsWith(CAPTURE_PREFIX)) { e.preventDefault() @@ -541,13 +545,13 @@ export function CanvasPage({ function onDragOver(e: DragEvent) { if (!carriesFiles(e) || e.defaultPrevented) return e.preventDefault() - if (e.dataTransfer) e.dataTransfer.dropEffect = canEditOpenCanvas(useStore.getState()) ? 'copy' : 'none' + if (e.dataTransfer) e.dataTransfer.dropEffect = canEditActivePage(useStore.getState()) ? 'copy' : 'none' } function onDrop(e: DragEvent) { endDrag() if (!carriesFiles(e) || e.defaultPrevented) return e.preventDefault() - if (!canEditOpenCanvas(useStore.getState())) return + if (!canEditActivePage(useStore.getState())) return const componentId = e.dataTransfer?.getData(COMPONENT_DRAG_TYPE) if (componentId) { void dropComponent(componentId, { x: e.clientX, y: e.clientY }) @@ -727,10 +731,10 @@ export function CanvasPage({ /* with nothing selected the slot is the page's own settings, once opened from the rail, until closed */ const pagePanelOpen = useStore((s) => s.pagePanelOpen) - const pageShown = !readOnly && !selectedFrame && pagePanelOpen && !deferPanel + const pageShown = pageEditable && !selectedFrame && pagePanelOpen && !deferPanel /* the frame Inspector, the element panel or the Page panel, whichever has the slot */ const propertiesShown = - (!readOnly && !!selectedFrame && !deferPanel && (!!panelElement || inspectorOpen)) || pageShown + (pageEditable && !!selectedFrame && !deferPanel && (!!panelElement || inspectorOpen)) || pageShown /* ⇧R docks the rulers on the canvas's top and left edges; the bar and the floating chrome step in past them (the same test Stage draws them by) */ const rulers = useStore((s) => s.rulers) @@ -1071,6 +1075,9 @@ export function CanvasPage({ {/* the presence pill in the bar already carries each agent's status line; this per-agent stack is only for windows too narrow for it */} + {!isMobile && !uiHidden && ( + + )} {!readOnly && } @@ -1102,7 +1109,7 @@ export function CanvasPage({ }} /> )} - {!isMobile && !readOnly && selectedFrame && panelElement && !deferPanel && ( + {!isMobile && pageEditable && selectedFrame && panelElement && !deferPanel && ( )} - {!isMobile && !readOnly && selectedFrame && inspectorOpen && !panelElement && !deferPanel && ( + {!isMobile && pageEditable && selectedFrame && inspectorOpen && !panelElement && !deferPanel && ( )} {!isMobile && pageShown && } @@ -1140,7 +1147,7 @@ export function CanvasPage({ agentsOpen={showActivity} onToggleAgents={() => setShowActivity((open) => !open)} inspectorOpen={propertiesShown} - inspectorAvailable={!readOnly} + inspectorAvailable={pageEditable} inspectTarget={selectedFrame ? 'frame' : 'page'} onToggleInspector={() => { const s = useStore.getState() @@ -1256,7 +1263,7 @@ export function CanvasPage({ the open state they read from is untouched, so they are back as they were when ⌘. restores the chrome */} { if (!open) select(null) }} diff --git a/tests/ledgerCanvasUi.test.tsx b/tests/ledgerCanvasUi.test.tsx new file mode 100644 index 000000000..36c6c5413 --- /dev/null +++ b/tests/ledgerCanvasUi.test.tsx @@ -0,0 +1,267 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import type { Canvas, CanvasPageInfo, Frame } from '../shared/types' + +/* The canvas side of the A5 ledger (CHE-9398 L8): the ledger caption, the read-only Finished page, and the + notice a `page_finished` refusal shows. Design: design/lifecycle-ui/approved/A5-project-ledger.html and + A-phone-390-all-five.html @ 572cc77. */ + +const updateFrame = vi.fn(() => Promise.resolve()) +const deleteFrame = vi.fn(() => Promise.resolve()) +const restackFrames = vi.fn(() => Promise.resolve([])) +const setPageFinished = vi.fn() +const getCanvas = vi.fn() +vi.mock('../src/lib/api', async (original) => { + const actual = await original() + return { + ...actual, + api: { + ...actual.api, + /* the Components tab's dot asks; nothing waits in these tests */ + canvasLibrary: () => new Promise(() => {}), + updateFrame: () => updateFrame(), + deleteFrame: () => deleteFrame(), + restackFrames: () => restackFrames(), + setPageFinished: (...args: unknown[]) => setPageFinished(...args), + getCanvas: (...args: unknown[]) => getCanvas(...args), + }, + } +}) +vi.mock('../src/lib/posthog', () => ({ posthog: { capture: vi.fn() } })) + +const storeModule = await import('../src/lib/store') +const { useStore } = storeModule +const { ApiError, req } = await import('../src/lib/api') +const { LayersPanel } = await import('../src/components/LayersPanel') +const { TooltipProvider } = await import('../src/components/ui/tooltip') + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true +globalThis.ResizeObserver ??= class { + observe() {} + unobserve() {} + disconnect() {} +} as unknown as typeof ResizeObserver + +const AT = { at: 1, by: 'user' } +const PAGES: CanvasPageInfo[] = [ + { id: 'base', name: 'Baseline', ledger: true }, + { id: 'flows', name: 'Flows' }, + { id: 'fin1', name: 'CHE-5162 · checkout', finished: AT }, +] +const CAPTION = 'Ledger page. The latest approved designs. It changes only when a locked proposal lands.' + +const frame = (id: string, pageId: string, createdAt: number): Frame => ({ + id, + canvasId: 'c1', + pageId, + name: `Frame ${id}`, + x: 0, + y: 0, + width: 100, + height: 100, + html: '

A

', + createdAt, + updatedAt: 0, + updatedBy: 'me', +}) +const canvasOf = (over: Partial = {}) => + ({ + id: 'c1', + name: 'Canvas', + pages: PAGES, + frames: [frame('f1', 'fin1', 1), frame('f2', 'fin1', 2), frame('o1', 'flows', 3), frame('o2', 'flows', 4)], + ...over, + }) as unknown as Canvas +function openPage(pageId: string, canvas: Canvas = canvasOf()) { + useStore.getState().setCanvas(canvas) + act(() => useStore.getState().setActivePage(pageId)) +} + +let container: HTMLDivElement +let root: Root +const text = () => container.textContent ?? '' +const settle = () => + act(async () => { + for (let i = 0; i < 12; i++) await Promise.resolve() + }) +const row = (key: string) => { + const el = container.querySelector(`[data-row-key="${key}"]`) + if (!el) throw new Error(`row ${key} not rendered`) + return el +} +/* happy-dom has no layout: the row under the pointer is the one the test names */ +function dragRow(from: string, onto: string) { + const target = row(onto) + document.elementFromPoint = () => target + target.getBoundingClientRect = () => ({ top: 0, height: 28 }) as DOMRect + act(() => { + row(from).dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0, clientX: 0, clientY: 0 })) + }) + act(() => { + window.dispatchEvent(new PointerEvent('pointermove', { clientX: 10, clientY: 2 })) + }) + act(() => { + window.dispatchEvent(new PointerEvent('pointerup', { clientX: 10, clientY: 2 })) + }) +} +const menuItems = () => [...document.querySelectorAll('[role="menuitem"]')].map((el) => el.textContent) +const isDisabled = (el: HTMLElement) => el.hasAttribute('data-disabled') || el.getAttribute('aria-disabled') === 'true' + +describe('canEditActivePage', () => { + beforeEach(() => useStore.setState({ connected: true, selectedIds: [], selectedId: null })) + + it('is false on a Finished page and true on an open page and on the ledger page', () => { + openPage('fin1') + expect(storeModule.canEditActivePage(useStore.getState())).toBe(false) + openPage('flows') + expect(storeModule.canEditActivePage(useStore.getState())).toBe(true) + openPage('base') + expect(storeModule.canEditActivePage(useStore.getState())).toBe(true) + }) + + it('stays false for a viewer on an open page, and the canvas role rule itself does not change', () => { + openPage('flows', canvasOf({ role: 'view' })) + expect(storeModule.canEditActivePage(useStore.getState())).toBe(false) + openPage('fin1', canvasOf()) + expect(storeModule.canEditOpenCanvas(useStore.getState())).toBe(true) + }) +}) + +describe('the ledger caption', () => { + async function renderCaption() { + const { LedgerCaption } = await import('../src/components/LedgerCaption') + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + act(() => root.render()) + } + afterEach(() => { + act(() => root.unmount()) + container.remove() + }) + + it('shows on the ledger page, with the lead in bold', async () => { + openPage('base') + await renderCaption() + expect(text()).toBe(CAPTION) + expect(container.querySelector('strong')?.textContent).toBe('Ledger page.') + }) + + it('shows on no other page', async () => { + openPage('flows') + await renderCaption() + expect(text()).toBe('') + openPage('fin1') + expect(text()).toBe('') + }) +}) + +describe('a Finished page in the Layers panel', () => { + beforeEach(() => { + for (const spy of [updateFrame, deleteFrame, restackFrames, setPageFinished, getCanvas]) spy.mockClear() + setPageFinished.mockResolvedValue({ pages: PAGES, skipped: [] }) + getCanvas.mockResolvedValue(canvasOf()) + useStore.setState({ connected: true, selectedIds: [], selectedId: null }) + openPage('fin1') + useStore.setState({ selectedId: 'f1', selectedIds: ['f1'], selectedElement: null }) + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + act(() => + root.render( + + {}} /> + , + ), + ) + }) + afterEach(() => { + act(() => root.unmount()) + container.remove() + }) + + it('does not delete on ⌫', () => { + const tree = container.querySelector('[role="tree"]')! + act(() => { + tree.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true, cancelable: true })) + }) + expect(deleteFrame).not.toHaveBeenCalled() + }) + + it('does not move a frame by dragging its row', () => { + dragRow('f1', 'f2') + expect(restackFrames).not.toHaveBeenCalled() + expect(updateFrame).not.toHaveBeenCalled() + }) + + it('offers no frame edit in the frame menu, only what reads the frame and the lock', async () => { + await act(async () => { + row('f1').dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, button: 2 })) + }) + const labels = menuItems() + expect(labels.some((label) => label?.startsWith('Copy'))).toBe(true) + expect(labels.some((label) => label?.startsWith('Lock'))).toBe(true) + for (const edit of ['Delete', 'Duplicate', 'Paste', 'Rename', 'Hide', 'Mark ready']) { + expect(labels.some((label) => label?.startsWith(edit))).toBe(false) + } + }) + + it('keeps the lock toggle on the row and hides the eye and the new-frame button', () => { + expect(row('f1').querySelector('button[aria-label="Lock"]')).not.toBeNull() + expect(row('f1').querySelector('button[aria-label="Hide"]')).toBeNull() + expect(container.querySelector('button[aria-label="New frame"]')).toBeNull() + }) + + it('still restores the page from its row in the Finished group', async () => { + const group = [...container.querySelectorAll('button')].find((b) => b.textContent?.startsWith('Finished'))! + await act(async () => { + group.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + const restore = [...container.querySelectorAll('button')].find((b) => b.textContent === 'Restore')! + expect(isDisabled(restore)).toBe(false) + await act(async () => { + restore.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) + await settle() + expect(setPageFinished).toHaveBeenCalledWith('c1', 'fin1', false, 'CHE-5162 · checkout') + }) + + it('lets an open page keep every edit', () => { + act(() => { + useStore.getState().setActivePage('flows') + useStore.setState({ selectedId: 'o1', selectedIds: ['o1'], selectedElement: null }) + }) + expect(container.querySelector('button[aria-label="New frame"]')).not.toBeNull() + dragRow('o1', 'o2') + expect(restackFrames).toHaveBeenCalled() + const tree = container.querySelector('[role="tree"]')! + act(() => { + tree.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true, cancelable: true })) + }) + expect(deleteFrame).toHaveBeenCalledTimes(1) + }) +}) + +describe('a page_finished refusal', () => { + const refuse = (status: number, body: Record) => + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify(body), { status })), + ) + beforeEach(() => useStore.setState({ notice: null })) + afterEach(() => vi.unstubAllGlobals()) + + it('shows the read-only notice and still rejects', async () => { + refuse(409, { error: 'page “CHE-5162 · checkout” is Finished. Restore the page first.', code: 'page_finished' }) + await expect(req('/api/frames/f1', { method: 'PATCH' })).rejects.toBeInstanceOf(ApiError) + expect(useStore.getState().notice?.text).toBe('Finished pages are read only. Restore the page to edit it.') + }) + + it('stays quiet for any other refusal', async () => { + refuse(409, { error: 'The frame changed while you were editing.' }) + await expect(req('/api/frames/f1', { method: 'PATCH' })).rejects.toBeInstanceOf(ApiError) + expect(useStore.getState().notice).toBeNull() + }) +})