Skip to content

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

refactor: apply read-only as a host restriction on the editor profile (#1616)

Danila Poyarkov205706bd164b
diff --git a/changes/1616/breaking.md b/changes/1616/breaking.md
new file mode 100644
index 000000000..193a91d6c
--- /dev/null
+++ b/changes/1616/breaking.md
@@ -0,0 +1 @@
+- `@open-pencil/core` replaces `state.readOnly` with `state.hostRestrictions` (`EditorRestrictions`, `{ readOnly }`, still set with `setReadOnly`) and no longer exports `READ_ONLY_TOOLS`; read whether the editor offers edits and which tools from `resolveEditorProfile(state)`'s `edits` and `tools`.
diff --git a/oxlint.json b/oxlint.json
index 35b855568..dda773ca4 100644
--- a/oxlint.json
+++ b/oxlint.json
@@ -231,7 +231,7 @@
"open-pencil/no-flat-kiwi-modules": "error",
"open-pencil/no-bun-globals-in-cli": "error",
"open-pencil/no-top-level-prefixed-test-files": "error",
- "open-pencil/no-canvas-view-checks": "error",
+ "open-pencil/no-editor-profile-inputs": "error",
"open-pencil/no-conditional-object-spreads": "error",
"open-pencil/no-sibling-domain-prefixed-files": "error",
"array-callback-return": "error",
diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.md
index 6c4a4f1b4..d5f6d2f4b 100644
--- a/packages/core/AGENTS.md
+++ b/packages/core/AGENTS.md
@@ -52,7 +52,7 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do
- 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`).
-- A canvas pane behaves by the profile its view resolves to (`resolveEditorProfile` in `packages/core/src/editor/views/`): pointer, shortcuts, editing chrome, live islands, panels, and where leaving goes. A new view is a new profile, and code outside the views and state modules reads profile values, never the view, which `open-pencil/no-canvas-view-checks` enforces (`packages/core/tests/editor/views/profile.test.ts`).
+- A canvas pane behaves by its profile (`resolveEditorProfile` in `packages/core/src/editor/views/`): its view's pointer, shortcuts, editing chrome, live islands, panels, and where leaving goes, narrowed by the host's restrictions to the edits and tools it allows. A new view is a new profile and a new host limit a new restriction; other code reads profile values, never the view or restrictions, which `open-pencil/no-editor-profile-inputs` enforces (`packages/core/tests/editor/views/profile.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 881516d27..fb9694a55 100644
--- a/packages/core/src/canvas/overlays/selection.ts
+++ b/packages/core/src/canvas/overlays/selection.ts
@@ -303,7 +303,7 @@ function drawBoundsHandles(
maxY: number,
stalk: RotationHandleLayout | null
): void {
- if (r.readOnly || !hasTransformHandles((maxX - minX) * r.zoom, (maxY - minY) * r.zoom)) return
+ if (!r.editHandles || !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 9fb69dcc9..9552a3cca 100644
--- a/packages/core/src/canvas/renderer.ts
+++ b/packages/core/src/canvas/renderer.ts
@@ -165,8 +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
+ /** Selections draw handles to drag; off while the canvas offers no edits. */
+ editHandles = true
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 62076d903..7a9ce0ca3 100644
--- a/packages/core/src/canvas/renderer/overlay-pass.ts
+++ b/packages/core/src/canvas/renderer/overlay-pass.ts
@@ -123,7 +123,7 @@ export function drawOverlayPass(
drawGradientHandles(r, canvas, graph, overlays.gradientEdit, overlays.rotationPreview)
else {
r.drawSelection(canvas, graph, selectedIds, overlays)
- if (!overlays.transforming && !r.readOnly)
+ if (!overlays.transforming && r.editHandles)
drawShapeHandles(
r,
canvas,
@@ -142,7 +142,7 @@ export function drawOverlayPass(
r.drawSnapGuides(canvas, overlays.snapGuides)
r.drawMarquee(canvas, overlays.marquee)
r.drawLayoutInsertIndicator(canvas, overlays.layoutInsertIndicator)
- if (!measuring && !overlays.transforming && !r.readOnly) {
+ if (!measuring && !overlays.transforming && r.editHandles) {
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 30fef19b3..ba06455d6 100644
--- a/packages/core/src/canvas/renderer/pipeline.ts
+++ b/packages/core/src/canvas/renderer/pipeline.ts
@@ -78,8 +78,8 @@ export function renderFromEditorState(
r.pageId = state.currentPageId
r.navigationPhase = state.navigation.phase
r.navigationGeneration = state.navigation.generation
- r.readOnly = state.readOnly
- const { editChrome, live } = resolveEditorProfile(state)
+ const { editChrome, live, edits } = resolveEditorProfile(state)
+ r.editHandles = edits
render(
r,
graph,
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index e4baba6b2..f291a5753 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -50,7 +50,7 @@ import { createDesignIssueActions } from './issues'
import { createLineEndActions } from './line-ends'
import { createNodeActions } from './nodes'
import { createPageActions } from './pages'
-import { createReadOnlyActions, guardReadOnly, guardUndo, READ_ONLY_TOOLS } from './read-only'
+import { createReadOnlyActions, guardReadOnly, guardUndo } from './read-only'
import { createSelectionActions } from './selection'
import { createShaderActions } from './shaders/actions'
import { createShaderFrames } from './shaders/frames'
@@ -75,7 +75,7 @@ import { createUndoActions } from './undo'
import { createVariableActions } from './variables'
import { createVectorizeActions } from './vectorize'
import { createViewportActions } from './viewport'
-import { createCanvasViewActions } from './views'
+import { createCanvasViewActions, resolveEditorProfile } from './views'
export { createDefaultEditorState } from './state'
@@ -210,7 +210,8 @@ export function createEditor(options?: EditorOptions) {
}
function setActiveTool(tool: EditorState['activeTool']) {
- if (state.readOnly && !READ_ONLY_TOOLS.has(tool)) return
+ const { tools } = resolveEditorProfile(state)
+ if (tools && !tools.has(tool)) return
const previous = state.activeTool
state.activeTool = tool
if (tool !== 'SELECT') state.measurementMode = 'off'
@@ -331,6 +332,8 @@ 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)
+ /** Whether the editor refuses edits: its profile offers none, as for a read-only document. */
+ const readsOnly = () => !resolveEditorProfile(state).edits
const readOnly = createReadOnlyActions(ctx, () => {
nodes.flushNudge()
nodes.cancelNodePreviews()
@@ -429,7 +432,7 @@ export function createEditor(options?: EditorOptions) {
get textEditor() {
return _textEditor
},
- undo: guardUndo(undo, () => state.readOnly),
+ undo: guardUndo(undo, readsOnly),
state,
// Graph reads
@@ -551,7 +554,7 @@ export function createEditor(options?: EditorOptions) {
// Read-only documents, which refuse every action above that changes them
...readOnly
}
- return guardReadOnly(editor, () => state.readOnly)
+ return guardReadOnly(editor, readsOnly)
}
/**
diff --git a/packages/core/src/editor/history/atomic-tool.ts b/packages/core/src/editor/history/atomic-tool.ts
index 49d02e76f..648813dab 100644
--- a/packages/core/src/editor/history/atomic-tool.ts
+++ b/packages/core/src/editor/history/atomic-tool.ts
@@ -4,6 +4,7 @@ import { captureGraphCheckpoint } from '@open-pencil/scene-graph/checkpoint'
import type { Editor } from '#core/editor/create'
import { ReadOnlyDocumentError } from '#core/editor/read-only'
import type { EditorState } from '#core/editor/types'
+import { resolveEditorProfile } from '#core/editor/views'
import type { FigmaAPI } from '#core/figma-api'
import { isAtomicTool, type ToolDef } from '#core/tools/schema'
@@ -16,7 +17,7 @@ type MutationEditor = Pick<
Editor,
'graph' | 'runLayoutForNode' | 'requestRender' | 'pushUndoStep'
> & {
- state: Pick<EditorState, 'readOnly'>
+ state: Pick<EditorState, 'canvasView' | 'hostRestrictions'>
}
function changes<T extends object>(
@@ -47,7 +48,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()
+ if (!resolveEditorProfile(editor.state).edits) 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 e4ea16abb..c8303345a 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -4,7 +4,7 @@ export {
ReadOnlyLibraryDefinitionError
} from './capabilities'
export type { NodeEditCapability } from './capabilities'
-export { READ_ONLY_TOOLS, ReadOnlyDocumentError } from './read-only'
+export { ReadOnlyDocumentError } from './read-only'
export { DEFAULT_SNAPPING_PREFERENCES } from './preferences'
export type { SnappingPreferences } from './preferences'
export { createDefaultEditorSharedState } from './state/shared'
@@ -35,7 +35,7 @@ export { resolvePasteTarget } from './clipboard/paste/target'
export { playIslandRoots } from './play/islands'
export { resolvePlayState, type InstanceState } from './play/states'
export { EDIT_VIEW, resolveEditorProfile } from './views'
-export type { CanvasView, EditorProfile } from './views'
+export type { CanvasView, EditorProfile, EditorRestrictions } from './views'
export type { ShaderRasterizer } from './shaders/types'
export type { ShaderPaintList } from './shaders/actions'
export type { Editor } from './create'
diff --git a/packages/core/src/editor/read-only/index.ts b/packages/core/src/editor/read-only/index.ts
index 337981e50..ee260145f 100644
--- a/packages/core/src/editor/read-only/index.ts
+++ b/packages/core/src/editor/read-only/index.ts
@@ -1,6 +1,7 @@
import type { UndoManager } from '@open-pencil/scene-graph/undo'
-import type { EditorContext, Tool } from '#core/editor/types'
+import type { EditorContext } from '#core/editor/types'
+import { resolveEditorProfile } from '#core/editor/views'
import { READ_ONLY_ACTIONS } from './actions'
@@ -12,12 +13,9 @@ export class ReadOnlyDocumentError extends Error {
}
}
-/** 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.
+ * holds, as it does while the editor's profile offers no edits; 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)
@@ -56,12 +54,11 @@ export function createReadOnlyActions(ctx: EditorContext, endEdits: () => void)
* 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
+ if (ctx.state.hostRestrictions.readOnly === readOnly) return
+ if (readOnly) endEdits()
+ ctx.state.hostRestrictions = { ...ctx.state.hostRestrictions, readOnly }
+ const { tools } = resolveEditorProfile(ctx.state)
+ if (tools && !tools.has(ctx.state.activeTool)) ctx.setActiveTool('SELECT')
ctx.emitEditorEvent('document:read-only-changed', readOnly)
ctx.requestRepaint()
}
diff --git a/packages/core/src/editor/state/shared.ts b/packages/core/src/editor/state/shared.ts
index fdcf93f4f..0cd31cd54 100644
--- a/packages/core/src/editor/state/shared.ts
+++ b/packages/core/src/editor/state/shared.ts
@@ -5,7 +5,7 @@ export function createDefaultEditorSharedState(): EditorSharedState {
return {
activeTool: 'SELECT',
shapeWithTextKind: 'SQUARE',
- readOnly: false,
+ hostRestrictions: { 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 65bdf82de..c76792514 100644
--- a/packages/core/src/editor/types.ts
+++ b/packages/core/src/editor/types.ts
@@ -28,7 +28,7 @@ import type { InterfaceTheme } from '#core/constants'
import type { ConnectorTarget } from '#core/editor/connectors/attach'
import type { SnappingPreferences } from '#core/editor/preferences'
import type { ShaderRasterizer } from '#core/editor/shaders/types'
-import type { CanvasView } from '#core/editor/views/types'
+import type { CanvasView, EditorRestrictions } from '#core/editor/views/types'
import type { RotationPreview, ShapeHandleKind } from '#core/geometry'
import type { IconProvider } from '#core/icons/provider'
import type { TextEditor } from '#core/text/editor'
@@ -79,10 +79,10 @@ export interface EditorSharedState {
/** The kind the shape-with-text tool places: the one picked last, as in FigJam. */
shapeWithTextKind: ShapeWithTextType
/**
- * 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`.
+ * What the host takes away from every canvas, such as editing for a viewer or an earlier version;
+ * read through `resolveEditorProfile`, set with `setReadOnly`.
*/
- readOnly: boolean
+ hostRestrictions: EditorRestrictions
snappingPreferences: SnappingPreferences
/** Draw the pixel grid once zoomed in far enough, as Figma's View › Pixel grid; shown unless false. */
showPixelGrid?: boolean
diff --git a/packages/core/src/editor/views/index.ts b/packages/core/src/editor/views/index.ts
index 394500870..c232c5f13 100644
--- a/packages/core/src/editor/views/index.ts
+++ b/packages/core/src/editor/views/index.ts
@@ -1,3 +1,3 @@
export { createCanvasViewActions } from './actions'
export { EDIT_VIEW, resolveEditorProfile } from './profile'
-export type { CanvasView, EditorProfile } from './types'
+export type { CanvasView, EditorProfile, EditorRestrictions } from './types'
diff --git a/packages/core/src/editor/views/profile.ts b/packages/core/src/editor/views/profile.ts
index fa8385581..03b01b4ed 100644
--- a/packages/core/src/editor/views/profile.ts
+++ b/packages/core/src/editor/views/profile.ts
@@ -1,16 +1,21 @@
-import type { EditorViewState } from '#core/editor/types'
+import type { EditorState, Tool } from '#core/editor/types'
-import type { CanvasView, EditorProfile } from './types'
+import type { CanvasView, EditorProfile, EditorRestrictions } from './types'
export const EDIT_VIEW: CanvasView = { id: 'edit' }
+/** 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'])
+
const EDIT_PROFILE: EditorProfile = {
pointer: 'tools',
shortcuts: 'all',
editChrome: true,
live: null,
panels: true,
- leaveTo: null
+ leaveTo: null,
+ edits: true,
+ tools: null
}
/** A preview runs the design: the canvas only pans, and its controls take the pointer. */
@@ -21,14 +26,31 @@ function playProfile(revision: number): EditorProfile {
editChrome: false,
live: { revision },
panels: false,
- leaveTo: EDIT_VIEW
+ leaveTo: EDIT_VIEW,
+ edits: true,
+ tools: null
}
}
+function viewProfile(view: CanvasView): EditorProfile {
+ return view.id === 'play' ? playProfile(view.revision) : EDIT_PROFILE
+}
+
+/** Narrows a view's profile by the host's restrictions; a restriction only ever takes away. */
+function restrict(profile: EditorProfile, restrictions: EditorRestrictions): EditorProfile {
+ if (!restrictions.readOnly) return profile
+ const tools = profile.tools
+ ? new Set([...profile.tools].filter((tool) => READ_ONLY_TOOLS.has(tool)))
+ : READ_ONLY_TOOLS
+ return { ...profile, edits: false, tools }
+}
+
/**
- * The profile a canvas behaves by. Pass the pane's own state, since each pane shows its own view.
+ * The profile a canvas behaves by: its view's, narrowed by the host's restrictions. Pass the
+ * pane's own state, since each pane shows its own view.
*/
-export function resolveEditorProfile(state: Pick<EditorViewState, 'canvasView'>): EditorProfile {
- const view = state.canvasView
- return view.id === 'play' ? playProfile(view.revision) : EDIT_PROFILE
+export function resolveEditorProfile(
+ state: Pick<EditorState, 'canvasView' | 'hostRestrictions'>
+): EditorProfile {
+ return restrict(viewProfile(state.canvasView), state.hostRestrictions)
}
diff --git a/packages/core/src/editor/views/types.ts b/packages/core/src/editor/views/types.ts
index de13712b7..72bb483dc 100644
--- a/packages/core/src/editor/views/types.ts
+++ b/packages/core/src/editor/views/types.ts
@@ -1,3 +1,13 @@
+import type { Tool } from '#core/editor/types'
+
+/**
+ * What the host takes away from every view, whatever the canvas shows: a read-only document, as
+ * for a viewer or an earlier version, can be looked at, selected in, and copied from, not changed.
+ */
+export interface EditorRestrictions {
+ readOnly: boolean
+}
+
/**
* What a canvas pane shows: the design being edited, or the design running as a preview whose
* controls respond to the pointer. Each pane has its own.
@@ -25,4 +35,11 @@ export interface EditorProfile {
panels: boolean
/** The view leaving this one returns to, as Escape does, or null when there is none. */
leaveTo: CanvasView | null
+ /**
+ * Whether the document can change: actions that edit it, undo, and the canvas's edit handles,
+ * text editing, value scrubbing, guide editing, and layer drags.
+ */
+ edits: boolean
+ /** The tools on offer, or null for every tool. */
+ tools: ReadonlySet<Tool> | null
}
diff --git a/packages/core/tests/editor/history/atomic-tools.test.ts b/packages/core/tests/editor/history/atomic-tools.test.ts
index d5dc2424f..afb2c7d9c 100644
--- a/packages/core/tests/editor/history/atomic-tools.test.ts
+++ b/packages/core/tests/editor/history/atomic-tools.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, test } from 'bun:test'
import { OpenPencilAPI } from '@open-pencil/core/openpencil-api'
-import { createEditor, executeAtomicTool } from '@open-pencil/core'
+import { createEditor, EDIT_VIEW, executeAtomicTool } from '@open-pencil/core'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { ALL_TOOLS, type ToolDef } from '@open-pencil/core/tools'
import { SceneGraph } from '@open-pencil/scene-graph'
@@ -13,7 +13,7 @@ function setup() {
const figma = new FigmaAPI(graph)
const editor = {
graph,
- state: { readOnly: false },
+ state: { canvasView: EDIT_VIEW, hostRestrictions: { readOnly: false } },
runLayoutForNode: () => undefined,
requestRender: () => undefined,
pushUndoStep: undo.pushStep.bind(undo)
diff --git a/packages/core/tests/editor/views/profile.test.ts b/packages/core/tests/editor/views/profile.test.ts
index 536cbecc0..8649d05cb 100644
--- a/packages/core/tests/editor/views/profile.test.ts
+++ b/packages/core/tests/editor/views/profile.test.ts
@@ -11,7 +11,9 @@ describe('canvas view profiles', () => {
editChrome: true,
live: null,
panels: true,
- leaveTo: null
+ leaveTo: null,
+ edits: true,
+ tools: null
})
})
@@ -24,7 +26,9 @@ describe('canvas view profiles', () => {
editChrome: false,
live: { revision: 0 },
panels: false,
- leaveTo: { id: 'edit' }
+ leaveTo: { id: 'edit' },
+ edits: true,
+ tools: null
})
})
@@ -50,3 +54,41 @@ describe('canvas view profiles', () => {
expect(editor.leaveCanvasView()).toBe(true)
})
})
+
+describe('host restrictions', () => {
+ test('a read-only document offers no edits and keeps Move and Hand in every view', () => {
+ const editor = createEditor()
+ editor.setReadOnly(true)
+ const editing = resolveEditorProfile(editor.state)
+ expect([editing.edits, editing.tools && [...editing.tools]]).toEqual([
+ false,
+ ['SELECT', 'HAND']
+ ])
+ editor.startPlay()
+ const previewing = resolveEditorProfile(editor.state)
+ expect([previewing.edits, previewing.pointer, previewing.live]).toEqual([
+ false,
+ 'pan',
+ { revision: 0 }
+ ])
+ expect(previewing.tools && [...previewing.tools]).toEqual(['SELECT', 'HAND'])
+ })
+
+ test('going read-only drops a tool it does not offer, and refuses picking one', () => {
+ const editor = createEditor()
+ editor.setTool('RECTANGLE')
+ editor.setReadOnly(true)
+ expect(editor.state.activeTool).toBe('SELECT')
+ editor.setTool('FRAME')
+ expect(editor.state.activeTool).toBe('SELECT')
+ editor.setTool('HAND')
+ expect(editor.state.activeTool).toBe('HAND')
+ })
+
+ test('lifting the restriction gives the view its own profile back', () => {
+ const editor = createEditor()
+ editor.setReadOnly(true)
+ editor.setReadOnly(false)
+ expect(resolveEditorProfile(editor.state)).toMatchObject({ edits: true, tools: null })
+ })
+})
diff --git a/packages/vue/src/canvas/islands/IslandLayer.vue b/packages/vue/src/canvas/islands/IslandLayer.vue
index 074bb53b8..f69b2a7d9 100644
--- a/packages/vue/src/canvas/islands/IslandLayer.vue
+++ b/packages/vue/src/canvas/islands/IslandLayer.vue
@@ -2,7 +2,7 @@
import { computedAsync } from '@vueuse/core'
import { computed, watch } from 'vue'
-import { playIslandRoots, resolveEditorProfile, type CanvasView } from '@open-pencil/core'
+import { playIslandRoots, resolveEditorProfile, type EditorState } from '@open-pencil/core'
import type { ViewportTransform } from '@open-pencil/core/geometry'
import { tokenStylesheet } from '@open-pencil/dom-css/export'
@@ -15,7 +15,10 @@ import Island from './Island.vue'
* canvas leaves these layers to the islands; wheel gestures over them still pan and zoom it.
*/
const { view, canvas, drawn } = defineProps<{
- view: { panX: number; panY: number; zoom: number; currentPageId: string; canvasView: CanvasView }
+ view: Pick<
+ EditorState,
+ 'panX' | 'panY' | 'zoom' | 'currentPageId' | 'canvasView' | 'hostRestrictions'
+ >
/** The canvas that wheel gestures over the islands are passed on to. */
canvas: HTMLElement | null
/**
diff --git a/packages/vue/src/canvas/surface/shader/playback.ts b/packages/vue/src/canvas/surface/shader/playback.ts
index fe8467732..7e3519789 100644
--- a/packages/vue/src/canvas/surface/shader/playback.ts
+++ b/packages/vue/src/canvas/surface/shader/playback.ts
@@ -85,7 +85,10 @@ export function useShaderPlayback(options: {
editor: Editor
getRenderer: () => SkiaRenderer | null
/** The view this canvas draws: its pan, zoom, page, and whether it previews. */
- getView: () => Pick<EditorState, 'panX' | 'panY' | 'zoom' | 'currentPageId' | 'canvasView'>
+ getView: () => Pick<
+ EditorState,
+ 'panX' | 'panY' | 'zoom' | 'currentPageId' | 'canvasView' | 'hostRestrictions'
+ >
getViewport: () => { width: number; height: number }
markDirty: () => void
}) {
diff --git a/packages/vue/src/canvas/text-edit/input.ts b/packages/vue/src/canvas/text-edit/input.ts
index 4bd3ef52d..ef1e923b4 100644
--- a/packages/vue/src/canvas/text-edit/input.ts
+++ b/packages/vue/src/canvas/text-edit/input.ts
@@ -1,4 +1,4 @@
-import { getNodeEditCapability, type Editor } from '@open-pencil/core'
+import { getNodeEditCapability, resolveEditorProfile, type Editor } from '@open-pencil/core'
import type { SceneNode } from '@open-pencil/scene-graph'
import { generatedFrameOwner, generatedFrameText } from '@open-pencil/scene-graph/generated'
@@ -143,7 +143,8 @@ export function createTextEditInput(options: TextEditInputOptions) {
}
const hit = getContainerDescendantHit(selectedId, cx, cy)
editor.enterContainer(selectedId)
- if (hit?.type === 'TEXT' && !editor.state.readOnly) startTextEditingAt(hit, cx, cy)
+ if (hit?.type === 'TEXT' && resolveEditorProfile(editor.state).edits)
+ startTextEditingAt(hit, cx, cy)
else if (hit) editor.select([hit.id])
else editor.clearSelection()
return true
@@ -154,7 +155,7 @@ export function createTextEditInput(options: TextEditInputOptions) {
if (editor.state.editingTextId) return
const { cx, cy } = getCoords(e)
- const { readOnly } = editor.state
+ const readOnly = !resolveEditorProfile(editor.state).edits
if (!readOnly && startLabelRename(cx, cy)) return
const selectedId =
diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.ts
index 9dedc6661..4a1e81f91 100644
--- a/packages/vue/src/canvas/useCanvasInput.ts
+++ b/packages/vue/src/canvas/useCanvasInput.ts
@@ -69,6 +69,7 @@ export function useCanvasInput(
zoomSpeed: () => number = () => 1
) {
const drag = ref<DragState | null>(null)
+ const profile = () => resolveEditorProfile(editor.state)
// Canvas chrome that explains layout, such as auto layout child outlines, steps aside while
// layers move, resize, or rotate.
watch(
@@ -132,11 +133,11 @@ export function useCanvasInput(
// 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
+ return mode === 'off' && profile().edits ? resolveAutoLayoutHover(cx, cy, editor) : null
}
function shapeHandleHoverAt(sx: number, sy: number, altKey: boolean) {
- return editor.state.readOnly ? null : resolveShapeHandleHover(editor, sx, sy, altKey)
+ return profile().edits ? resolveShapeHandleHover(editor, sx, sy, altKey) : null
}
function updateModifier(code: string, held: boolean) {
@@ -193,9 +194,9 @@ export function useCanvasInput(
} = createCanvasTransformInput(editor, setDrag)
function onDblClick(e: MouseEvent) {
- if (resolveEditorProfile(editor.state).pointer === 'pan') return
+ if (profile().pointer === 'pan') return
const { cx, cy } = getCoords(e)
- if (!editor.state.readOnly && valueEdit.start(cx, cy)) {
+ if (profile().edits && valueEdit.start(cx, cy)) {
e.preventDefault()
e.stopPropagation()
return
@@ -207,7 +208,7 @@ export function useCanvasInput(
onActivate?.()
if (!isEnabled()) return
// A canvas that only pans, as a preview's does, leaves its controls to the islands above it.
- const panOnly = resolveEditorProfile(editor.state).pointer === 'pan'
+ const panOnly = profile().pointer === 'pan'
if (panOnly && e.button === 0 && editor.state.activeTool !== 'HAND') {
e.preventDefault()
return
@@ -222,7 +223,7 @@ export function useCanvasInput(
editor.setHoveredNode(null)
const { sx, sy, cx, cy } = getCoords(e)
// Guides belong to the document, so a read-only one neither moves nor gains them.
- const guidesEditable = e.button === 0 && !editor.state.readOnly
+ const guidesEditable = e.button === 0 && profile().edits
if (guidesEditable && guideInput.tryStartExisting(sx, sy, e.altKey)) {
e.preventDefault()
return
@@ -262,7 +263,7 @@ export function useCanvasInput(
onCursorMove(coords.cx, coords.cy)
}
- if (resolveEditorProfile(editor.state).pointer === 'pan' && !drag.value) return
+ if (profile().pointer === 'pan' && !drag.value) return
if (!drag.value) {
const { cx, cy } = coords
@@ -281,7 +282,7 @@ export function useCanvasInput(
if (!drag.value && editor.state.activeTool === 'SELECT') {
const { sx, sy, cx, cy } = coords
- const guideCursor = editor.state.readOnly ? null : guideInput.updateHover(sx, sy)
+ const guideCursor = profile().edits ? guideInput.updateHover(sx, sy) : null
cursorOverride.value =
guideCursor ??
updateHoverCursor(
diff --git a/packages/vue/src/primitives/LayerTree/useLayerDrag.ts b/packages/vue/src/primitives/LayerTree/useLayerDrag.ts
index 3140339a7..db11574db 100644
--- a/packages/vue/src/primitives/LayerTree/useLayerDrag.ts
+++ b/packages/vue/src/primitives/LayerTree/useLayerDrag.ts
@@ -11,7 +11,7 @@ import {
} from '@atlaskit/pragmatic-drag-and-drop/element/adapter'
import { onScopeDispose, ref, watchEffect, type Ref } from 'vue'
-import type { Editor } from '@open-pencil/core'
+import { resolveEditorProfile, type Editor } from '@open-pencil/core'
import type { LayerDragInstruction } from '#vue/primitives/LayerTree/context'
import { dropIndex, listsChildrenInFlow } from '#vue/primitives/LayerTree/model'
@@ -57,7 +57,7 @@ export function useLayerDrag(
draggable({
element,
// A read-only document's layers keep their order.
- canDrag: () => acceptsSiblings && !editor.state.readOnly,
+ canDrag: () => acceptsSiblings && resolveEditorProfile(editor.state).edits,
getInitialData: () => ({ id: data.id }),
onDragStart: () => {
draggingId.value = data.id
diff --git a/packages/vue/src/shared/input/select.ts b/packages/vue/src/shared/input/select.ts
index eee6345f4..866e43db7 100644
--- a/packages/vue/src/shared/input/select.ts
+++ b/packages/vue/src/shared/input/select.ts
@@ -2,7 +2,7 @@ import { getNodeEditState, handleNodeEditDown } from '#vue/shared/input/vector'
export { resolveHit } from '#vue/shared/input/select/hit'
import { hitTestLabel, resolveHit, tinySelectionAt } from '#vue/shared/input/select/hit'
export { updateHoverCursor } from '#vue/shared/input/select/hover'
-import { editedGradient, type Editor } from '@open-pencil/core'
+import { editedGradient, resolveEditorProfile, type Editor } from '@open-pencil/core'
import type { SceneNode } from '@open-pencil/scene-graph'
import { tryStartConnectorEndDrag } from '#vue/shared/input/connector/end'
@@ -51,7 +51,7 @@ function tryStartHandleDrag(
tryStartRotation: (cx: number, cy: number) => boolean,
setDrag: (d: DragState) => void
): boolean {
- if (editor.state.readOnly) return false
+ if (!resolveEditorProfile(editor.state).edits) 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
@@ -118,7 +118,7 @@ export function handleSelectDown(
const keepsSelection = !e.shiftKey && pressesSelection(hit, cx, cy, editor)
selectOnPress(hit, e.shiftKey, keepsSelection, editor)
- if (editor.state.readOnly) {
+ if (!resolveEditorProfile(editor.state).edits) {
selectInsideOnPress(hit, keepsSelection, editor)
return
}
diff --git a/packages/vue/src/shared/input/select/hover.ts b/packages/vue/src/shared/input/select/hover.ts
index 8e1dcc8bc..eda106e4f 100644
--- a/packages/vue/src/shared/input/select/hover.ts
+++ b/packages/vue/src/shared/input/select/hover.ts
@@ -1,4 +1,4 @@
-import type { Editor } from '@open-pencil/core'
+import { resolveEditorProfile, type Editor } from '@open-pencil/core'
import { layerResizes, layerRotates } from '@open-pencil/scene-graph/generated'
import { connectorLineCursor } from '#vue/shared/input/connector/line'
@@ -90,7 +90,7 @@ export function updateHoverCursor(
// As a press does: a line's ends, a connector's line handles, then resizing, then a label, then
// rotation; a read-only document has none.
- const cursor = editor.state.readOnly
+ const cursor = !resolveEditorProfile(editor.state).edits
? null
: ((lineEndAt(editor, cx, cy) ? MOVE_CURSOR : null) ??
connectorLineCursor(editor, cx, cy) ??
diff --git a/src/app/cloud/versions/history.ts b/src/app/cloud/versions/history.ts
index 95390d3df..4a8c0f658 100644
--- a/src/app/cloud/versions/history.ts
+++ b/src/app/cloud/versions/history.ts
@@ -101,7 +101,7 @@ export function openVersionHistory(store: EditorStore): void {
if (histories.value.has(store)) return
update(store, {
store,
- wasReadOnly: store.state.readOnly,
+ wasReadOnly: store.state.hostRestrictions.readOnly,
preview: null,
opening: null,
failed: false
diff --git a/src/app/collab/document/sync.ts b/src/app/collab/document/sync.ts
index 96f4a4205..b43b098fd 100644
--- a/src/app/collab/document/sync.ts
+++ b/src/app/collab/document/sync.ts
@@ -181,7 +181,7 @@ export function bindDocumentSync({
function send() {
// A joining tab's own document is not the room's until it follows the room.
- if (receiving || store.state.readOnly || !holdsRoomRoot()) return
+ if (receiving || store.state.hostRestrictions.readOnly || !holdsRoomRoot()) return
write()
}
@@ -292,7 +292,7 @@ export function bindDocumentSync({
* root, and the sharing tab is the room's source, so it has nothing to follow.
*/
share() {
- if (store.state.readOnly) return
+ if (store.state.hostRestrictions.readOnly) return
followedRoot = store.graph.rootId
sent = { entries: new Map(), threads: new Map(), libraries: new Map(), colorSpace: undefined }
write()
diff --git a/src/app/collab/session.ts b/src/app/collab/session.ts
index 9cbe36d36..60ef653fc 100644
--- a/src/app/collab/session.ts
+++ b/src/app/collab/session.ts
@@ -257,7 +257,7 @@ export function openRoomSession({
// A rename reaches the room once the tab shows the room's copy; before that the room's name
// wins, as the room's other document data does when the tab starts following it.
function publishName(name: string) {
- if (disposed || store.state.readOnly || !hasDocument.value) return
+ if (disposed || store.state.hostRestrictions.readOnly || !hasDocument.value) return
if (readRoot(meta) !== store.graph.rootId || name === readRoomName(meta)) return
writeRoomName(meta, name)
}
diff --git a/src/app/collab/yjs-sync.ts b/src/app/collab/yjs-sync.ts
index 115429fac..caadedd7f 100644
--- a/src/app/collab/yjs-sync.ts
+++ b/src/app/collab/yjs-sync.ts
@@ -85,7 +85,13 @@ export function bindCollabGraphEvents({
function record(update: (pending: LocalEdit) => void) {
// 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 (
+ store.state.hostRestrictions.readOnly ||
+ getSuppressGraphSync() ||
+ !getYdoc() ||
+ !getYnodes()
+ )
+ return
if (isLocalEditEmpty(edit)) queueMicrotask(flush)
update(edit)
}
diff --git a/src/app/document/io/source/actions.ts b/src/app/document/io/source/actions.ts
index d0c78599f..8c7b72635 100644
--- a/src/app/document/io/source/actions.ts
+++ b/src/app/document/io/source/actions.ts
@@ -135,7 +135,7 @@ export function createDocumentSourceActions({
function renameDocument(name: string) {
const trimmed = name.trim()
- if (state.readOnly || !trimmed || trimmed === state.documentName) return
+ if (state.hostRestrictions.readOnly || !trimmed || trimmed === state.documentName) return
state.documentName = trimmed
// Storage keeps the name with the document; a file's name is its path, which saving leaves as is.
if (getStorageBinding()) changes.markChanged()
diff --git a/src/app/editor/toolbar/layout.ts b/src/app/editor/toolbar/layout.ts
index ad5103015..dfebd1f3e 100644
--- a/src/app/editor/toolbar/layout.ts
+++ b/src/app/editor/toolbar/layout.ts
@@ -1,6 +1,6 @@
import { uniq } from 'es-toolkit'
-import { EDITOR_TOOLS, READ_ONLY_TOOLS, type EditorToolDef, type Tool } from '@open-pencil/core'
+import { EDITOR_TOOLS, type EditorToolDef, type Tool } from '@open-pencil/core'
/** Toolbar buttons that run a command instead of switching the tool. */
export const TOOLBAR_ACTIONS = ['insert-icon'] as const
@@ -108,19 +108,25 @@ export type ToolbarItem =
| { kind: 'tool'; tool: EditorToolDef }
| { 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 {
+/**
+ * The layout narrowed to the tools the editor's profile offers: the whole layout when it names
+ * none, and otherwise only those tools, with no actions, as a read-only document keeps Move and
+ * Hand in Figma.
+ */
+export function toolbarLayoutFor(
+ layout: ToolbarLayout,
+ tools: ReadonlySet<Tool> | null
+): ToolbarLayout {
+ if (!tools) return layout
return {
groups: layout.groups
- .map((group) =>
- group.filter((entry) => !isToolbarAction(entry) && READ_ONLY_TOOLS.has(entry))
- )
+ .map((group) => group.filter((entry) => !isToolbarAction(entry) && tools.has(entry)))
.filter((group) => group.length > 0),
hidden: layout.hidden
}
}
+/** The toolbar's buttons and flyouts for a layout, without its hidden entries. */
export function toolbarItems(
layout: ToolbarLayout,
labels: Readonly<Record<Tool, string>>,
diff --git a/src/components/CodePanel.vue b/src/components/CodePanel.vue
index e176d48ed..f19b527e1 100644
--- a/src/components/CodePanel.vue
+++ b/src/components/CodePanel.vue
@@ -12,6 +12,7 @@ import {
watch
} from 'vue'
+import { resolveEditorProfile } from '@open-pencil/core'
import { JSX_REFERENCE } from '@open-pencil/design-jsx'
import type { SceneNode } from '@open-pencil/scene-graph'
import { useEditorEvent } from '@open-pencil/vue/editor/events'
@@ -141,7 +142,7 @@ 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 codeReadOnly = computed(() => readOnly.value || !resolveEditorProfile(store.state).edits)
const editorLabel = computed(() => {
if (source.value === 'html-css') return code.value.editorHTMLCSSLabel
if (source.value === 'vue') return code.value.sourceVue
diff --git a/src/components/toolbar/EditorToolbar.vue b/src/components/toolbar/EditorToolbar.vue
index 7fde08caa..130ec83b8 100644
--- a/src/components/toolbar/EditorToolbar.vue
+++ b/src/components/toolbar/EditorToolbar.vue
@@ -1,13 +1,14 @@
<script setup lang="ts">
import { computed } from 'vue'
+import { resolveEditorProfile } from '@open-pencil/core'
import { useEditorCommands } from '@open-pencil/vue/editor/commands'
import { useViewportKind } from '@open-pencil/vue/editor/viewport-kind'
import { useI18n } from '@open-pencil/vue/i18n'
import { ToolbarRoot, useToolbarState } from '@open-pencil/vue/primitives/Toolbar'
import { useEditorStore } from '@/app/editor/active-store'
-import { readOnlyToolbarLayout, TOOLBAR_ACTIONS, toolbarItems } from '@/app/editor/toolbar/layout'
+import { TOOLBAR_ACTIONS, toolbarItems, toolbarLayoutFor } 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,7 +34,7 @@ const toolShortcuts = toolShortcutLabels()
const items = computed(() => {
const layout = appPreferences.value.toolbar
return toolbarItems(
- store.state.readOnly ? readOnlyToolbarLayout(layout) : layout,
+ toolbarLayoutFor(layout, resolveEditorProfile(store.state).tools),
toolLabels.value,
toolShortcuts
)
@@ -49,7 +50,7 @@ const actionItems = computed(() =>
* a read-only document leaves them out, as it does the buttons.
*/
const hiddenActions = computed(() =>
- store.state.readOnly
+ !resolveEditorProfile(store.state).edits
? []
: TOOLBAR_ACTIONS.filter((action) => !actionItems.value.includes(action))
)
diff --git a/tests/app/cloud/versions/history.test.ts b/tests/app/cloud/versions/history.test.ts
index 3f90d4dfb..5a7d93cca 100644
--- a/tests/app/cloud/versions/history.test.ts
+++ b/tests/app/cloud/versions/history.test.ts
@@ -22,13 +22,13 @@ describe('version history', () => {
const store = createEditorStore()
openVersionHistory(store)
expect(isVersionHistoryOpen(store)).toBe(true)
- expect(store.state.readOnly).toBe(true)
+ expect(store.state.hostRestrictions.readOnly).toBe(true)
expect(shownEditorStore(store)).toBe(store)
expect(versionPreviewKey(store)).toBe('')
closeVersionHistory(store)
expect(isVersionHistoryOpen(store)).toBe(false)
- expect(store.state.readOnly).toBe(false)
+ expect(store.state.hostRestrictions.readOnly).toBe(false)
})
test('leaves a viewer’s document read-only after closing', () => {
@@ -36,7 +36,7 @@ describe('version history', () => {
store.setReadOnly(true)
openVersionHistory(store)
closeVersionHistory(store)
- expect(store.state.readOnly).toBe(true)
+ expect(store.state.hostRestrictions.readOnly).toBe(true)
})
test('reloads only the list of the document whose history changed', () => {
diff --git a/tests/app/editor/toolbar/layout.test.ts b/tests/app/editor/toolbar/layout.test.ts
index 188fc84b1..01cf9b8fc 100644
--- a/tests/app/editor/toolbar/layout.test.ts
+++ b/tests/app/editor/toolbar/layout.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, test } from 'bun:test'
+import { resolveEditorProfile } from '@open-pencil/core'
+
import {
combineToolbarEntry,
DEFAULT_TOOLBAR_LAYOUT,
@@ -8,10 +10,10 @@ import {
moveToolbarEntry,
normalizeToolbarLayout,
placeToolbarEntry,
- readOnlyToolbarLayout,
setToolbarEntryHidden,
toolbarDropOperations,
toolbarItems,
+ toolbarLayoutFor,
toolbarRows,
type ToolbarEntry,
type ToolbarLayout
@@ -240,11 +242,20 @@ describe('dragging', () => {
})
})
-describe('readOnlyToolbarLayout', () => {
- test('keeps Move and Hand, as Figma does while a version is viewed', () => {
+describe('toolbarLayoutFor', () => {
+ const profileTools = (readOnly: boolean) =>
+ resolveEditorProfile({ canvasView: { id: 'edit' }, hostRestrictions: { readOnly } }).tools
+
+ test('keeps the whole layout when the profile offers every tool', () => {
+ const base = layout([['SELECT', 'HAND'], ['FRAME'], ['insert-icon']])
+ expect(toolbarLayoutFor(base, profileTools(false))).toBe(base)
+ })
+
+ test('keeps Move and Hand in a read-only document, 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
+ toolbarItems(toolbarLayoutFor(layout(groups), profileTools(true)), 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']
diff --git a/tests/integration/collab/cloud-relay.test.ts b/tests/integration/collab/cloud-relay.test.ts
index 73f08e304..0d841e12b 100644
--- a/tests/integration/collab/cloud-relay.test.ts
+++ b/tests/integration/collab/cloud-relay.test.ts
@@ -285,9 +285,15 @@ describe('Cloud document rooms, version history', () => {
await until(() => versionListRevision(grace) > before)
// Stopping the room leaves the tab as it was before it joined.
- expect([grace.state.readOnly, cloudRoomPermissions.value.get(grace)]).toEqual([true, 'view'])
+ expect([grace.state.hostRestrictions.readOnly, cloudRoomPermissions.value.get(grace)]).toEqual([
+ true,
+ 'view'
+ ])
room.stop()
- expect([grace.state.readOnly, cloudRoomPermissions.value.has(grace)]).toEqual([false, false])
+ expect([grace.state.hostRestrictions.readOnly, cloudRoomPermissions.value.has(grace)]).toEqual([
+ false,
+ false
+ ])
})
})
diff --git a/tools/checks/lint/src/plugin.ts b/tools/checks/lint/src/plugin.ts
index abd049005..3eb54266c 100644
--- a/tools/checks/lint/src/plugin.ts
+++ b/tools/checks/lint/src/plugin.ts
@@ -4,7 +4,7 @@ import {
noCloudSecretLoggingRule
} from '#lint/rules/cloud.ts'
import {
- noCanvasViewChecks,
+ noEditorProfileInputs,
noConditionalObjectSpreads,
noFlatKiwiModules,
noMixedCaseAcronymIdentifiers
@@ -502,7 +502,7 @@ const plugin = {
'no-flat-kiwi-modules': noFlatKiwiModules,
'no-bun-globals-in-cli': noBunGlobalsInCli,
'no-top-level-prefixed-test-files': noTopLevelPrefixedTestFiles,
- 'no-canvas-view-checks': noCanvasViewChecks,
+ 'no-editor-profile-inputs': noEditorProfileInputs,
'no-conditional-object-spreads': noConditionalObjectSpreads,
'no-hand-rolled-base64': noHandRolledBase64Rule,
'no-raw-sql': noRawSQLRule,
diff --git a/tools/checks/lint/src/rules/policy.ts b/tools/checks/lint/src/rules/policy.ts
index 15cedd7ff..3171b84cd 100644
--- a/tools/checks/lint/src/rules/policy.ts
+++ b/tools/checks/lint/src/rules/policy.ts
@@ -1,4 +1,4 @@
-import { normalizedFilename, staticPropertyName } from '#lint/support/context.ts'
+import { normalizedFilename } from '#lint/support/context.ts'
import { createProgramFilenameRule } from '#lint/support/factories.ts'
import type { RuleDefinition } from '#lint/support/types.ts'
import {
@@ -140,16 +140,30 @@ const noConditionalObjectSpreads = {
}
} satisfies RuleDefinition
-/** The key a member expression reads when it is fixed (`a.key`, `a['key']`, ``a[`key`]``), not `a[key]`. */
-function memberName(node: TSESTree.MemberExpression): string | null {
- const key = node.property
- if (!node.computed || key.type === 'Literal') return staticPropertyName(key)
+/** A key when it is fixed (`key`, `'key'`, `` `key` ``), not one read from a variable. */
+function fixedKey(key: TSESTree.Node, computed: boolean): string | null {
+ if (key.type === 'Identifier') return computed ? null : key.name
+ if (key.type === 'Literal') return typeof key.value === 'string' ? key.value : null
if (key.type === 'TemplateLiteral' && key.expressions.length === 0) {
return key.quasis[0]?.value.cooked ?? null
}
return null
}
+const CORE_PROFILE = ['/packages/core/src/editor/views/', '/packages/core/src/editor/state/']
+
+/**
+ * What the editor profile resolves from, and the code that may read each: Core's views and state
+ * own both, the read-only module applies the restrictions, and the app, as the host, sets them.
+ */
+const PROFILE_INPUTS: Record<string, (file: string) => boolean> = {
+ canvasView: (file) => CORE_PROFILE.some((owner) => file.includes(owner)),
+ hostRestrictions: (file) =>
+ CORE_PROFILE.some((owner) => file.includes(owner)) ||
+ file.includes('/packages/core/src/editor/read-only/') ||
+ (file.includes('/src/app/') && !file.includes('/packages/'))
+}
+
/** The fixed key a template member expression reads (`a.key`, `a['key']`), or null. */
function templateMemberKey(node: ExpressionAstNode): string | null {
if (node.type !== 'MemberExpression' && node.type !== 'OptionalMemberExpression') return null
@@ -159,67 +173,68 @@ function templateMemberKey(node: ExpressionAstNode): string | null {
return null
}
-/** Whether a Vue template expression reads `canvasView` from anything. */
-function templateReadsCanvasView(expression: VueTemplateNode): boolean {
- if (expression.type !== VUE_SIMPLE_EXPRESSION_NODE || !expression.ast) return false
- let found = false
+/** The profile inputs a Vue template expression reads. */
+function templateProfileInputs(expression: VueTemplateNode, inputs: Set<string>): string[] {
+ if (expression.type !== VUE_SIMPLE_EXPRESSION_NODE || !expression.ast) return []
+ const found: string[] = []
walkExpressionAst(expression.ast as ExpressionAstNode, (node) => {
- if (templateMemberKey(node) === 'canvasView') found = true
+ const key = templateMemberKey(node)
+ if (key && inputs.has(key)) found.push(key)
})
return found
}
-const CANVAS_VIEW_MESSAGE =
- "Read the canvas's behaviour from resolveEditorProfile instead of reading which view it shows."
+function profileInputMessage(input: string): string {
+ return `Read how the editor behaves from resolveEditorProfile instead of its ${input}.`
+}
/**
- * A canvas behaves by the profile its view resolves to, so code outside Core's editor views and
- * state reads the profile's values, never the view: checks of the view's id are how preview came to
- * branch at every place it behaves differently.
+ * The editor behaves by the profile its canvas view resolves to, narrowed by the host's
+ * restrictions, so other code reads the profile's values, never those inputs: checks of the view
+ * and of read-only are how each came to branch at every place the editor behaves differently.
*/
-const noCanvasViewChecks: RuleDefinition = {
+const noEditorProfileInputs: RuleDefinition = {
meta: {
type: 'problem',
docs: {
description:
- 'Disallow reading the canvas view outside core editor views and state — read resolveEditorProfile instead'
+ "Disallow reading the editor profile's inputs (canvas view, restrictions) outside their owners — read resolveEditorProfile instead"
},
schema: []
},
create(context) {
const file = normalizedFilename(context)
- const checked = file.includes('/src/') || file.includes('/packages/docs/.vitepress/theme/')
- const owner =
- file.includes('/packages/core/src/editor/views/') ||
- file.includes('/packages/core/src/editor/state/')
- if (!checked || owner) return {}
+ if (!file.includes('/src/') && !file.includes('/packages/docs/.vitepress/theme/')) return {}
+ const inputs = new Set(
+ Object.keys(PROFILE_INPUTS).filter((input) => !PROFILE_INPUTS[input]?.(file))
+ )
+ if (inputs.size === 0) return {}
+ const report = (node: TSESTree.Node, input: string | null) => {
+ if (input && inputs.has(input)) context.report({ node, message: profileInputMessage(input) })
+ }
return {
Program(node) {
if (!file.endsWith('.vue')) return
const template = vueTemplateAst(context.sourceCode.getText(), file)
if (!template) return
- let reads = false
+ const read = new Set<string>()
walkVueTemplateAst(template, (templateNode) => {
- reads ||= templateReadsCanvasView(templateNode)
+ for (const input of templateProfileInputs(templateNode, inputs)) read.add(input)
})
- if (reads) context.report({ node, message: CANVAS_VIEW_MESSAGE })
+ for (const input of read) report(node, input)
},
MemberExpression(node) {
- if (memberName(node) === 'canvasView')
- context.report({ node, message: CANVAS_VIEW_MESSAGE })
+ report(node, fixedKey(node.property, node.computed))
},
Property(node) {
- if (node.parent.type !== 'ObjectPattern' || node.computed) return
- if (staticPropertyName(node.key) === 'canvasView') {
- context.report({ node, message: CANVAS_VIEW_MESSAGE })
- }
+ if (node.parent.type === 'ObjectPattern') report(node, fixedKey(node.key, node.computed))
}
}
}
}
export {
- noCanvasViewChecks,
+ noEditorProfileInputs,
noMixedCaseAcronymIdentifiers,
noFlatKiwiModules,
noConditionalObjectSpreads
diff --git a/tools/checks/lint/tests/canvas-view-checks.test.ts b/tools/checks/lint/tests/editor-profile-inputs.test.ts
similarity index 64%
rename from tools/checks/lint/tests/canvas-view-checks.test.ts
rename to tools/checks/lint/tests/editor-profile-inputs.test.ts
index 094a22999..b1c09aca2 100644
--- a/tools/checks/lint/tests/canvas-view-checks.test.ts
+++ b/tools/checks/lint/tests/editor-profile-inputs.test.ts
@@ -4,12 +4,12 @@ import dedent from 'dedent'
import { lint, ruleDiagnostics } from './helpers/lint.ts'
-const rule = 'no-canvas-view-checks'
+const rule = 'no-editor-profile-inputs'
const rules = { [`open-pencil/${rule}`]: 'error' }
const check = "export const previewing = editor.state.canvasView.id === 'play'"
const path = 'packages/vue/src/canvas/useCanvasInput.ts'
-describe('no-canvas-view-checks', () => {
+describe('no-editor-profile-inputs', () => {
test.each([
'packages/vue/src/canvas/useCanvasInput.ts',
'packages/core/src/canvas/renderer/pipeline.ts',
@@ -32,7 +32,8 @@ describe('no-canvas-view-checks', () => {
'export const previewing = editor.state[`canvasView`].id',
'export const view = editor.state.canvasView',
'export const { id } = editor.state.canvasView',
- 'export const { canvasView } = editor.state'
+ 'export const { canvasView } = editor.state',
+ "export const { ['hostRestrictions']: limits } = editor.state"
])('rejects reading the view: %s', async (source) => {
expect(ruleDiagnostics(await lint(source, rules, path), rule)).toHaveLength(1)
})
@@ -58,6 +59,35 @@ describe('no-canvas-view-checks', () => {
expect(ruleDiagnostics(await lint(source, rules, path), rule)).toHaveLength(0)
})
+ const restriction = 'export const locked = editor.state.hostRestrictions.readOnly'
+
+ test.each([
+ 'packages/vue/src/canvas/useCanvasInput.ts',
+ 'packages/core/src/canvas/renderer/pipeline.ts',
+ 'src/components/CodePanel.ts',
+ 'packages/cli/src/app/session.ts'
+ ])('rejects reading the restrictions in %s', async (path) => {
+ expect(ruleDiagnostics(await lint(restriction, rules, path), rule)).toHaveLength(1)
+ })
+
+ test.each([
+ 'packages/core/src/editor/read-only/index.ts',
+ 'packages/core/src/editor/views/profile.ts',
+ 'src/app/collab/yjs-sync.ts'
+ ])('accepts reading the restrictions in %s, which owns or sets them', async (path) => {
+ expect(ruleDiagnostics(await lint(restriction, rules, path), rule)).toHaveLength(0)
+ })
+
+ test('the host still reads the view through the profile', async () => {
+ const path = 'src/app/collab/yjs-sync.ts'
+ expect(ruleDiagnostics(await lint(check, rules, path), rule)).toHaveLength(1)
+ })
+
+ test('accepts an unrelated restrictions field', async () => {
+ const source = 'export const limits = account.restrictions'
+ expect(ruleDiagnostics(await lint(source, rules, path), rule)).toHaveLength(0)
+ })
+
test('accepts reading the profile anywhere', async () => {
const source = "export const panOnly = resolveEditorProfile(state).pointer === 'pan'"
expect(ruleDiagnostics(await lint(source, rules, path), rule)).toHaveLength(0)