Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(whiteboard): a save that did not land never closes the board

review6f8a0d55450a
diff --git a/CLAUDE.md b/CLAUDE.md
index 3ccd8c73d..8771cbaac 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2179,7 +2179,10 @@ number: change the table in that one module, never in one emulator.
saved, not with disk. The unmount flush writes a snapshot kept from `onChange` — Excalidraw's api
is empty by cleanup time, and reading it there once erased a board; (5) the project folder is
bound by its REAL path — a `.nodeterm` or `.nodeterm/whiteboards` symlink leading out of the
- project is not followed (the board falls back to the app folder). Excalidraw loads lazily; fonts
+ project is not followed (the board falls back to the app folder); (6) finishing (Esc, a press
+ outside) waits for a save that SUCCEEDED — a failed or refused one keeps the editor open with
+ "Keep mine" / "Discard my changes" in the header, since after the exit there is no flush left to
+ retry — and a hosted-team Viewer opens the board view-only. Excalidraw loads lazily; fonts
come from `scripts/excalidraw-assets-plugin.ts`; mermaid is aliased to a stub.
- **Run node** (a `terminal` node carrying `data.runConfig`, NOT a new NodeKind;
`@shared/run-config`, `core/run-service.ts`, `nodes/RunBar.tsx`) — VS Code's "Run Without
diff --git a/docs/whiteboard-node.md b/docs/whiteboard-node.md
index 251cae128..3bab408b1 100644
--- a/docs/whiteboard-node.md
+++ b/docs/whiteboard-node.md
@@ -7,7 +7,8 @@ pasted images, undo and export. It embeds [Excalidraw](https://github.com/excali
Add one from right-click → **New view → New whiteboard**, the sessions-sidebar "+", the Dock, or
⌘K "New whiteboard" (`node.newWhiteboard`, unbound by default). A new board opens ready to draw.
-Double-click (or Enter on) a board to draw on it again; Esc or a click outside finishes. The header
+Double-click (or Enter on) a board to draw on it again; Esc or a click outside finishes — once the
+board is saved (see "When a save does not land" below). The header
has **Present** (maximize + Excalidraw's zen mode, restored on Esc) and **Copy as image** (the board
as a PNG on the clipboard). Its default size is a Settings → Behavior → Default node size entry.
@@ -87,6 +88,18 @@ check; two cores writing one folder (a desktop and a Server Edition) can still i
moment between the check and the rename. A core on an older build ignores the revision and answers
the bare path, and the save is then unchecked, as before.
+**When a save does not land, the board stays open.** Finishing (Esc, a press outside) waits for a
+save that succeeded; a failed or refused one keeps the editor open, because once editing ends the
+unsaved strokes have nowhere to go. The header says why — **Not saved** (the save could not be
+written: a full disk, a board over the Server Edition's 8 MiB frame, a core that went away) or
+**Changed elsewhere** (above) — and offers the way forward: **Keep mine** after a conflict saves
+over the other version knowingly (it sends that version's revision), and **Discard my changes**
+ends editing without the unsaved strokes, leaving the board on disk as it is. A project switch or
+deleting the node still flushes what it can on the way out; a failure there is not reported.
+
+**A hosted-team Viewer or Commenter opens the board view-only** (Excalidraw's view mode): the host
+refuses their saves, so the editor never offers drawing that cannot be written.
+
**The project folder is bound by its real path.** `.nodeterm/` is git-shared, so a repository can
commit `.nodeterm` or `.nodeterm/whiteboards` as a symlink to any directory on this machine. Each
existing component is resolved before anything is created through it and must stay inside the
diff --git a/src/renderer/nodes/WhiteboardNode.test.tsx b/src/renderer/nodes/WhiteboardNode.test.tsx
index ee4164355..b8c1fe7b4 100644
--- a/src/renderer/nodes/WhiteboardNode.test.tsx
+++ b/src/renderer/nodes/WhiteboardNode.test.tsx
@@ -24,11 +24,21 @@ interface EditorProps {
readOnly?: boolean
onSave: (scene: string, thumbnailBase64?: string) => Promise<boolean>
onExit: (changed: boolean) => void
+ controlRef?: { current: { saveNow: () => Promise<boolean>; discard: () => void } | null }
}
-const editor: { props: EditorProps | null } = { props: null }
+const editor: { props: EditorProps | null; discarded: number } = { props: null, discarded: 0 }
vi.mock('../whiteboard/WhiteboardEditor', () => ({
default: (props: EditorProps) => {
editor.props = props
+ if (props.controlRef) {
+ props.controlRef.current = {
+ saveNow: () => props.onSave(JSON.stringify({ type: 'excalidraw', elements: [] })),
+ discard: () => {
+ editor.discarded++
+ props.onExit(false)
+ }
+ }
+ }
return <div data-testid="editor" />
}
}))
@@ -43,6 +53,7 @@ vi.mock('../session/session', () => ({
import { WhiteboardNode } from './WhiteboardNode'
import { useProjects } from '../state/projects'
+import { useHostedTeams } from '../state/hostedTeams'
const SCENE = JSON.stringify({ type: 'excalidraw', elements: [] })
@@ -95,6 +106,8 @@ async function openEditor(): Promise<EditorProps> {
beforeEach(() => {
editor.props = null
+ editor.discarded = 0
+ useHostedTeams.getState().forget('local')
files.readWhiteboard.mockReset()
files.saveWhiteboard.mockReset()
useProjects.setState({ activeProjectId: 'p1' })
@@ -155,3 +168,55 @@ describe('saving sends the revision the editor started from', () => {
expect(host.querySelector('.whiteboard-node__save-failed')).toBeNull()
})
})
+
+const button = (label: RegExp): HTMLButtonElement | undefined =>
+ [...host.querySelectorAll('button')].find((b) => label.test(b.textContent ?? '') || label.test(b.getAttribute('aria-label') ?? ''))
+
+describe('a save that did not land offers a way forward instead of losing the work', () => {
+ it('"Keep mine" after a conflict saves over the other version, knowingly (its revision)', async () => {
+ files.readWhiteboard.mockResolvedValue({ scene: SCENE, updatedAt: 1, rev: 'r1', fromSource: false })
+ files.saveWhiteboard
+ .mockResolvedValueOnce({ ok: false, conflict: true, currentRev: 'r9' })
+ .mockResolvedValueOnce({ ok: true, path: '/p/whiteboard-1.excalidraw', rev: 'r10' })
+ mount()
+ const props = await openEditor()
+ await act(async () => void (await props.onSave(SCENE)))
+ const keep = button(/keep mine/i)
+ expect(keep).toBeDefined()
+ await act(async () => keep!.click())
+ await settle()
+ expect(files.saveWhiteboard.mock.calls[1]?.[4]).toBe('r9')
+ expect(host.querySelector('.whiteboard-node__save-failed')).toBeNull()
+ })
+
+ it('"Discard my changes" appears while a save keeps failing and ends editing without them', async () => {
+ files.readWhiteboard.mockResolvedValue({ scene: SCENE, updatedAt: 1, rev: 'r1', fromSource: false })
+ files.saveWhiteboard.mockResolvedValue(null)
+ mount()
+ const props = await openEditor()
+ expect(button(/discard my changes/i)).toBeUndefined()
+ await act(async () => void (await props.onSave(SCENE)))
+ const discard = button(/discard my changes/i)
+ expect(discard).toBeDefined()
+ await act(async () => discard!.click())
+ expect(editor.discarded).toBe(1)
+ })
+})
+
+describe('a hosted-team Viewer', () => {
+ it('opens the board read-only (the host refuses their saves)', async () => {
+ useHostedTeams.getState().set('local', { role: 'viewer', teamLabel: 'Team' })
+ files.readWhiteboard.mockResolvedValue({ scene: SCENE, updatedAt: 1, rev: 'r1', fromSource: false })
+ mount()
+ const props = await openEditor()
+ expect(props.readOnly).toBe(true)
+ })
+
+ it('an Editor does not', async () => {
+ useHostedTeams.getState().set('local', { role: 'editor', teamLabel: 'Team' })
+ files.readWhiteboard.mockResolvedValue({ scene: SCENE, updatedAt: 1, rev: 'r1', fromSource: false })
+ mount()
+ const props = await openEditor()
+ expect(props.readOnly).toBeFalsy()
+ })
+})
diff --git a/src/renderer/nodes/WhiteboardNode.tsx b/src/renderer/nodes/WhiteboardNode.tsx
index f012c78c9..eef1c1fa4 100644
--- a/src/renderer/nodes/WhiteboardNode.tsx
+++ b/src/renderer/nodes/WhiteboardNode.tsx
@@ -9,7 +9,9 @@ import { useAppTheme } from '../state/useAppTheme'
import { useProjects } from '../state/projects'
import { markWorkspaceDirty } from '../state/workspaceDirty'
import { useSession } from '../session/session'
+import { useHostedReadOnly } from '../state/hostedTeams'
import { MaximizeButton, useNodeMaximize } from './MaximizeButton'
+import type { WhiteboardEditorControl } from '../whiteboard/WhiteboardEditor'
// Excalidraw (~1.7 MB of JS + CSS) loads the first time a board is opened for editing, never at
// startup and never for a board that is only being looked at. The asset path must be set before
@@ -60,7 +62,11 @@ const pngDataUrl = (base64: string): string => `data:image/png;base64,${base64}`
*/
export function WhiteboardNode({ id, data, selected, positionAbsoluteX, positionAbsoluteY, width, height }: NodeProps<CanvasNode>) {
const { updateNodeData, deleteElements } = useReactFlow()
- const { api } = useSession()
+ const session = useSession()
+ const { api } = session
+ // A hosted-team Viewer or Commenter: the host refuses their saves, so the board opens view-only
+ // rather than letting them draw what can never be written.
+ const readOnly = useHostedReadOnly(session.id)
const theme = useAppTheme()
const setMaximized = useNodeMaximize(id)
// A node renders only inside its own project, and a project switch unmounts it — after the
@@ -76,6 +82,9 @@ export function WhiteboardNode({ id, data, selected, positionAbsoluteX, position
const [mode, setMode] = useState<null | 'edit' | 'present'>(null)
const [geom, setGeom] = useState<Geometry | null>(null)
const [thumb, setThumb] = useState<string>()
+ // Bumped when editing ends, so the resting picture is read again: after "Discard my changes" the
+ // board on disk may be someone else's newer version, which no node-data change announces here.
+ const [pictureTick, setPictureTick] = useState(0)
const sceneRef = useRef<string | undefined>(undefined)
// The revision of the board file this editing session started from, then of each save it made —
// what every save sends, so the core can refuse one made over somebody else's newer board
@@ -86,6 +95,9 @@ export function WhiteboardNode({ id, data, selected, positionAbsoluteX, position
const [loadState, setLoadState] = useState<'loading' | 'ready' | 'unreadable'>('loading')
// `conflict`: the core refused the last save because someone else saved this board meanwhile.
const [saveState, setSaveState] = useState<'saved' | 'failed' | 'conflict'>('saved')
+ // The revision on disk when the last save was refused: "Keep mine" saves over exactly that one.
+ const conflictRevRef = useRef<string | null>(null)
+ const editorControl = useRef<WhiteboardEditorControl | null>(null)
const [copied, setCopied] = useState(false)
const maximizedByPresentRef = useRef(false)
const viewKey = useStore(transformKey)
@@ -112,7 +124,7 @@ export function WhiteboardNode({ id, data, selected, positionAbsoluteX, position
return () => {
live = false
}
- }, [api, id, data.whiteboardSource, data.boardRev])
+ }, [api, id, data.whiteboardSource, data.boardRev, pictureTick])
const measure = useCallback(() => {
const body = bodyRef.current
@@ -154,6 +166,7 @@ export function WhiteboardNode({ id, data, selected, positionAbsoluteX, position
return false
}
if (typeof res === 'object' && !res.ok) {
+ conflictRevRef.current = res.currentRev
setSaveState('conflict')
return false
}
@@ -219,6 +232,8 @@ export function WhiteboardNode({ id, data, selected, positionAbsoluteX, position
if (maximizedByPresentRef.current && dataRef.current.premaxRect) setMaximized(true)
maximizedByPresentRef.current = false
setMode(null)
+ setSaveState('saved')
+ setPictureTick((t) => t + 1)
// Read again on the next open; a board at rest keeps only its picture.
sceneRef.current = undefined
if (changed) {
@@ -265,12 +280,39 @@ export function WhiteboardNode({ id, data, selected, positionAbsoluteX, position
title={
saveState === 'conflict'
? 'Someone else saved this board while it was open here (another tab, another computer on this folder, or a teammate). Their version was kept; your changes are not saved.'
- : 'The last change could not be written. The board stays open; it retries on the next change.'
+ : 'The last change could not be written. The board stays open and finishing waits until a save succeeds; it retries on the next change.'
}
>
{saveState === 'conflict' ? 'Changed elsewhere' : 'Not saved'}
</span>
)}
+ {mode && saveState === 'conflict' && (
+ <Tooltip label="Save your version over the one saved elsewhere">
+ <button
+ className="whiteboard-node__save-action nodrag"
+ onClick={(e) => {
+ e.stopPropagation()
+ revRef.current = conflictRevRef.current
+ void editorControl.current?.saveNow()
+ }}
+ >
+ Keep mine
+ </button>
+ </Tooltip>
+ )}
+ {mode && saveState !== 'saved' && (
+ <Tooltip label="Stop editing without your unsaved changes; the board on disk is kept as it is">
+ <button
+ className="whiteboard-node__save-action nodrag"
+ onClick={(e) => {
+ e.stopPropagation()
+ editorControl.current?.discard()
+ }}
+ >
+ Discard my changes
+ </button>
+ </Tooltip>
+ )}
<span className="term-node__spacer" />
<Tooltip label={copied ? 'Copied' : 'Copy as image'}>
<button
@@ -343,6 +385,8 @@ export function WhiteboardNode({ id, data, selected, positionAbsoluteX, position
theme={theme}
canvasZoom={canvasZoom}
present={mode === 'present'}
+ readOnly={readOnly}
+ controlRef={editorControl}
geometryKey={`${geom.board.left},${geom.board.top},${geom.board.width},${geom.board.height},${geom.clip.left},${geom.clip.top}`}
overlayRef={overlayRef}
frameRef={frameRef}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 08ee19ec2..ff9e82305 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -18335,6 +18335,21 @@ body.focus-mode .dock:hover {
font-size: 11px;
font-weight: 600;
}
+/* "Keep mine" / "Discard my changes": the way forward from a save that did not land. */
+.whiteboard-node__save-action {
+ flex: 0 0 auto;
+ padding: 1px 7px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ background: transparent;
+ color: var(--text);
+ font-size: 11px;
+ cursor: pointer;
+}
+.whiteboard-node__save-action:hover {
+ background: var(--panel-2);
+ color: var(--text-strong);
+}
/* The canvas area, in .canvas-root coordinates: clips the live editor to the canvas and stacks it
under the sessions sidebar (z 12) and the Dock (z 20), which sit beside .flow-wrap. */
.whiteboard-clip {
diff --git a/src/renderer/whiteboard/WhiteboardEditor.test.tsx b/src/renderer/whiteboard/WhiteboardEditor.test.tsx
new file mode 100644
index 000000000..897f6deb1
--- /dev/null
+++ b/src/renderer/whiteboard/WhiteboardEditor.test.tsx
@@ -0,0 +1,184 @@
+// @vitest-environment jsdom
+//
+// The editor's save-and-finish rules with the real component. Excalidraw itself is replaced by a
+// stub that hands over a fake imperative api: what is under test is when this component saves, and
+// whether it lets editing END over work that is not on disk.
+import { act, createRef, useEffect } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+type El = { id: string; version: number; isDeleted?: boolean }
+const scene: { elements: El[] } = { elements: [] }
+const appState = {
+ selectedElementIds: {},
+ editingTextElement: null,
+ newElement: null,
+ openMenu: null,
+ openPopup: null,
+ openDialog: null,
+ zoom: { value: 1 },
+ theme: 'dark'
+}
+const fakeApi = {
+ getSceneElementsIncludingDeleted: () => scene.elements,
+ getSceneElements: () => scene.elements,
+ getAppState: () => appState,
+ getFiles: () => ({}),
+ updateScene: vi.fn(),
+ refresh: vi.fn()
+}
+const excalidraw: { props: Record<string, unknown> | null } = { props: null }
+
+vi.mock('@excalidraw/excalidraw/index.css', () => ({}))
+vi.mock('@excalidraw/excalidraw', () => {
+ const Nothing = () => null
+ const MainMenu = Object.assign(Nothing, {
+ DefaultItems: {
+ SaveAsImage: Nothing,
+ SearchMenu: Nothing,
+ Help: Nothing,
+ ClearCanvas: Nothing,
+ ChangeCanvasBackground: Nothing
+ },
+ Separator: Nothing
+ })
+ return {
+ Excalidraw: (props: { excalidrawAPI: (api: unknown) => void } & Record<string, unknown>) => {
+ excalidraw.props = props
+ useEffect(() => props.excalidrawAPI(fakeApi), [])
+ return <div data-testid="excalidraw" />
+ },
+ MainMenu,
+ exportToBlob: async () => new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: 'image/png' }),
+ getNonDeletedElements: (els: El[]) => els.filter((e) => !e.isDeleted),
+ hashElementsVersion: (els: El[]) => els.map((e) => `${e.id}@${e.version}`).join(','),
+ restore: (d: { elements?: El[] }) => ({ elements: d.elements ?? [], appState: {}, files: {} }),
+ serializeAsJSON: (els: El[]) => JSON.stringify({ type: 'excalidraw', elements: els })
+ }
+})
+
+import WhiteboardEditor, { type WhiteboardEditorControl } from './WhiteboardEditor'
+
+let host: HTMLDivElement
+let root: Root
+let overlay: HTMLDivElement
+
+function mount(props: {
+ onSave: (scene: string, thumb?: string) => Promise<boolean>
+ onExit: (changed: boolean) => void
+ readOnly?: boolean
+ control?: { current: WhiteboardEditorControl | null }
+}) {
+ host = document.createElement('div')
+ overlay = document.createElement('div')
+ const frame = document.createElement('div')
+ host.append(overlay, frame)
+ document.body.append(host)
+ const overlayRef = { current: overlay }
+ const frameRef = { current: frame }
+ root = createRoot(overlay)
+ act(() =>
+ root.render(
+ <WhiteboardEditor
+ initialScene={JSON.stringify({ type: 'excalidraw', elements: scene.elements })}
+ theme="dark"
+ canvasZoom={1}
+ present={false}
+ geometryKey="0"
+ overlayRef={overlayRef}
+ frameRef={frameRef}
+ onSave={props.onSave}
+ onExit={props.onExit}
+ readOnly={props.readOnly}
+ controlRef={props.control}
+ />
+ )
+ )
+}
+
+/** The user draws: one element changes version, which is what makes the scene differ from disk. */
+function draw() {
+ scene.elements = [{ id: 'stroke', version: scene.elements.length + 2 }]
+}
+
+async function pressEscape() {
+ await act(async () => {
+ overlay.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))
+ for (let i = 0; i < 5; i++) await new Promise((r) => setTimeout(r, 0))
+ })
+}
+
+beforeEach(() => {
+ scene.elements = [{ id: 'start', version: 1 }]
+ excalidraw.props = null
+})
+
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+})
+
+describe('finishing never closes the board over work that is not on disk', () => {
+ it('a failed save keeps the board open, and a later save that succeeds finishes it', async () => {
+ const onSave = vi.fn(async () => false)
+ const onExit = vi.fn()
+ mount({ onSave, onExit })
+ draw()
+ await pressEscape()
+ expect(onSave).toHaveBeenCalled()
+ expect(onExit).not.toHaveBeenCalled()
+
+ onSave.mockImplementation(async () => true)
+ await pressEscape()
+ expect(onExit).toHaveBeenCalledWith(true)
+ })
+
+ it('a save that succeeds finishes at once', async () => {
+ const onExit = vi.fn()
+ mount({ onSave: async () => true, onExit })
+ draw()
+ await pressEscape()
+ expect(onExit).toHaveBeenCalledWith(true)
+ })
+
+ it('discarding finishes without saving, and nothing is written when the editor goes away', async () => {
+ const onSave = vi.fn(async () => false)
+ const onExit = vi.fn()
+ const control = createRef<WhiteboardEditorControl>() as { current: WhiteboardEditorControl | null }
+ mount({ onSave, onExit, control })
+ draw()
+ await act(async () => control.current?.discard())
+ expect(onExit).toHaveBeenCalledWith(false)
+ act(() => root.unmount())
+ root = createRoot(overlay)
+ expect(onSave).not.toHaveBeenCalled()
+ })
+
+ it('saveNow writes the pending changes on request (the header\'s "Keep mine")', async () => {
+ const onSave = vi.fn(async () => true)
+ const control = { current: null as WhiteboardEditorControl | null }
+ mount({ onSave, onExit: vi.fn(), control })
+ draw()
+ let ok: boolean | undefined
+ await act(async () => {
+ ok = await control.current?.saveNow()
+ })
+ expect(ok).toBe(true)
+ expect(onSave).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('a read-only board (a hosted-team Viewer)', () => {
+ it('opens Excalidraw in view mode and never saves, so finishing loses nothing', async () => {
+ const onSave = vi.fn(async () => true)
+ const onExit = vi.fn()
+ mount({ onSave, onExit, readOnly: true })
+ expect(excalidraw.props?.viewModeEnabled).toBe(true)
+ draw()
+ await pressEscape()
+ expect(onSave).not.toHaveBeenCalled()
+ expect(onExit).toHaveBeenCalledWith(false)
+ })
+})
diff --git a/src/renderer/whiteboard/WhiteboardEditor.tsx b/src/renderer/whiteboard/WhiteboardEditor.tsx
index 36f1d8cb3..5e2f6049c 100644
--- a/src/renderer/whiteboard/WhiteboardEditor.tsx
+++ b/src/renderer/whiteboard/WhiteboardEditor.tsx
@@ -1,5 +1,5 @@
import '@excalidraw/excalidraw/index.css'
-import { useCallback, useEffect, useMemo, useRef, type RefObject } from 'react'
+import { useCallback, useEffect, useMemo, useRef, type MutableRefObject, type RefObject } from 'react'
import {
Excalidraw,
MainMenu,
@@ -66,6 +66,15 @@ const serialize = (s: Snapshot, canvasZoom: number): string => {
return serializeAsJSON(s.elements, appState, s.files, 'local')
}
+/** What the node can ask of a live editor (its header's "Keep mine" and "Discard my changes"). */
+export interface WhiteboardEditorControl {
+ /** Write the pending changes now. Resolves whether the board on disk is now up to date. */
+ saveNow: () => Promise<boolean>
+ /** Stop editing WITHOUT writing the pending changes: the explicit way out of a board whose save
+ * keeps failing, which finishing otherwise refuses to close. */
+ discard: () => void
+}
+
export default function WhiteboardEditor({
initialScene,
theme,
@@ -75,7 +84,9 @@ export default function WhiteboardEditor({
overlayRef,
frameRef,
onSave,
- onExit
+ onExit,
+ readOnly = false,
+ controlRef
}: {
/** The board's `.excalidraw` JSON as read from its file; undefined for a new board. */
initialScene: string | undefined
@@ -91,11 +102,16 @@ export default function WhiteboardEditor({
frameRef: RefObject<HTMLDivElement | null>
onSave: (scene: string, thumbnailBase64?: string) => Promise<boolean>
onExit: (changed: boolean) => void
+ /** View only (a hosted-team Viewer, whose saves the host refuses): Excalidraw's view mode, and
+ * nothing is ever written — so there is never unsaved work to lose. */
+ readOnly?: boolean
+ controlRef?: MutableRefObject<WhiteboardEditorControl | null>
}): React.JSX.Element {
const apiRef = useRef<ExcalidrawImperativeAPI | null>(null)
const canvasZoomRef = useRef(canvasZoom)
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const exitingRef = useRef(false)
+ const discardedRef = useRef(false)
const changedThisSessionRef = useRef(false)
const onSaveRef = useRef(onSave)
onSaveRef.current = onSave
@@ -135,35 +151,66 @@ export default function WhiteboardEditor({
* flag an onChange had to set. `unmounting` reads the kept snapshot instead of the api (see
* `latestRef`) and writes no picture — exporting one needs the live editor.
*/
- const flush = useCallback(async (withThumbnail: boolean, unmounting = false): Promise<void> => {
+ const readOnlyRef = useRef(readOnly)
+ readOnlyRef.current = readOnly
+
+ /** Resolves whether the board on disk is up to date afterwards: true when there was nothing to
+ * write (or the board is read-only, where nothing ever is), false when the save failed. */
+ const flush = useCallback(async (withThumbnail: boolean, unmounting = false): Promise<boolean> => {
if (timerRef.current) clearTimeout(timerRef.current)
timerRef.current = null
+ if (readOnlyRef.current || discardedRef.current) return true
const api = apiRef.current
if (!unmounting && api) latestRef.current = fromApi(api)
const snap = latestRef.current
const version = versionOf(snap.elements, snap.files)
const needScene = version !== savedVersionRef.current
const needThumb = !unmounting && !!api && withThumbnail && version !== thumbVersionRef.current
- if (!needScene && !needThumb) return
+ if (!needScene && !needThumb) return true
// '' = "the board is empty now": the core removes the old picture rather than keep showing it.
const thumb = needThumb && api ? ((await thumbnailBase64(api).catch(() => undefined)) ?? '') : undefined
- if (await onSaveRef.current(serialize(snap, canvasZoomRef.current), thumb)) {
- savedVersionRef.current = version
- if (needThumb) thumbVersionRef.current = version
- changedThisSessionRef.current = true
- }
+ if (!(await onSaveRef.current(serialize(snap, canvasZoomRef.current), thumb))) return false
+ savedVersionRef.current = version
+ if (needThumb) thumbVersionRef.current = version
+ changedThisSessionRef.current = true
+ return true
}, [])
+ // Finishing (Esc, a press outside) waits for a save that SUCCEEDED. A failed one keeps the board
+ // open — the node's header says why ("Not saved", "Changed elsewhere") and offers the way out
+ // (`discard`) — because closing it here would drop the unsaved strokes with no second chance:
+ // the unmount flush below is skipped once an exit has begun. A later Esc or press tries again.
const exit = useCallback(async () => {
if (exitingRef.current) return
exitingRef.current = true
- await flush(true)
+ if (!(await flush(true))) {
+ exitingRef.current = false
+ return
+ }
onExit(changedThisSessionRef.current)
}, [flush, onExit])
- // Leaving without an exit (a project switch, the node deleted, the app quitting): write whatever
- // is unsaved. The api is still readable synchronously here; the write itself is async and the
- // core finishes it after this component is gone.
+ useEffect(() => {
+ if (!controlRef) return
+ controlRef.current = {
+ saveNow: () => flush(false),
+ discard: () => {
+ if (exitingRef.current) return
+ exitingRef.current = true
+ discardedRef.current = true
+ if (timerRef.current) clearTimeout(timerRef.current)
+ timerRef.current = null
+ onExit(changedThisSessionRef.current)
+ }
+ }
+ return () => {
+ controlRef.current = null
+ }
+ }, [controlRef, flush, onExit])
+
+ // Leaving without an exit (a project switch, the node deleted): write whatever is unsaved. The
+ // api is still readable synchronously here; the write itself is async and the core finishes it
+ // after this component is gone.
useEffect(
() => () => {
if (!exitingRef.current) void flush(false, true)
@@ -233,12 +280,13 @@ export default function WhiteboardEditor({
initialData={initialData}
onChange={(elements, appState, files) => {
latestRef.current = { elements, appState, files }
- if (versionOf(elements, files) === savedVersionRef.current) return
+ if (readOnlyRef.current || versionOf(elements, files) === savedVersionRef.current) return
if (timerRef.current) clearTimeout(timerRef.current)
timerRef.current = setTimeout(() => void flush(false), AUTOSAVE_MS)
}}
theme={theme}
zenModeEnabled={present}
+ viewModeEnabled={readOnly}
autoFocus
aiEnabled={false}
UIOptions={{