From 16637da27ed26c27494a5d56bddcf3ac528640c7 Mon Sep 17 00:00:00 2001 From: Diao Shengjia <104132148+GoDiao@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:39:26 +0800 Subject: [PATCH] feat(slides): let the user edit, reorder and delete slides, and make the agent wait while the user edits an artifact Slides, with Edit on in the deck toolbar: - Click a text block to change it in place. Enter saves, Shift+Enter starts a new line, Escape cancels. The block under the pointer that a click would edit is outlined. The block keeps its layout while it is edited, whatever line breaks and indentation its source has. - Reorder slides in the overview by dragging or with Cmd/Ctrl and the arrow keys. The dragged slide follows the pointer, the others glide to their places, the overview scrolls at its edges, and Escape cancels the drag. - Delete the current slide from the toolbar or with Delete in the overview, after a confirmation. - The overview shows slide numbers, and the current slide zooms between the overview and the single-slide view. Artifacts in general: - While the user edits an artifact in the app (slide text, slide order, a canvas board), the sidecar holds a lock on that artifact folder. The agent's Write and Edit wait for it, the conversation says it is waiting, and the write is refused with the list of changed files if the user changed something meanwhile. - After the user changes an artifact, a chip in that session's composer tells the agent with the next message which files changed, and for a deck whose slides were reordered or deleted, to check its section numbers. --- CHANGELOG.md | 3 +- desktop/public/artifact-shell/canvas.js | 10 +- desktop/public/artifact-shell/deck.js | 500 +++++++++++++- desktop/src/__tests__/pages.test.tsx | 1 + desktop/src/api/artifacts.ts | 14 +- .../artifacts/ArtifactViewer.test.tsx | 21 +- .../components/artifacts/ArtifactViewer.tsx | 4 +- .../artifacts/DeckControls.test.tsx | 125 +++- .../src/components/artifacts/DeckControls.tsx | 104 ++- .../chat/BrowserGrantRequests.test.tsx | 1 + .../src/components/chat/ChatInput.test.tsx | 33 + desktop/src/components/chat/ChatInput.tsx | 11 +- .../chat/PendingReportsBar.test.tsx | 1 + .../chat/QueuedMessagesBar.test.tsx | 1 + .../chat/StreamingIndicator.test.tsx | 32 + .../components/chat/StreamingIndicator.tsx | 5 +- .../chat/streamingRenderScenario.ts | 1 + .../controls/ModelSelector.test.tsx | 1 + .../src/components/design/StartPage.test.tsx | 2 +- .../workspace/BrowserActivityBar.test.tsx | 1 + .../components/workspace/BrowserView.test.tsx | 30 +- .../src/components/workspace/BrowserView.tsx | 4 +- .../WorkspacePanel.sideChatPrewarm.test.tsx | 1 + .../src/hooks/useArtifactThumbnail.test.tsx | 2 +- desktop/src/hooks/useCanvasTab.test.tsx | 51 +- desktop/src/hooks/useCanvasTab.ts | 30 +- desktop/src/i18n/locales/en.ts | 13 + desktop/src/i18n/locales/zh.ts | 13 + desktop/src/lib/artifactEditReference.ts | 35 + desktop/src/lib/artifactExport.test.ts | 11 +- desktop/src/lib/artifactExport.ts | 7 +- desktop/src/lib/artifactUserEdits.test.ts | 71 ++ desktop/src/lib/artifactUserEdits.ts | 63 ++ desktop/src/lib/browserGuests.test.ts | 39 +- desktop/src/lib/browserGuests.ts | 18 +- desktop/src/lib/canvasBridge.test.ts | 6 + desktop/src/lib/canvasBridge.ts | 2 + desktop/src/lib/canvasShell.test.ts | 20 +- desktop/src/lib/deckBridge.test.ts | 40 +- desktop/src/lib/deckBridge.ts | 29 +- desktop/src/lib/deckEdits.test.ts | 179 +++++ desktop/src/lib/deckEdits.ts | 47 ++ desktop/src/lib/deckShell.test.ts | 626 +++++++++++++++++- desktop/src/stores/chatStore.test.ts | 1 + .../stores/workspaceChatContextStore.test.ts | 33 + .../src/stores/workspaceChatContextStore.ts | 14 +- docs/features/artifacts/tech-design.md | 97 ++- docs/features/session-state/tech-design.md | 2 + docs/features/slides/tech-design.md | 167 +++-- src/entrypoints/sdk/controlSchemas.ts | 18 + .../__tests__/artifact-edit-locks.test.ts | 255 +++++++ src/server/__tests__/artifacts.test.ts | 159 ++++- .../__tests__/conversation-service.test.ts | 1 + src/server/__tests__/deckEditNotice.test.ts | 174 +++++ src/server/__tests__/session-state.test.ts | 18 + src/server/api/artifacts.ts | 34 +- src/server/api/requestBody.ts | 18 + src/server/services/artifactEditLocks.ts | 119 ++++ src/server/services/artifactService.ts | 122 +++- src/server/services/conversationService.ts | 2 + src/server/services/recoverableJsonFile.ts | 6 +- src/server/session/state/reducer.ts | 10 +- src/server/session/state/types.ts | 7 + src/server/ws/handler.ts | 7 +- src/skills/bundled/artifacts.test.ts | 14 + src/skills/bundled/artifacts.ts | 8 + src/skills/bundled/slides.test.ts | 10 + src/skills/bundled/slides.ts | 6 + .../ArtifactCopyTool/ArtifactCopyTool.test.ts | 36 +- .../ArtifactCopyTool/ArtifactCopyTool.ts | 16 +- src/tools/FileEditTool/FileEditTool.ts | 3 + src/tools/FileWriteTool/FileWriteTool.ts | 4 +- src/utils/artifactEditLock.ts | 20 + src/utils/artifacts.ts | 32 +- src/utils/hostRequests.ts | 4 + 75 files changed, 3446 insertions(+), 179 deletions(-) create mode 100644 desktop/src/lib/artifactEditReference.ts create mode 100644 desktop/src/lib/artifactUserEdits.test.ts create mode 100644 desktop/src/lib/artifactUserEdits.ts create mode 100644 desktop/src/lib/deckEdits.test.ts create mode 100644 desktop/src/lib/deckEdits.ts create mode 100644 src/server/__tests__/artifact-edit-locks.test.ts create mode 100644 src/server/__tests__/deckEditNotice.test.ts create mode 100644 src/server/services/artifactEditLocks.ts create mode 100644 src/utils/artifactEditLock.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 9522f50e..0f42154f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,10 +10,11 @@ All notable changes to DreamCoder will be documented in this file. - **Sessions are nested in the sidebar.** Sessions the agent started, and conversations you forked, appear under the session they came from, with an icon for each kind and a count that collapses or expands them. Messages from another session appear in the conversation as a one-line row with the sender, which expands to the full text (#239). - **Project board.** Each project gets a persistent board of tasks and sub-tasks that you and your sessions share; every worktree of the project uses the same board. Open it from the project in the sidebar. A task records its owner, reviewer and creator, acceptance criteria, priority, dependencies, progress, and the owner's and reviewer's reports. Sessions read and update the board with four tools (`KanbanList`, `KanbanGet`, `KanbanCreate`, `KanbanUpdate`): they split work into sub-tasks, record progress, block a task with a question, submit their work and review it. The board notifies the sessions involved when they are assigned, when work is submitted, blocked, sent back, reset or cancelled, and when you comment. `StartSession` can start a session as a task's owner or reviewer. The board page has a board view and a hierarchy view, opens a task in the side panel, and lists what waits on you under "Needs me": blocked tasks, deliveries to accept and tasks whose owner session is gone. You approve every time a session creates the board, starts a session on a task, cancels a task, changes acceptance criteria it did not set, or makes itself a reviewer; only a task's creator or you choose its reviewer (#242). - **Side chats.** Start a side chat from the side panel's new-tab page, or select text in the conversation and choose **Start a side chat** to quote it in a new one, to ask about something without interrupting the session: it continues from the session's latest message, in the same working folder, with the same tools, and opens as a tab in the session's side panel. It shows only its own messages; the model still has the whole conversation. A session can have several. Pages, files and browser tabs a side chat opens appear in the same panel. The tab is named `btw: ` plus your first message; right-click it to rename it, or to detach it into a regular forked session in the sidebar. Closing the tab deletes the side chat, and deleting a session deletes its side chats. Side chats stay out of the sidebar, search and board pickers; `ListSessions` shows a session its own side chats so it can message them. Cmd+. stops the conversation that has the focus. -- **Slides.** The agent can make a slide deck as an artifact with the new `/slides` skill, from scratch or from a bundled slide template; the Artifacts page has a Slides entry next to Design, with the slide templates, previews and the design system library. A deck opens in the side browser with controls to page through the slides, see them all in an overview and present full screen, where elements can appear step by step. It exports as a PDF with one page per slide, a PNG of the current slide, or one HTML file that pages and presents on its own. A comment on a slide tells the agent which slide it is about, and the tab stays on your slide while the agent changes the deck. +- **Slides.** The agent can make a slide deck as an artifact with the new `/slides` skill, from scratch or from a bundled slide template; the Artifacts page has a Slides entry next to Design, with the slide templates, previews and the design system library. A deck opens in the side browser with controls to page through the slides, see them all in an overview and present full screen, where elements can appear step by step. With **Edit** on, you can change the text of a slide in place (Shift+Enter starts a new line) and reorder slides in the overview by dragging them or with Cmd/Ctrl and the arrow keys, and you can delete a slide with the toolbar button or the Delete key in the overview; the changes are saved to the deck's files. Slides glide when their order changes, and the current slide zooms between the overview and the single-slide view. It exports as a PDF with one page per slide, a PNG of the current slide, or one HTML file that pages and presents on its own. A comment on a slide tells the agent which slide it is about, and the tab stays on your slide while the agent changes the deck. ### Changed +- **You and the agent no longer write an artifact at the same time.** While you edit a slide or move or resize a board of a canvas, the agent's file edits in that artifact wait until you are done, the conversation says it is waiting for you, and if you changed files meanwhile it reads them before going on. After you change an artifact in the app, a chip above the message box tells the agent with your next message which files you changed (and, for a deck whose slides you reordered or deleted, to check its section numbers). - **A cleaner desktop look.** All seven themes share one set of semantic colors, the conversation, sidebar and panels use one type scale (14px body text), and corners use one radius scale. The pages of the side panel (terminal, browser, files, changes) no longer draw their own frames; the terminal follows the light or dark theme, its project and branch sit in a row above the output with the clear and restart buttons, and the browser shows a loading bar under its address field. - **The Files tab previews a file beside the tree.** Clicking a file in the tree previews it in place instead of opening a tab; the tree's right-click menu can still open it in its own tab, and recent files and typed paths on the new-tab page select the file in the Files tab. A path bar above the preview holds an editor button with a menu of editors and file managers, a preview toggle for Markdown (which opens rendered), a line-wrap toggle (on by default) and a tree toggle; in a narrow panel the tree shows until you pick a file, then hides. Each part of the path has a menu (add to chat and copy path; folders can also open in an editor, the file manager or a terminal tab started there), shows its full path on hover, and is revealed in the tree when clicked. Right-clicking a file's content adds the file or the selection to the chat, copies its path or contents, and in source view comments on the clicked line or selects all. The file tree is built on `@pierre/trees`. `.bmp` and `.ico` files now preview as images. - **Changed files** have an open-file button and a menu on each row (add to chat, copy path, open file, open in an editor or the file manager). diff --git a/desktop/public/artifact-shell/canvas.js b/desktop/public/artifact-shell/canvas.js index ced5d21c..42b599db 100644 --- a/desktop/public/artifact-shell/canvas.js +++ b/desktop/public/artifact-shell/canvas.js @@ -404,6 +404,10 @@ var dx = (event.clientX - drag.startX) / view.scale var dy = (event.clientY - drag.startY) / view.scale var board = drag.entry.board + if (!drag.busy) { + drag.busy = true + emit({ type: 'busy', on: true }) + } if (drag.mode === 'move') { board.x = drag.origin.x + dx board.y = drag.origin.y + dy @@ -419,6 +423,7 @@ var board = activeDrag.entry.board var origin = activeDrag.origin var entry = activeDrag.entry + var busy = activeDrag.busy activeDrag = null document.body.classList.remove('dragging') board.x = Math.round(board.x) @@ -426,8 +431,9 @@ board.width = Math.round(board.width) board.height = Math.round(board.height) place(entry.element, board) - if (board.x === origin.x && board.y === origin.y && board.width === origin.width && board.height === origin.height) return - emit({ type: 'move', id: board.id, x: board.x, y: board.y, width: board.width, height: board.height }) + var moved = board.x !== origin.x || board.y !== origin.y || board.width !== origin.width || board.height !== origin.height + if (moved) emit({ type: 'move', id: board.id, x: board.x, y: board.y, width: board.width, height: board.height }) + if (busy) emit({ type: 'busy', on: false }) } document.addEventListener('pointerup', endDrag) document.addEventListener('pointercancel', endDrag) diff --git a/desktop/public/artifact-shell/deck.js b/desktop/public/artifact-shell/deck.js index 84e05243..8854581c 100644 --- a/desktop/public/artifact-shell/deck.js +++ b/desktop/public/artifact-shell/deck.js @@ -15,6 +15,16 @@ var SLIDE_ID = /^[A-Za-z0-9_-]{1,64}$/ var REFERENCES = 'iframe[src],img[src],video[src],audio[src],source[src]' var MODES = ['browse', 'overview', 'present'] + var INLINE = /^(A|ABBR|B|BDI|BDO|BR|CITE|CODE|DATA|DEL|DFN|EM|I|INS|KBD|MARK|Q|S|SAMP|SMALL|SPAN|STRONG|SUB|SUP|TIME|U|VAR|WBR)$/ + var DRAG_DISTANCE = 6 + var MOVE_MS = 150 + var ZOOM_MS = 220 + var SAVED_MS = 600 + var EASE = 'cubic-bezier(.2,0,0,1)' + var LIFT = '0 24px 96px rgba(0,0,0,.4)' + var LABEL = 22 + var EDGE = 56 + var EDGE_SPEED = 0.3 var TEXT = { en: { empty: 'This deck has no slides yet', failed: 'Could not read the deck', missing: 'Could not read this slide', keys: '← → slides · F present · O overview · Esc back' }, zh: { empty: '这份幻灯片还没有页面', failed: '无法读取幻灯片', missing: '无法读取这一页', keys: '← → 翻页 · F 演示 · O 总览 · Esc 返回' }, @@ -33,10 +43,23 @@ var currentId = null var step = 0 var columns = 1 + var scale = 1 var standalone = false var bare = false var reported = '' var bust = 0 + var editing = false + var active = null + var held = false + var edits = [] + var drag = null + var dragged = false + var motions = new WeakMap() + var hovered = null + var RAISED = { zIndex: 1 } + var LIFTED = { zIndex: 1, boxShadow: LIFT } + var LANDED = { zIndex: 1, boxShadow: 'none' } + var busy = false var queue = Promise.resolve() var resolveLoaded = null var loaded = new Promise(function (resolve) { @@ -55,11 +78,18 @@ '.dc-slide{counter-increment:dc-slide}', '.dc-slide[data-current]{visibility:visible;opacity:1}', '.dc-slide>section{position:relative;box-sizing:border-box;width:' + WIDTH + 'px;height:' + HEIGHT + 'px;overflow:hidden}', - '#dc-deck[data-mode=overview] .dc-stage{display:grid;grid-template-columns:repeat(var(--dc-columns,1),' + WIDTH + 'px);gap:' + GRID_GAP + 'px;width:max-content;height:auto;padding-bottom:var(--dc-tail,0px)}', - '#dc-deck[data-mode=overview] .dc-slide{position:relative;visibility:visible;opacity:1;cursor:pointer;outline:12px solid transparent;outline-offset:12px}', + '#dc-deck[data-mode=overview] .dc-stage{display:grid;grid-template-columns:repeat(var(--dc-columns,1),' + WIDTH + 'px);gap:calc(' + GRID_GAP + 'px + ' + LABEL + 'px / var(--dc-scale,1)) ' + GRID_GAP + 'px;width:max-content;height:auto;padding-bottom:var(--dc-tail,0px)}', + '#dc-deck[data-mode=overview] .dc-slide{position:relative;overflow:visible;visibility:visible;opacity:1;cursor:pointer;user-select:none;outline:12px solid transparent;outline-offset:12px;transition:outline-color .12s}', + '#dc-deck[data-mode=overview] .dc-slide:hover{outline-color:color-mix(in srgb,var(--dc-accent) 35%,transparent)}', '#dc-deck[data-mode=overview] .dc-slide[data-current]{outline-color:var(--dc-accent)}', + '#dc-deck[data-mode=overview] .dc-slide::after{content:counter(dc-slide);position:absolute;left:0;top:100%;padding-top:calc(7px / var(--dc-scale,1));font:calc(11px / var(--dc-scale,1))/1 system-ui,-apple-system,"Segoe UI",sans-serif;font-variant-numeric:tabular-nums;color:var(--dc-ink)}', + '#dc-deck[data-mode=overview] .dc-slide[data-current]::after{color:var(--dc-accent)}', '#dc-deck[data-mode=overview] .dc-slide>section{pointer-events:none}', '[data-dc-pending]{visibility:hidden!important;opacity:0!important}', + '#dc-deck[data-editing] [data-dc-editable]{cursor:text;outline:4px solid color-mix(in srgb,var(--dc-accent) 40%,transparent);outline-offset:8px}', + '.dc-slide [contenteditable]{outline:4px solid var(--dc-accent);outline-offset:8px}', + '#dc-deck[data-editing][data-mode=overview] .dc-slide{cursor:grab}', + '#dc-deck[data-mode=overview] .dc-slide[data-dc-dragging]{z-index:1;box-shadow:' + LIFT + ';cursor:grabbing}', '.dc-missing{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px;width:' + WIDTH + 'px;height:' + HEIGHT + 'px;font:36px system-ui,-apple-system,"Segoe UI",sans-serif;color:#6b6b66;background:#f4f4f2}', '.dc-notice{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);font:13px system-ui,-apple-system,"Segoe UI",sans-serif;color:var(--dc-ink);text-align:center}', '.dc-hint{position:absolute;left:0;right:0;bottom:5px;font:11px system-ui,-apple-system,"Segoe UI",sans-serif;color:var(--dc-ink);text-align:center;pointer-events:none}', @@ -72,6 +102,8 @@ '.dc-slide{position:relative!important;visibility:visible!important;opacity:1!important;outline:0!important;break-after:page;break-inside:avoid}', '.dc-slide:last-child{break-after:auto}', '[data-dc-pending]{visibility:visible!important;opacity:1!important}', + '.dc-slide [contenteditable],[data-dc-editable]{outline:0!important}', + '.dc-slide::after{display:none!important}', '.dc-notice,.dc-hint{display:none!important}', '}', ].join('\n') @@ -109,6 +141,7 @@ index: index, count: entries.length, mode: mode, + editing: editing, } } @@ -146,16 +179,16 @@ if (mode === 'overview') { columns = Math.max(1, Math.min(MAX_COLUMNS, entries.length, Math.floor((width - GRID_PAD * 2) / MIN_THUMBNAIL))) var natural = columns * WIDTH + (columns - 1) * GRID_GAP - var fit = Math.max(0.01, (width - GRID_PAD * 2) / natural) + scale = Math.max(0.01, (width - GRID_PAD * 2) / natural) setVariable('--dc-columns', String(columns)) - setVariable('--dc-scale', String(fit)) + setVariable('--dc-scale', String(scale)) setVariable('--dc-x', GRID_PAD + 'px') setVariable('--dc-y', GRID_PAD + 'px') - setVariable('--dc-tail', GRID_PAD / fit + 'px') + setVariable('--dc-tail', GRID_PAD / scale + 'px') return } var margin = bare || mode === 'present' ? 0 : MARGIN - var scale = Math.max(0.01, Math.min((width - margin * 2) / WIDTH, (height - margin * 2) / HEIGHT)) + scale = Math.max(0.01, Math.min((width - margin * 2) / WIDTH, (height - margin * 2) / HEIGHT)) setVariable('--dc-scale', String(scale)) setVariable('--dc-x', (width - WIDTH * scale) / 2 + 'px') setVariable('--dc-y', (height - HEIGHT * scale) / 2 + 'px') @@ -177,6 +210,7 @@ function show(id) { var index = indexOf(id) if (index < 0) return false + if (active && active.entry.id !== id) finishEdit(true) currentId = id entries.forEach(function (entry) { if (entry.id === id) entry.element.setAttribute('data-current', '') @@ -228,13 +262,25 @@ function setMode(nextMode) { if (MODES.indexOf(nextMode) < 0 || nextMode === mode) return + finishEdit(true) + cancelDrag() + hover(null) + entries.forEach(stopMotion) + if (nextMode === 'present') markEditing(false) + var entry = entries[indexOf(currentId)] + var from = entry && mode !== 'present' && nextMode !== 'present' ? entry.element.getBoundingClientRect() : null mode = nextMode step = 0 root.setAttribute('data-mode', mode) applyStep() layout() - var entry = entries[indexOf(currentId)] if (entry) reveal(entry) + if (from) { + glide(entry.element, from, entry.element.getBoundingClientRect(), RAISED, RAISED) + if (mode === 'overview') entries.forEach(function (other) { + if (other !== entry) fadeIn(other.element) + }) + } report() } @@ -265,7 +311,393 @@ return !!target && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName || '')) } + function markBusy(on) { + if (busy === on) return + busy = on + emit({ type: 'busy', on: on }) + } + + function markEditing(on) { + editing = on + if (on) root.setAttribute('data-editing', '') + else { + root.removeAttribute('data-editing') + hover(null) + } + } + + function setEditing(on) { + var next = !!on && !standalone && mode !== 'present' + if (next === editing) return + if (!next) { + finishEdit(true) + cancelDrag() + } + markEditing(next) + report() + } + + function onlyInline(element) { + for (var i = 0; i < element.children.length; i += 1) { + var child = element.children[i] + if (!INLINE.test(child.tagName) || !onlyInline(child)) return false + } + return true + } + + function editableBlock(element) { + return !!element && /\S/.test(element.textContent || '') && onlyInline(element) + } + + function editableUnit(target, section) { + if (!(target instanceof HTMLElement) || target.closest('svg')) return null + var node = target + var outer = null + while (node !== section && INLINE.test(node.tagName)) { + outer = node + node = node.parentElement + } + if (node !== section && editableBlock(node)) return node + return editableBlock(outer) ? outer : null + } + + function pathOf(element, section) { + var path = [] + for (var node = element; node !== section; node = node.parentElement) path.unshift(Array.prototype.indexOf.call(node.parentElement.children, node)) + return path + } + + function follow(section, path) { + var node = section + for (var i = 0; node && i < path.length; i += 1) node = node.children[path[i]] + return node || null + } + + function currentSection() { + var entry = entries[indexOf(currentId)] + var section = entry && entry.element.firstElementChild + return section && section.tagName === 'SECTION' ? { entry: entry, section: section } : null + } + + function unitAt(target) { + if (!editing || mode !== 'browse') return null + var current = currentSection() + return current && current.section.contains(target) ? editableUnit(target, current.section) : null + } + + function hover(unit) { + if (unit === hovered) return + if (hovered) hovered.removeAttribute('data-dc-editable') + hovered = unit + if (unit) unit.setAttribute('data-dc-editable', '') + } + + function trimEnd(node) { + if (node) node.nodeValue = node.nodeValue.replace(/ $/, '') + } + + function collapseSpace(element) { + var walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT) + var last = null + var open = true + while (walker.nextNode()) { + var node = walker.currentNode + if (node.nodeType !== Node.TEXT_NODE) { + if (node.tagName !== 'BR') continue + trimEnd(last) + last = null + open = true + continue + } + var value = node.nodeValue.replace(/[ \t\n\r\f]+/g, ' ') + if (open && value.charAt(0) === ' ') value = value.slice(1) + node.nodeValue = value + if (value === '') continue + open = value.charAt(value.length - 1) === ' ' + last = node + } + trimEnd(last) + } + + function breakLines(element) { + var walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT) + var nodes = [] + while (walker.nextNode()) if (walker.currentNode.nodeValue !== '') nodes.push(walker.currentNode) + var last = nodes[nodes.length - 1] + if (last) last.nodeValue = last.nodeValue.replace(/\n+$/, '') + nodes.forEach(function (node) { + var lines = node.nodeValue.split('\n') + if (lines.length === 1) return + var parts = document.createDocumentFragment() + lines.forEach(function (line, index) { + if (index > 0) parts.appendChild(document.createElement('br')) + parts.appendChild(document.createTextNode(line)) + }) + node.parentNode.replaceChild(parts, node) + }) + } + + function startEdit(event) { + if (event.button !== 0 || (active && active.element.contains(event.target))) return + finishEdit(true) + var unit = unitAt(event.target) + if (!unit) return + hover(null) + var original = unit.innerHTML + var spaced = /^(pre|pre-wrap|pre-line|break-spaces)$/.test(getComputedStyle(unit).whiteSpace) + if (!spaced) collapseSpace(unit) + unit.setAttribute('contenteditable', 'plaintext-only') + unit.addEventListener('keydown', editKey) + unit.addEventListener('blur', editBlur) + active = { entry: entries[indexOf(currentId)], element: unit, original: original, before: unit.innerHTML, spaced: spaced } + markBusy(true) + unit.focus() + } + + function editKey(event) { + if (event.isComposing) return + if (event.key === 'Enter' && !event.shiftKey) { + event.preventDefault() + finishEdit(true) + } else if (event.key === 'Escape') { + event.preventDefault() + finishEdit(false) + } + } + + function editBlur() { + finishEdit(true) + } + + function finishEdit(commit) { + var current = active + if (!current) return + active = null + var element = current.element + element.removeEventListener('keydown', editKey) + element.removeEventListener('blur', editBlur) + element.removeAttribute('contenteditable') + if (document.activeElement === element) element.blur() + if (commit && !current.spaced) breakLines(element) + var changed = commit && element.innerHTML !== current.before + if (!changed) element.innerHTML = current.original + var submitted = changed && submitEdit(current.entry, element) + if (submitted) { + element.animate([{ outline: '4px solid var(--dc-accent)', outlineOffset: '8px' }, { outline: '4px solid transparent', outlineOffset: '8px' }], { duration: SAVED_MS, easing: 'ease-out' }) + report() + } + markBusy(false) + if (!held) return + held = false + if (!submitted) refresh() + } + + function submitEdit(entry, element) { + var previous = entry.source + var copy = typeof previous === 'string' ? parseSection(previous) : null + var target = copy && follow(copy, pathOf(element, entry.element.firstElementChild)) + if (!target) { + console.warn('[deck] could not place an edit in the source of a slide', entry.id) + return false + } + target.innerHTML = element.innerHTML + var html = previous.match(/^\s*/)[0] + copy.outerHTML + previous.match(/\s*$/)[0] + entry.source = html + edits.push({ id: entry.id, html: html, previous: previous }) + emit({ type: 'edit' }) + return true + } + + function takeEdit() { + return edits.shift() || null + } + + function moveEntry(entry, index) { + var from = entries.indexOf(entry) + if (from === index) return + entries.splice(from, 1) + entries.splice(index, 0, entry) + stage.insertBefore(entry.element, stage.children[index + (index > from ? 1 : 0)] || null) + } + + function slotOf(index) { + return { x: (index % columns) * (WIDTH + GRID_GAP), y: Math.floor(index / columns) * (HEIGHT + GRID_GAP + LABEL / scale) } + } + + function slotAt(clientX, clientY) { + var box = stage.getBoundingClientRect() + var pitch = slotOf(columns) + var column = Math.max(0, Math.min(columns - 1, Math.floor(((clientX - box.left) / scale + GRID_GAP / 2) / (WIDTH + GRID_GAP)))) + var row = Math.max(0, Math.floor(((clientY - box.top) / scale + (pitch.y - HEIGHT) / 2) / pitch.y)) + return Math.min(entries.length - 1, row * columns + column) + } + + function stopMotion(entry) { + var running = motions.get(entry.element) + if (running) running.cancel() + } + + function play(element, start, end, duration) { + motions.set(element, element.animate([start, end], { duration: duration, easing: EASE })) + } + + function fadeIn(element) { + play(element, { opacity: 0 }, { opacity: 1 }, MOVE_MS) + } + + function glide(element, from, to, start, end) { + if (to.width === 0 || (from.left === to.left && from.top === to.top && from.width === to.width)) return + var zoomed = from.width !== to.width + var transform = 'translate(' + (from.left - to.left) / scale + 'px,' + (from.top - to.top) / scale + 'px)' + (zoomed ? ' scale(' + from.width / to.width + ')' : '') + play(element, Object.assign({ transformOrigin: '0 0', transform: transform }, start), Object.assign({ transformOrigin: '0 0', transform: 'none' }, end), zoomed ? ZOOM_MS : MOVE_MS) + } + + function flow(change, landing) { + if (mode !== 'overview') return change() + var before = entries.slice() + var boxes = before.map(boxOf) + var result = change() + before.forEach(stopMotion) + var targets = entries.map(boxOf) + entries.forEach(function (entry, index) { + var from = boxes[before.indexOf(entry)] + if (!from) fadeIn(entry.element) + else if (drag && entry === drag.entry) return + else if (entry === landing) glide(entry.element, from, targets[index], LIFTED, LANDED) + else glide(entry.element, from, targets[index]) + }) + return result + } + + function boxOf(entry) { + return entry.element.getBoundingClientRect() + } + + function carry() { + var box = stage.getBoundingClientRect() + var slot = slotOf(entries.indexOf(drag.entry)) + var x = Math.max(0, Math.min(slotOf(columns - 1).x, (drag.clientX - box.left) / scale - drag.grab.x)) + var y = Math.max(0, Math.min(slotOf(entries.length - 1).y, (drag.clientY - box.top) / scale - drag.grab.y)) + drag.entry.element.style.transform = 'translate(' + (x - slot.x) + 'px,' + (y - slot.y) + 'px)' + } + + function place() { + var to = slotAt(drag.clientX, drag.clientY) + if (to !== entries.indexOf(drag.entry)) { + flow(function () { + moveEntry(drag.entry, to) + }) + } + carry() + } + + function scrollAtEdge(current) { + if (drag !== current) return + var past = current.clientY < EDGE ? current.clientY - EDGE : Math.max(0, current.clientY - (window.innerHeight - EDGE)) + var top = root.scrollTop + if (past !== 0) root.scrollTop = top + past * EDGE_SPEED + if (root.scrollTop !== top) place() + requestAnimationFrame(function () { + scrollAtEdge(current) + }) + } + + function drop(current) { + current.entry.element.removeAttribute('data-dc-dragging') + current.entry.element.removeAttribute('style') + } + + function startDrag(event) { + dragged = false + if (!editing || mode !== 'overview' || event.button !== 0) return + var element = event.target.closest && event.target.closest('.dc-slide') + var index = element ? indexOf(element.getAttribute('data-slide')) : -1 + if (index < 0) return + var box = stage.getBoundingClientRect() + var slot = slotOf(index) + drag = { + entry: entries[index], + x: event.clientX, + y: event.clientY, + clientX: event.clientX, + clientY: event.clientY, + grab: { x: (event.clientX - box.left) / scale - slot.x, y: (event.clientY - box.top) / scale - slot.y }, + moved: false, + before: entries.map(idOf), + } + } + + function idOf(entry) { + return entry.id + } + + function moveDrag(event) { + if (!drag) return + drag.clientX = event.clientX + drag.clientY = event.clientY + if (!drag.moved) { + if (Math.abs(event.clientX - drag.x) < DRAG_DISTANCE && Math.abs(event.clientY - drag.y) < DRAG_DISTANCE) return + drag.moved = true + drag.entry.element.setAttribute('data-dc-dragging', '') + markBusy(true) + scrollAtEdge(drag) + } + place() + } + + function endDrag() { + var current = drag + if (!current) return + drag = null + if (!current.moved) return + dragged = true + flow(function () { + drop(current) + }, current.entry) + var ids = entries.map(idOf) + if (ids.join('\n') !== current.before.join('\n')) { + report() + emit({ type: 'order', slides: ids }) + } + markBusy(false) + } + + function cancelDrag() { + if (!drag) return + var current = drag + drag = null + dragged = current.moved + flow(function () { + drop(current) + current.before.forEach(function (id, index) { + moveEntry(entries[indexOf(id)], index) + }) + }, current.entry) + markBusy(false) + } + + function nudge(delta) { + var from = indexOf(currentId) + var to = Math.max(0, Math.min(entries.length - 1, from + delta)) + if (from < 0 || to === from) return + flow(function () { + moveEntry(entries[from], to) + }) + reveal(entries[to]) + report() + emit({ type: 'order', slides: entries.map(idOf) }) + } + + function moveAction(event) { + var delta = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -columns, ArrowDown: columns }[event.key] + if (!delta || !editing || mode !== 'overview' || drag || event.repeat) return null + return function () { + nudge(delta) + } + } + function keyActions() { + if (drag && drag.moved) return { Escape: cancelDrag } var actions = { Home: function () { turn(-entries.length) @@ -290,6 +722,11 @@ actions.Enter = actions.Escape = function () { setMode('browse') } + if (!standalone) { + actions.Delete = actions.Backspace = function () { + if (currentId) emit({ type: 'delete' }) + } + } } else { actions.ArrowRight = actions.PageDown = next actions.ArrowLeft = actions.PageUp = prev @@ -424,10 +861,20 @@ entries.forEach(function (entry) { known[entry.id] = entry }) - var nextEntries = data.ids.map(function (id, index) { + var sources = {} + data.ids.forEach(function (id, index) { + sources[id] = data.sources[index] + }) + var ids = data.ids + if (drag && ids.join('\n') === drag.before.join('\n')) ids = entries.map(idOf) + else cancelDrag() + if (active && ids.indexOf(active.entry.id) < 0) finishEdit(false) + var nextEntries = ids.map(function (id) { var entry = known[id] || createEntry(id) - if (entry.source !== data.sources[index]) { - fill(entry, data.sources[index]) + if (entry.source === sources[id]) return entry + if (active && active.entry === entry) held = true + else { + fill(entry, sources[id]) changed = true } return entry @@ -515,7 +962,10 @@ return load() .then(function (data) { var previous = indexOf(currentId) - if (apply(data)) keepPlace(currentId, previous) + var changed = flow(function () { + return apply(data) + }) + if (changed) keepPlace(currentId, previous) return syncReferences() }) .then( @@ -632,13 +1082,31 @@ if (id !== currentId) goTo(id) }) document.addEventListener('keydown', function (event) { - if (event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey || isTyping(event.target)) return - var action = keyActions()[event.key] + if (event.defaultPrevented || event.altKey || isTyping(event.target)) return + var action = event.ctrlKey || event.metaKey ? moveAction(event) : keyActions()[event.key] if (!action) return event.preventDefault() action() }) + stage.addEventListener('pointerdown', function (event) { + startEdit(event) + startDrag(event) + }) + stage.addEventListener('pointermove', function (event) { + var unit = unitAt(event.target) + hover(active && active.element === unit ? null : unit) + }) + stage.addEventListener('pointerleave', function () { + hover(null) + }) + document.addEventListener('pointermove', moveDrag) + document.addEventListener('pointerup', endDrag) + document.addEventListener('pointercancel', cancelDrag) stage.addEventListener('click', function (event) { + if (dragged) { + dragged = false + return + } if (mode !== 'overview') return var slide = event.target.closest('.dc-slide') if (!slide) return @@ -682,6 +1150,10 @@ stage = root.querySelector('.dc-stage') notice = root.querySelector('.dc-notice') root.setAttribute('data-mode', mode) + root.removeAttribute('data-editing') + Array.prototype.forEach.call(root.querySelectorAll('[contenteditable]'), function (element) { + element.removeAttribute('contenteditable') + }) entries = Array.prototype.map.call(stage.querySelectorAll(':scope > .dc-slide'), function (element) { return { id: element.getAttribute('data-slide'), element: element, source: undefined } }) @@ -711,6 +1183,8 @@ stageRect: stageRect, overflow: overflow, prepareCapture: prepareCapture, + setEditing: setEditing, + takeEdit: takeEdit, } if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot) diff --git a/desktop/src/__tests__/pages.test.tsx b/desktop/src/__tests__/pages.test.tsx index 36a0f490..8772931d 100644 --- a/desktop/src/__tests__/pages.test.tsx +++ b/desktop/src/__tests__/pages.test.tsx @@ -114,6 +114,7 @@ function runtimeMirror(selection: RuntimeSelection): SessionState { pendingPermissions: [], pendingBrowserGrants: [], browserActivity: null, + artifactWait: null, slashCommands: [], activeGoal: null, backgroundTasks: [], diff --git a/desktop/src/api/artifacts.ts b/desktop/src/api/artifacts.ts index c48e3ae8..10f9d929 100644 --- a/desktop/src/api/artifacts.ts +++ b/desktop/src/api/artifacts.ts @@ -1,6 +1,8 @@ import { api, getBaseUrl } from './client' import type { ArtifactCopyResult, ArtifactListItem, ArtifactOpenTarget } from '../types/artifact' +type ArtifactUserWrite = { dir: string; files: string[]; latestMtimeMs: number } + export const artifactsApi = { list: () => api.get<{ artifacts: ArtifactListItem[] }>('/api/artifacts'), @@ -12,7 +14,17 @@ export const artifactsApi = { putThumbnail: (id: string, mtimeMs: number, data: string) => api.put<{ ok: true }>('/api/artifacts/thumbnail', { id, mtimeMs, data }), moveBoard: (body: { dir: string; name: string; boardId: string; x: number; y: number; width: number; height: number }) => - api.patch<{ latestMtimeMs: number }>('/api/artifacts/boards', body), + api.patch('/api/artifacts/boards', body), + + holdEdit: (dir: string, name: string, holder: string) => api.post<{ ok: true }>('/api/artifacts/edit-lock', { dir, name, holder }), + + releaseEdit: (dir: string, name: string, holder: string) => api.delete<{ ok: true }>(`/api/artifacts/edit-lock?${new URLSearchParams({ dir, name, holder }).toString()}`), + + reorderSlides: (body: { dir: string; name: string; slides: string[] }) => api.patch('/api/artifacts/slides/order', body), + + deleteSlide: (dir: string, name: string, id: string) => api.delete(`/api/artifacts/slides?${new URLSearchParams({ dir, name, id }).toString()}`), + + writeSlide: (body: { dir: string; name: string; id: string; html: string; previous: string }) => api.put('/api/artifacts/slides/content', body), markOpened: (id: string) => api.post<{ ok: true }>('/api/artifacts/opened', { id }), diff --git a/desktop/src/components/artifacts/ArtifactViewer.test.tsx b/desktop/src/components/artifacts/ArtifactViewer.test.tsx index 815584d6..34d60bff 100644 --- a/desktop/src/components/artifacts/ArtifactViewer.test.tsx +++ b/desktop/src/components/artifacts/ArtifactViewer.test.tsx @@ -11,6 +11,9 @@ const mocks = vi.hoisted(() => ({ submitBrowserInput: vi.fn(), browserReload: vi.fn(), setCanvasMessageHandler: vi.fn(), + setDeckMessageHandler: vi.fn(), + applyDeckEdit: vi.fn(), + flushDeckEdits: vi.fn(async () => undefined), continueInSession: vi.fn(), continueInNewSession: vi.fn(), toastError: vi.fn(), @@ -24,6 +27,7 @@ vi.mock('../../lib/browserGuests', () => ({ submitBrowserInput: mocks.submitBrowserInput, browserReload: mocks.browserReload, setCanvasMessageHandler: mocks.setCanvasMessageHandler, + setDeckMessageHandler: mocks.setDeckMessageHandler, })) vi.mock('../../lib/continueArtifactInSession', () => ({ continueArtifactInSession: mocks.continueInSession, @@ -34,6 +38,7 @@ vi.mock('../../lib/artifactExport', async (importOriginal) => ({ exportArtifactPage: mocks.exportArtifactPage, })) vi.mock('sonner', () => ({ toast: { error: mocks.toastError } })) +vi.mock('../../lib/deckEdits', async (importOriginal) => ({ ...(await importOriginal()), applyDeckEdit: mocks.applyDeckEdit, flushDeckEdits: mocks.flushDeckEdits })) import type { ArtifactListItem } from '../../types/artifact' import { useArtifactListStore } from '../../stores/artifactListStore' @@ -154,12 +159,26 @@ describe('ArtifactViewer', () => { render() expect(screen.queryByTestId('deck-controls')).not.toBeInTheDocument() act(() => { - useBrowserStore.getState().patchPage(ARTIFACT_VIEW_TAB, { deck: { artifact: 'id-report', slide: 'cover', title: 'Cover', index: 0, count: 2, mode: 'browse' } }) + useBrowserStore.getState().patchPage(ARTIFACT_VIEW_TAB, { deck: { artifact: 'id-report', slide: 'cover', title: 'Cover', index: 0, count: 2, mode: 'browse', editing: false } }) }) expect(screen.getByTestId('deck-position')).toHaveTextContent('1 / 2') await waitFor(() => expect(mocks.markOpened).toHaveBeenCalled()) }) + it('offers editing on a deck and writes the edits back to the artifact it shows', async () => { + mocks.applyDeckEdit.mockResolvedValue(undefined) + useArtifactListStore.setState({ items: [{ ...listed, manifest: { ...listed.manifest!, kind: 'deck' } }] }) + act(() => { + useBrowserStore.getState().patchPage(ARTIFACT_VIEW_TAB, { deck: { artifact: 'id-report', slide: 'cover', title: 'Cover', index: 0, count: 2, mode: 'browse', editing: false } }) + }) + render() + expect(screen.getByRole('button', { name: 'Edit' })).toBeInTheDocument() + const handler = mocks.setDeckMessageHandler.mock.calls.find((call) => call[0] === ARTIFACT_VIEW_TAB && call[1])?.[1] + handler({ type: 'edit' }) + expect(mocks.applyDeckEdit).toHaveBeenCalledWith({ tabId: ARTIFACT_VIEW_TAB, root: '/repo/dc_artifacts', name: 'report', title: listed.manifest!.title, sessionId: null }, { type: 'edit' }) + await waitFor(() => expect(mocks.markOpened).toHaveBeenCalled()) + }) + it('closes the page when it goes away', () => { const { unmount } = render() unmount() diff --git a/desktop/src/components/artifacts/ArtifactViewer.tsx b/desktop/src/components/artifacts/ArtifactViewer.tsx index 400d49b9..26ee1c35 100644 --- a/desktop/src/components/artifacts/ArtifactViewer.tsx +++ b/desktop/src/components/artifacts/ArtifactViewer.tsx @@ -37,7 +37,7 @@ export function ArtifactViewer({ viewing }: { viewing: ViewedArtifact }) { () => artifactsApi.openById(viewing.id), () => artifactsApi.markOpened(viewing.id), ) - useCanvasTab(item && kind === 'canvas' ? { tabId: ARTIFACT_VIEW_TAB, sessionId: null, root: artifactRoot(item), name: item.name } : null) + useCanvasTab(item && kind === 'canvas' ? { tabId: ARTIFACT_VIEW_TAB, sessionId: null, root: artifactRoot(item), name: item.name, title: item.manifest?.title ?? item.name } : null) const exportActions = useArtifactExportActions({ tabId: ARTIFACT_VIEW_TAB, sessionId: null, title: viewing.title }) const report = (error: unknown) => toast.error(errorMessage(error)) @@ -94,7 +94,7 @@ export function ArtifactViewer({ viewing }: { viewing: ViewedArtifact }) { } /> - +
) diff --git a/desktop/src/components/artifacts/DeckControls.test.tsx b/desktop/src/components/artifacts/DeckControls.test.tsx index a52f6dfd..46a3ac79 100644 --- a/desktop/src/components/artifacts/DeckControls.test.tsx +++ b/desktop/src/components/artifacts/DeckControls.test.tsx @@ -6,23 +6,35 @@ const mocks = vi.hoisted(() => ({ runDeckCall: vi.fn(), presentDeck: vi.fn(), toastError: vi.fn(), + setDeckMessageHandler: vi.fn(), + applyDeckEdit: vi.fn(), + deleteDeckSlide: vi.fn(), + flushDeckEdits: vi.fn(), + stopArtifactHold: vi.fn(), })) -vi.mock('../../lib/browserGuests', () => ({ runDeckCall: mocks.runDeckCall, presentDeck: mocks.presentDeck })) +vi.mock('../../lib/browserGuests', () => ({ runDeckCall: mocks.runDeckCall, presentDeck: mocks.presentDeck, setDeckMessageHandler: mocks.setDeckMessageHandler })) +vi.mock('../../lib/artifactUserEdits', async (importOriginal) => ({ ...(await importOriginal()), stopArtifactHold: mocks.stopArtifactHold })) +vi.mock('../../lib/deckEdits', async (importOriginal) => ({ ...(await importOriginal()), applyDeckEdit: mocks.applyDeckEdit, deleteDeckSlide: mocks.deleteDeckSlide, flushDeckEdits: mocks.flushDeckEdits })) vi.mock('sonner', () => ({ toast: { error: mocks.toastError } })) -import type { DeckState } from '../../lib/deckBridge' +import { ApiError } from '../../api/client' +import type { DeckRequest, DeckState } from '../../lib/deckBridge' import { useBrowserStore } from '../../stores/browserStore' import { useSettingsStore } from '../../stores/settingsStore' import { DeckControls } from './DeckControls' -const deck = (overrides: Partial = {}): DeckState => ({ artifact: 'deck-1', slide: 'agenda', title: 'Agenda', index: 1, count: 3, mode: 'browse', ...overrides }) +const deck = (overrides: Partial = {}): DeckState => ({ artifact: 'deck-1', slide: 'agenda', title: 'Agenda', index: 1, count: 3, mode: 'browse', editing: false, ...overrides }) +const target = { root: '/repo/dc_artifacts', name: 'talk', title: 'Talk', sessionId: 's1' } const show = (state: DeckState | null) => act(() => useBrowserStore.getState().patchPage('t1', { deck: state })) describe('DeckControls', () => { beforeEach(() => { mocks.runDeckCall.mockResolvedValue(undefined) mocks.presentDeck.mockResolvedValue(undefined) + mocks.applyDeckEdit.mockResolvedValue(undefined) + mocks.deleteDeckSlide.mockResolvedValue(undefined) + mocks.flushDeckEdits.mockResolvedValue(undefined) }) afterEach(() => { @@ -95,6 +107,109 @@ describe('DeckControls', () => { for (const name of ['Previous slide', 'Next slide', 'Overview', 'Present']) expect(screen.getByRole('button', { name })).toBeDisabled() }) + it('offers editing and deleting only for a deck its tab can write to', () => { + show(deck()) + const { rerender } = render() + expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Delete slide' })).not.toBeInTheDocument() + expect(mocks.setDeckMessageHandler).not.toHaveBeenCalledWith('t1', expect.any(Function)) + rerender() + expect(screen.getByRole('button', { name: 'Edit' })).toBeEnabled() + expect(screen.getByRole('button', { name: 'Delete slide' })).toBeEnabled() + }) + + it('turns editing on and off, showing which one is on and what the user can do', () => { + show(deck()) + render() + const edit = screen.getByRole('button', { name: 'Edit' }) + expect(edit).toHaveAttribute('aria-pressed', 'false') + fireEvent.click(edit) + expect(mocks.runDeckCall).toHaveBeenLastCalledWith('t1', 'window.__dreamcoderDeck?.setEditing(true)') + + show(deck({ editing: true })) + expect(edit).toHaveAttribute('aria-pressed', 'true') + expect(screen.getByTestId('deck-editing-hint')).toHaveTextContent('Click a text to change it. Enter saves, Shift+Enter starts a new line.') + show(deck({ editing: true, mode: 'overview' })) + expect(screen.getByTestId('deck-editing-hint')).toHaveTextContent('Drag a slide to move it, or press ⌘/Ctrl and an arrow key.') + fireEvent.click(edit) + expect(mocks.runDeckCall).toHaveBeenLastCalledWith('t1', 'window.__dreamcoderDeck?.setEditing(false)') + }) + + it('offers no editing or deleting during the presentation or in a deck without slides', () => { + show(deck({ mode: 'present' })) + render() + expect(screen.getByRole('button', { name: 'Edit' })).toBeDisabled() + expect(screen.getByRole('button', { name: 'Delete slide' })).toBeDisabled() + show(deck({ slide: null, title: null, index: -1, count: 0 })) + expect(screen.getByRole('button', { name: 'Edit' })).toBeDisabled() + expect(screen.getByRole('button', { name: 'Delete slide' })).toBeDisabled() + }) + + it('writes back the order and the edits its deck sends, and tells the user when one conflicts or fails', async () => { + show(deck()) + const { unmount } = render() + const handler = mocks.setDeckMessageHandler.mock.calls.find((call) => call[0] === 't1' && call[1])?.[1] as (message: DeckRequest) => void + handler({ type: 'order', slides: ['b', 'a'] }) + expect(mocks.applyDeckEdit).toHaveBeenCalledWith({ tabId: 't1', ...target }, { type: 'order', slides: ['b', 'a'] }) + + mocks.applyDeckEdit.mockRejectedValueOnce(new ApiError(409, { message: 'changed' })) + handler({ type: 'order', slides: ['b', 'a'] }) + await waitFor(() => expect(mocks.toastError).toHaveBeenLastCalledWith('The slides were just changed elsewhere. The latest order is shown.')) + mocks.applyDeckEdit.mockRejectedValueOnce(new ApiError(409, { message: 'changed' })) + handler({ type: 'edit' }) + await waitFor(() => expect(mocks.toastError).toHaveBeenLastCalledWith('This slide was just changed elsewhere. The latest version is shown; make your edit again.')) + mocks.applyDeckEdit.mockRejectedValueOnce(new Error('offline')) + handler({ type: 'edit' }) + await waitFor(() => expect(mocks.toastError).toHaveBeenLastCalledWith('Could not save the change: offline')) + + unmount() + expect(mocks.setDeckMessageHandler).toHaveBeenLastCalledWith('t1', null) + expect(mocks.stopArtifactHold).toHaveBeenCalledWith('t1') + }) + + it('writes the edits its deck made while no handler listened, as soon as it listens again', () => { + show(deck()) + render() + expect(mocks.flushDeckEdits).toHaveBeenCalledWith({ tabId: 't1', ...target }) + }) + + it('deletes the current slide only after the user confirms', async () => { + show(deck()) + render() + fireEvent.click(screen.getByRole('button', { name: 'Delete slide' })) + expect(screen.getByRole('alertdialog')).toHaveTextContent('Agenda') + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) + expect(mocks.deleteDeckSlide).not.toHaveBeenCalled() + + fireEvent.click(screen.getByRole('button', { name: 'Delete slide' })) + fireEvent.click(screen.getByRole('button', { name: 'Delete' })) + await waitFor(() => expect(mocks.deleteDeckSlide).toHaveBeenCalledWith({ tabId: 't1', ...target }, 'agenda')) + await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()) + + mocks.deleteDeckSlide.mockRejectedValueOnce(new Error('gone')) + fireEvent.click(screen.getByRole('button', { name: 'Delete slide' })) + fireEvent.click(screen.getByRole('button', { name: 'Delete' })) + await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith('Could not delete the slide: gone')) + }) + + it('says what Edit is for while it is off', async () => { + show(deck()) + render() + fireEvent.focus(screen.getByRole('button', { name: 'Edit' })) + expect(await screen.findByRole('tooltip')).toHaveTextContent('Change text and reorder slides') + }) + + it('asks before deleting when the deck itself asks to delete the current slide', async () => { + show(deck()) + render() + const handler = mocks.setDeckMessageHandler.mock.calls.find((call) => call[0] === 't1' && call[1])?.[1] as (message: DeckRequest) => void + act(() => handler({ type: 'delete' })) + expect(screen.getByRole('alertdialog')).toHaveTextContent('Agenda') + expect(mocks.applyDeckEdit).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('button', { name: 'Delete' })) + await waitFor(() => expect(mocks.deleteDeckSlide).toHaveBeenCalledWith({ tabId: 't1', ...target }, 'agenda')) + }) + it('uses the language of the app', () => { useSettingsStore.setState({ locale: 'zh' }) show(deck()) @@ -102,5 +217,9 @@ describe('DeckControls', () => { expect(screen.getByRole('button', { name: '总览' })).toBeInTheDocument() expect(screen.getByRole('button', { name: '演示' })).toBeInTheDocument() expect(screen.getByRole('button', { name: '下一页' })).toBeInTheDocument() + cleanup() + render() + expect(screen.getByRole('button', { name: '编辑' })).toBeInTheDocument() + expect(screen.getByRole('button', { name: '删除本页' })).toBeInTheDocument() }) }) diff --git a/desktop/src/components/artifacts/DeckControls.tsx b/desktop/src/components/artifacts/DeckControls.tsx index 9966f3f8..3deb161a 100644 --- a/desktop/src/components/artifacts/DeckControls.tsx +++ b/desktop/src/components/artifacts/DeckControls.tsx @@ -1,16 +1,111 @@ -import { ChevronLeft, ChevronRight, LayoutGrid, Presentation } from 'lucide-react' +import { useEffect, useState } from 'react' +import { ChevronLeft, ChevronRight, LayoutGrid, PencilLine, Presentation, Trash2 } from 'lucide-react' import { toast } from 'sonner' import { useTranslation } from '../../i18n' -import { presentDeck, runDeckCall } from '../../lib/browserGuests' -import { DECK_NEXT_CALL, DECK_PREV_CALL, deckModeCall } from '../../lib/deckBridge' +import { presentDeck, runDeckCall, setDeckMessageHandler } from '../../lib/browserGuests' +import { DECK_NEXT_CALL, DECK_PREV_CALL, deckEditingCall, deckModeCall, type DeckEditMessage, type DeckState } from '../../lib/deckBridge' +import { stopArtifactHold, type ArtifactEditTarget } from '../../lib/artifactUserEdits' +import { applyDeckEdit, deleteDeckSlide, flushDeckEdits, isDeckConflict } from '../../lib/deckEdits' import { errorMessage } from '../../lib/errorMessage' import { useBrowserStore } from '../../stores/browserStore' +import { ConfirmDialog } from '../shared/ConfirmDialog' import { Tooltip } from '../shared/Tooltip' import { Button } from '../shared/ui/button' -export function DeckControls({ tabId }: { tabId: string }) { +type DeckEditTarget = Omit + +function useDeckWriteBack(tabId: string, editTarget: DeckEditTarget | undefined, askToDelete: (asking: boolean) => void) { + const t = useTranslation() + const root = editTarget?.root + const name = editTarget?.name + const title = editTarget?.title + const sessionId = editTarget?.sessionId + useEffect(() => { + if (root === undefined || name === undefined || title === undefined || sessionId === undefined) return + const target: ArtifactEditTarget = { tabId, root, name, title, sessionId } + const report = (type: DeckEditMessage['type']) => (error: unknown) => { + if (!isDeckConflict(error)) toast.error(t('deck.saveFailed', { message: errorMessage(error) })) + else toast.error(t(type === 'order' ? 'deck.orderConflict' : 'deck.editConflict')) + } + setDeckMessageHandler(tabId, (message) => { + if (message.type === 'delete') askToDelete(true) + else applyDeckEdit(target, message).catch(report(message.type)) + }) + flushDeckEdits(target).catch(report('edit')) + return () => { + setDeckMessageHandler(tabId, null) + stopArtifactHold(tabId) + } + }, [tabId, root, name, title, sessionId, askToDelete, t]) +} + +function DeckEditControls({ + tabId, + deck, + editTarget, + confirming, + setConfirming, +}: { + tabId: string + deck: DeckState + editTarget: DeckEditTarget + confirming: boolean + setConfirming: (confirming: boolean) => void +}) { + const t = useTranslation() + const [deleting, setDeleting] = useState(false) + const unavailable = deck.count === 0 || deck.mode === 'present' + const slide = deck.slide + + const remove = async () => { + if (!slide) return + setDeleting(true) + try { + await deleteDeckSlide({ tabId, ...editTarget }, slide) + setConfirming(false) + } catch (error) { + toast.error(t('deck.deleteFailed', { message: errorMessage(error) })) + } finally { + setDeleting(false) + } + } + + return ( +
+ {deck.editing && ( + + {t(deck.mode === 'overview' ? 'deck.editingHintOverview' : 'deck.editingHintBrowse')} + + )} + + + + + setConfirming(false)} + onConfirm={remove} + title={t('deck.deleteTitle')} + body={t('deck.deleteBody', { title: deck.title ?? slide ?? '' })} + confirmLabel={t('common.delete')} + cancelLabel={t('common.cancel')} + loading={deleting} + /> +
+ ) +} + +export function DeckControls({ tabId, editTarget }: { tabId: string; editTarget?: DeckEditTarget }) { const t = useTranslation() const deck = useBrowserStore((state) => state.pageByTab[tabId]?.deck) + const [confirming, setConfirming] = useState(false) + useDeckWriteBack(tabId, editTarget, setConfirming) if (!deck) return null const overview = deck.mode === 'overview' @@ -47,6 +142,7 @@ export function DeckControls({ tabId }: { tabId: string }) {