Skip to content

AI-native design editor. Open-source Figma alternative.

feat: open documents read-only, as Cloud viewers and version previews need (#1271)

Danila Poyarkov7b6f1dc4083b
diff --git a/changes/1069/added.md b/changes/1069/added.md
index a21e5dd3c..f366529b4 100644
--- a/changes/1069/added.md
+++ b/changes/1069/added.md
@@ -1 +1 @@
-- OpenPencil Cloud is ready to self-host, and to try before the hosted service opens: open the editor with `?cloud=preview`, or follow an invitation, to keep documents on your team's server and edit them together. Connect a server in **Settings → Cloud**, which also holds the hosted service's waitlist: email and password sign in, and create an account, right in the dialog, while Google, Apple, and two-step sign-in finish in the browser. Home lists the server's workspaces and the documents shared with you, every account starts with a workspace of its own and can create team workspaces whose admins invite people by email as admins, editors, or viewers and delete them once they are empty, **New design** creates in the place Home shows, **File → Save to…** saves the open document straight to the only workspace or bucket it can go to and asks only when there are several, **File → Browse files…** opens Home where you left it, and a status beside the name appears when the document is offline, couldn't save, changed in two places, with the choice to keep both versions, or is view only. Opening a Cloud document joins its live room, so everyone with it open sees edits and cursors as they happen while one editor saves for all. **Share** invites people by email and turns on a link that opens the document for guests, within what the workspace's plan allows; on a computer, the web editor offers to open invitations and shared links in the desktop app. The server, its relay, and its pages for signing in, account security, and administration are in `@open-pencil/cloud` under the Apache License 2.0, while the protocol the editor speaks to it stays MIT; `VITE_OPENPENCIL_CLOUD=off` builds the editor without Cloud.
+- OpenPencil Cloud is ready to self-host, and to try before the hosted service opens: open the editor with `?cloud=preview`, or follow an invitation, to keep documents on your team's server and edit them together. Connect a server in **Settings → Cloud**, which also holds the hosted service's waitlist: email and password sign in, and create an account, right in the dialog, while Google, Apple, and two-step sign-in finish in the browser. Home lists the server's workspaces and the documents shared with you, every account starts with a workspace of its own and can create team workspaces whose admins invite people by email as admins, editors, or viewers and delete them once they are empty, **New design** creates in the place Home shows, **File → Save to…** saves the open document straight to the only workspace or bucket it can go to and asks only when there are several, **File → Browse files…** opens Home where you left it, and a status beside the name appears when the document is offline, couldn't save, changed in two places, with the choice to keep both versions, or is view only. A viewer's document is read-only, as in Figma: layers can be selected, copied, and exported, the toolbar keeps Move and Hand, and edits, from the canvas, panels, shortcuts, and agents alike, are refused. Opening a Cloud document joins its live room, so everyone with it open sees edits and cursors as they happen while one editor saves for all. **Share** invites people by email and turns on a link that opens the document for guests, within what the workspace's plan allows; on a computer, the web editor offers to open invitations and shared links in the desktop app. The server, its relay, and its pages for signing in, account security, and administration are in `@open-pencil/cloud` under the Apache License 2.0, while the protocol the editor speaks to it stays MIT; `VITE_OPENPENCIL_CLOUD=off` builds the editor without Cloud.
diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.md
index f8be4f99d..42627d738 100644
--- a/packages/core/AGENTS.md
+++ b/packages/core/AGENTS.md
@@ -45,6 +45,7 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do
- Live property controls use selected-node projections from `packages/core/src/editor/selection-state/nodes.ts`: shallow reactive copies that receive `node:previewUpdated` patches at property granularity. Never add preview invalidation to all `useSceneComputed` consumers; catalogs and unrelated controls must not refresh for geometry previews. Projection subscriptions belong to the consuming scope or session and must be disposed.
- Numeric geometry edits own a `beginNodePreview()` handle with `update`, `commit`, and `cancel`. It captures all affected fields and layout children, publishes the complete delta once, and restores exact originals on cancellation. Selection, page, and graph changes and disposal cancel the old edit; trailing input must not target the new selection. Controls must close previews even when a gesture returns to its starting value.
- Rotation previews change through `setRotationPreview()` and `rotation:preview-changed`; cancellation must close the owning gesture without deselecting or committing it.
+- A read-only document (`setReadOnly`) refuses every editor action not listed in `READ_ONLY_ACTIONS`, so a new action that only reads, selects, or navigates is added there; front ends ignore the refusal and change only what behaves differently, such as the toolbar (`packages/core/tests/editor/read-only.test.ts`).
- Renderer interaction policy uses explicit `beginInteractiveEdit()` leases and `isInteractiveEditing()`, not undo batching. Release leases on every terminal path. Keep live queries callable across app facades that spread editor actions.
- `packages/core/src/editor/history/atomic-tool.ts` owns synchronous property/variable transactions for AI, MCP, and WebMCP tools; see Tools above.
diff --git a/packages/core/src/canvas/overlays/selection.ts b/packages/core/src/canvas/overlays/selection.ts
index 3af35c064..761b29713 100644
--- a/packages/core/src/canvas/overlays/selection.ts
+++ b/packages/core/src/canvas/overlays/selection.ts
@@ -289,7 +289,7 @@ function drawTextPathSelection(
/**
* Figma's corner handles and our rotation stalk, absent for a layer that does not turn; a layer
- * too small for handles shows none.
+ * too small for handles, or in a read-only document, shows none.
*/
function drawBoundsHandles(
r: SkiaRenderer,
@@ -300,7 +300,7 @@ function drawBoundsHandles(
maxY: number,
stalk: RotationHandleLayout | null
): void {
- if (!hasTransformHandles((maxX - minX) * r.zoom, (maxY - minY) * r.zoom)) return
+ if (r.readOnly || !hasTransformHandles((maxX - minX) * r.zoom, (maxY - minY) * r.zoom)) return
r.drawHandle(canvas, minX, minY)
r.drawHandle(canvas, maxX, minY)
r.drawHandle(canvas, minX, maxY)
diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.ts
index 6c12e9f07..07467c2fc 100644
--- a/packages/core/src/canvas/renderer.ts
+++ b/packages/core/src/canvas/renderer.ts
@@ -165,6 +165,8 @@ export class SkiaRenderer {
sceneBackingLastViewportEventAt = 0
navigationPhase: EditorState['navigation']['phase'] = 'idle'
navigationGeneration = 0
+ /** The document is read-only: selections draw without handles to drag. */
+ readOnly = false
tiledSceneEnabled = false
/**
* What an empty sticky note shows while it is edited on this canvas, in the interface language;
diff --git a/packages/core/src/canvas/renderer/overlay-pass.ts b/packages/core/src/canvas/renderer/overlay-pass.ts
index 0677d9eed..82b7c76da 100644
--- a/packages/core/src/canvas/renderer/overlay-pass.ts
+++ b/packages/core/src/canvas/renderer/overlay-pass.ts
@@ -121,7 +121,7 @@ export function drawOverlayPass(
drawGradientHandles(r, canvas, graph, overlays.gradientEdit, overlays.rotationPreview)
else {
r.drawSelection(canvas, graph, selectedIds, overlays)
- if (!overlays.transforming)
+ if (!overlays.transforming && !r.readOnly)
drawShapeHandles(
r,
canvas,
@@ -140,7 +140,7 @@ export function drawOverlayPass(
r.drawSnapGuides(canvas, overlays.snapGuides)
r.drawMarquee(canvas, overlays.marquee)
r.drawLayoutInsertIndicator(canvas, overlays.layoutInsertIndicator)
- if (!measuring && !overlays.transforming) {
+ if (!measuring && !overlays.transforming && !r.readOnly) {
r.drawAutoLayoutHover(canvas, graph, overlays.autoLayoutHover)
}
r.drawNodeEditOverlay(canvas, graph, overlays.nodeEditState)
diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.ts
index 9477d6ee4..b5cf1c03c 100644
--- a/packages/core/src/canvas/renderer/pipeline.ts
+++ b/packages/core/src/canvas/renderer/pipeline.ts
@@ -77,6 +77,7 @@ export function renderFromEditorState(
r.pageId = state.currentPageId
r.navigationPhase = state.navigation.phase
r.navigationGeneration = state.navigation.generation
+ r.readOnly = state.readOnly
// A previewing canvas shows the design as it runs: no selection, hover, or edit chrome.
const previewing = state.play !== null
render(
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index b520fd78c..1894490ce 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -44,6 +44,7 @@ import { createDesignIssueActions } from './issues'
import { createNodeActions } from './nodes'
import { createPageActions } from './pages'
import { createPlayActions } from './play/actions'
+import { createReadOnlyActions, guardReadOnly, guardUndo, READ_ONLY_TOOLS } from './read-only'
import { createSelectionActions } from './selection'
import { createShaderActions } from './shaders/actions'
import { createShaderFrames } from './shaders/frames'
@@ -197,6 +198,7 @@ export function createEditor(options?: EditorOptions) {
}
function setActiveTool(tool: EditorState['activeTool']) {
+ if (state.readOnly && !READ_ONLY_TOOLS.has(tool)) return
const previous = state.activeTool
state.activeTool = tool
if (tool !== 'SELECT') state.measurementMode = 'off'
@@ -300,6 +302,14 @@ export function createEditor(options?: EditorOptions) {
const undoBridge = createUndoBridge(undoActions, selection, nodes.flushNudge)
const lintFixBridge = createLintFixBridge(ctx, nodes, structure, clipboard)
const textSelectionStyle = createTextSelectionStyle(ctx, text.runTextEditStep)
+ const readOnly = createReadOnlyActions(ctx, () => {
+ nodes.flushNudge()
+ nodes.cancelNodePreviews()
+ if (state.editingTextId) text.commitTextEdit()
+ shapes.penCancel()
+ shapes.pencilCancel()
+ state.gradientEdit = null
+ })
// The edited text follows changes made outside the editor, such as a panel field being
// dragged, so its caret and selection move with the text instead of after the change.
@@ -376,7 +386,7 @@ export function createEditor(options?: EditorOptions) {
releaseOriginalFigArchive(_graph)
}
- return {
+ const editor = {
get graph() {
return _graph
},
@@ -389,7 +399,7 @@ export function createEditor(options?: EditorOptions) {
get textEditor() {
return _textEditor
},
- undo,
+ undo: guardUndo(undo, () => state.readOnly),
state,
// Graph reads
@@ -495,8 +505,12 @@ export function createEditor(options?: EditorOptions) {
...structureBridge,
// Lint fixes, which touch nodes, structure and deletion in one undo step
- ...lintFixBridge
+ ...lintFixBridge,
+
+ // Read-only documents, which refuse every action above that changes them
+ ...readOnly
}
+ return guardReadOnly(editor, () => state.readOnly)
}
export type Editor = ReturnType<typeof createEditor>
diff --git a/packages/core/src/editor/history/atomic-tool.ts b/packages/core/src/editor/history/atomic-tool.ts
index 7089cfd16..aa007c44f 100644
--- a/packages/core/src/editor/history/atomic-tool.ts
+++ b/packages/core/src/editor/history/atomic-tool.ts
@@ -6,6 +6,8 @@ import {
} from '@open-pencil/scene-graph'
import type { Editor } from '#core/editor/create'
+import { ReadOnlyDocumentError } from '#core/editor/read-only'
+import type { EditorState } from '#core/editor/types'
import type { FigmaAPI } from '#core/figma-api'
import { isAtomicTool, type ToolDef } from '#core/tools/schema'
@@ -14,7 +16,12 @@ import { diffFields, type FieldChanges } from './diff'
// Capture property changes across pages. Component synchronization remains editor-owned.
const MAX_TRANSACTION_NODES = 10_000
-type MutationEditor = Pick<Editor, 'graph' | 'runLayoutForNode' | 'requestRender' | 'pushUndoStep'>
+type MutationEditor = Pick<
+ Editor,
+ 'graph' | 'runLayoutForNode' | 'requestRender' | 'pushUndoStep'
+> & {
+ state: Pick<EditorState, 'readOnly'>
+}
function changes<T extends object>(
before: Map<string, T>,
@@ -44,6 +51,7 @@ export function executeAtomicTool(
options: { signal?: AbortSignal; isLive?: () => boolean; label?: string } = {}
): unknown {
if (!isAtomicTool(def)) throw new Error(`Not an atomic tool: ${def.name}`)
+ if (editor.state.readOnly) throw new ReadOnlyDocumentError()
options.signal?.throwIfAborted()
if (editor.graph !== figma.graph || options.isLive?.() === false) {
throw new Error('The target document is no longer open')
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index 462f10b27..a1a2672cc 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -4,6 +4,7 @@ export {
ReadOnlyLibraryDefinitionError
} from './capabilities'
export type { NodeEditCapability } from './capabilities'
+export { READ_ONLY_TOOLS, ReadOnlyDocumentError } from './read-only'
export { DEFAULT_SNAPPING_PREFERENCES } from './preferences'
export type { SnappingPreferences } from './preferences'
export { createDefaultEditorSharedState } from './state/shared'
diff --git a/packages/core/src/editor/read-only/actions.ts b/packages/core/src/editor/read-only/actions.ts
new file mode 100644
index 000000000..b9bfdd74e
--- /dev/null
+++ b/packages/core/src/editor/read-only/actions.ts
@@ -0,0 +1,154 @@
+/**
+ * Editor actions a read-only document still offers: reading it, selecting, moving around and
+ * between pages, previewing, copying, and the canvas's own lifecycle, as Figma keeps while a
+ * version is viewed. Every other action changes the document and is refused, so an action added
+ * later is refused until it is listed here (`packages/core/tests/editor/read-only.test.ts`).
+ */
+export const READ_ONLY_ACTIONS: ReadonlySet<string> = new Set([
+ // Reads
+ 'acceptingParent',
+ 'acceptsChildren',
+ 'canDistributeNodes',
+ 'captureDocumentChange',
+ 'collectVariantOptions',
+ 'findVariantByValues',
+ 'getChildren',
+ 'getCollection',
+ 'getCollectionCount',
+ 'getCollections',
+ 'getComponentPropertyAuthoring',
+ 'getComponentPropertyBindings',
+ 'getComponentSetPropertyDefs',
+ 'getComponentSetVariantConflicts',
+ 'getDefaultVariantForComponentSet',
+ 'getExposableInstances',
+ 'getImage',
+ 'getInstanceComponentPropertyDefinitions',
+ 'getInstanceComponentPropertyValue',
+ 'getLayerTree',
+ 'getNode',
+ 'getPages',
+ 'getSelectedNode',
+ 'getSelectedNodes',
+ 'getShownStatus',
+ 'getTextSelectionStyle',
+ 'getVariable',
+ 'getVariableCount',
+ 'getVariablesByType',
+ 'getVariablesForCollection',
+ 'getVariantOptionAvailability',
+ 'getVariantOptions',
+ 'hitTestAtPoint',
+ 'isInteractiveEditing',
+ 'isTopLevel',
+ 'pageSwitchCount',
+ 'previewRenameSelected',
+ 'resolveColorVariable',
+ 'resolveNumberVariable',
+ 'screenToCanvas',
+ 'selectionSpacing',
+ 'snapshotPage',
+ 'statusWorkflow',
+ 'validateComponentSet',
+
+ // Selection and hover
+ 'clearSelection',
+ 'enterContainer',
+ 'exitContainer',
+ 'select',
+ 'selectAll',
+ 'selectAtPoint',
+ 'selectChildren',
+ 'selectInverse',
+ 'selectNextSibling',
+ 'selectParent',
+ 'selectPreviousSibling',
+ 'setCodeFocusNode',
+ 'setHoveredNode',
+ 'setMarquee',
+ 'setMeasurementMode',
+ 'setTool',
+ 'validateEnteredContainer',
+
+ // Canvas overlays that show without changing anything
+ 'clearDesignIssues',
+ 'setAutoLayoutHover',
+ 'setDesignIssueHighlight',
+ 'setDesignIssueMarkers',
+ 'setDropTarget',
+ 'setGuidePreview',
+ 'setGuideRedline',
+ 'setHoveredGuide',
+ 'setHoveredIssueMarker',
+ 'setLayoutInsertIndicator',
+ 'setRotationPreview',
+ 'setSelectedGuide',
+ 'setShapeHandleHover',
+ 'setSnapGuides',
+ 'setTransforming',
+
+ // Viewport and pages
+ 'applyZoom',
+ 'centerOn',
+ 'clearPageViewports',
+ 'commitPageSwitch',
+ 'focusComponent',
+ 'goToMainComponent',
+ 'pan',
+ 'preparePage',
+ 'preparePageNodes',
+ 'loadPageNodes',
+ 'revealNodes',
+ 'setZoomAroundPoint',
+ 'switchPage',
+ 'switchToNextPage',
+ 'switchToPreviousPage',
+ 'zoomTo100',
+ 'zoomToBounds',
+ 'zoomToFit',
+ 'zoomToLevel',
+ 'zoomToNextFrame',
+ 'zoomToPreviousFrame',
+ 'zoomToSelection',
+
+ // Preview
+ 'resetPlay',
+ 'startPlay',
+ 'stopPlay',
+ 'togglePlay',
+
+ // Copying out
+ 'copySelectionAsJSX',
+ 'copySelectionAsSVG',
+ 'copySelectionAsText',
+ 'prepareCopy',
+
+ // Ending what was in progress
+ 'cancelNodePreviews',
+ 'flushNudge',
+ 'penCancel',
+ 'pencilCancel',
+
+ // Canvas, layout, and document lifecycle
+ 'beginInteractiveEdit',
+ 'dispose',
+ 'drawPageShaderFrames',
+ 'hasShaderRasterizer',
+ 'loadFontsForNodes',
+ 'onEditorEvent',
+ 'refreshVariables',
+ 'releaseGraphResources',
+ 'removeCanvasRenderer',
+ 'replaceGraph',
+ 'requestRefresh',
+ 'requestRender',
+ 'requestRepaint',
+ 'runLayoutForNode',
+ 'setCanvasKit',
+ 'setNavigationPhase',
+ 'setReadOnly',
+ 'setShaderRasterizer',
+ 'settleShaderFrames',
+ 'subscribeToGraph',
+ 'textSelectionChanged'
+])
diff --git a/packages/core/src/editor/read-only/index.ts b/packages/core/src/editor/read-only/index.ts
new file mode 100644
index 000000000..337981e50
--- /dev/null
+++ b/packages/core/src/editor/read-only/index.ts
@@ -0,0 +1,70 @@
+import type { UndoManager } from '@open-pencil/scene-graph/undo'
+
+import type { EditorContext, Tool } from '#core/editor/types'
+
+import { READ_ONLY_ACTIONS } from './actions'
+
+/** Raised by an edit to a document that is open read-only, in Figma's words for its own. */
+export class ReadOnlyDocumentError extends Error {
+ constructor() {
+ super("Can't edit the document in read-only mode")
+ this.name = 'ReadOnlyDocumentError'
+ }
+}
+
+/** The tools a read-only document keeps, as Figma's toolbar shows while a version is viewed. */
+export const READ_ONLY_TOOLS: ReadonlySet<Tool> = new Set<Tool>(['SELECT', 'HAND'])
+
+/**
+ * Returns the editor with every action that changes the document refused while `isReadOnly`
+ * holds; the actions in `READ_ONLY_ACTIONS` and the editor's getters pass through.
+ */
+export function guardReadOnly<T extends object>(editor: T, isReadOnly: () => boolean): T {
+ const descriptors = Object.getOwnPropertyDescriptors(editor)
+ for (const [name, descriptor] of Object.entries(descriptors)) {
+ const action: unknown = descriptor.value
+ if (typeof action !== 'function' || READ_ONLY_ACTIONS.has(name)) continue
+ descriptor.value = (...args: unknown[]): unknown => {
+ if (isReadOnly()) throw new ReadOnlyDocumentError()
+ return Reflect.apply(action, undefined, args)
+ }
+ }
+ return Object.defineProperties({}, descriptors) as T
+}
+
+/**
+ * Returns the editor's undo history with undo and redo refused while `isReadOnly` holds, since
+ * they change the document; batches and reads pass through for the gestures that open them.
+ */
+export function guardUndo(undo: UndoManager, isReadOnly: () => boolean): UndoManager {
+ return new Proxy(undo, {
+ get(target, key) {
+ const value: unknown = Reflect.get(target, key)
+ if ((key === 'undo' || key === 'redo') && isReadOnly()) {
+ return () => {
+ throw new ReadOnlyDocumentError()
+ }
+ }
+ return typeof value === 'function' ? value.bind(target) : value
+ }
+ })
+}
+
+export function createReadOnlyActions(ctx: EditorContext, endEdits: () => void) {
+ /**
+ * Opens the document read-only or editable again. Going read-only ends what is being edited and
+ * drops a tool that would edit, as Figma does on opening version history.
+ */
+ function setReadOnly(readOnly: boolean): void {
+ if (ctx.state.readOnly === readOnly) return
+ if (readOnly) {
+ endEdits()
+ if (!READ_ONLY_TOOLS.has(ctx.state.activeTool)) ctx.setActiveTool('SELECT')
+ }
+ ctx.state.readOnly = readOnly
+ ctx.emitEditorEvent('document:read-only-changed', readOnly)
+ ctx.requestRepaint()
+ }
+
+ return { setReadOnly }
+}
diff --git a/packages/core/src/editor/state/shared.ts b/packages/core/src/editor/state/shared.ts
index 4870e0ee0..5bb6335ee 100644
--- a/packages/core/src/editor/state/shared.ts
+++ b/packages/core/src/editor/state/shared.ts
@@ -4,6 +4,7 @@ import type { EditorSharedState } from '#core/editor/types'
export function createDefaultEditorSharedState(): EditorSharedState {
return {
activeTool: 'SELECT',
+ readOnly: false,
snappingPreferences: { ...DEFAULT_SNAPPING_PREFERENCES },
showPixelGrid: true,
gradientEdit: null,
diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.ts
index 6de3ba9d8..81440a94e 100644
--- a/packages/core/src/editor/types.ts
+++ b/packages/core/src/editor/types.ts
@@ -71,6 +71,11 @@ export interface ShapeHandleHover {
export interface EditorSharedState {
activeTool: Tool
+ /**
+ * The document can be looked at, selected in, and copied from but not changed, as for a viewer
+ * or an earlier version; set with `setReadOnly`.
+ */
+ readOnly: boolean
snappingPreferences: SnappingPreferences
/** Draw the pixel grid once zoomed in far enough, as Figma's View › Pixel grid; shown unless false. */
showPixelGrid?: boolean
@@ -189,6 +194,7 @@ export interface EditorEvents extends SceneGraphEvents {
'repaint:requested': (versions: { renderVersion: number; sceneVersion: number }) => void
'graph:replaced': (graph: SceneGraph) => void
'document:color-space-changed': (colorSpace: DocumentColorSpace) => void
+ 'document:read-only-changed': (readOnly: boolean) => void
'history:changed': () => void
'selection:changed': (selectedIds: string[], previousIds: string[]) => void
'rotation:preview-changed': (preview: RotationPreview | null) => void
diff --git a/packages/core/tests/editor/history/atomic-tools.test.ts b/packages/core/tests/editor/history/atomic-tools.test.ts
index 32a717144..d5e763155 100644
--- a/packages/core/tests/editor/history/atomic-tools.test.ts
+++ b/packages/core/tests/editor/history/atomic-tools.test.ts
@@ -12,6 +12,7 @@ function setup() {
const figma = new FigmaAPI(graph)
const editor = {
graph,
+ state: { readOnly: false },
runLayoutForNode: () => undefined,
requestRender: () => undefined,
pushUndoStep: undo.pushStep.bind(undo)
diff --git a/packages/core/tests/editor/read-only.test.ts b/packages/core/tests/editor/read-only.test.ts
new file mode 100644
index 000000000..cd65fe1ff
--- /dev/null
+++ b/packages/core/tests/editor/read-only.test.ts
@@ -0,0 +1,125 @@
+import { describe, expect, test } from 'bun:test'
+
+import { getNodeOrThrow } from '#core-tests/helpers/assert'
+
+import { createEditor, executeAtomicTool, ReadOnlyDocumentError } from '@open-pencil/core/editor'
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { ALL_TOOLS } from '@open-pencil/core/tools'
+
+import { READ_ONLY_ACTIONS } from '#core/editor/read-only/actions'
+
+function setup() {
+ const editor = createEditor()
+ const pageId = editor.graph.getPages()[0].id
+ const rect = editor.graph.createNode('RECTANGLE', pageId, {
+ name: 'Rect',
+ x: 10,
+ y: 20,
+ width: 50,
+ height: 50
+ })
+ editor.select([rect.id])
+ return { editor, pageId, rect }
+}
+
+describe('read-only documents', () => {
+ test('every action kept while read-only is an editor action', () => {
+ const { editor } = setup()
+ const actions = new Set(
+ Object.entries(Object.getOwnPropertyDescriptors(editor))
+ .filter(([, descriptor]) => typeof descriptor.value === 'function')
+ .map(([name]) => name)
+ )
+ expect([...READ_ONLY_ACTIONS].filter((name) => !actions.has(name))).toEqual([])
+ })
+
+ test('refuses edits and leaves the document as it was', () => {
+ const { editor, rect } = setup()
+ editor.setReadOnly(true)
+
+ expect(() => editor.setOpacity(0.5)).toThrow(ReadOnlyDocumentError)
+ expect(() => editor.nudgeSelected(10, 0)).toThrow(ReadOnlyDocumentError)
+ expect(() => editor.deleteSelected()).toThrow(ReadOnlyDocumentError)
+ expect(() => editor.updateNodeWithUndo(rect.id, { name: 'Renamed' })).toThrow(
+ ReadOnlyDocumentError
+ )
+ expect(() => editor.addPage('Second')).toThrow(ReadOnlyDocumentError)
+ expect(() => editor.undoAction()).toThrow(ReadOnlyDocumentError)
+
+ const node = getNodeOrThrow(editor.graph, rect.id)
+ expect(node).toMatchObject({ name: 'Rect', x: 10, opacity: 1 })
+ expect(editor.graph.getPages()).toHaveLength(1)
+ })
+
+ test('keeps selecting, moving around, and copying', () => {
+ const { editor, rect } = setup()
+ editor.setReadOnly(true)
+
+ editor.clearSelection()
+ editor.selectAll()
+ expect([...editor.state.selectedIds]).toEqual([rect.id])
+ editor.zoomToSelection()
+ editor.pan(10, 10)
+ expect(editor.copySelectionAsText([rect.id])).toBe('Rect')
+ expect(editor.getNode(rect.id)?.name).toBe('Rect')
+ })
+
+ test('clears a rotation preview, which only shows on the canvas', () => {
+ const { editor, rect } = setup()
+ editor.setRotationPreview({ nodeId: rect.id, angle: 30 })
+ editor.setReadOnly(true)
+
+ editor.setRotationPreview(null)
+ expect(editor.state.rotationPreview).toBeNull()
+ })
+
+ test('keeps only the tools that do not edit', () => {
+ const { editor } = setup()
+ editor.setTool('RECTANGLE')
+ const changes: boolean[] = []
+ editor.onEditorEvent('document:read-only-changed', (readOnly) => changes.push(readOnly))
+
+ editor.setReadOnly(true)
+ expect(editor.state.activeTool).toBe('SELECT')
+ editor.setTool('PEN')
+ expect(editor.state.activeTool).toBe('SELECT')
+ editor.setTool('HAND')
+ expect(editor.state.activeTool).toBe('HAND')
+
+ editor.setReadOnly(false)
+ editor.setTool('PEN')
+ expect(editor.state.activeTool).toBe('PEN')
+ expect(changes).toEqual([true, false])
+ })
+
+ test('edits again once editable', () => {
+ const { editor, rect } = setup()
+ editor.setReadOnly(true)
+ editor.setReadOnly(false)
+
+ editor.setOpacity(0.5)
+ expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(0.5)
+ })
+
+ test('agents cannot edit through atomic tools', () => {
+ const { editor, rect } = setup()
+ const setOpacity = ALL_TOOLS.find((tool) => tool.name === 'set_opacity')
+ if (!setOpacity) throw new Error('set_opacity is missing')
+ editor.setReadOnly(true)
+
+ expect(() =>
+ executeAtomicTool(editor, new FigmaAPI(editor.graph), setOpacity, { id: rect.id, value: 0.5 })
+ ).toThrow(ReadOnlyDocumentError)
+ expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(1)
+ })
+
+ test('keeps the undo history but refuses to step through it', () => {
+ const { editor, rect } = setup()
+ editor.setOpacity(0.5)
+ editor.setReadOnly(true)
+
+ expect(editor.undo.canUndo).toBe(true)
+ expect(() => editor.undo.undo()).toThrow(ReadOnlyDocumentError)
+ expect(getNodeOrThrow(editor.graph, rect.id).opacity).toBe(0.5)
+ })
+})
diff --git a/packages/vue/src/canvas/text-edit/input.ts b/packages/vue/src/canvas/text-edit/input.ts
index f437c1f57..0418d4fc5 100644
--- a/packages/vue/src/canvas/text-edit/input.ts
+++ b/packages/vue/src/canvas/text-edit/input.ts
@@ -145,7 +145,7 @@ export function createTextEditInput(options: TextEditInputOptions) {
}
const hit = getContainerDescendantHit(selectedId, cx, cy)
editor.enterContainer(selectedId)
- if (hit?.type === 'TEXT') startTextEditingAt(hit, cx, cy)
+ if (hit?.type === 'TEXT' && !editor.state.readOnly) startTextEditingAt(hit, cx, cy)
else if (hit) editor.select([hit.id])
else editor.clearSelection()
return true
@@ -156,7 +156,8 @@ export function createTextEditInput(options: TextEditInputOptions) {
if (editor.state.editingTextId) return
const { cx, cy } = getCoords(e)
- if (startLabelRename(cx, cy)) return
+ const { readOnly } = editor.state
+ if (!readOnly && startLabelRename(cx, cy)) return
const selectedId =
editor.state.selectedIds.size === 1 ? [...editor.state.selectedIds][0] : undefined
@@ -166,6 +167,11 @@ export function createTextEditInput(options: TextEditInputOptions) {
if (!found) return
// A generated frame's sublayers are edited through the frame.
const hit = generatedFrameOwner(editor.graph, found) ?? found
+ // A read-only document selects what a double-click would edit, as Figma does.
+ if (readOnly) {
+ editor.select([hit.id])
+ return
+ }
if (hit.type === 'TEXT') {
const isTopLevelText = hit.parentId === editor.state.currentPageId
diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.ts
index c890ac143..a5406499a 100644
--- a/packages/vue/src/canvas/useCanvasInput.ts
+++ b/packages/vue/src/canvas/useCanvasInput.ts
@@ -22,7 +22,7 @@ import {
import { resolveAutoLayoutHover } from '#vue/shared/input/auto-layout-hover'
import { createClickCounter } from '#vue/shared/input/click-count'
import { handleDrawMove } from '#vue/shared/input/draw'
-import { handleMoveMove, handleMoveUp } from '#vue/shared/input/move/drag'
+import { cancelMove, handleMoveMove, handleMoveUp } from '#vue/shared/input/move/drag'
import { setupPanZoom } from '#vue/shared/input/pan/zoom'
import { applyResize, cancelResizePreview, commitResizePreview } from '#vue/shared/input/resize'
import { updateHoverCursor } from '#vue/shared/input/select'
@@ -107,10 +107,17 @@ export function useCanvasInput(
hitFns,
mode === 'deep' || hoverDeep()
)
- editor.setAutoLayoutHover(
- mode === 'off' ? resolveAutoLayoutHover(pointer.cx, pointer.cy, editor) : null
- )
- editor.setShapeHandleHover(resolveShapeHandleHover(editor, pointer.sx, pointer.sy, altHeld))
+ editor.setAutoLayoutHover(autoLayoutHoverAt(pointer.cx, pointer.cy, mode))
+ editor.setShapeHandleHover(shapeHandleHoverAt(pointer.sx, pointer.sy, altHeld))
+ }
+
+ // Handles that edit, which a read-only document does not offer.
+ function autoLayoutHoverAt(cx: number, cy: number, mode: typeof editor.state.measurementMode) {
+ return mode === 'off' && !editor.state.readOnly ? resolveAutoLayoutHover(cx, cy, editor) : null
+ }
+
+ function shapeHandleHoverAt(sx: number, sy: number, altKey: boolean) {
+ return editor.state.readOnly ? null : resolveShapeHandleHover(editor, sx, sy, altKey)
}
function updateModifier(code: string, held: boolean) {
@@ -169,7 +176,7 @@ export function useCanvasInput(
function onDblClick(e: MouseEvent) {
if (editor.state.play) return
const { cx, cy } = getCoords(e)
- if (valueEdit.start(cx, cy)) {
+ if (!editor.state.readOnly && valueEdit.start(cx, cy)) {
e.preventDefault()
e.stopPropagation()
return
@@ -194,11 +201,13 @@ export function useCanvasInput(
if (!editor.state.editingTextId) canvasRef.value?.focus()
editor.setHoveredNode(null)
const { sx, sy, cx, cy } = getCoords(e)
- if (e.button === 0 && guideInput.tryStartExisting(sx, sy, e.altKey)) {
+ // Guides belong to the document, so a read-only one neither moves nor gains them.
+ const guidesEditable = e.button === 0 && !editor.state.readOnly
+ if (guidesEditable && guideInput.tryStartExisting(sx, sy, e.altKey)) {
e.preventDefault()
return
}
- if (e.button === 0 && guideInput.tryStartFromRuler(sx, sy, cx, cy)) {
+ if (guidesEditable && guideInput.tryStartFromRuler(sx, sy, cx, cy)) {
e.preventDefault()
return
}
@@ -243,12 +252,12 @@ export function useCanvasInput(
if (!drag.value) {
const { cx, cy, sx, sy } = coords
updateNodeEditHover(editor, cx, cy)
- editor.setShapeHandleHover(resolveShapeHandleHover(editor, sx, sy, e.altKey))
+ editor.setShapeHandleHover(shapeHandleHoverAt(sx, sy, e.altKey))
}
if (!drag.value && editor.state.activeTool === 'SELECT') {
const { sx, sy, cx, cy } = coords
- const guideCursor = guideInput.updateHover(sx, sy)
+ const guideCursor = editor.state.readOnly ? null : guideInput.updateHover(sx, sy)
cursorOverride.value =
guideCursor ??
updateHoverCursor(
@@ -258,9 +267,7 @@ export function useCanvasInput(
hitFns,
editor.state.measurementMode === 'deep' || hoverDeep(e)
)
- editor.setAutoLayoutHover(
- editor.state.measurementMode === 'off' ? resolveAutoLayoutHover(cx, cy, editor) : null
- )
+ editor.setAutoLayoutHover(autoLayoutHoverAt(cx, cy, editor.state.measurementMode))
}
if (!drag.value) return
@@ -401,33 +408,24 @@ export function useCanvasInput(
else if (d.type === 'pencil-drag') editor.pencilCancel()
}
- function cancelPointerInteraction() {
- if (drag.value) discardDrawnPreview(drag.value)
- if (drag.value?.type === 'rotate') {
- const rotation = drag.value
- drag.value = null
- if (editor.state.rotationPreview?.nodeId === rotation.nodeId) editor.setRotationPreview(null)
- }
- if (
- drag.value?.type === 'draw' ||
- drag.value?.type === 'gradient' ||
- drag.value?.type === 'shape-handle'
- ) {
- const drawing = drag.value
- drag.value = null
- drawing.cancel()
- }
- if (
- drag.value?.type === 'edit-node' ||
- drag.value?.type === 'edit-handle' ||
- drag.value?.type === 'bend-handle'
- ) {
- const methods = editor as Editor & {
- nodeEditCancelDrag?: () => void
- }
+ /** Takes back what a drag in progress has previewed, by its kind. */
+ function discardDrag(d: DragState) {
+ discardDrawnPreview(d)
+ if (d.type === 'move') cancelMove(d, editor)
+ else if (d.type === 'rotate') {
+ if (editor.state.rotationPreview?.nodeId === d.nodeId) editor.setRotationPreview(null)
+ } else if (d.type === 'draw' || d.type === 'gradient' || d.type === 'shape-handle') d.cancel()
+ else if (d.type === 'edit-node' || d.type === 'edit-handle' || d.type === 'bend-handle') {
+ const methods = editor as Editor & { nodeEditCancelDrag?: () => void }
methods.nodeEditCancelDrag?.()
}
+ }
+
+ function cancelPointerInteraction() {
+ const d = drag.value
+ // Cleared first: ending a preview fires events whose listeners cancel again.
drag.value = null
+ if (d) discardDrag(d)
cursorOverride.value = null
clearTransientInteractionFeedback()
}
@@ -523,6 +521,13 @@ export function useCanvasInput(
editor.setMeasurementMode('off')
cancelPointerInteraction()
})
+ // A document that turns read-only mid-gesture drops the gesture and any open inline edit.
+ const stopReadOnlyListener = editor.onEditorEvent('document:read-only-changed', (readOnly) => {
+ if (!readOnly) return
+ valueEdit.cancel()
+ canvasLabelEdit.cancel()
+ cancelPointerInteraction()
+ })
const stopPlayListeners = (['selection:changed', 'page:changed', 'graph:replaced'] as const).map(
(event) =>
editor.onEditorEvent(event, () => {
@@ -540,6 +545,7 @@ export function useCanvasInput(
onScopeDispose(() => {
stopRotationListener()
stopToolListener()
+ stopReadOnlyListener()
for (const stop of stopPlayListeners) stop()
cancelPointerInteraction()
})
diff --git a/packages/vue/src/primitives/LayerTree/useLayerDrag.ts b/packages/vue/src/primitives/LayerTree/useLayerDrag.ts
index 612950172..a684cbf59 100644
--- a/packages/vue/src/primitives/LayerTree/useLayerDrag.ts
+++ b/packages/vue/src/primitives/LayerTree/useLayerDrag.ts
@@ -56,7 +56,8 @@ export function useLayerDrag(
const cleanup = combine(
draggable({
element,
- canDrag: () => acceptsSiblings,
+ // A read-only document's layers keep their order.
+ canDrag: () => acceptsSiblings && !editor.state.readOnly,
getInitialData: () => ({ id: data.id }),
onDragStart: () => {
draggingId.value = data.id
diff --git a/packages/vue/src/shared/input/move/drag.ts b/packages/vue/src/shared/input/move/drag.ts
index 999df6803..f0936d572 100644
--- a/packages/vue/src/shared/input/move/drag.ts
+++ b/packages/vue/src/shared/input/move/drag.ts
@@ -322,6 +322,21 @@ function placeAbsoluteDrop(d: DragMove, editor: Editor) {
editor.reorderChildWithUndo(id, targetId, index + offset)
}
+/**
+ * Ends a move without recording it: the layers go back where the drag found them, and a
+ * duplicate's copies go away with the selection before them coming back.
+ */
+export function cancelMove(d: DragMove, editor: Editor) {
+ if (d.duplicated) {
+ for (const id of [...d.originals.keys()].toReversed()) editor.graph.deleteNode(id)
+ editor.select([...(d.duplicatedPreviousSelection ?? [])])
+ } else {
+ restoreOriginalPositions(d, editor)
+ }
+ editor.setDropTarget(null)
+ editor.requestRender()
+}
+
export function handleMoveUp(d: DragMove, editor: Editor) {
if (!d.dragStarted) {
editor.setLayoutInsertIndicator(null)
diff --git a/packages/vue/src/shared/input/select.ts b/packages/vue/src/shared/input/select.ts
index 86c824c42..7d4cf0a8f 100644
--- a/packages/vue/src/shared/input/select.ts
+++ b/packages/vue/src/shared/input/select.ts
@@ -34,7 +34,8 @@ function startMarquee(cx: number, cy: number, editor: Editor, setDrag: (d: DragS
/**
* Starts dragging a gradient handle, or else the selection's corner radius, resize, or rotation
- * handles. A layer's label takes the press before rotation but after resizing, as in Figma.
+ * handles. A layer's label takes the press before rotation but after resizing, as in Figma; a
+ * read-only document has no handles.
*/
function tryStartHandleDrag(
cx: number,
@@ -47,6 +48,7 @@ function tryStartHandleDrag(
tryStartRotation: (cx: number, cy: number) => boolean,
setDrag: (d: DragState) => void
): boolean {
+ if (editor.state.readOnly) return false
if (tryStartGradientDrag(editor, sx, sy, setDrag)) return true
// An open gradient's handles replace the layer's selection handles, which then do not respond.
if (editedGradient(editor.graph, editor.state.gradientEdit)) return false
@@ -64,6 +66,18 @@ function tryStartHandleDrag(
return !hitTestLabel(cx, cy, fns) && tryStartRotation(cx, cy)
}
+/** Shift adds to the selection; a plain press selects the layer unless it keeps the selection. */
+function selectOnPress(hit: SceneNode, shiftKey: boolean, keepsSelection: boolean, editor: Editor) {
+ if (shiftKey) editor.select([hit.id], true)
+ else if (!editor.state.selectedIds.has(hit.id) && !keepsSelection) editor.select([hit.id])
+}
+
+/** A read-only document moves nothing, so a press selects a layer inside a selected frame at once. */
+function selectInsideOnPress(hit: SceneNode, keepsSelection: boolean, editor: Editor) {
+ if (keepsSelection && !editor.state.selectedIds.has(hit.id) && clickSelectsInside(hit, editor))
+ editor.select([hit.id])
+}
+
export function handleSelectDown(
e: MouseEvent,
cx: number,
@@ -96,12 +110,12 @@ export function handleSelectDown(
}
const keepsSelection = !e.shiftKey && pressesSelection(hit, cx, cy, editor)
- if (!editor.state.selectedIds.has(hit.id) && !e.shiftKey && !keepsSelection) {
- editor.select([hit.id])
- } else if (e.shiftKey) {
- editor.select([hit.id], true)
- }
+ selectOnPress(hit, e.shiftKey, keepsSelection, editor)
+ if (editor.state.readOnly) {
+ selectInsideOnPress(hit, keepsSelection, editor)
+ return
+ }
if (selectionIsLocked(editor)) return
const drag = createSelectionMoveDrag(cx, cy, sx, sy, editor, e.altKey)
diff --git a/packages/vue/src/shared/input/select/hover.ts b/packages/vue/src/shared/input/select/hover.ts
index 207bf8e33..03e04ba65 100644
--- a/packages/vue/src/shared/input/select/hover.ts
+++ b/packages/vue/src/shared/input/select/hover.ts
@@ -83,10 +83,11 @@ export function updateHoverCursor(
return null
}
- // As a press does: resizing first, then a label, then rotation.
- const cursor =
- getResizeCursorForSelection(cx, cy, editor) ??
- (hitTestLabel(cx, cy, fns) ? null : getRotationCursorForSelection(cx, cy, editor))
+ // As a press does: resizing first, then a label, then rotation; a read-only document has none.
+ const cursor = editor.state.readOnly
+ ? null
+ : (getResizeCursorForSelection(cx, cy, editor) ??
+ (hitTestLabel(cx, cy, fns) ? null : getRotationCursorForSelection(cx, cy, editor)))
updateHoveredNode(cx, cy, editor, fns, deep)
return cursor
}
diff --git a/packages/vue/tests/shared/input/move/cancel.test.ts b/packages/vue/tests/shared/input/move/cancel.test.ts
new file mode 100644
index 000000000..f7a532d83
--- /dev/null
+++ b/packages/vue/tests/shared/input/move/cancel.test.ts
@@ -0,0 +1,35 @@
+import { expect, test } from 'bun:test'
+
+import { cancelMove, handleMoveMove } from '#vue/shared/input/move/drag'
+import { createSelectionMoveDrag } from '#vue/shared/input/select/move'
+
+import { createMoveHarness } from './harness'
+
+function startMove(alt: boolean) {
+ const harness = createMoveHarness()
+ const { editor, page, node } = harness
+ const rect = node('RECTANGLE', page, { x: 10, y: 10 })
+ editor.select([rect.id])
+ const move = createSelectionMoveDrag(30, 30, 30, 30, editor, alt)
+ if (move.type !== 'move') throw new Error('Expected a move drag')
+ handleMoveMove(move, 130, 80, 130, 80, editor)
+ return { ...harness, rect, move }
+}
+
+test('a cancelled move puts the layer back and records nothing', () => {
+ const { editor, rect, move } = startMove(false)
+ expect(editor.graph.getNode(rect.id)?.x).not.toBe(10)
+
+ cancelMove(move, editor)
+ expect(editor.graph.getNode(rect.id)).toMatchObject({ x: 10, y: 10 })
+ expect(editor.undo.canUndo).toBe(false)
+})
+
+test('a cancelled duplicate removes its copies and selects the original again', () => {
+ const { editor, page, rect, move } = startMove(true)
+ expect(editor.graph.getChildren(page)).toHaveLength(2)
+
+ cancelMove(move, editor)
+ expect(editor.graph.getChildren(page).map((child) => child.id)).toEqual([rect.id])
+ expect([...editor.state.selectedIds]).toEqual([rect.id])
+})
diff --git a/packages/vue/tests/shared/input/select/read-only.test.ts b/packages/vue/tests/shared/input/select/read-only.test.ts
new file mode 100644
index 000000000..c48e0948a
--- /dev/null
+++ b/packages/vue/tests/shared/input/select/read-only.test.ts
@@ -0,0 +1,91 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { createEditor, type Editor } from '@open-pencil/core/editor'
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+import { handleSelectDown, type HitTestFns } from '#vue/shared/input/select'
+import { updateHoverCursor } from '#vue/shared/input/select/hover'
+import type { DragState } from '#vue/shared/input/types'
+
+// Figma desktop, version history open (2026-10-17): a press selects, nothing moves or resizes,
+// and selected layers show no handles to drag.
+
+let editor: Editor
+
+afterEach(() => editor.dispose())
+
+const press = { shiftKey: false, altKey: false, metaKey: false, ctrlKey: false } as MouseEvent
+
+function setup() {
+ editor = createEditor()
+ const pageId = editor.state.currentPageId
+ const frame = editor.graph.createNode('FRAME', pageId, { width: 240, height: 160 })
+ const rect = editor.graph.createNode('RECTANGLE', frame.id, {
+ x: 40,
+ y: 40,
+ width: 80,
+ height: 80
+ })
+ let under: SceneNode | null = rect
+ const fns: HitTestFns = {
+ hitTestInScope: () => under,
+ isInsideContainerBounds: () => false,
+ hitTestFrameTitle: () => null,
+ hitTestSectionTitle: () => null,
+ hitTestComponentLabel: () => null
+ }
+ const pressAt = (x: number, y: number, target: SceneNode | null) => {
+ under = target
+ let drag: DragState | null = null
+ handleSelectDown(
+ press,
+ x,
+ y,
+ x,
+ y,
+ editor,
+ fns,
+ () => false,
+ () => false,
+ (next) => {
+ drag = next
+ }
+ )
+ return drag as DragState | null
+ }
+ editor.setReadOnly(true)
+ return { frame, rect, fns, pressAt }
+}
+
+describe('pointer input on a read-only document', () => {
+ test('a press on a layer selects it and starts no move', () => {
+ const { rect, pressAt } = setup()
+ expect(pressAt(80, 80, rect)).toBeNull()
+ expect([...editor.state.selectedIds]).toEqual([rect.id])
+ })
+
+ test('a press on a corner handle starts no resize', () => {
+ const { rect, pressAt } = setup()
+ editor.select([rect.id])
+ expect(pressAt(120, 120, rect)?.type).not.toBe('resize')
+ })
+
+ test('a press inside a selected frame selects the layer under it', () => {
+ const { frame, rect, pressAt } = setup()
+ editor.select([frame.id])
+ expect(pressAt(80, 80, rect)).toBeNull()
+ expect([...editor.state.selectedIds]).toEqual([rect.id])
+ })
+
+ test('a press on empty canvas still draws a marquee', () => {
+ const { pressAt } = setup()
+ expect(pressAt(400, 400, null)?.type).toBe('marquee')
+ })
+
+ test('hovering a corner shows no resize or rotation cursor', () => {
+ const { rect, fns } = setup()
+ editor.select([rect.id])
+ expect(updateHoverCursor(120, 120, editor, fns)).toBeNull()
+ expect(updateHoverCursor(128, 128, editor, fns)).toBeNull()
+ })
+})
diff --git a/src/app/cloud/rooms/live.ts b/src/app/cloud/rooms/live.ts
index 5741ccfa3..bc81aee72 100644
--- a/src/app/cloud/rooms/live.ts
+++ b/src/app/cloud/rooms/live.ts
@@ -131,6 +131,8 @@ export function openCloudDocumentRoom(
const canSave = canEdit && !options.guest
const session = openDocumentRoom(store, options.roomId, options.transport)
setPermission(store, options.permission)
+ // A viewer sees the room's edits and makes none, as Figma's view-only files do.
+ store.setReadOnly(!canEdit)
if (!canSave) store.state.autosaveEnabled = false
const stopSynced = session.onSynced((peerId) => {
if (peerId !== RELAY_SERVER_PEER) return
@@ -144,6 +146,7 @@ export function openCloudDocumentRoom(
stopSynced()
stopSaver()
setPermission(store, null)
+ store.setReadOnly(false)
}
}
}
@@ -180,7 +183,7 @@ export function stopWithTab(store: EditorStore, room: { stop(): void }): void {
/**
* Joins a Cloud document's room on its server's relay, when the server runs one. Edits reach
* everyone in the room as they happen; an empty room takes this tab's document once the relay
- * has answered; viewers' edits never leave the tab.
+ * has answered; a viewer's tab is read-only.
*/
export async function startCloudRoom(store: EditorStore): Promise<void> {
const binding = store.getStorageBinding()
diff --git a/src/app/collab/yjs-sync.ts b/src/app/collab/yjs-sync.ts
index 56f3f95fa..ab560ce8a 100644
--- a/src/app/collab/yjs-sync.ts
+++ b/src/app/collab/yjs-sync.ts
@@ -74,7 +74,8 @@ export function bindCollabGraphEvents({
let bound = true
function record(update: (pending: LocalEdit) => void) {
- if (getSuppressGraphSync() || !getYdoc() || !getYnodes()) return
+ // A read-only document makes no edits of its own; what changes it is the room's.
+ if (store.state.readOnly || getSuppressGraphSync() || !getYdoc() || !getYnodes()) return
if (isLocalEditEmpty(edit)) queueMicrotask(flush)
update(edit)
}
diff --git a/src/app/editor/session/modules.ts b/src/app/editor/session/modules.ts
index 9338cab7e..2c2a7084b 100644
--- a/src/app/editor/session/modules.ts
+++ b/src/app/editor/session/modules.ts
@@ -72,6 +72,11 @@ export function createEditorStoreModules(
...flash,
...pen,
...vectorEdit,
+ /** Going read-only keeps a vector edit in progress, as the editor keeps edited text. */
+ setReadOnly(readOnly: boolean) {
+ if (readOnly) vectorEdit.exitNodeEditMode(true)
+ editor.setReadOnly(readOnly)
+ },
openFigFile: documentIO.openFigFile,
openDOMFile: documentIO.openDOMFile,
importDOMText: documentIO.importDOMText,
diff --git a/src/app/editor/toolbar/layout.ts b/src/app/editor/toolbar/layout.ts
index 7effbcfb5..d46306053 100644
--- a/src/app/editor/toolbar/layout.ts
+++ b/src/app/editor/toolbar/layout.ts
@@ -1,6 +1,11 @@
import { uniq } from 'es-toolkit'
-import { EDITOR_TOOLS, type EditorToolDef, type Tool } from '@open-pencil/core/editor'
+import {
+ EDITOR_TOOLS,
+ READ_ONLY_TOOLS,
+ type EditorToolDef,
+ type Tool
+} from '@open-pencil/core/editor'
/** Toolbar buttons that run a command instead of switching the tool. */
export const TOOLBAR_ACTIONS = ['insert-icon'] as const
@@ -109,6 +114,18 @@ export type ToolbarItem =
| { kind: 'action'; action: ToolbarAction }
/** The toolbar's buttons and flyouts for a layout, without its hidden entries. */
+/** A read-only document's toolbar keeps only the tools that do not edit, as Figma shows Move and Hand. */
+export function readOnlyToolbarLayout(layout: ToolbarLayout): ToolbarLayout {
+ return {
+ groups: layout.groups
+ .map((group) =>
+ group.filter((entry) => !isToolbarAction(entry) && READ_ONLY_TOOLS.has(entry))
+ )
+ .filter((group) => group.length > 0),
+ hidden: layout.hidden
+ }
+}
+
export function toolbarItems(
layout: ToolbarLayout,
labels: Readonly<Record<Tool, string>>,
diff --git a/src/app/shell/ui.ts b/src/app/shell/ui.ts
index acb97561b..19491ad3b 100644
--- a/src/app/shell/ui.ts
+++ b/src/app/shell/ui.ts
@@ -1,6 +1,8 @@
import { useEventListener } from '@vueuse/core'
import { ref } from 'vue'
+import { ReadOnlyDocumentError } from '@open-pencil/core/editor'
+
import { recordRuntimeError } from '@/app/diagnostics'
import { isTauri } from '@/app/tauri/env'
import type { ProgressAmount } from '@/components/ui/feedback/progress'
@@ -136,11 +138,20 @@ function setupGlobalErrorHandler() {
if (errorHandlersInitialized) return
errorHandlersInitialized = true
+ // An edit to a read-only document does nothing, as in Figma, wherever it came from.
useEventListener(window, 'error', (e) => {
+ if (e.error instanceof ReadOnlyDocumentError) {
+ e.preventDefault()
+ return
+ }
recordRuntimeError(e.error ?? e.message, 'window')
error(e.message || 'An unexpected error occurred')
})
useEventListener(window, 'unhandledrejection', (e) => {
+ if (e.reason instanceof ReadOnlyDocumentError) {
+ e.preventDefault()
+ return
+ }
recordRuntimeError(e.reason, 'rejection')
const msg = e.reason instanceof Error ? e.reason.message : String(e.reason)
error(msg || 'An unexpected error occurred')
diff --git a/src/boot.ts b/src/boot.ts
index 89e2826dc..a5bd41856 100644
--- a/src/boot.ts
+++ b/src/boot.ts
@@ -1,6 +1,7 @@
import { createHead } from '@unhead/vue/client'
import { createApp, nextTick } from 'vue'
+import { ReadOnlyDocumentError } from '@open-pencil/core/editor'
import { createRetainedScopePlugin } from '@open-pencil/vue'
import './app.css'
@@ -36,6 +37,8 @@ export async function boot(): Promise<void> {
}
// Component errors after boot reach only this handler, not the window; keep them diagnosable.
app.config.errorHandler = (error, _instance, info) => {
+ // A panel's edit to a read-only document does nothing, as in Figma.
+ if (error instanceof ReadOnlyDocumentError) return
recordRuntimeError(error, 'vue', info)
console.error(error)
}
diff --git a/src/components/CodePanel.vue b/src/components/CodePanel.vue
index b79faacd4..4e002467b 100644
--- a/src/components/CodePanel.vue
+++ b/src/components/CodePanel.vue
@@ -139,6 +139,8 @@ const stylingOptions = computed(() => [
])
/** Components are generated; Design JSX and HTML are edited into layers. */
const readOnly = computed(() => source.value === 'vue' || source.value === 'react')
+/** A read-only document's code is read, never previewed or applied back. */
+const codeReadOnly = computed(() => readOnly.value || store.state.readOnly)
const editorLabel = computed(() => {
if (source.value === 'html-css') return code.value.editorHTMLCSSLabel
if (source.value === 'vue') return code.value.sourceVue
@@ -204,7 +206,7 @@ async function commitCurrentSession(): Promise<void> {
}
async function runPreview(version: number): Promise<void> {
- if (version !== updateVersion || readOnly.value || !draft.value.trim()) return
+ if (version !== updateVersion || codeReadOnly.value || !draft.value.trim()) return
const edits = takeCanvasEdits()
status.value = 'updating'
error.value = ''
@@ -450,7 +452,7 @@ watch(
:autofocus="composing"
:model-value="draft"
:language="source"
- :read-only="readOnly"
+ :read-only="codeReadOnly"
:label="editorLabel"
:layer-links="codeLayers.links.value"
:layer-issues="codeLayers.issues.value"
@@ -484,7 +486,7 @@ watch(
</span>
<div class="flex items-center gap-1">
<AppButton
- v-if="edited && !readOnly"
+ v-if="edited && !codeReadOnly"
color="neutral"
variant="ghost"
size="xs"
diff --git a/src/components/toolbar/Toolbar.vue b/src/components/toolbar/Toolbar.vue
index 80846ef72..b6bd79839 100644
--- a/src/components/toolbar/Toolbar.vue
+++ b/src/components/toolbar/Toolbar.vue
@@ -11,7 +11,7 @@ import {
import { useEditorStore } from '@/app/editor/active-store'
import { toolIcons } from '@/app/editor/icons'
-import { toolbarItems } from '@/app/editor/toolbar/layout'
+import { readOnlyToolbarLayout, toolbarItems } from '@/app/editor/toolbar/layout'
import { toolShortcutLabels } from '@/app/editor/toolbar/shortcuts'
import { appPreferences } from '@/app/settings/preferences/store'
import { useActionToast } from '@/app/shell/toast/action'
@@ -33,9 +33,14 @@ const { menu } = useI18n()
const toolLabels = useToolLabels()
const toolShortcuts = toolShortcutLabels()
-const items = computed(() =>
- toolbarItems(appPreferences.value.toolbar, toolLabels.value, toolShortcuts)
-)
+const items = computed(() => {
+ const layout = appPreferences.value.toolbar
+ return toolbarItems(
+ store.state.readOnly ? readOnlyToolbarLayout(layout) : layout,
+ toolLabels.value,
+ toolShortcuts
+ )
+})
const tools = computed(() =>
items.value.flatMap((item) => (item.kind === 'tool' ? [item.tool] : []))
)
diff --git a/tests/app/editor/toolbar/layout.test.ts b/tests/app/editor/toolbar/layout.test.ts
index b32ea1df3..7a6a9a3b5 100644
--- a/tests/app/editor/toolbar/layout.test.ts
+++ b/tests/app/editor/toolbar/layout.test.ts
@@ -8,6 +8,7 @@ import {
moveToolbarEntry,
normalizeToolbarLayout,
placeToolbarEntry,
+ readOnlyToolbarLayout,
setToolbarEntryHidden,
toolbarDropOperations,
toolbarItems,
@@ -235,3 +236,16 @@ describe('dragging', () => {
expect(combineToolbarEntry(base, 'PEN', 'insert-icon')).toBe(base)
})
})
+
+describe('readOnlyToolbarLayout', () => {
+ test('keeps Move and Hand, as Figma does while a version is viewed', () => {
+ const keys = (groups: ToolbarEntry[][]) =>
+ toolbarItems(readOnlyToolbarLayout(layout(groups)), LABELS, SHORTCUTS).map((item) =>
+ item.kind === 'tool' ? [item.tool.key, ...(item.tool.flyout ?? [])] : item.action
+ )
+ expect(keys([['SELECT', 'HAND'], ['FRAME'], ['insert-icon']])).toEqual([
+ ['SELECT', 'SELECT', 'HAND']
+ ])
+ expect(keys(DEFAULT_TOOLBAR_LAYOUT.groups)).toEqual([['SELECT'], ['HAND']])
+ })
+})