AI-native design editor. Open-source Figma alternative.
feat: give boards FigJam's tools, keys, and grid through the editor profile (#1622)
Danila Poyarkov18d9f8195513
diff --git a/changes/1622/added.md b/changes/1622/added.mdnew file mode 100644index 000000000..1cc902e64--- /dev/null+++ b/changes/1622/added.md@@ -0,0 +1 @@+- Boards: Home and the New file tab (⌘T or + in the tab bar, as in Figma) offer Design and Board side by side; a board has FigJam's tools (sticky note, shape, connector, section, text), its keys (S, R, X), and a 16-unit snap grid, and saves and opens as a FigJam `.jam` file, which the desktop app also opens from Finder.diff --git a/desktop/generated/menu.json b/desktop/generated/menu.jsonindex a9514febf..2d39222bd 100644--- a/desktop/generated/menu.json+++ b/desktop/generated/menu.json@@ -4,9 +4,14 @@"items": [{"id": "new",- "label": "New",+ "label": "New Design","accelerator": "CmdOrCtrl+N"},+ {+ "id": "new-tab",+ "label": "New Tab",+ "accelerator": "CmdOrCtrl+T"+ },{"id": "open","label": "Open…",@@ -16,10 +21,6 @@"id": "open-recent","label": "Open Recent"},- {- "id": "browse-files",- "label": "Browse Files…"- },{"id": "open-tour","label": "Open the Tour"diff --git a/desktop/src/files/fig.rs b/desktop/src/files/fig.rsindex ecb23d940..02af40c8f 100644--- a/desktop/src/files/fig.rs+++ b/desktop/src/files/fig.rs@@ -10,10 +10,11 @@ pub struct ImageEntry {/// The zstd level Figma itself saves with.const DEFAULT_COMPRESSION_LEVEL: i32 = 3;-/// Writes the `.fig` archive on a blocking thread: high zstd levels take seconds on large-/// documents, which would otherwise stall the window.-#[tauri::command]-pub async fn build_fig_file(+/// The archive a save writes: the encoded document, its thumbnail and `meta.json`, the images it+/// holds, and whether it is a FigJam board, which `.jam` marks only in the canvas header.+#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FigFile {schema_deflated: Vec<u8>,kiwi_data: Vec<u8>,thumbnail_png: Vec<u8>,@@ -21,31 +22,30 @@ pub async fn build_fig_file(images: Option<Vec<ImageEntry>>,fig_kiwi_version: Option<u32>,compression_level: Option<i32>,-) -> Result<tauri::ipc::Response, String> {- tauri::async_runtime::spawn_blocking(move || {- write_fig_file(- schema_deflated,- kiwi_data,- thumbnail_png,- meta_json,- images,- fig_kiwi_version,- compression_level,- )- })- .await- .map_err(|e| e.to_string())?+ #[serde(default)]+ board: bool,}-fn write_fig_file(- schema_deflated: Vec<u8>,- kiwi_data: Vec<u8>,- thumbnail_png: Vec<u8>,- meta_json: String,- images: Option<Vec<ImageEntry>>,- fig_kiwi_version: Option<u32>,- compression_level: Option<i32>,-) -> Result<tauri::ipc::Response, String> {+/// Writes the `.fig` or `.jam` archive on a blocking thread: high zstd levels take seconds on+/// large documents, which would otherwise stall the window.+#[tauri::command]+pub async fn build_fig_file(file: FigFile) -> Result<tauri::ipc::Response, String> {+ tauri::async_runtime::spawn_blocking(move || write_fig_file(file))+ .await+ .map_err(|e| e.to_string())?+}++fn write_fig_file(file: FigFile) -> Result<tauri::ipc::Response, String> {+ let FigFile {+ schema_deflated,+ kiwi_data,+ thumbnail_png,+ meta_json,+ images,+ fig_kiwi_version,+ compression_level,+ board,+ } = file;let levels = zstd::compression_level_range();let level = compression_level.unwrap_or(DEFAULT_COMPRESSION_LEVEL)@@ -64,7 +64,8 @@ fn write_fig_file(let version: u32 = fig_kiwi_version.unwrap_or(101);let fig_kiwi_len = 8 + 4 + 4 + schema_deflated.len() + 4 + zstd_data.len();let mut fig_kiwi = Vec::with_capacity(fig_kiwi_len);- fig_kiwi.extend_from_slice(b"fig-kiwi");+ // A FigJam board's `.jam` differs from a design's `.fig` only in this header.+ fig_kiwi.extend_from_slice(if board { b"fig-jam." } else { b"fig-kiwi" });fig_kiwi.extend_from_slice(&version.to_le_bytes());fig_kiwi.extend_from_slice(&(schema_deflated.len() as u32).to_le_bytes());fig_kiwi.extend_from_slice(&schema_deflated);diff --git a/desktop/src/launch/args.rs b/desktop/src/launch/args.rsindex 87ba80ed1..16872e67c 100644--- a/desktop/src/launch/args.rs+++ b/desktop/src/launch/args.rs@@ -8,7 +8,11 @@ pub fn file_association_path(path: PathBuf) -> Option<PathBuf> {return None;}let ext = path.extension()?.to_string_lossy().to_lowercase();- matches!(ext.as_str(), "fig" | "pen" | "drawio" | "dio" | "mmd" | "mermaid").then_some(path)+ matches!(+ ext.as_str(),+ "fig" | "jam" | "pen" | "drawio" | "dio" | "mmd" | "mermaid"+ )+ .then_some(path)}fn path_from_arg(arg: String, cwd: &Path) -> Option<PathBuf> {diff --git a/desktop/tauri.conf.json b/desktop/tauri.conf.jsonindex 92dfe4c9f..ebd73812e 100644--- a/desktop/tauri.conf.json+++ b/desktop/tauri.conf.json@@ -51,6 +51,14 @@"mimeType": "application/x-figma","rank": "Alternate"},+ {+ "ext": ["jam"],+ "name": "FigJam Board",+ "description": "FigJam board",+ "role": "Editor",+ "mimeType": "application/x-figjam",+ "rank": "Alternate"+ },{"ext": ["drawio", "dio"],"name": "draw.io Diagram",diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.mdindex d5f6d2f4b..a17ebf590 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 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`).+- A canvas pane behaves by its profile (`resolveEditorProfile` in `packages/core/src/editor/views/`): the document's kind (design or board) decides its tools, tool keys, and snap grid, its view the pointer, shortcuts, editing chrome, live islands, panels, and where leaving goes, and the host's restrictions narrow both. A new kind, view, or host limit is a new entry there; other code reads profile values, never the kind, view, or restrictions themselves, 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/labels/draw.ts b/packages/core/src/canvas/labels/draw.tsindex 8822e6126..9c7ceee8b 100644--- a/packages/core/src/canvas/labels/draw.ts+++ b/packages/core/src/canvas/labels/draw.ts@@ -38,6 +38,7 @@ export function drawSectionTitles(if (sections.length === 0) returnfor (const { node, nested } of sections) {+ if (node.id === overlays?.renamingLabelId) continuedrawSectionTitle(r, canvas, provider, node, graph, nested, overlays)}}@@ -194,20 +195,23 @@ export function drawComponentLabels(immutablePath.delete()}- const textWidth = r.labelParagraphCache.draw(- r.ck,- canvas,- provider,- node.name,- layout.fontSize,- layout.maxTextWidth,- compColor,- r.fontGeneration,- layout.text.x,- layout.text.y,- layout.fontWeight- )- drawTitleStatus(r, canvas, graph, node, layout, textWidth, node.width * r.zoom, matrix)+ // The field renaming a component starts after its icon and stands in for its name.+ if (node.id !== overlays?.renamingLabelId) {+ const textWidth = r.labelParagraphCache.draw(+ r.ck,+ canvas,+ provider,+ node.name,+ layout.fontSize,+ layout.maxTextWidth,+ compColor,+ r.fontGeneration,+ layout.text.x,+ layout.text.y,+ layout.fontWeight+ )+ drawTitleStatus(r, canvas, graph, node, layout, textWidth, node.width * r.zoom, matrix)+ }canvas.restore()}}@@ -233,6 +237,7 @@ export function drawFrameTitles(overlays?.rotationPreview)for (const { node } of frames) {+ if (node.id === overlays?.renamingLabelId) continueconst transform = frameLabelPlacement(node, graph, overlays?.rotationPreview)const room = shownStatusState(graph, node) ? TITLE_STATUS_ROOM : 0const layout = labelLayout('frame', transform.width * r.zoom - room)diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.tsindex ba06455d6..6b9eb4f5a 100644--- a/packages/core/src/canvas/renderer/pipeline.ts+++ b/packages/core/src/canvas/renderer/pipeline.ts@@ -94,6 +94,7 @@ export function renderFromEditorState(measurementMode: state.measurementMode,enteredContainerId: state.enteredContainerId,editingTextId: state.editingTextId,+ renamingLabelId: state.renamingLabelId,textEditor: textEditor as RenderOverlays['textEditor'],marquee: state.marquee,snapGuides: state.snapGuides,diff --git a/packages/core/src/canvas/renderer/types.ts b/packages/core/src/canvas/renderer/types.tsindex 7b7fe55a1..99eccbbcb 100644--- a/packages/core/src/canvas/renderer/types.ts+++ b/packages/core/src/canvas/renderer/types.ts@@ -53,6 +53,8 @@ export interface RenderOverlays {measurementMode?: MeasurementModeenteredContainerId?: string | nulleditingTextId?: string | null+ /** The layer whose name a field over the canvas renames, whose title the canvas leaves out. */+ renamingLabelId?: string | nulltextEditor?: TextEditor | nullmarquee?: Rect | nullsnapGuides?: SnapGuide[]diff --git a/packages/core/src/canvas/text/layout/index.ts b/packages/core/src/canvas/text/layout/index.tsindex 6dbc0061d..c8a825744 100644--- a/packages/core/src/canvas/text/layout/index.ts+++ b/packages/core/src/canvas/text/layout/index.ts@@ -387,6 +387,8 @@ export class TextLayout {bottom: top + first.height}}+ const after = this.caretAfterLineBreak(block, local)+ if (after) return afterlet lo = locallet hi = local + 1let useRight = false@@ -417,6 +419,21 @@ export class TextLayout {}}+ /**+ * The caret after a line break that ends the paragraph: at the start of the empty line Skia+ * lays out below it, where typing goes, not after the break on the line above.+ */+ private caretAfterLineBreak(block: TextLayoutBlock, local: number): TextCaretBox | null {+ if (local < block.length) return null+ const lines = block.paragraph.getLineMetrics()+ const last = lines.at(-1)+ const previous = lines.at(-2)+ if (!last || !previous?.isHardBreak || last.endIndex > previous.endIncludingNewline) return null+ const lineTop = last.baseline - last.ascent+ const y = block.y + this.offsetAt(block, lineTop + last.height / 2)+ return { x: block.x + last.left, top: y + lineTop, bottom: y + lineTop + last.height }+ }+/*** Shaped lines of the text in whole-text coordinates, one per line; run offsets are UTF-8* byte offsets into the whole text, as CanvasKit gives them. An empty line, which shapingdiff --git a/packages/core/src/canvas/text/layout/lines.ts b/packages/core/src/canvas/text/layout/lines.tsindex 272a5f27a..cffc68965 100644--- a/packages/core/src/canvas/text/layout/lines.ts+++ b/packages/core/src/canvas/text/layout/lines.ts@@ -73,11 +73,17 @@ function metric(value: number): number {* tallest font, centred in that height, puts it. Fonts' heights are the shaped runs' own, so a* fallback font counts with its metrics. Returns `null` for a line with nothing to measure.*/+/** The line a point `y` of the paragraph falls on, or `fallback` past them all. */+function lineAt(lines: readonly LineMetrics[], y: number, fallback: LineMetrics): LineMetrics {+ return lines.find((line) => y < line.baseline + line.descent) ?? fallback+}+export function figmaLineBox(ck: CanvasKit,paragraph: Paragraph,line: LineMetrics,- runs: readonly LineHeightRun[]+ runs: readonly LineHeightRun[],+ lines: readonly LineMetrics[] = paragraph.getLineMetrics()): LineBox | null {// An empty line is as tall as the newline that makes it.const start = line.startIndex@@ -102,7 +108,9 @@ export function figmaLineBox(height = Math.max(height, Math.round(run.lineHeight ?? runNatural))if (runNatural > natural) {natural = runNatural- ascent = metric(line.baseline - rect[1])+ // The newline that makes an empty line stands on the line above, so its box is+ // measured from the baseline of the line it stands on.+ ascent = metric(lineAt(lines, (rect[1] + rect[3]) / 2, line).baseline - rect[1])}}}@@ -128,7 +136,7 @@ function lineBoxes(if (!heights) return nullconst blockBoxes: LineBox[] = []for (const line of metrics[index]) {- const box = figmaLineBox(ck, block.paragraph, line, heights)+ const box = figmaLineBox(ck, block.paragraph, line, heights, metrics[index])if (!box) return nullblockBoxes.push(box)}diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.tsindex 9d6256be2..3decbd9c2 100644--- a/packages/core/src/constants.ts+++ b/packages/core/src/constants.ts@@ -34,6 +34,8 @@ export const MEASUREMENT_PILL_RADIUS = 3export const MEASUREMENT_TEXT_BASELINE = 4export const CANVAS_BG_COLOR = { r: 0.96, g: 0.96, b: 0.96, a: 1 } satisfies Colorexport const SNAP_THRESHOLD_SCREEN_PX = 5+/** The grid a board's layers land on, as FigJam's dots every 16 units. */+export const BOARD_GRID = 16export const RULER_SIZE = 20export const RULER_BG_COLOR = { r: 0.14, g: 0.14, b: 0.14, a: 1 } satisfies Color@@ -244,6 +246,14 @@ export const PAGE_DEFAULT_BACKGROUNDS: Record<InterfaceTheme, Color> = {dark: { r: 0x1e / 255, g: 0x1e / 255, b: 0x1e / 255, a: 1 }}+/** A FigJam board's page, #F5F5F5 whatever the interface theme, as Figma saves it. */+export const BOARD_PAGE_BACKGROUND = {+ r: 245 / 255,+ g: 245 / 255,+ b: 245 / 255,+ a: 1+} satisfies Color+/** A new section's fill, which Figma picks from the interface theme it was made in. */export const SECTION_DEFAULT_FILLS: Record<InterfaceTheme, Fill> = {light: { type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true },diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.tsindex f291a5753..4fc77de9a 100644--- a/packages/core/src/editor/create.ts+++ b/packages/core/src/editor/create.ts@@ -75,7 +75,7 @@ import { createUndoActions } from './undo'import { createVariableActions } from './variables'import { createVectorizeActions } from './vectorize'import { createViewportActions } from './viewport'-import { createCanvasViewActions, resolveEditorProfile } from './views'+import { createCanvasViewActions, offeredTool, resolveEditorProfile } from './views'export { createDefaultEditorState } from './state'@@ -108,6 +108,8 @@ export function createEditor(options?: EditorOptions) {void prefetchFigmaSchema()const state: EditorState = options?.state ?? createDefaultEditorState(_graph.getPages()[0].id)+ state.documentKind = _graph.documentKind+ state.activeTool = offeredTool(state, state.activeTool)function emitEditorEvent<K extends EditorEventName>(event: K,@@ -210,8 +212,7 @@ export function createEditor(options?: EditorOptions) {}function setActiveTool(tool: EditorState['activeTool']) {- const { tools } = resolveEditorProfile(state)- if (tools && !tools.has(tool)) return+ if (offeredTool(state, tool) !== tool) returnconst previous = state.activeToolstate.activeTool = toolif (tool !== 'SELECT') state.measurementMode = 'off'@@ -384,6 +385,8 @@ export function createEditor(options?: EditorOptions) {nodes.cancelNodePreviews()undo.discardBatches()_graph = newGraph+ state.documentKind = _graph.documentKind+ setActiveTool(offeredTool(state, state.activeTool))pendingTextLayout.clear()subscribeToGraph()const previousPageId = state.currentPageId@@ -533,6 +536,7 @@ export function createEditor(options?: EditorOptions) {setDocumentColorSpace: colorSpace.setDocumentColorSpace,updateEnabledLibraries: documentSettings.updateEnabledLibraries,refreshDocumentSettings: documentSettings.refreshDocumentSettings,+ setDocumentKind: documentSettings.setDocumentKind,figCompression: figCompression.figCompression,setFigCompression: figCompression.setFigCompression,diff --git a/packages/core/src/editor/document-settings.ts b/packages/core/src/editor/document-settings.tsindex d6dd8eb76..86a792908 100644--- a/packages/core/src/editor/document-settings.ts+++ b/packages/core/src/editor/document-settings.ts@@ -1,9 +1,31 @@import { isEqual } from 'es-toolkit'-import type { EnabledLibraryBinding } from '@open-pencil/scene-graph'+import { SceneGraph, type DocumentKind, type EnabledLibraryBinding } from '@open-pencil/scene-graph'++import { BOARD_PAGE_BACKGROUND } from '#core/constants'+import { offeredTool } from '#core/editor/views'+import { setPageBackgrounds } from '#core/figma-api/page-backgrounds'import type { EditorContext } from './types'+/** An empty document of this kind: a board starts on FigJam's light page. */+export function createDocumentGraph(kind: DocumentKind): SceneGraph {+ const graph = new SceneGraph()+ graph.documentKind = kind+ if (kind === 'board') {+ setPageBackgrounds(graph, graph.getPages()[0], [+ {+ type: 'SOLID',+ color: BOARD_PAGE_BACKGROUND,+ opacity: 1,+ visible: true,+ blendMode: 'NORMAL'+ }+ ])+ }+ return graph+}+export function createDocumentSettingsActions(ctx: EditorContext) {/*** Changes which library revisions the document uses, and announces it when anything changed,@@ -31,5 +53,18 @@ export function createDocumentSettingsActions(ctx: EditorContext) {ctx.requestRender()}- return { updateEnabledLibraries, refreshDocumentSettings }+ /**+ * Makes the document a design or a board, which decides the tools, keys, and grid the editor+ * offers; a tool the new kind does not offer gives way to Move.+ */+ function setDocumentKind(kind: DocumentKind) {+ if (ctx.graph.documentKind === kind) return+ ctx.graph.documentKind = kind+ ctx.state.documentKind = kind+ ctx.setActiveTool(offeredTool(ctx.state, ctx.state.activeTool))+ ctx.emitEditorEvent('document:kind-changed', kind)+ ctx.requestRepaint()+ }++ return { updateEnabledLibraries, refreshDocumentSettings, setDocumentKind }}diff --git a/packages/core/src/editor/history/atomic-tool.ts b/packages/core/src/editor/history/atomic-tool.tsindex 648813dab..f1ac193c1 100644--- a/packages/core/src/editor/history/atomic-tool.ts+++ b/packages/core/src/editor/history/atomic-tool.ts@@ -3,8 +3,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 { resolveEditorProfile, type EditorProfileInputs } from '#core/editor/views'import type { FigmaAPI } from '#core/figma-api'import { isAtomicTool, type ToolDef } from '#core/tools/schema'@@ -17,7 +16,7 @@ type MutationEditor = Pick<Editor,'graph' | 'runLayoutForNode' | 'requestRender' | 'pushUndoStep'> & {- state: Pick<EditorState, 'canvasView' | 'hostRestrictions'>+ state: EditorProfileInputs}function changes<T extends object>(diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.tsindex c8303345a..664094b7b 100644--- a/packages/core/src/editor/index.ts+++ b/packages/core/src/editor/index.ts@@ -7,6 +7,7 @@ export type { NodeEditCapability } from './capabilities'export { ReadOnlyDocumentError } from './read-only'export { DEFAULT_SNAPPING_PREFERENCES } from './preferences'export type { SnappingPreferences } from './preferences'+export { createDocumentGraph } from './document-settings'export { createDefaultEditorSharedState } from './state/shared'export { editedGradient, editedGradientLayout } from './gradient-edit'export type { SelectionSpacing } from './alignment'@@ -35,7 +36,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, EditorRestrictions } from './views'+export type { CanvasView, EditorProfile, EditorProfileInputs, EditorRestrictions } from './views'export type { ShaderRasterizer } from './shaders/types'export type { ShaderPaintList } from './shaders/actions'export type { Editor } from './create'@@ -54,7 +55,7 @@ export { resizedPathTextGlyphs } from './text/path-edit'export { opacityFromBuffer } from './nodes'export { layerTypeOptions, type LayerType } from './structure/layer-type'export type { NodePreview } from './node-preview'-export { EDITOR_TOOLS, TOOL_SHORTCUTS } from './tool-registry'+export { BOARD_TOOL_SHORTCUTS, BOARD_TOOLS, EDITOR_TOOLS, TOOL_SHORTCUTS } from './tool-registry'export type { RenameSelectionOptions, RenameSelectionPreview } from './structure/rename'export type { EditorToolDef } from './tool-registry'export type {diff --git a/packages/core/src/editor/read-only/actions.ts b/packages/core/src/editor/read-only/actions.tsindex 0773816da..3a2750e1b 100644--- a/packages/core/src/editor/read-only/actions.ts+++ b/packages/core/src/editor/read-only/actions.ts@@ -83,6 +83,7 @@ export const READ_ONLY_ACTIONS: ReadonlySet<string> = new Set(['setHoveredGuide','setHoveredIssueMarker','setLayoutInsertIndicator',+ 'setRenamingLabel','setRotationPreview','setSelectedGuide','setShapeHandleHover',diff --git a/packages/core/src/editor/read-only/index.ts b/packages/core/src/editor/read-only/index.tsindex ee260145f..002ac4c8e 100644--- a/packages/core/src/editor/read-only/index.ts+++ b/packages/core/src/editor/read-only/index.ts@@ -1,7 +1,7 @@import type { UndoManager } from '@open-pencil/scene-graph/undo'import type { EditorContext } from '#core/editor/types'-import { resolveEditorProfile } from '#core/editor/views'+import { offeredTool } from '#core/editor/views'import { READ_ONLY_ACTIONS } from './actions'@@ -57,8 +57,7 @@ export function createReadOnlyActions(ctx: EditorContext, endEdits: () => void)if (ctx.state.hostRestrictions.readOnly === readOnly) returnif (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.setActiveTool(offeredTool(ctx.state, ctx.state.activeTool))ctx.emitEditorEvent('document:read-only-changed', readOnly)ctx.requestRepaint()}diff --git a/packages/core/src/editor/selection/overlays.ts b/packages/core/src/editor/selection/overlays.tsindex 015fc87ab..be36701b2 100644--- a/packages/core/src/editor/selection/overlays.ts+++ b/packages/core/src/editor/selection/overlays.ts@@ -73,6 +73,13 @@ export function createSelectionOverlayActions(ctx: EditorContext) {ctx.requestRepaint()}+ /** Hands a layer's name on the canvas to the field renaming it, or back to the canvas. */+ function setRenamingLabel(id: string | null) {+ if (ctx.state.renamingLabelId === id) return+ ctx.state.renamingLabelId = id+ ctx.requestRepaint()+ }+function setDropTarget(id: string | null) {if (ctx.state.dropTargetId === id) returnctx.state.dropTargetId = id@@ -125,6 +132,7 @@ export function createSelectionOverlayActions(ctx: EditorContext) {setCodeFocusNode,setMeasurementMode,setDropTarget,+ setRenamingLabel,setLayoutInsertIndicator,setAutoLayoutHover,setShapeHandleHoverdiff --git a/packages/core/src/editor/state/shared.ts b/packages/core/src/editor/state/shared.tsindex 0cd31cd54..3be4e93f5 100644--- a/packages/core/src/editor/state/shared.ts+++ b/packages/core/src/editor/state/shared.ts@@ -6,6 +6,7 @@ export function createDefaultEditorSharedState(): EditorSharedState {activeTool: 'SELECT',shapeWithTextKind: 'SQUARE',hostRestrictions: { readOnly: false },+ documentKind: 'design',snappingPreferences: { ...DEFAULT_SNAPPING_PREFERENCES },showPixelGrid: true,gradientEdit: null,diff --git a/packages/core/src/editor/state/view.ts b/packages/core/src/editor/state/view.tsindex 5b81164e4..face837ca 100644--- a/packages/core/src/editor/state/view.ts+++ b/packages/core/src/editor/state/view.ts@@ -16,6 +16,7 @@ export function createDefaultEditorViewState(pageId: string): EditorViewState {transforming: false,measurementMode: 'off',editingTextId: null,+ renamingLabelId: null,penState: null,penCursorX: null,penCursorY: null,diff --git a/packages/core/src/editor/tool-registry.ts b/packages/core/src/editor/tool-registry.tsindex c9aa9a8fa..5e9299f2f 100644--- a/packages/core/src/editor/tool-registry.ts+++ b/packages/core/src/editor/tool-registry.ts@@ -42,3 +42,30 @@ export const TOOL_SHORTCUTS: Partial<Record<string, Tool>> = {KeyH: 'HAND',KeyC: 'COMMENT'}++/**+ * The tools a board offers, as FigJam's toolbar does: moving and panning, sticky notes, shapes,+ * connectors, sections, text, and comments, without Figma Design's drawing tools.+ */+export const BOARD_TOOLS: ReadonlySet<Tool> = new Set<Tool>([+ 'SELECT',+ 'HAND',+ 'STICKY',+ 'SHAPE_WITH_TEXT',+ 'CONNECTOR',+ 'SECTION',+ 'TEXT',+ 'COMMENT'+])++/** A board's tool keys, as in FigJam: S places a sticky note, R a shape, and X a connector. */+export const BOARD_TOOL_SHORTCUTS: Partial<Record<string, Tool>> = {+ KeyV: 'SELECT',+ KeyH: 'HAND',+ KeyS: 'STICKY',+ 'Shift+KeyS': 'SECTION',+ KeyR: 'SHAPE_WITH_TEXT',+ KeyX: 'CONNECTOR',+ KeyT: 'TEXT',+ KeyC: 'COMMENT'+}diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.tsindex c76792514..205b52141 100644--- a/packages/core/src/editor/types.ts+++ b/packages/core/src/editor/types.ts@@ -2,6 +2,7 @@ import type { CanvasKit } from 'canvaskit-wasm'import type {DocumentColorSpace,+ DocumentKind,SceneGraph,SceneGraphEvents,SceneNode,@@ -82,6 +83,8 @@ export interface EditorSharedState {* What the host takes away from every canvas, such as editing for a viewer or an earlier version;* read through `resolveEditorProfile`, set with `setReadOnly`.*/+ /** What the open document is for, as its graph records it; set with `setDocumentKind`. */+ documentKind: DocumentKindhostRestrictions: EditorRestrictionssnappingPreferences: SnappingPreferences/** Draw the pixel grid once zoomed in far enough, as Figma's View › Pixel grid; shown unless false. */@@ -149,6 +152,8 @@ export interface EditorViewState {transforming: booleanmeasurementMode: MeasurementModeeditingTextId: string | null+ /** The layer whose name a field over the canvas renames; the canvas leaves its title to the field. */+ renamingLabelId: string | nullpenState: {vertices: VectorVertex[]segments: VectorSegment[]@@ -218,6 +223,7 @@ export interface EditorEvents extends SceneGraphEvents {'document:color-space-changed': (colorSpace: DocumentColorSpace) => void'document:libraries-changed': () => void'document:read-only-changed': (readOnly: boolean) => void+ 'document:kind-changed': (kind: DocumentKind) => void'history:changed': () => void'selection:changed': (selectedIds: string[], previousIds: string[]) => void'rotation:preview-changed': (preview: RotationPreview | null) => voiddiff --git a/packages/core/src/editor/views/index.ts b/packages/core/src/editor/views/index.tsindex c232c5f13..89a65b4b6 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, EditorRestrictions } from './types'+export { EDIT_VIEW, offeredTool, resolveEditorProfile } from './profile'+export type { CanvasView, EditorProfile, EditorProfileInputs, EditorRestrictions } from './types'diff --git a/packages/core/src/editor/views/profile.ts b/packages/core/src/editor/views/profile.tsindex 03b01b4ed..d6c339442 100644--- a/packages/core/src/editor/views/profile.ts+++ b/packages/core/src/editor/views/profile.ts@@ -1,42 +1,53 @@-import type { EditorState, Tool } from '#core/editor/types'+import type { DocumentKind } from '@open-pencil/scene-graph'-import type { CanvasView, EditorProfile, EditorRestrictions } from './types'+import { BOARD_GRID } from '#core/constants'+import { BOARD_TOOL_SHORTCUTS, BOARD_TOOLS, TOOL_SHORTCUTS } from '#core/editor/tool-registry'+import type { Tool } from '#core/editor/types'++import type { CanvasView, EditorProfile, EditorProfileInputs, 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 = {+/** What the document's kind decides: the tools and keys it offers and the grid it snaps to. */+type DocumentBehaviour = Pick<EditorProfile, 'edits' | 'tools' | 'toolKeys' | 'snapGrid'>++/** What the canvas's view decides: how the pointer, keys, chrome, and panels behave. */+type ViewBehaviour = Omit<EditorProfile, keyof DocumentBehaviour>++const DOCUMENT_BEHAVIOURS: Readonly<Record<DocumentKind, DocumentBehaviour>> = {+ design: { edits: true, tools: null, toolKeys: TOOL_SHORTCUTS, snapGrid: 1 },+ board: { edits: true, tools: BOARD_TOOLS, toolKeys: BOARD_TOOL_SHORTCUTS, snapGrid: BOARD_GRID }+}++const EDIT_BEHAVIOUR: ViewBehaviour = {pointer: 'tools',shortcuts: 'all',editChrome: true,live: null,panels: true,- leaveTo: null,- edits: true,- tools: null+ leaveTo: null}/** A preview runs the design: the canvas only pans, and its controls take the pointer. */-function playProfile(revision: number): EditorProfile {+function playBehaviour(revision: number): ViewBehaviour {return {pointer: 'pan',shortcuts: 'view',editChrome: false,live: { revision },panels: false,- leaveTo: EDIT_VIEW,- edits: true,- tools: null+ leaveTo: EDIT_VIEW}}-function viewProfile(view: CanvasView): EditorProfile {- return view.id === 'play' ? playProfile(view.revision) : EDIT_PROFILE+function viewBehaviour(view: CanvasView): ViewBehaviour {+ return view.id === 'play' ? playBehaviour(view.revision) : EDIT_BEHAVIOUR}-/** Narrows a view's profile by the host's restrictions; a restriction only ever takes away. */+/** Narrows a profile by the host's restrictions; a restriction only ever takes away. */function restrict(profile: EditorProfile, restrictions: EditorRestrictions): EditorProfile {if (!restrictions.readOnly) return profileconst tools = profile.tools@@ -46,11 +57,19 @@ function restrict(profile: EditorProfile, restrictions: EditorRestrictions): Edi}/**- * 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.+ * The profile a canvas behaves by: what its document is for, then the view it shows, narrowed by+ * the host's restrictions. Pass the pane's own state, since each pane shows its own view.+ */+export function resolveEditorProfile(state: EditorProfileInputs): EditorProfile {+ const profile = { ...DOCUMENT_BEHAVIOURS[state.documentKind], ...viewBehaviour(state.canvasView) }+ return restrict(profile, state.hostRestrictions)+}++/**+ * The tool, if the profile offers it, or Move: a tool the profile stops offering, as when a+ * document opens as a board, turns into one, or goes read-only, gives way to Move.*/-export function resolveEditorProfile(- state: Pick<EditorState, 'canvasView' | 'hostRestrictions'>-): EditorProfile {- return restrict(viewProfile(state.canvasView), state.hostRestrictions)+export function offeredTool(state: EditorProfileInputs, tool: Tool): Tool {+ const { tools } = resolveEditorProfile(state)+ return !tools || tools.has(tool) ? tool : 'SELECT'}diff --git a/packages/core/src/editor/views/types.ts b/packages/core/src/editor/views/types.tsindex 72bb483dc..f982b269b 100644--- a/packages/core/src/editor/views/types.ts+++ b/packages/core/src/editor/views/types.ts@@ -1,4 +1,4 @@-import type { Tool } from '#core/editor/types'+import type { EditorState, Tool } from '#core/editor/types'/*** What the host takes away from every view, whatever the canvas shows: a read-only document, as@@ -15,7 +15,8 @@ export interface EditorRestrictions {export type CanvasView = { id: 'edit' } | { id: 'play'; revision: number }/**- * How the editor behaves for a canvas, resolved from its view. Front ends read these values+ * How the editor behaves for a canvas, resolved from what the document is for and the view it+ * shows. Front ends read these values* rather than asking which view is showing, so a new view is a new profile, not a new branch at* every place that behaves differently.*/@@ -42,4 +43,17 @@ export interface EditorProfile {edits: boolean/** The tools on offer, or null for every tool. */tools: ReadonlySet<Tool> | null+ /** Which tool each key picks, by key code (`KeyR`, `Shift+KeyS`). */+ toolKeys: Readonly<Partial<Record<string, Tool>>>+ /**+ * The grid moves, resizes, and placements land on while Snap to pixel grid is on, in canvas+ * units: whole pixels in a design, FigJam's 16 on a board.+ */+ snapGrid: number}++/** The state a profile resolves from: the document's kind, the pane's view, and the host's limits. */+export type EditorProfileInputs = Pick<+ EditorState,+ 'documentKind' | 'canvasView' | 'hostRestrictions'+>diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.tsindex 06f0cd45e..9078e1d6e 100644--- a/packages/core/src/io/formats.ts+++ b/packages/core/src/io/formats.ts@@ -11,7 +11,7 @@ import {type PenIconRequest,type PenIconSource} from '@open-pencil/pen'-import type { SceneGraph } from '@open-pencil/scene-graph'+import type { DocumentKind, SceneGraph } from '@open-pencil/scene-graph'import { defaultIcons, drawIcon, type IconData, type IconProvider } from '#core/icons'import { layoutAuthoredNodes } from '#core/layout'@@ -166,12 +166,18 @@ function rasterFormat<F extends RasterExportFormat>(format: F): IOFormatAdapter<}}+/** The file a document saves as: Figma's `.fig` for a design, FigJam's `.jam` for a board. */+export const DOCUMENT_EXTENSIONS: Readonly<Record<DocumentKind, 'fig' | 'jam'>> = {+ design: 'fig',+ board: 'jam'+}+export const figFormat: IOFormatAdapter<'fig'> = {id: 'fig',label: 'OpenPencil Document',role: 'native-document',category: 'document',- extensions: ['fig'],+ extensions: ['fig', 'jam'],mimeTypes: ['application/octet-stream'],support: {readDocument: true,@@ -183,7 +189,8 @@ export const figFormat: IOFormatAdapter<'fig'> = {},exportOptions: FIXED_SIZE_EXPORT,matchesFile(fileName) {- return lowerExt(fileName) === 'fig'+ const ext = lowerExt(fileName)+ return ext === 'fig' || ext === 'jam'},async readDocument(input) {const data = input.data.slice().buffer@@ -223,7 +230,8 @@ async function writeFig(renderHeadlessThumbnail: options?.renderThumbnail ?? false,documentName: options?.documentName ?? (fileName && filename(fileName))})- return { format: 'fig', mimeType: 'application/octet-stream', extension: 'fig', data }+ const extension = DOCUMENT_EXTENSIONS[graph.documentKind]+ return { format: 'fig', mimeType: 'application/octet-stream', extension, data }}/** The size icons are fetched at; each is scaled to the box it is drawn in. */diff --git a/packages/core/src/io/formats/fig/export/index.ts b/packages/core/src/io/formats/fig/export/index.tsindex 074c20b13..a1c247313 100644--- a/packages/core/src/io/formats/fig/export/index.ts+++ b/packages/core/src/io/formats/fig/export/index.ts@@ -7,7 +7,7 @@ import {} from '@open-pencil/fig/node-change'import { initCodec } from '@open-pencil/kiwi/fig/codec'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'-import { loadFigDataCompressor } from '@open-pencil/kiwi/fig/container'+import { loadFigDataCompressor, type FigFileKind } from '@open-pencil/kiwi/fig/container'import type { SceneGraph } from '@open-pencil/scene-graph'import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'import type { GUID } from '@open-pencil/scene-graph/primitives'@@ -200,13 +200,16 @@ async function writeFigFile(const { invoke } = await import('@tauri-apps/api/core')return new Uint8Array(await invoke<ArrayBuffer>('build_fig_file', {- schemaDeflated: Array.from(schemaDeflated),- kiwiData: Array.from(kiwiData),- thumbnailPng: Array.from(extras.thumbnailPNG),- metaJson: extras.metaJSON,- images: extras.images.map((e) => ({ name: e.name, data: Array.from(e.data) })),- figKiwiVersion: version,- compressionLevel+ file: {+ schemaDeflated: Array.from(schemaDeflated),+ kiwiData: Array.from(kiwiData),+ thumbnailPng: Array.from(extras.thumbnailPNG),+ metaJson: extras.metaJSON,+ images: extras.images.map((e) => ({ name: e.name, data: Array.from(e.data) })),+ figKiwiVersion: version,+ compressionLevel,+ board: graph.documentKind === 'board'+ }}))}@@ -218,7 +221,8 @@ async function writeFigFile(extras.metaJSON,extras.images,version,- compressionLevel+ compressionLevel,+ graph.documentKind)}@@ -235,7 +239,8 @@ function compressViaWorker(metaJSON: string,imageEntries: Array<{ name: string; data: Uint8Array }>,figKiwiVersion?: number,- compressionLevel?: number+ compressionLevel?: number,+ kind?: FigFileKind): Promise<Uint8Array> {return new Promise((resolve, reject) => {const worker = new Worker(new URL('./worker.js', import.meta.url), {@@ -263,7 +268,8 @@ function compressViaWorker(metaJSON,images: imageEntries,figKiwiVersion,- compressionLevel+ compressionLevel,+ kind})})}@@ -276,7 +282,8 @@ export async function compressFigData(metaJSON: string,imageEntries: Array<{ name: string; data: Uint8Array }>,figKiwiVersion?: number,- compressionLevel?: number+ compressionLevel?: number,+ kind?: FigFileKind): Promise<Uint8Array> {if (canUseWorker()) {return compressViaWorker(@@ -286,7 +293,8 @@ export async function compressFigData(metaJSON,imageEntries,figKiwiVersion,- compressionLevel+ compressionLevel,+ kind)}return compressFigDataSync(@@ -296,6 +304,7 @@ export async function compressFigData(metaJSON,imageEntries,figKiwiVersion,- await loadFigDataCompressor(compressionLevel)+ await loadFigDataCompressor(compressionLevel),+ kind)}diff --git a/packages/core/src/io/formats/fig/export/patch/index.ts b/packages/core/src/io/formats/fig/export/patch/index.tsindex 637834de4..c6cff16e4 100644--- a/packages/core/src/io/formats/fig/export/patch/index.ts+++ b/packages/core/src/io/formats/fig/export/patch/index.ts@@ -436,6 +436,7 @@ export async function writePatchedFigFile(thumbnailPNG: extras.thumbnailPNG,metaJSON: extras.metaJSON,images: extras.images.filter((image) => !archivedImages.has(image.name)),- compressionLevel: figCompressionLevel(source)+ compressionLevel: figCompressionLevel(source),+ kind: source.documentKind})}diff --git a/packages/core/src/io/formats/fig/export/worker.ts b/packages/core/src/io/formats/fig/export/worker.tsindex 0cde6f221..b69b5bd9a 100644--- a/packages/core/src/io/formats/fig/export/worker.ts+++ b/packages/core/src/io/formats/fig/export/worker.ts@@ -1,5 +1,5 @@import { compressFigDataSync } from '@open-pencil/fig'-import { loadFigDataCompressor } from '@open-pencil/kiwi/fig/container'+import { loadFigDataCompressor, type FigFileKind } from '@open-pencil/kiwi/fig/container'interface CompressMessage {schemaDeflated: Uint8Array@@ -9,13 +9,14 @@ interface CompressMessage {images: Array<{ name: string; data: Uint8Array }>figKiwiVersion?: numbercompressionLevel?: number+ kind?: FigFileKind}/** The archive, or why it could not be written: a rejected handler would never reach `onerror`. */export type CompressResult = Uint8Array | { error: string }self.onmessage = async (e: MessageEvent<CompressMessage>) => {- const { schemaDeflated, kiwiData, thumbnailPNG, metaJSON, images, figKiwiVersion } = e.data+ const { schemaDeflated, kiwiData, thumbnailPNG, metaJSON, images, figKiwiVersion, kind } = e.datatry {const result = compressFigDataSync(schemaDeflated,@@ -24,7 +25,8 @@ self.onmessage = async (e: MessageEvent<CompressMessage>) => {metaJSON,images,figKiwiVersion,- await loadFigDataCompressor(e.data.compressionLevel)+ await loadFigDataCompressor(e.data.compressionLevel),+ kind)self.postMessage(result, { transfer: [result.buffer] })} catch (error) {diff --git a/packages/core/src/io/index.ts b/packages/core/src/io/index.tsindex 2c61848de..7e50a7183 100644--- a/packages/core/src/io/index.ts+++ b/packages/core/src/io/index.ts@@ -3,6 +3,7 @@ export { extractExportGraph, findPageId } from './subgraph'export {BUILTIN_IO_FORMATS,type BuiltinIOFormatId,+ DOCUMENT_EXTENSIONS,figFormat,penFormat,pngFormat,diff --git a/packages/core/src/io/subgraph.ts b/packages/core/src/io/subgraph.tsindex 33796afc9..d97a43a2a 100644--- a/packages/core/src/io/subgraph.ts+++ b/packages/core/src/io/subgraph.ts@@ -58,6 +58,7 @@ function cloneIntoGraph(graph.figKiwiVersion = source.figKiwiVersiongraph.figSchemaDeflated = source.figSchemaDeflatedgraph.documentColorSpace = source.documentColorSpace+ graph.documentKind = source.documentKindincludeReferencedStyles(source, ids)diff --git a/packages/core/src/kiwi/fig/parse/transfer.ts b/packages/core/src/kiwi/fig/parse/transfer.tsindex a9cdce5b8..f72edb493 100644--- a/packages/core/src/kiwi/fig/parse/transfer.ts+++ b/packages/core/src/kiwi/fig/parse/transfer.ts@@ -1,5 +1,5 @@import { SceneGraph } from '@open-pencil/scene-graph'-import type { EnabledLibraryBinding, SceneNode } from '@open-pencil/scene-graph'+import type { DocumentKind, EnabledLibraryBinding, SceneNode } from '@open-pencil/scene-graph'import type { PortableSceneGraphData } from '#core/kiwi/fig/parse/portable-data'@@ -7,6 +7,7 @@ export interface SerializedSceneGraph extends PortableSceneGraphData {instanceIndex: Array<[string, string[]]>figKiwiVersion: number | nullfigSchemaDeflated: Uint8Array | null+ documentKind: DocumentKindenabledLibraries?: Array<[string, EnabledLibraryBinding]>}@@ -22,6 +23,7 @@ export function serializeSceneGraph(graph: SceneGraph): SerializedSceneGraph {figKiwiVersion: graph.figKiwiVersion,figSchemaDeflated: graph.figSchemaDeflated,documentColorSpace: graph.documentColorSpace,+ documentKind: graph.documentKind,enabledLibraries: [...graph.enabledLibraries]}}@@ -72,6 +74,7 @@ export function cloneSceneGraphForFigExport(graph: SceneGraph): SceneGraph {cloned.figKiwiVersion = graph.figKiwiVersioncloned.figSchemaDeflated = graph.figSchemaDeflatedcloned.documentColorSpace = graph.documentColorSpace+ cloned.documentKind = graph.documentKindcloned.enabledLibraries = new Map(graph.enabledLibraries)return cloned@@ -103,6 +106,7 @@ export function deserializeSceneGraph(data: SerializedSceneGraph): SceneGraph {graph.figKiwiVersion = data.figKiwiVersiongraph.figSchemaDeflated = data.figSchemaDeflatedgraph.documentColorSpace = data.documentColorSpace+ graph.documentKind = data.documentKindgraph.enabledLibraries = data.enabledLibraries ? new Map(data.enabledLibraries) : new Map()return graphdiff --git a/packages/core/src/kiwi/fig/session/archive/changes.ts b/packages/core/src/kiwi/fig/session/archive/changes.tsindex 2ad6d5a2d..40d844de7 100644--- a/packages/core/src/kiwi/fig/session/archive/changes.ts+++ b/packages/core/src/kiwi/fig/session/archive/changes.ts@@ -2,6 +2,7 @@ import { isEqual } from 'es-toolkit/predicate'import type {DocumentColorSpace,+ DocumentKind,EnabledLibraryBinding,SceneGraph,SceneNode,@@ -36,6 +37,7 @@ interface ArchiveChanges {/** The document's own settings, which its record holds rather than any layer. */interface SettingsSnapshot {colorSpace: DocumentColorSpace+ kind: DocumentKindlibraries: Array<[string, EnabledLibraryBinding]>}@@ -50,6 +52,7 @@ const changes = new WeakMap<SceneGraph, ArchiveChanges>()function settingsSnapshot(graph: SceneGraph): SettingsSnapshot {return structuredClone({colorSpace: graph.documentColorSpace,+ kind: graph.documentKind,libraries: [...graph.enabledLibraries]})}diff --git a/packages/core/tests/canvas/text/lines.test.ts b/packages/core/tests/canvas/text/lines.test.tsindex 01c275501..971d79ae8 100644--- a/packages/core/tests/canvas/text/lines.test.ts+++ b/packages/core/tests/canvas/text/lines.test.ts@@ -177,6 +177,17 @@ describe('lines of mixed sizes', () => {expect(Math.ceil(empty.getHeight())).toBe(106)})+ // Typing Enter at the end grows the box at once, and the caret starts the new line.+ test('counts the empty line a closing newline makes', () => {+ const closed = layOut({ text: 'abc\n' })+ const open = layOut({ text: 'abc\nx' })+ expect(Math.ceil(closed.getHeight())).toBe(Math.ceil(open.getHeight()))+ const caret = expectDefined(closed.getCaretRect(4, false), 'caret after the newline')+ const lineTwo = expectDefined(open.getCaretRect(4, false), 'caret before x')+ expect(caret.x).toBe(lineTwo.x)+ expect(caret.top).toBeCloseTo(lineTwo.top, 2)+ })+test('draws, selects, and hits each line where it is placed', () => {const layout = layOut({text: 'first line\nSmall LARGE',diff --git a/packages/core/tests/editor/history/atomic-tools.test.ts b/packages/core/tests/editor/history/atomic-tools.test.tsindex afb2c7d9c..ba153dfbb 100644--- a/packages/core/tests/editor/history/atomic-tools.test.ts+++ b/packages/core/tests/editor/history/atomic-tools.test.ts@@ -1,7 +1,12 @@import { describe, expect, test } from 'bun:test'import { OpenPencilAPI } from '@open-pencil/core/openpencil-api'-import { createEditor, EDIT_VIEW, executeAtomicTool } from '@open-pencil/core'+import {+ createEditor,+ EDIT_VIEW,+ executeAtomicTool,+ type EditorProfileInputs+} 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'@@ -11,9 +16,14 @@ function setup() {const graph = new SceneGraph()const undo = new UndoManager()const figma = new FigmaAPI(graph)+ const state: EditorProfileInputs = {+ documentKind: 'design',+ canvasView: EDIT_VIEW,+ hostRestrictions: { readOnly: false }+ }const editor = {graph,- state: { canvasView: EDIT_VIEW, hostRestrictions: { readOnly: false } },+ state,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.tsindex 8649d05cb..6c131206c 100644--- a/packages/core/tests/editor/views/profile.test.ts+++ b/packages/core/tests/editor/views/profile.test.ts@@ -1,6 +1,14 @@import { describe, expect, test } from 'bun:test'-import { createEditor, resolveEditorProfile } from '@open-pencil/core'+import {+ BOARD_TOOL_SHORTCUTS,+ createDefaultEditorState,+ createDocumentGraph,+ createEditor,+ resolveEditorProfile,+ TOOL_SHORTCUTS+} from '@open-pencil/core'+import { SceneGraph } from '@open-pencil/scene-graph'describe('canvas view profiles', () => {test('an editing canvas takes every tool and shortcut and draws its chrome', () => {@@ -13,7 +21,9 @@ describe('canvas view profiles', () => {panels: true,leaveTo: null,edits: true,- tools: null+ tools: null,+ toolKeys: TOOL_SHORTCUTS,+ snapGrid: 1})})@@ -28,7 +38,9 @@ describe('canvas view profiles', () => {panels: false,leaveTo: { id: 'edit' },edits: true,- tools: null+ tools: null,+ toolKeys: TOOL_SHORTCUTS,+ snapGrid: 1})})@@ -92,3 +104,65 @@ describe('host restrictions', () => {expect(resolveEditorProfile(editor.state)).toMatchObject({ edits: true, tools: null })})})++describe('document kinds', () => {+ test('a board offers FigJam\'s tools and keys and snaps to its 16-unit grid', () => {+ const editor = createEditor()+ editor.setDocumentKind('board')+ const profile = resolveEditorProfile(editor.state)+ expect(profile.tools && [...profile.tools]).toEqual([+ 'SELECT',+ 'HAND',+ 'STICKY',+ 'SHAPE_WITH_TEXT',+ 'CONNECTOR',+ 'SECTION',+ 'TEXT',+ 'COMMENT'+ ])+ expect([profile.toolKeys, profile.snapGrid]).toEqual([BOARD_TOOL_SHORTCUTS, 16])+ })++ test('becoming a board drops a design tool, and refuses picking one', () => {+ const editor = createEditor()+ editor.setTool('RECTANGLE')+ editor.setDocumentKind('board')+ expect(editor.state.activeTool).toBe('SELECT')+ editor.setTool('PEN')+ expect(editor.state.activeTool).toBe('SELECT')+ editor.setTool('STICKY')+ expect(editor.state.activeTool).toBe('STICKY')+ })++ test('the kind belongs to the document, so a replaced graph brings its own', () => {+ const editor = createEditor()+ editor.setDocumentKind('board')+ expect(editor.graph.documentKind).toBe('board')+ editor.replaceGraph(new SceneGraph())+ expect(editor.state.documentKind).toBe('design')+ })++ test('a board opened or swapped in with a design tool active gives way to Move', () => {+ const state = createDefaultEditorState(new SceneGraph().getPages()[0].id)+ state.activeTool = 'RECTANGLE'+ const opened = createEditor({ graph: createDocumentGraph('board'), state })+ expect(opened.state.activeTool).toBe('SELECT')++ const editor = createEditor()+ editor.setTool('PEN')+ editor.replaceGraph(createDocumentGraph('board'))+ expect(editor.state.activeTool).toBe('SELECT')+ })++ test('a read-only board keeps only Move and Hand of its tools', () => {+ const editor = createEditor()+ editor.setDocumentKind('board')+ editor.setReadOnly(true)+ const profile = resolveEditorProfile(editor.state)+ expect([profile.edits, profile.tools && [...profile.tools], profile.snapGrid]).toEqual([+ false,+ ['SELECT', 'HAND'],+ 16+ ])+ })+})diff --git a/packages/core/tests/io/formats/fig/roundtrip/board.test.ts b/packages/core/tests/io/formats/fig/roundtrip/board.test.tsnew file mode 100644index 000000000..e1679a8e3--- /dev/null+++ b/packages/core/tests/io/formats/fig/roundtrip/board.test.ts@@ -0,0 +1,35 @@+import { describe, expect, test } from 'bun:test'++import { unzipSync } from 'fflate'++import { createDocumentGraph } from '@open-pencil/core'+import { getPageBackgrounds } from '@open-pencil/core/figma-api'+import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'++describe('FigJam boards', () => {+ test('a board saves as a .jam canvas and opens as a board again', async () => {+ const graph = createDocumentGraph('board')+ const bytes = await exportFigFile(graph)+ const canvas = unzipSync(bytes)['canvas.fig']+ expect(new TextDecoder().decode(canvas?.slice(0, 8))).toBe('fig-jam.')+ const reopened = await parseFigFile(bytes.slice().buffer)+ expect(reopened.documentKind).toBe('board')+ })++ test('a design keeps the .fig header', async () => {+ const bytes = await exportFigFile(createDocumentGraph('design'))+ const canvas = unzipSync(bytes)['canvas.fig']+ expect(new TextDecoder().decode(canvas?.slice(0, 8))).toBe('fig-kiwi')+ expect((await parseFigFile(bytes.slice().buffer)).documentKind).toBe('design')+ })++ test("a new board starts on FigJam's #F5F5F5 page", () => {+ const graph = createDocumentGraph('board')+ expect(getPageBackgrounds(graph.getPages()[0])[0]?.color).toEqual({+ r: 245 / 255,+ g: 245 / 255,+ b: 245 / 255,+ a: 1+ })+ })+})diff --git a/packages/fig/src/archive.ts b/packages/fig/src/archive.tsindex 90c422cfb..2edb71340 100644--- a/packages/fig/src/archive.ts+++ b/packages/fig/src/archive.ts@@ -6,7 +6,8 @@ import type { NodeChange } from '@open-pencil/kiwi/fig/codec'import {buildFigKiwi,parseFigKiwiChunks,- type FigDataCompressor+ type FigDataCompressor,+ type FigFileKind} from '@open-pencil/kiwi/fig/container'import { decodeFigKiwiCanvas, parseFigKiwiContainer } from '@open-pencil/kiwi/fig/parse'import type { HeaderFields } from '@open-pencil/kiwi/schema-runtime'@@ -29,6 +30,8 @@ export interface WriteFigArchiveInput {figKiwiVersion?: number/** Compresses the document data; Bun's zstd or deflate when omitted. */compress?: FigDataCompressor+ /** A design file, or a FigJam board saved as `.jam`; a design when omitted. */+ kind?: FigFileKind}export interface FigParseResult {@@ -38,6 +41,8 @@ export interface FigParseResult {figKiwiVersion: number/** Deflated Kiwi schema bytes from the original file, retained for round-trip fidelity. */figSchemaDeflated: Uint8Array+ /** A design file or a FigJam board, by the canvas's header. */+ kind: FigFileKindthumbnailPNG: Uint8Array | nullmetaJSON: string | null}@@ -126,6 +131,8 @@ export interface FigArchiveParts {/** The inflated Kiwi message. */dataRaw: Uint8ArrayfigKiwiVersion: number+ /** A design file or a FigJam board, by the canvas's header. */+ kind: FigFileKindimages: Array<[string, Uint8Array]>thumbnailPNG: Uint8Array | nullmetaJSON: string | null@@ -137,7 +144,8 @@ function canvasParts(canvasData: Uint8Array) {return {schemaDeflated: payload.schemaDeflated,dataRaw: payload.dataRaw,- figKiwiVersion: payload.version+ figKiwiVersion: payload.version,+ kind: payload.kind}}@@ -245,7 +253,8 @@ export function writeFigArchive(input: WriteFigArchiveInput): Uint8Array {input.schemaDeflated,input.kiwiData,input.figKiwiVersion,- input.compress+ input.compress,+ input.kind)const entries: Zippable = {'canvas.fig': [canvasData, { level: 0 }],@@ -264,7 +273,8 @@ export function compressFigDataSync(metaJSON: string,imageEntries: FigImageEntry[],figKiwiVersion?: number,- compress?: FigDataCompressor+ compress?: FigDataCompressor,+ kind?: FigFileKind): Uint8Array {return writeFigArchive({schemaDeflated,@@ -273,6 +283,7 @@ export function compressFigDataSync(metaJSON,images: imageEntries,figKiwiVersion,- compress+ compress,+ kind})}diff --git a/packages/fig/src/document/materialize.ts b/packages/fig/src/document/materialize.tsindex 8b84cc659..2656fde97 100644--- a/packages/fig/src/document/materialize.ts+++ b/packages/fig/src/document/materialize.ts@@ -156,6 +156,8 @@ export function createFigDocumentSession(? restoreAssemblyState(resume, archive.reader, sessionOptions): materializeReader(archive.reader, archive.blobs, sessionOptions)state.graph.figKiwiVersion = archive.figKiwiVersion+ // A resumed session runs on the open graph, whose kind may have changed since it was read.+ if (!resume) state.graph.documentKind = archive.kindstate.graph.figSchemaDeflated = archive.figSchemaDeflatedconst loaded = new Set<string>(resume?.checkpoint.loadedPageIds)const edits = watchGraphEdits(state.graph, resume !== undefined)diff --git a/packages/fig/src/document/read.ts b/packages/fig/src/document/read.tsindex fa8d2c74c..390f93170 100644--- a/packages/fig/src/document/read.ts+++ b/packages/fig/src/document/read.ts@@ -53,6 +53,7 @@ export function createArchiveDocumentReader(bytes: ArrayBuffer, pageIds?: Readonreturn {figKiwiVersion: parsed.figKiwiVersion,figSchemaDeflated: parsed.figSchemaDeflated,+ kind: parsed.kind,reader: createScopedReader(archiveRecords(parsed.nodeChanges), pageIds),blobs: parsed.blobs,images: parsed.images,diff --git a/packages/fig/src/record-patch/index.ts b/packages/fig/src/record-patch/index.tsindex 0b0b7a4d4..156a48bc7 100644--- a/packages/fig/src/record-patch/index.ts+++ b/packages/fig/src/record-patch/index.ts@@ -2,7 +2,7 @@ import { inflateSync } from 'fflate'import type { GUID } from '@open-pencil/kiwi/fig'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'-import type { FigDataCompressor } from '@open-pencil/kiwi/fig/container'+import type { FigDataCompressor, FigFileKind } from '@open-pencil/kiwi/fig/container'import { guidToString } from '@open-pencil/kiwi/fig/guid'import {ByteBuffer,@@ -61,6 +61,8 @@ export interface FigPatchedArchiveInput {images: FigImageEntry[]/** The zstd level the document data is written at; the archive is read whatever it used. */compressionLevel?: number+ /** A design file or a FigJam board; the archive's own kind when omitted. */+ kind?: FigFileKind}const VARIABLE_TYPES = new Set(['VARIABLE', 'VARIABLE_SET'])@@ -485,7 +487,8 @@ export function patchFigArchive(...input.images.filter((image) => !archiveImages.has(image.name.replace(/^images\//, '')))],figKiwiVersion: parts.figKiwiVersion,- compress+ compress,+ kind: input.kind ?? parts.kind})}diff --git a/packages/kiwi/src/fig/container.ts b/packages/kiwi/src/fig/container.tsindex 0287129dd..f28db30b4 100644--- a/packages/kiwi/src/fig/container.ts+++ b/packages/kiwi/src/fig/container.ts@@ -5,6 +5,23 @@ import { isZstdCompressed } from './protocol'export const FIG_KIWI_DEFAULT_VERSION = 101+/**+ * The header a canvas starts with. Figma's design files and FigJam boards differ only here:+ * a board's `.jam` archive holds the same records under `fig-jam.`.+ */+export const FIG_FILE_HEADERS = { design: 'fig-kiwi', board: 'fig-jam.' } as const++/** What a canvas is for, by its header. */+export type FigFileKind = keyof typeof FIG_FILE_HEADERS++/** The kind a canvas's header names, or null when it is no Figma canvas. */+export function figFileKind(binary: Uint8Array): FigFileKind | null {+ const header = new TextDecoder().decode(binary.slice(0, 8))+ if (header === FIG_FILE_HEADERS.design) return 'design'+ if (header === FIG_FILE_HEADERS.board) return 'board'+ return null+}+/** Compresses a fig-kiwi data chunk. */export type FigDataCompressor = (data: Uint8Array) => Uint8Array@@ -108,8 +125,7 @@ function decompressZstd(compressed: Uint8Array): Uint8Array {}export function parseFigKiwiChunks(binary: Uint8Array): Uint8Array[] | null {- const header = new TextDecoder().decode(binary.slice(0, 8))- if (header !== 'fig-kiwi') return null+ if (!figFileKind(binary)) return nullconst view = new DataView(binary.buffer, binary.byteOffset, binary.byteLength)let offset = 12@@ -138,7 +154,8 @@ export function buildFigKiwi(schemaDeflated: Uint8Array,dataRaw: Uint8Array,version = FIG_KIWI_DEFAULT_VERSION,- compress: FigDataCompressor = defaultFigDataCompressor+ compress: FigDataCompressor = defaultFigDataCompressor,+ kind: FigFileKind = 'design'): Uint8Array {const dataCompressed = compress(dataRaw)@@ -146,7 +163,7 @@ export function buildFigKiwi(const out = new Uint8Array(total)const view = new DataView(out.buffer)- out.set(new TextEncoder().encode('fig-kiwi'), 0)+ out.set(new TextEncoder().encode(FIG_FILE_HEADERS[kind]), 0)view.setUint32(8, version, true)let offset = 12diff --git a/packages/kiwi/src/fig/parse.ts b/packages/kiwi/src/fig/parse.tsindex 6a9f8a320..63935a96b 100644--- a/packages/kiwi/src/fig/parse.ts+++ b/packages/kiwi/src/fig/parse.ts@@ -8,7 +8,7 @@ import {type RuntimeMessage} from '../schema-runtime'import type { NodeChange } from './codec'-import { decompressFigKiwiData } from './container'+import { decompressFigKiwiData, figFileKind, type FigFileKind } from './container'import { extractFigPageManifest, type FigPageManifestEntry } from './page-manifest'/**@@ -44,11 +44,12 @@ interface FigKiwiPayload {schemaDeflated: Uint8ArraydataRaw: Uint8Arrayversion: number+ kind: FigFileKind}export function parseFigKiwiContainer(data: Uint8Array): FigKiwiPayload | null {- const header = new TextDecoder().decode(data.slice(0, 8))- if (header !== 'fig-kiwi') return null+ const kind = figFileKind(data)+ if (!kind) return nullconst view = new DataView(data.buffer, data.byteOffset, data.byteLength)const version = view.getUint32(8, true)@@ -69,7 +70,7 @@ export function parseFigKiwiContainer(data: Uint8Array): FigKiwiPayload | null {}if (chunks.length < 2) return null- return { schemaDeflated: chunks[0], dataRaw: decompressFigKiwiData(chunks[1]), version }+ return { schemaDeflated: chunks[0], dataRaw: decompressFigKiwiData(chunks[1]), version, kind }}function isRuntimeMessage(value: unknown): value is RuntimeMessage {@@ -87,6 +88,8 @@ export interface FigKiwiDecodeResult {figKiwiVersion: number/** Deflated kiwi schema bytes from the original file (for roundtrip fidelity). */figSchemaDeflated: Uint8Array+ /** A design file or a FigJam board, by the canvas's header. */+ kind: FigFileKind}/** Decode one raw `fig-kiwi` canvas payload. Outer `.fig` archive handling lives in `@open-pencil/fig`. */@@ -127,6 +130,7 @@ export function decodeFigKiwiCanvas(nodeChanges,blobs,figKiwiVersion: payload.version,- figSchemaDeflated: payload.schemaDeflated+ figSchemaDeflated: payload.schemaDeflated,+ kind: payload.kind}}diff --git a/packages/kiwi/tests/container.test.ts b/packages/kiwi/tests/container.test.tsindex 03ac042cc..041f26d56 100644--- a/packages/kiwi/tests/container.test.ts+++ b/packages/kiwi/tests/container.test.ts@@ -7,6 +7,7 @@ import {decompressFigKiwiData,decompressFigKiwiDataAsync,FIG_KIWI_DEFAULT_VERSION,+ figFileKind,loadFigDataCompressor,loadFigDataDecompressor,loadWasmFigDataCompressor,@@ -122,6 +123,24 @@ describe('Figma FIG Kiwi container helpers', () => {expect(parseFigKiwiChunks(new TextEncoder().encode('not-fig-kiwi'))).toBeNull()})+ // Figma's "Save local copy" of a FigJam board writes `fig-jam.` where a design has `fig-kiwi`.+ test('writes and reads a FigJam board under its own header', () => {+ const schema = new Uint8Array([1, 2, 3])+ const board = buildFigKiwi(+ schema,+ sampleDocument(),+ FIG_KIWI_DEFAULT_VERSION,+ undefined,+ 'board'+ )+ expect(new TextDecoder().decode(board.slice(0, 8))).toBe('fig-jam.')+ expect([figFileKind(board), figFileKind(buildFigKiwi(schema, sampleDocument()))]).toEqual([+ 'board',+ 'design'+ ])+ expect(parseFigKiwiChunks(board)?.[0]).toEqual(schema)+ })+// Bun's own zstd where it runs, and the WebAssembly build browsers and webviews read with.for (const [decoder, load] of [['native', loadFigDataDecompressor],diff --git a/packages/scene-graph/src/graph.ts b/packages/scene-graph/src/graph.tsindex be900c883..e1c339e9c 100644--- a/packages/scene-graph/src/graph.ts+++ b/packages/scene-graph/src/graph.ts@@ -27,6 +27,7 @@ import { markSourceFieldsEdited } from './source-metadata'import { invalidateTextCaches } from './text/picture'import type {DocumentColorSpace,+ DocumentKind,EnabledLibraryBinding,NodeChangeObserver,NodeType,@@ -56,6 +57,7 @@ export class SceneGraph {/** Deflated kiwi schema bytes from the original .fig file, preserved for roundtrip fidelity. */figSchemaDeflated: Uint8Array | null = nulldocumentColorSpace: DocumentColorSpace = 'srgb'+ documentKind: DocumentKind = 'design'enabledLibraries = new Map<string, EnabledLibraryBinding>()readonly emitter = new BufferedSceneEmitter()private absPosCache = new Map<string, Vector>()diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.tsindex f278a80c8..8fe7c03f3 100644--- a/packages/scene-graph/src/types.ts+++ b/packages/scene-graph/src/types.ts@@ -44,6 +44,9 @@ export interface NodeChangeObserver {export type DocumentColorSpace = 'srgb' | 'display-p3'+/** What a document is for, as Figma keeps design files and FigJam boards apart. */+export type DocumentKind = 'design' | 'board'+export interface FigmaSourcePayload {rawSize: Vector | nullrawTransform: Matrix | nulldiff --git a/packages/vue/src/canvas/islands/IslandLayer.vue b/packages/vue/src/canvas/islands/IslandLayer.vueindex f69b2a7d9..3d9358b98 100644--- a/packages/vue/src/canvas/islands/IslandLayer.vue+++ b/packages/vue/src/canvas/islands/IslandLayer.vue@@ -2,7 +2,12 @@import { computedAsync } from '@vueuse/core'import { computed, watch } from 'vue'-import { playIslandRoots, resolveEditorProfile, type EditorState } from '@open-pencil/core'+import {+ playIslandRoots,+ resolveEditorProfile,+ type EditorProfileInputs,+ type EditorState+} from '@open-pencil/core'import type { ViewportTransform } from '@open-pencil/core/geometry'import { tokenStylesheet } from '@open-pencil/dom-css/export'@@ -15,10 +20,7 @@ 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: Pick<- EditorState,- 'panX' | 'panY' | 'zoom' | 'currentPageId' | 'canvasView' | 'hostRestrictions'- >+ view: Pick<EditorState, 'panX' | 'panY' | 'zoom' | 'currentPageId'> & EditorProfileInputs/** The canvas that wheel gestures over the islands are passed on to. */canvas: HTMLElement | null/**diff --git a/packages/vue/src/canvas/labels/edit.ts b/packages/vue/src/canvas/labels/edit.tsindex 98708ba79..968fc9414 100644--- a/packages/vue/src/canvas/labels/edit.ts+++ b/packages/vue/src/canvas/labels/edit.ts@@ -24,6 +24,7 @@ export function createCanvasLabelEdit(editor: Editor): CanvasLabelEditControllerfunction start(kind: CanvasLabelKind, node: SceneNode) {edit.value = { nodeId: node.id, kind, value: node.name }+ editor.setRenamingLabel(node.id)}function update(value: string) {@@ -39,10 +40,12 @@ export function createCanvasLabelEdit(editor: Editor): CanvasLabelEditControllerif (value !== node.name) editor.updateNodeWithUndo(node.id, { name: value }, 'Rename layer')}edit.value = null+ editor.setRenamingLabel(null)}function cancel() {edit.value = null+ editor.setRenamingLabel(null)}return { edit, start, update, commit, cancel }diff --git a/packages/vue/src/canvas/surface/shader/playback.ts b/packages/vue/src/canvas/surface/shader/playback.tsindex 7e3519789..54bee18d5 100644--- a/packages/vue/src/canvas/surface/shader/playback.ts+++ b/packages/vue/src/canvas/surface/shader/playback.ts@@ -2,7 +2,12 @@ import { useRafFn, watchThrottled } from '@vueuse/core'import type { createRendererFromJSON } from 'shaders/core'import { onScopeDispose, watch } from 'vue'-import { resolveEditorProfile, type Editor, type EditorState } from '@open-pencil/core'+import {+ resolveEditorProfile,+ type Editor,+ type EditorProfileInputs,+ type EditorState+} from '@open-pencil/core'import type { SkiaRenderer } from '@open-pencil/core/canvas'import type { Rect } from '@open-pencil/scene-graph/primitives'import {@@ -85,10 +90,7 @@ export function useShaderPlayback(options: {editor: EditorgetRenderer: () => SkiaRenderer | null/** The view this canvas draws: its pan, zoom, page, and whether it previews. */- getView: () => Pick<- EditorState,- 'panX' | 'panY' | 'zoom' | 'currentPageId' | 'canvasView' | 'hostRestrictions'- >+ getView: () => Pick<EditorState, 'panX' | 'panY' | 'zoom' | 'currentPageId'> & EditorProfileInputsgetViewport: () => { width: number; height: number }markDirty: () => void}) {diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.tsindex 64d26f78a..dc87926dc 100644--- a/packages/vue/src/canvas/useCanvasInput.ts+++ b/packages/vue/src/canvas/useCanvasInput.ts@@ -587,6 +587,8 @@ export function useCanvasInput(stopReadOnlyListener()for (const stop of stopPlayListeners) stop()cancelPointerInteraction()+ // A canvas unmounted mid-rename keeps the name typed, as the field's blur does in Chromium.+ canvasLabelEdit.commit()})setupPanZoom(canvasRef, editor, drag, onMouseDown, onMouseMove, onMouseUp, zoomSpeed)diff --git a/packages/vue/src/i18n/locales/de/files.json b/packages/vue/src/i18n/locales/de/files.jsonindex 0c15764fa..4b3afd698 100644--- a/packages/vue/src/i18n/locales/de/files.json+++ b/packages/vue/src/i18n/locales/de/files.json@@ -25,6 +25,10 @@"searchFiles": "Dateien suchen…","searchRecentAndStorageFiles": "Zuletzt verwendete und gespeicherte Dateien suchen…","newDesign": "Neues Design",+ "newFile": "Neue Datei",+ "createDesign": "Design",+ "createBoard": "Board",+ "createIn": "Wird in {place} erstellt","noMatchingFiles": "Keine Dateien entsprechen „{query}“.","documentActions": "Aktionen für {name}","deleteDocument": "Löschen",@@ -32,6 +36,5 @@"deleteDocumentDescription": "Das Dokument wird für alle gelöscht, die es öffnen können. Das lässt sich nicht rückgängig machen.","deleteDocumentFailed": "„{name}“ konnte nicht gelöscht werden. Versuche es erneut.","saveAsPrompt": "Speichern unter:",- "browserFileAPINotSupported": "Dein Browser unterstützt die lokale Datei-API nicht. Dateien werden heruntergeladen, statt direkt gespeichert zu werden.",- "newDesignIn": "Neues Design in {place}"+ "browserFileAPINotSupported": "Dein Browser unterstützt die lokale Datei-API nicht. Dateien werden heruntergeladen, statt direkt gespeichert zu werden."}diff --git a/packages/vue/src/i18n/locales/de/menu.json b/packages/vue/src/i18n/locales/de/menu.jsonindex bbe0b7521..76f0140d7 100644--- a/packages/vue/src/i18n/locales/de/menu.json+++ b/packages/vue/src/i18n/locales/de/menu.json@@ -5,7 +5,8 @@"object": "Objekt","arrange": "Anordnen","text": "Text",- "new": "Neu",+ "new": "Neues Design",+ "newTab": "Neuer Tab","open": "Öffnen…","openTour": "Rundgang öffnen","diagnostics": "Diagnose…",@@ -84,7 +85,6 @@"exportSelectionAsDrawIO": "Auswahl als draw.io exportieren","exportSelectionAsFig": "Auswahl als .fig exportieren","togglePreview": "Vorschau",- "browseFiles": "Dateien durchsuchen…","saveTo": "Speichern in…","showVersionHistory": "Versionsverlauf anzeigen","saveToVersionHistory": "Im Versionsverlauf speichern…"diff --git a/packages/vue/src/i18n/locales/es/files.json b/packages/vue/src/i18n/locales/es/files.jsonindex 60ae0106a..6a9c9191a 100644--- a/packages/vue/src/i18n/locales/es/files.json+++ b/packages/vue/src/i18n/locales/es/files.json@@ -25,6 +25,10 @@"searchFiles": "Buscar archivos…","searchRecentAndStorageFiles": "Buscar en archivos recientes y almacenados…","newDesign": "Nuevo diseño",+ "newFile": "Archivo nuevo",+ "createDesign": "Diseño",+ "createBoard": "Tablero",+ "createIn": "Se crea en {place}","noMatchingFiles": "Ningún archivo coincide con «{query}».","documentActions": "Acciones de {name}","deleteDocument": "Eliminar",@@ -32,6 +36,5 @@"deleteDocumentDescription": "El documento se elimina para todas las personas que pueden abrirlo. No se puede deshacer.","deleteDocumentFailed": "No se pudo eliminar «{name}». Inténtalo de nuevo.","saveAsPrompt": "Guardar como:",- "browserFileAPINotSupported": "Tu navegador no admite la API de archivos locales. Los archivos se descargarán en lugar de guardarse en el mismo lugar.",- "newDesignIn": "Nuevo diseño en {place}"+ "browserFileAPINotSupported": "Tu navegador no admite la API de archivos locales. Los archivos se descargarán en lugar de guardarse en el mismo lugar."}diff --git a/packages/vue/src/i18n/locales/es/menu.json b/packages/vue/src/i18n/locales/es/menu.jsonindex 235245fa4..a71420988 100644--- a/packages/vue/src/i18n/locales/es/menu.json+++ b/packages/vue/src/i18n/locales/es/menu.json@@ -5,7 +5,8 @@"object": "Objeto","arrange": "Organizar","text": "Texto",- "new": "Nuevo",+ "new": "Nuevo diseño",+ "newTab": "Nueva pestaña","open": "Abrir…","openTour": "Abrir el recorrido","diagnostics": "Diagnóstico…",@@ -84,7 +85,6 @@"exportSelectionAsDrawIO": "Exportar selección como draw.io","exportSelectionAsFig": "Exportar selección como .fig","togglePreview": "Vista previa",- "browseFiles": "Explorar archivos…","saveTo": "Guardar en…","showVersionHistory": "Mostrar historial de versiones","saveToVersionHistory": "Guardar en el historial de versiones…"diff --git a/packages/vue/src/i18n/locales/fr/files.json b/packages/vue/src/i18n/locales/fr/files.jsonindex cf5ed5d8d..482743fbf 100644--- a/packages/vue/src/i18n/locales/fr/files.json+++ b/packages/vue/src/i18n/locales/fr/files.json@@ -25,6 +25,10 @@"searchFiles": "Rechercher des fichiers…","searchRecentAndStorageFiles": "Rechercher dans les fichiers récents et stockés…","newDesign": "Nouveau design",+ "newFile": "Nouveau fichier",+ "createDesign": "Design",+ "createBoard": "Tableau blanc",+ "createIn": "Créé dans {place}","noMatchingFiles": "Aucun fichier ne correspond à « {query} ».","documentActions": "Actions pour {name}","deleteDocument": "Supprimer",@@ -32,6 +36,5 @@"deleteDocumentDescription": "Le document est supprimé pour toutes les personnes qui peuvent l’ouvrir. Cette action est irréversible.","deleteDocumentFailed": "Impossible de supprimer « {name} ». Réessayez.","saveAsPrompt": "Enregistrer sous :",- "browserFileAPINotSupported": "Votre navigateur ne prend pas en charge l’API de fichiers locaux. Les fichiers seront téléchargés au lieu d’être enregistrés sur place.",- "newDesignIn": "Nouveau design dans {place}"+ "browserFileAPINotSupported": "Votre navigateur ne prend pas en charge l’API de fichiers locaux. Les fichiers seront téléchargés au lieu d’être enregistrés sur place."}diff --git a/packages/vue/src/i18n/locales/fr/menu.json b/packages/vue/src/i18n/locales/fr/menu.jsonindex cdf7dc93f..b7876b154 100644--- a/packages/vue/src/i18n/locales/fr/menu.json+++ b/packages/vue/src/i18n/locales/fr/menu.json@@ -5,7 +5,8 @@"object": "Objet","arrange": "Disposition","text": "Texte",- "new": "Nouveau",+ "new": "Nouveau design",+ "newTab": "Nouvel onglet","open": "Ouvrir…","openTour": "Ouvrir la visite","diagnostics": "Diagnostics…",@@ -84,7 +85,6 @@"exportSelectionAsDrawIO": "Exporter la sélection en draw.io","exportSelectionAsFig": "Exporter la sélection en .fig","togglePreview": "Aperçu",- "browseFiles": "Parcourir les fichiers…","saveTo": "Enregistrer dans…","showVersionHistory": "Afficher l’historique des versions","saveToVersionHistory": "Enregistrer dans l’historique des versions…"diff --git a/packages/vue/src/i18n/locales/it/files.json b/packages/vue/src/i18n/locales/it/files.jsonindex bbf74eb3e..3275b052a 100644--- a/packages/vue/src/i18n/locales/it/files.json+++ b/packages/vue/src/i18n/locales/it/files.json@@ -25,6 +25,10 @@"searchFiles": "Cerca file…","searchRecentAndStorageFiles": "Cerca nei file recenti e archiviati…","newDesign": "Nuovo design",+ "newFile": "Nuovo file",+ "createDesign": "Design",+ "createBoard": "Lavagna",+ "createIn": "Viene creato in {place}","noMatchingFiles": "Nessun file corrisponde a «{query}».","documentActions": "Azioni per {name}","deleteDocument": "Elimina",@@ -32,6 +36,5 @@"deleteDocumentDescription": "Il documento viene eliminato per tutti coloro che possono aprirlo. L’operazione non può essere annullata.","deleteDocumentFailed": "Impossibile eliminare «{name}». Riprova.","saveAsPrompt": "Salva con nome:",- "browserFileAPINotSupported": "Il browser non supporta l’API dei file locali. I file verranno scaricati anziché salvati nella posizione corrente.",- "newDesignIn": "Nuovo design in {place}"+ "browserFileAPINotSupported": "Il browser non supporta l’API dei file locali. I file verranno scaricati anziché salvati nella posizione corrente."}diff --git a/packages/vue/src/i18n/locales/it/menu.json b/packages/vue/src/i18n/locales/it/menu.jsonindex 2c095d67e..9b4e221f0 100644--- a/packages/vue/src/i18n/locales/it/menu.json+++ b/packages/vue/src/i18n/locales/it/menu.json@@ -5,7 +5,8 @@"object": "Oggetto","arrange": "Disponi","text": "Testo",- "new": "Nuovo",+ "new": "Nuovo design",+ "newTab": "Nuova scheda","open": "Apri…","openTour": "Apri il tour","diagnostics": "Diagnostica…",@@ -84,7 +85,6 @@"exportSelectionAsDrawIO": "Esporta selezione come draw.io","exportSelectionAsFig": "Esporta selezione come .fig","togglePreview": "Anteprima",- "browseFiles": "Sfoglia file…","saveTo": "Salva in…","showVersionHistory": "Mostra cronologia versioni","saveToVersionHistory": "Salva nella cronologia versioni…"diff --git a/packages/vue/src/i18n/locales/ja/files.json b/packages/vue/src/i18n/locales/ja/files.jsonindex cfd233945..9f4be918d 100644--- a/packages/vue/src/i18n/locales/ja/files.json+++ b/packages/vue/src/i18n/locales/ja/files.json@@ -25,6 +25,10 @@"searchFiles": "ファイルを検索…","searchRecentAndStorageFiles": "最近使用したファイルとストレージを検索…","newDesign": "新しいデザイン",+ "newFile": "新規ファイル",+ "createDesign": "デザイン",+ "createBoard": "ボード",+ "createIn": "{place} に作成します","noMatchingFiles": "「{query}」に一致するファイルはありません。","documentActions": "{name} の操作","deleteDocument": "削除",@@ -32,6 +36,5 @@"deleteDocumentDescription": "このドキュメントは開けるすべての人に対して削除されます。この操作は元に戻せません。","deleteDocumentFailed": "「{name}」を削除できませんでした。もう一度お試しください。","saveAsPrompt": "名前を付けて保存:",- "browserFileAPINotSupported": "このブラウザはローカルファイルAPIに対応していません。ファイルは同じ場所に保存されず、ダウンロードされます。",- "newDesignIn": "{place} に新規デザイン"+ "browserFileAPINotSupported": "このブラウザはローカルファイルAPIに対応していません。ファイルは同じ場所に保存されず、ダウンロードされます。"}diff --git a/packages/vue/src/i18n/locales/ja/menu.json b/packages/vue/src/i18n/locales/ja/menu.jsonindex c15097e0a..066edcaa0 100644--- a/packages/vue/src/i18n/locales/ja/menu.json+++ b/packages/vue/src/i18n/locales/ja/menu.json@@ -5,7 +5,8 @@"object": "オブジェクト","arrange": "配置","text": "テキスト",- "new": "新規作成",+ "new": "新規デザイン",+ "newTab": "新規タブ","open": "開く…","openTour": "ツアーを開く","diagnostics": "診断…",@@ -84,7 +85,6 @@"exportSelectionAsDrawIO": "選択範囲を draw.io としてエクスポート","exportSelectionAsFig": "選択範囲を .fig としてエクスポート","togglePreview": "プレビュー",- "browseFiles": "ファイルを表示…","saveTo": "保存先を選んで保存…","showVersionHistory": "バージョン履歴を表示","saveToVersionHistory": "バージョン履歴に保存…"diff --git a/packages/vue/src/i18n/locales/pl/files.json b/packages/vue/src/i18n/locales/pl/files.jsonindex 6de4307f4..0dcdbc1b7 100644--- a/packages/vue/src/i18n/locales/pl/files.json+++ b/packages/vue/src/i18n/locales/pl/files.json@@ -25,6 +25,10 @@"searchFiles": "Szukaj plików…","searchRecentAndStorageFiles": "Szukaj w ostatnich i zapisanych plikach…","newDesign": "Nowy projekt",+ "newFile": "Nowy plik",+ "createDesign": "Projekt",+ "createBoard": "Tablica",+ "createIn": "Tworzy w: {place}","noMatchingFiles": "Brak plików pasujących do „{query}”.","documentActions": "Działania dla {name}","deleteDocument": "Usuń",@@ -32,6 +36,5 @@"deleteDocumentDescription": "Dokument zostanie usunięty dla wszystkich, którzy mogą go otworzyć. Tej operacji nie można cofnąć.","deleteDocumentFailed": "Nie udało się usunąć „{name}”. Spróbuj ponownie.","saveAsPrompt": "Zapisz jako:",- "browserFileAPINotSupported": "Twoja przeglądarka nie obsługuje interfejsu API plików lokalnych. Pliki będą pobierane zamiast zapisywane w bieżącym miejscu.",- "newDesignIn": "Nowy projekt w {place}"+ "browserFileAPINotSupported": "Twoja przeglądarka nie obsługuje interfejsu API plików lokalnych. Pliki będą pobierane zamiast zapisywane w bieżącym miejscu."}diff --git a/packages/vue/src/i18n/locales/pl/menu.json b/packages/vue/src/i18n/locales/pl/menu.jsonindex 2766c365a..a39366d61 100644--- a/packages/vue/src/i18n/locales/pl/menu.json+++ b/packages/vue/src/i18n/locales/pl/menu.json@@ -5,7 +5,8 @@"object": "Obiekt","arrange": "Rozmieszczenie","text": "Tekst",- "new": "Nowy",+ "new": "Nowy projekt",+ "newTab": "Nowa karta","open": "Otwórz…","openTour": "Otwórz przewodnik","diagnostics": "Diagnostyka…",@@ -84,7 +85,6 @@"exportSelectionAsDrawIO": "Eksportuj zaznaczenie jako draw.io","exportSelectionAsFig": "Eksportuj zaznaczenie jako .fig","togglePreview": "Podgląd",- "browseFiles": "Przeglądaj pliki…","saveTo": "Zapisz w…","showVersionHistory": "Pokaż historię wersji","saveToVersionHistory": "Zapisz w historii wersji…"diff --git a/packages/vue/src/i18n/locales/ru/files.json b/packages/vue/src/i18n/locales/ru/files.jsonindex 0a3bc1777..341e35983 100644--- a/packages/vue/src/i18n/locales/ru/files.json+++ b/packages/vue/src/i18n/locales/ru/files.json@@ -25,6 +25,10 @@"searchFiles": "Поиск файлов…","searchRecentAndStorageFiles": "Поиск в недавних файлах и хранилище…","newDesign": "Новый дизайн",+ "newFile": "Новый файл",+ "createDesign": "Дизайн",+ "createBoard": "Доска",+ "createIn": "Создаётся в {place}","noMatchingFiles": "Нет файлов по запросу «{query}».","documentActions": "Действия с {name}","deleteDocument": "Удалить",@@ -32,6 +36,5 @@"deleteDocumentDescription": "Документ будет удалён для всех, кто может его открыть. Это действие нельзя отменить.","deleteDocumentFailed": "Не удалось удалить «{name}». Попробуйте ещё раз.","saveAsPrompt": "Сохранить как:",- "browserFileAPINotSupported": "Ваш браузер не поддерживает API локальных файлов. Вместо сохранения на месте файлы будут скачиваться.",- "newDesignIn": "Новый дизайн в {place}"+ "browserFileAPINotSupported": "Ваш браузер не поддерживает API локальных файлов. Вместо сохранения на месте файлы будут скачиваться."}diff --git a/packages/vue/src/i18n/locales/ru/menu.json b/packages/vue/src/i18n/locales/ru/menu.jsonindex 1dd908ca2..2c17c102d 100644--- a/packages/vue/src/i18n/locales/ru/menu.json+++ b/packages/vue/src/i18n/locales/ru/menu.json@@ -5,7 +5,8 @@"object": "Объект","arrange": "Порядок","text": "Текст",- "new": "Создать",+ "new": "Новый дизайн",+ "newTab": "Новая вкладка","open": "Открыть…","openTour": "Открыть тур","diagnostics": "Диагностика…",@@ -84,7 +85,6 @@"exportSelectionAsDrawIO": "Экспортировать выделение как draw.io","exportSelectionAsFig": "Экспортировать выделение как .fig","togglePreview": "Просмотр",- "browseFiles": "Обзор файлов…","saveTo": "Сохранить в…","showVersionHistory": "Показать историю версий","saveToVersionHistory": "Сохранить в историю версий…"diff --git a/packages/vue/src/i18n/locales/zh-cn/files.json b/packages/vue/src/i18n/locales/zh-cn/files.jsonindex 2c1934d6f..443f27ea9 100644--- a/packages/vue/src/i18n/locales/zh-cn/files.json+++ b/packages/vue/src/i18n/locales/zh-cn/files.json@@ -25,6 +25,10 @@"searchFiles": "搜索文件…","searchRecentAndStorageFiles": "搜索最近使用和存储的文件…","newDesign": "新建设计",+ "newFile": "新建文件",+ "createDesign": "设计",+ "createBoard": "白板",+ "createIn": "在 {place} 中创建","noMatchingFiles": "没有与“{query}”匹配的文件。","documentActions": "{name} 的操作","deleteDocument": "删除",@@ -32,6 +36,5 @@"deleteDocumentDescription": "该文档将对所有可以打开它的人删除。此操作无法撤销。","deleteDocumentFailed": "无法删除“{name}”。请重试。","saveAsPrompt": "另存为:",- "browserFileAPINotSupported": "你的浏览器不支持本地文件 API。文件将被下载,而不是保存在原位置。",- "newDesignIn": "在 {place} 中新建设计"+ "browserFileAPINotSupported": "你的浏览器不支持本地文件 API。文件将被下载,而不是保存在原位置。"}diff --git a/packages/vue/src/i18n/locales/zh-cn/menu.json b/packages/vue/src/i18n/locales/zh-cn/menu.jsonindex 0baa95189..94dbcabc1 100644--- a/packages/vue/src/i18n/locales/zh-cn/menu.json+++ b/packages/vue/src/i18n/locales/zh-cn/menu.json@@ -5,7 +5,8 @@"object": "对象","arrange": "排列","text": "文本",- "new": "新建",+ "new": "新建设计",+ "newTab": "新建标签页","open": "打开…","openTour": "打开导览","diagnostics": "诊断…",@@ -84,7 +85,6 @@"exportSelectionAsDrawIO": "将所选内容导出为 draw.io","exportSelectionAsFig": "将所选内容导出为 .fig","togglePreview": "预览",- "browseFiles": "浏览文件…","saveTo": "保存到…","showVersionHistory": "显示版本历史","saveToVersionHistory": "保存到版本历史…"diff --git a/packages/vue/src/i18n/messages/files.ts b/packages/vue/src/i18n/messages/files.tsindex f3c432fbd..47f4613ab 100644--- a/packages/vue/src/i18n/messages/files.ts+++ b/packages/vue/src/i18n/messages/files.ts@@ -35,7 +35,10 @@ export const filesMessageDefaults = {searchFiles: 'Search files…',searchRecentAndStorageFiles: 'Search recent and storage files…',newDesign: 'New design',- newDesignIn: params('New design in {place}'),+ newFile: 'New file',+ createDesign: 'Design',+ createBoard: 'Board',+ createIn: params('Creates it in {place}'),noMatchingFiles: params('No files match “{query}”.'),documentActions: params('Actions for {name}'),deleteDocument: 'Delete',diff --git a/packages/vue/src/i18n/messages/menu.ts b/packages/vue/src/i18n/messages/menu.tsindex 94b3f8381..ee0809e8d 100644--- a/packages/vue/src/i18n/messages/menu.ts+++ b/packages/vue/src/i18n/messages/menu.ts@@ -8,9 +8,9 @@ export const menuMessageDefaults = {arrange: 'Arrange',text: 'Text',- new: 'New',+ new: 'New design',+ newTab: 'New tab',open: 'Open…',- browseFiles: 'Browse files…',openTour: 'Open the Tour',diagnostics: 'Diagnostics…',save: 'Save',diff --git a/packages/vue/src/shared/input/draw.ts b/packages/vue/src/shared/input/draw.tsindex 4ce897520..9be4ffc5f 100644--- a/packages/vue/src/shared/input/draw.ts+++ b/packages/vue/src/shared/input/draw.ts@@ -6,6 +6,7 @@ import { generatedFrameText, SHAPE_WITH_TEXT_SIZE } from '@open-pencil/scene-graimport Matrix from '@open-pencil/scene-graph/matrix'import { findDrawParent } from '#vue/shared/input/drop-target'+import { gridRounding } from '#vue/shared/input/snap'import { TOOL_TO_NODE } from '#vue/shared/input/types'import type { DragDraw, DragState } from '#vue/shared/input/types'@@ -32,7 +33,7 @@ function startDraw(const parentId = findDrawParent(cx, cy, type, editor)const toLocal = parentSpace(editor, parentId)// Figma rounds both corners of a drawn layer to whole pixels.- const snap = editor.state.snappingPreferences.pixelGrid ? Math.round : (value: number) => value+ const snap = gridRounding(editor)const local = toLocal(cx, cy)const start = { x: snap(local.x), y: snap(local.y) }const nodeId = editor.createShape(type, start.x, start.y, 0, 0, parentId)diff --git a/packages/vue/src/shared/input/snap.ts b/packages/vue/src/shared/input/snap.tsindex bf70afc7d..ec437fbec 100644--- a/packages/vue/src/shared/input/snap.ts+++ b/packages/vue/src/shared/input/snap.ts@@ -1,6 +1,6 @@import { uniq } from 'es-toolkit'-import type { Editor } from '@open-pencil/core'+import { resolveEditorProfile, type Editor } from '@open-pencil/core'import { SNAP_THRESHOLD_SCREEN_PX } from '@open-pencil/core/constants'import type { SceneNode } from '@open-pencil/scene-graph'import { getAxisAlignedWorldBounds, getWorldMatrix } from '@open-pencil/scene-graph/coordinate'@@ -13,18 +13,31 @@ export interface PixelSnapResult {guides: SnapGuide[]}+/** Rounds to a multiple of `step`. */+function roundTo(value: number, step: number): number {+ return Math.round(value / step) * step+}+/**- * Lands the bounds on whole pixels, as Figma's Snap to pixel grid does at any zoom: a move ends on- * a whole position and a resized edge on a whole size, even from a fractional start.+ * Lands the bounds on the snap grid, as Figma's Snap to pixel grid does at any zoom: a move ends on+ * a whole position and a resized edge on a whole size, even from a fractional start. The grid is+ * the editor profile's: whole pixels in a design, FigJam's 16 units on a board.*/-export function computePixelGridSnap(bounds: Rect): PixelSnapResult {+export function computePixelGridSnap(bounds: Rect, step = 1): PixelSnapResult {return {- delta: { x: Math.round(bounds.x) - bounds.x, y: Math.round(bounds.y) - bounds.y },+ delta: { x: roundTo(bounds.x, step) - bounds.x, y: roundTo(bounds.y, step) - bounds.y },// Pixel rounding is not alignment with another object or an explicit guide.guides: []}}+/** How a drawn layer's corners land while Snap to pixel grid is on, on the profile's grid. */+export function gridRounding(editor: Editor): (value: number) => number {+ if (!editor.state.snappingPreferences.pixelGrid) return (value) => value+ const step = resolveEditorProfile(editor.state).snapGrid+ return (value) => roundTo(value, step)+}+export interface ExplicitSnapTarget extends SnapGuide {kind: 'canvas-guide' | 'layout-guide'}@@ -131,7 +144,7 @@ export function resolveObjectPixelSnap(? computeSnap(movingIds, movingBounds, targets, threshold): { dx: 0, dy: 0, guides: [] }const pixelSnap = editor.state.snappingPreferences.pixelGrid- ? computePixelGridSnap(movingBounds)+ ? computePixelGridSnap(movingBounds, resolveEditorProfile(editor.state).snapGrid): { delta: { x: 0, y: 0 }, guides: [] }const objectX = objectSnap.guides.some((guide) => guide.axis === 'x')const objectY = objectSnap.guides.some((guide) => guide.axis === 'y')diff --git a/packages/vue/src/shared/input/sticky/draw.ts b/packages/vue/src/shared/input/sticky/draw.tsindex d34d3b655..b96bb2a8d 100644--- a/packages/vue/src/shared/input/sticky/draw.ts+++ b/packages/vue/src/shared/input/sticky/draw.ts@@ -8,6 +8,7 @@ import { scaleNodeChanges } from '@open-pencil/scene-graph/scaling'import { parentSpace } from '#vue/shared/input/draw'import { findDrawParent } from '#vue/shared/input/drop-target'+import { gridRounding } from '#vue/shared/input/snap'import { subtree } from '#vue/shared/input/sticky/scale'import type { DragState, DragStickyDraw } from '#vue/shared/input/types'@@ -28,7 +29,7 @@ export function startStickyDraw(editor.undo.beginBatch('Create sticky')const parentId = findDrawParent(cx, cy, 'STICKY', editor)const toLocal = parentSpace(editor, parentId)- const snap = editor.state.snappingPreferences.pixelGrid ? Math.round : (value: number) => value+ const snap = gridRounding(editor)const local = toLocal(cx, cy)const start = { x: snap(local.x), y: snap(local.y) }const sticky = editor.createStickyNote(parentId, {diff --git a/packages/vue/tests/canvas/labels/edit.test.ts b/packages/vue/tests/canvas/labels/edit.test.tsnew file mode 100644index 000000000..8d73f9445--- /dev/null+++ b/packages/vue/tests/canvas/labels/edit.test.ts@@ -0,0 +1,26 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core'++import { createCanvasLabelEdit } from '#vue/canvas/labels/edit'++describe('canvas label renaming', () => {+ // The canvas skips the title of `renamingLabelId` (tests/e2e/canvas/labels/name-editing.spec.ts).+ test('marks the layer being renamed until the rename ends', () => {+ const editor = createEditor()+ const id = editor.createShape('SECTION', 0, 0, 224, 192)+ const node = editor.graph.getNode(id)+ if (!node) throw new Error('Expected the section')+ const labels = createCanvasLabelEdit(editor)++ labels.start('section-title', node)+ expect(editor.state.renamingLabelId).toBe(id)+ labels.update('Se')+ labels.commit()+ expect([editor.state.renamingLabelId, editor.graph.getNode(id)?.name]).toEqual([null, 'Se'])++ labels.start('section-title', node)+ labels.cancel()+ expect(editor.state.renamingLabelId).toBeNull()+ })+})diff --git a/src/app/ai/chat/run-location.ts b/src/app/ai/chat/run-location.tsindex c3600b7cb..bcc2f7ee2 100644--- a/src/app/ai/chat/run-location.ts+++ b/src/app/ai/chat/run-location.ts@@ -14,7 +14,7 @@ export interface ChatRunLocation {export function useChatRunLocation() {return computed<ChatRunLocation | null>(() => {const tab = activeTab.value- if (!tab || tab.kind === 'home') return null+ if (tab?.kind !== 'document') return nullconst store = tab.storeconst agentId = runAgentId(store)const agent = presenceOf(store).agents.value.find((entry) => entry.id === agentId)diff --git a/src/app/collab/use.ts b/src/app/collab/use.tsindex c53224cd7..269ce0fc6 100644--- a/src/app/collab/use.ts+++ b/src/app/collab/use.ts@@ -67,7 +67,7 @@ export function useCollab() {/** Puts the active tab's document into a room and returns the room ID. */shareCurrentDoc: (roomId?: string): string | null => {const store = activeTab.value?.store- if (!store || activeTab.value?.kind === 'home') return null+ if (!store || activeTab.value?.kind !== 'document') return nullreturn shareDocument(store, roomId).roomId},disconnect: () => {diff --git a/src/app/document/io/names.ts b/src/app/document/io/names.tsindex 40ab99a4a..da1704bce 100644--- a/src/app/document/io/names.ts+++ b/src/app/document/io/names.ts@@ -1,6 +1,20 @@import { basename } from 'pathe'import { filename } from 'pathe/utils'+import { DOCUMENT_EXTENSIONS } from '@open-pencil/core/io'+import type { DocumentKind } from '@open-pencil/scene-graph'++/** Whether a file is a Figma archive: a design's `.fig` or a FigJam board's `.jam`. */+export function isFigArchiveName(name: string): boolean {+ const lower = name.toLowerCase()+ return lower.endsWith('.fig') || lower.endsWith('.jam')+}++/** The file name a document of this kind saves under: `.fig` for a design, `.jam` for a board. */+export function documentFileName(name: string, kind: DocumentKind): string {+ return `${name}.${DOCUMENT_EXTENSIONS[kind]}`+}+export function documentNameFromFigPath(path: string): string {return filename(path) || 'Untitled'}diff --git a/src/app/document/io/save/actions.ts b/src/app/document/io/save/actions.tsindex 16e85294c..a60bd4a06 100644--- a/src/app/document/io/save/actions.ts+++ b/src/app/document/io/save/actions.ts@@ -3,7 +3,7 @@ import { filesMessages } from '@open-pencil/vue/i18n'import { downloadBlob } from '@/app/document/io/browser'import { isFileWriteRefused } from '@/app/document/io/capability'-import { documentNameFromFigPath } from '@/app/document/io/names'+import { documentFileName, documentNameFromFigPath } from '@/app/document/io/names'import { chooseBrowserFigSaveHandle, chooseTauriFigSavePath } from '@/app/document/io/save/targets'import type { DocumentSourceAccess } from '@/app/document/io/types'import { createDocumentWriter } from '@/app/document/io/write'@@ -80,7 +80,7 @@ export function createSaveActions({const { data, version } = await buildVersionedFigFile()if (IS_TAURI) {- const path = await chooseTauriFigSavePath()+ const path = await chooseTauriFigSavePath(state.documentKind)if (!path) return falsesetStorageBinding(null)setFilePath(path)@@ -93,7 +93,7 @@ export function createSaveActions({}// The picker helper returns null when the browser has no File System Access API.- const handle = await chooseBrowserFigSaveHandle()+ const handle = await chooseBrowserFigSaveHandle(state.documentKind)if (handle) {setStorageBinding(null)setFileHandle(handle)@@ -114,7 +114,10 @@ export function createSaveActions({}}- const filename = prompt(filesMessages.get().saveAsPrompt, getDownloadName() ?? 'Untitled.fig')+ const filename = prompt(+ filesMessages.get().saveAsPrompt,+ getDownloadName() ?? documentFileName('Untitled', state.documentKind)+ )if (!filename) return falsereturn downloadAs(filename, data, version)}diff --git a/src/app/document/io/save/targets.ts b/src/app/document/io/save/targets.tsindex f0d650cce..3f5985092 100644--- a/src/app/document/io/save/targets.ts+++ b/src/app/document/io/save/targets.ts@@ -1,21 +1,31 @@+import { DOCUMENT_EXTENSIONS } from '@open-pencil/core/io'+import type { DocumentKind } from '@open-pencil/scene-graph'+import { pickBrowserSaveFile } from '@/app/document/io/capability'+import { documentFileName } from '@/app/document/io/names'++/** What the save dialog calls a document's file type. */+const FILE_TYPE_NAMES: Readonly<Record<DocumentKind, string>> = {+ design: 'Figma file',+ board: 'FigJam board'+}-export async function chooseTauriFigSavePath() {+export async function chooseTauriFigSavePath(kind: DocumentKind) {const { save } = await import('@tauri-apps/plugin-dialog')return save({- defaultPath: 'Untitled.fig',- filters: [{ name: 'Figma file', extensions: ['fig'] }]+ defaultPath: documentFileName('Untitled', kind),+ filters: [{ name: FILE_TYPE_NAMES[kind], extensions: [DOCUMENT_EXTENSIONS[kind]] }]})}-export async function chooseBrowserFigSaveHandle() {+export async function chooseBrowserFigSaveHandle(kind: DocumentKind) {try {return await pickBrowserSaveFile({- suggestedName: 'Untitled.fig',+ suggestedName: documentFileName('Untitled', kind),types: [{- description: 'Figma file',- accept: { 'application/octet-stream': ['.fig'] }+ description: FILE_TYPE_NAMES[kind],+ accept: { 'application/octet-stream': [`.${DOCUMENT_EXTENSIONS[kind]}`] }}]})diff --git a/src/app/document/io/source/actions.ts b/src/app/document/io/source/actions.tsindex 8c7b72635..bb798d4ea 100644--- a/src/app/document/io/source/actions.ts+++ b/src/app/document/io/source/actions.ts@@ -6,6 +6,7 @@ import { exportFigFile } from '@open-pencil/core/io/formats/fig'import { createAutosave } from '@/app/document/autosave'import { createDocumentChanges } from '@/app/document/io/changes'import {+ documentFileName,documentNameFromFigPath,downloadNameFromPath,figDownloadName@@ -167,7 +168,7 @@ export function createDocumentSourceActions({stopWatchingFile()setFileHandle(null)setFilePath(null)- setDownloadName(`${documentName}.fig`)+ setDownloadName(documentFileName(documentName, state.documentKind))setSourceIdentity({ handle: null, path: null })setStorageBinding(binding)state.documentName = documentName@@ -248,7 +249,7 @@ export function createDocumentSourceActions({stopWatchingFile()setFileHandle(null)setFilePath(null)- setDownloadName(`${state.documentName}.fig`)+ setDownloadName(documentFileName(state.documentName, state.documentKind))setStorageBinding({ ...storageLocationOf(location), documentId: createCanvasId() })})if (saved) {diff --git a/src/app/editor/pages/palette.ts b/src/app/editor/pages/palette.tsindex 016512430..bf2872aec 100644--- a/src/app/editor/pages/palette.ts+++ b/src/app/editor/pages/palette.ts@@ -45,7 +45,7 @@ export function usePagePaletteGroup() {return computed<CommandPaletteGroup | null>(() => {const tab = activeTab.value- if (!tab || tab.kind === 'home') return null+ if (tab?.kind !== 'document') return nullconst store = tab.store// Pages and their names change with the scene.void store.state.sceneVersiondiff --git a/src/app/editor/toolbar/layout.ts b/src/app/editor/toolbar/layout.tsindex dfebd1f3e..15b9fca22 100644--- a/src/app/editor/toolbar/layout.ts+++ b/src/app/editor/toolbar/layout.ts@@ -110,8 +110,8 @@ export type ToolbarItem =/*** 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.+ * none, and otherwise every one of those tools, shown even where the layout hides them, with no+ * actions, as a read-only document keeps Move and Hand in Figma and a board offers FigJam's tools.*/export function toolbarLayoutFor(layout: ToolbarLayout,@@ -122,7 +122,7 @@ export function toolbarLayoutFor(groups: layout.groups.map((group) => group.filter((entry) => !isToolbarAction(entry) && tools.has(entry))).filter((group) => group.length > 0),- hidden: layout.hidden+ hidden: []}}diff --git a/src/app/editor/toolbar/shortcuts.ts b/src/app/editor/toolbar/shortcuts.tsindex cea2b2ad2..de17da74a 100644--- a/src/app/editor/toolbar/shortcuts.ts+++ b/src/app/editor/toolbar/shortcuts.ts@@ -1,31 +1,52 @@import { mapValues } from 'es-toolkit/object'-import type { Tool } from '@open-pencil/core'+import { TOOL_SHORTCUTS, type Tool } from '@open-pencil/core'import { formatShortcut, type ShortcutPlatform } from '@open-pencil/vue/editor/commands'-/** Each tool's key in the command registry's notation; empty for tools without one. */-const TOOL_SHORTCUT_KEYS: Readonly<Record<Tool, string>> = {- SELECT: 'V',- FRAME: 'F',- SECTION: 'SHIFT+S',- RECTANGLE: 'R',- ELLIPSE: 'O',- LINE: 'L',+/** A key code (`KeyR`, `Shift+KeyS`) in the command registry's notation (`R`, `SHIFT+S`). */+function registryKeys(code: string): string {+ return code+ .split('+')+ .map((part) => (part.startsWith('Key') ? part.slice(3) : part.toUpperCase()))+ .join('+')+}++/** Every tool, each without a key until the profile's key map gives it one. */+const UNKEYED: Readonly<Record<Tool, string>> = {+ SELECT: '',+ FRAME: '',+ SECTION: '',+ RECTANGLE: '',+ ELLIPSE: '',+ LINE: '',POLYGON: '',STAR: '',- PEN: 'P',- PENCIL: 'SHIFT+P',- TEXT: 'T',+ PEN: '',+ PENCIL: '',+ TEXT: '',STICKY: '',SHAPE_WITH_TEXT: '',CONNECTOR: '',- HAND: 'H',- COMMENT: 'C'+ HAND: '',+ COMMENT: ''}-/** Each tool's key as the toolbar and Settings print it on this platform. */-export function toolShortcutLabels(platform?: ShortcutPlatform): Readonly<Record<Tool, string>> {- return mapValues(TOOL_SHORTCUT_KEYS, (keys) => formatShortcut(keys, platform) ?? '')+/**+ * Each tool's key as the toolbar and Settings print it on this platform, from the key map the+ * editor profile offers: the first key that picks a tool names it.+ */+export function toolShortcutLabels(+ toolKeys: Readonly<Partial<Record<string, Tool>>> = TOOL_SHORTCUTS,+ platform?: ShortcutPlatform+): Readonly<Record<Tool, string>> {+ const keys = new Map<Tool, string>()+ for (const [code, tool] of Object.entries(toolKeys)) {+ if (tool && !keys.has(tool)) keys.set(tool, registryKeys(code))+ }+ return mapValues(UNKEYED, (_, tool) => {+ const key = keys.get(tool)+ return key ? (formatShortcut(key, platform) ?? '') : ''+ })}/** A tool's tooltip: its name, then its key when it has one. */diff --git a/src/app/recent-files/thumbnails.ts b/src/app/recent-files/thumbnails.tsindex 899d7c95e..3236011eb 100644--- a/src/app/recent-files/thumbnails.ts+++ b/src/app/recent-files/thumbnails.ts@@ -1,6 +1,7 @@import { extractFigThumbnailFromReader } from '@open-pencil/fig'import { readCacheBytes, removeCachePrefix, writeCacheBytes } from '@/app/cache'+import { isFigArchiveName } from '@/app/document/io/names'import { isTauri } from '@/app/tauri/env'const RECENT_FILE_THUMBNAIL_CACHE_DIR = 'recent-file-thumbnails/v2'@@ -38,7 +39,7 @@ export function clearRecentFileThumbnails(): Promise<void> {}export async function loadRecentFileThumbnail(path: string): Promise<Uint8Array | null> {- if (!isTauri() || !path.toLowerCase().endsWith('.fig')) return null+ if (!isTauri() || !isFigArchiveName(path)) return nullconst cached = await loadCachedRecentFileThumbnail(path)if (cached) return cachedconst { open, SeekMode } = await import('@tauri-apps/plugin-fs')diff --git a/src/app/shell/keyboard/registry.ts b/src/app/shell/keyboard/registry.tsindex dafe749ff..21a3418c0 100644--- a/src/app/shell/keyboard/registry.ts+++ b/src/app/shell/keyboard/registry.ts@@ -1,8 +1,9 @@import { useEventListener } from '@vueuse/core'+import { uniq } from 'es-toolkit'import { createKeybindingsHandler } from 'tinykeys'import type { KeyBindingMap } from 'tinykeys'-import { resolveEditorProfile } from '@open-pencil/core'+import { BOARD_TOOL_SHORTCUTS, resolveEditorProfile } from '@open-pencil/core'import { isCanvasTextInput } from '@open-pencil/vue/canvas/text-edit'import { editorCommandMetadata, type EditorCommandId } from '@open-pencil/vue/editor/commands'@@ -24,6 +25,7 @@ import type {KeyboardShortcutRunOptions} from '@/app/shell/keyboard/types'import { appMenuTinykeysShortcut } from '@/app/shell/menu/shortcut'+import { showsDocument } from '@/app/tabs'type ShortcutAction = (options: KeyboardShortcutRunOptions) => void@@ -153,10 +155,16 @@ function bindShortcut(for (const key of Array.isArray(keys) ? keys : [keys]) bindings[key] = run}+/**+ * Binds every key a design or a board picks a tool with; which tool a key picks, if any, comes+ * from the editor profile's key map when it is pressed.+ */function bindToolShortcuts(bindings: KeyBindingMap, options: KeyboardShortcutRunOptions) {- for (const [code, tool] of Object.entries(TOOL_SHORTCUTS)) {- if (!tool) continue+ const codes = uniq([...Object.keys(TOOL_SHORTCUTS), ...Object.keys(BOARD_TOOL_SHORTCUTS)])+ for (const code of codes) {bindings[code] = (event: KeyboardEvent) => {+ const tool = resolveEditorProfile(options.store.state).toolKeys[code]+ if (!tool) returnevent.preventDefault()options.spaceTool.resetToolBeforeSpace()options.store.setTool(tool)@@ -204,7 +212,9 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {{id: 'save-as',keys: appMenuTinykeysShortcut('save-as') ?? '$mod+Shift+KeyS',- run: ({ store }) => void store.saveFigFileAs()+ run: ({ store }) => {+ if (showsDocument()) void store.saveFigFileAs()+ }},{id: 'save-version',@@ -300,7 +310,11 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {keys: appMenuTinykeysShortcut('new') ?? '$mod+KeyN',run: ({ createTab }) => createTab()},- { id: 'show-home', keys: '$mod+KeyT', run: ({ showHome }) => showHome() },+ {+ id: 'new-tab',+ keys: appMenuTinykeysShortcut('new-tab') ?? '$mod+KeyT',+ run: ({ openNewFileTab }) => openNewFileTab()+ },{id: 'next-tab',keys: 'Control+Tab',@@ -335,7 +349,9 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {{id: 'save',keys: appMenuTinykeysShortcut('save') ?? '$mod+KeyS',- run: ({ store }) => void store.saveFigFile()+ run: ({ store }) => {+ if (showsDocument()) void store.saveFigFile()+ }},{id: 'open-file',diff --git a/src/app/shell/keyboard/types.ts b/src/app/shell/keyboard/types.tsindex 8cf0ce251..7f8cb0eda 100644--- a/src/app/shell/keyboard/types.ts+++ b/src/app/shell/keyboard/types.ts@@ -24,7 +24,8 @@ export type KeyboardShortcutOptions = {openFileDialog: () => voidcloseActiveTab: () => voidcreateTab: () => void- showHome: () => void+ /** Opens a New file tab, as Figma's ⌘T does. */+ openNewFileTab: () => voidswitchAdjacentTab: (step: 1 | -1) => void}diff --git a/src/app/shell/keyboard/use.ts b/src/app/shell/keyboard/use.tsindex e16964927..0e8cc62c0 100644--- a/src/app/shell/keyboard/use.ts+++ b/src/app/shell/keyboard/use.ts@@ -14,7 +14,7 @@ import { registerKeyboardShortcuts } from '@/app/shell/keyboard/registry'import { openFileDialog } from '@/app/shell/menu/use'import {closeTab,- createHomeTab,+ openNewFileTab,createTab,switchAdjacentTab,activeTab as activeTabRef@@ -51,7 +51,7 @@ export function useKeyboard() {if (activeTabRef.value) void closeTab(activeTabRef.value.id)},createTab: () => createTab(),- showHome: () => createHomeTab(),+ openNewFileTab: () => openNewFileTab(),switchAdjacentTab})}diff --git a/src/app/shell/menu/app-menu.ts b/src/app/shell/menu/app-menu.tsindex bae3e8f44..37fc2c1b7 100644--- a/src/app/shell/menu/app-menu.ts+++ b/src/app/shell/menu/app-menu.ts@@ -1,6 +1,5 @@import type { Component } from 'vue'import { computed } from 'vue'-import { useRouter } from 'vue-router'import IconDownload from '~icons/lucide/download'import IconEye from '~icons/lucide/eye'import IconFile from '~icons/lucide/file'@@ -38,7 +37,6 @@ import { appPreferences } from '@/app/settings/preferences/store'import { createSharedEditorMenuActions } from '@/app/shell/menu/actions/editor'import { createSelectionMenuActions } from '@/app/shell/menu/actions/selection'import { menuFeatureAvailable } from '@/app/shell/menu/features'-import { browseFiles } from '@/app/shell/menu/navigation'import { createSaveMenuActions } from '@/app/shell/menu/save-actions'import type {AppMenuActionItem,@@ -97,7 +95,6 @@ function isSeparator(entry: AppMenuEntry): entry is Extract<AppMenuEntry, { typeexport function useAppMenu() {const store = useEditorStore()- const router = useRouter()const {commands,menuItem: commandMenuItem,@@ -109,8 +106,8 @@ export function useAppMenu() {const translatedMenuItemLabels: Partial<Record<string, keyof typeof menu.value>> = {new: 'new',+ 'new-tab': 'newTab',open: 'open',- 'browse-files': 'browseFiles','open-tour': 'openTour',diagnostics: 'diagnostics',save: 'save',@@ -183,8 +180,10 @@ export function useAppMenu() {new: () => {void import('@/app/tabs').then((m) => m.createTab())},+ 'new-tab': () => {+ void import('@/app/tabs').then((m) => m.openNewFileTab())+ },open: () => void openFileDialog(),- 'browse-files': () => browseFiles(router),'open-tour': () => {openTour().catch((error: unknown) => console.error('[Tour] Could not open the tour:', error))},diff --git a/src/app/shell/menu/editor.ts b/src/app/shell/menu/editor.tsindex 0d995275d..8def1a8f9 100644--- a/src/app/shell/menu/editor.ts+++ b/src/app/shell/menu/editor.ts@@ -13,7 +13,7 @@ import { createSaveMenuActions } from '@/app/shell/menu/save-actions'import { APP_MENU_SCHEMA, type AppMenuEntry } from '@/app/shell/menu/schema'import { SHELL_MENU_IDS } from '@/app/shell/menu/shell'import { useAppTheme } from '@/app/shell/theme'-import { createTab, closeTab, activeTab, switchAdjacentTab } from '@/app/tabs'+import { createTab, closeTab, activeTab, openNewFileTab, switchAdjacentTab } from '@/app/tabs'import { isTauri } from '@/app/tauri/env'function commandMenuIds(entries: readonly AppMenuEntry[]): EditorCommandId[] {@@ -39,6 +39,7 @@ export function useEditorMenu() {const actions: Partial<Record<string, () => void>> = {new: () => createTab(),+ 'new-tab': () => openNewFileTab(),open: () => void openFileDialog(),close: () => {if (activeTab.value) void closeTab(activeTab.value.id)diff --git a/src/app/shell/menu/files.ts b/src/app/shell/menu/files.tsindex 5602b87fc..5b72de9a7 100644--- a/src/app/shell/menu/files.ts+++ b/src/app/shell/menu/files.ts@@ -174,7 +174,7 @@ export async function openFileDialog() {{description: 'Design file',accept: {- 'application/octet-stream': ['.fig'],+ 'application/octet-stream': ['.fig', '.jam'],'application/json': ['.pen'],'text/html': ['.html', '.htm'],'application/xhtml+xml': ['.xhtml'],diff --git a/src/app/shell/menu/navigation.ts b/src/app/shell/menu/navigation.tsindex d711786df..9c1ce11f5 100644--- a/src/app/shell/menu/navigation.ts+++ b/src/app/shell/menu/navigation.ts@@ -14,8 +14,3 @@ export function openHomeLocation(router: Router, location: HomeLocation): void {homeLocation.value = locationshowHome(router)}--/** Home at the place the person browsed last: a Cloud workspace, the bucket, or Recent. */-export function browseFiles(router: Router): void {- showHome(router)-}diff --git a/src/app/shell/menu/save-actions.ts b/src/app/shell/menu/save-actions.tsindex a4dc1f2d6..e75816fa1 100644--- a/src/app/shell/menu/save-actions.ts+++ b/src/app/shell/menu/save-actions.ts@@ -1,13 +1,21 @@import { openVersionDialog, openVersionHistory } from '@/app/cloud/integration'import type { EditorStore } from '@/app/editor/active-store'import { openSaveTo } from '@/app/storage/save-to/session'+import { showsDocument } from '@/app/tabs'++/** Runs a save only while a document is in front: Home and a New file tab have none. */+function onDocument(run: () => void): () => void {+ return () => {+ if (showsDocument()) run()+ }+}export function createSaveMenuActions(store: EditorStore) {return {- save: () => void store.saveFigFile(),- 'save-as': () => void store.saveFigFileAs(),- 'save-to': () => void openSaveTo(store),- 'save-version': () => openVersionDialog(store),- 'version-history': () => openVersionHistory(store)+ save: onDocument(() => void store.saveFigFile()),+ 'save-as': onDocument(() => void store.saveFigFileAs()),+ 'save-to': onDocument(() => void openSaveTo(store)),+ 'save-version': onDocument(() => openVersionDialog(store)),+ 'version-history': onDocument(() => openVersionHistory(store))}}diff --git a/src/app/shell/menu/schema.ts b/src/app/shell/menu/schema.tsindex 8f7377bf7..7278836bf 100644--- a/src/app/shell/menu/schema.ts+++ b/src/app/shell/menu/schema.ts@@ -80,10 +80,10 @@ export const APP_MENU_SCHEMA = [label: 'File',paletteIcon: 'file',items: [- { id: 'new', label: 'New', shortcut: 'MOD+N' },+ { id: 'new', label: 'New Design', shortcut: 'MOD+N' },+ { id: 'new-tab', label: 'New Tab', shortcut: 'MOD+T' },{ id: 'open', label: 'Open…', shortcut: 'MOD+O' },{ id: 'open-recent', label: 'Open Recent', target: 'native' },- { id: 'browse-files', label: 'Browse Files…', handler: 'shell' },{ id: 'open-tour', label: 'Open the Tour', handler: 'shell' },{id: 'diagnostics',diff --git a/src/app/shell/menu/shell.ts b/src/app/shell/menu/shell.tsindex 44a7c9ba0..8fe989584 100644--- a/src/app/shell/menu/shell.ts+++ b/src/app/shell/menu/shell.ts@@ -11,7 +11,6 @@ import {} from '@/app/settings/preferences/native-menu'import { appPreferences } from '@/app/settings/preferences/store'import { useNativeMenuEvents } from '@/app/shell/menu/native-events'-import { browseFiles } from '@/app/shell/menu/navigation'import { APP_MENU_SCHEMA, type AppMenuEntry } from '@/app/shell/menu/schema'import { useAppTheme } from '@/app/shell/theme'import { checkForAppUpdate } from '@/app/shell/updater/check'@@ -53,9 +52,6 @@ export function useShellMenu() {const { setTheme } = useAppTheme()const { updates } = useI18n()const actions: Partial<Record<string, () => void>> = {- 'browse-files': () => {- void import('@/router').then(({ default: router }) => browseFiles(router))- },'open-tour': () => {openTour().catch((error: unknown) => console.error('[Tour] Could not open the tour:', error))},diff --git a/src/app/storage/workspace/create.ts b/src/app/storage/workspace/create.tsindex bbdba43bf..c754b9a75 100644--- a/src/app/storage/workspace/create.ts+++ b/src/app/storage/workspace/create.ts@@ -1,10 +1,18 @@+import type { DocumentKind } from '@open-pencil/scene-graph'+import type { StorageLocation } from '@/app/integrations/storage'import { rememberRecentStorageDocument } from '@/app/recent-files'-import { createTab } from '@/app/tabs'+import { createDocumentTab } from '@/app/tabs'-/** Starts a design that lives in a Cloud workspace or the storage bucket from its first edit. */-export async function createStoredDocument(location: StorageLocation): Promise<void> {- const { store } = createTab()+/**+ * Starts a design or a board that lives in a Cloud workspace or the storage bucket from its first+ * edit.+ */+export async function createStoredDocument(+ location: StorageLocation,+ kind: DocumentKind = 'design'+): Promise<void> {+ const { store } = createDocumentTab(kind)if (!(await store.saveFigFileToStorage(location))) returnconst binding = store.getStorageBinding()if (binding) rememberRecentStorageDocument(binding, store.state.documentName)diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.tsindex 039ad329a..2477585ca 100644--- a/src/app/tabs/index.ts+++ b/src/app/tabs/index.ts@@ -2,11 +2,12 @@ import { promiseTimeout } from '@vueuse/core'import { filename } from 'pathe/utils'import { shallowRef, computed, triggerRef } from 'vue'+import { createDocumentGraph } from '@open-pencil/core'import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'import { figThumbnailPageId, populateFigPage } from '@open-pencil/core/io/formats/fig'import { renderThumbnail } from '@open-pencil/core/io/formats/raster'import { computeAllLayouts } from '@open-pencil/core/layout'-import type { SceneGraph } from '@open-pencil/scene-graph'+import type { DocumentKind, SceneGraph } from '@open-pencil/scene-graph'import { setOpenPencilStore } from '@/app/browser-bridge'import { describeDiagnosticError, recordStorageFailure } from '@/app/diagnostics'@@ -17,6 +18,7 @@ import { requestDocumentClose } from '@/app/document/close/prompt'import { documentAssetReader } from '@/app/document/io/assets'import { readFigDocument } from '@/app/document/io/fig'import { applyImportedDocument } from '@/app/document/io/imported-document'+import { isFigArchiveName } from '@/app/document/io/names'import type { DocumentSourceIdentity } from '@/app/document/io/types'import { getRecoveryStore, type RecoverySnapshotMeta } from '@/app/document/recovery'import { setActiveEditorStore } from '@/app/editor/active-store'@@ -44,7 +46,11 @@ import { createFileOpenCoordinator } from '@/app/tabs/open/coordinator'import { findTabByFileIdentity } from '@/app/tabs/open/identity'import { readStorageDocument } from '@/app/tabs/open/storage'-export type TabKind = 'home' | 'document'+/**+ * Home, pinned first; a New file tab, which offers what to create and the recent files, as+ * Figma's ⌘T and + do, and becomes the document picked there; or a document.+ */+export type TabKind = 'home' | 'new-file' | 'document'export interface Tab {id: string@@ -68,11 +74,17 @@ const activeTabId = shallowRef('')export const activeTab = computed(() => tabsRef.value.find((t) => t.id === activeTabId.value))+/** Whether the tab in front holds a document: Home and a New file tab have none to save. */+export function showsDocument(): boolean {+ return activeTab.value?.kind === 'document'+}+export const allTabs = computed(() =>tabsRef.value.map((t) => ({id: t.id,name: t.store.state.documentName,isHome: t.kind === 'home',+ isNewFile: t.kind === 'new-file',isDirty: t.kind === 'document' && t.store.hasUnsavedChanges(),isPreparing: t.store.state.preparation !== null,preparationProgress: t.store.state.preparation?.progress ?? null,@@ -110,6 +122,29 @@ export function createTab(store?: EditorStore, initialGraph?: SceneGraph): Tab {return tab}+/**+ * Opens an empty document of this kind: a design or a board. Picked in a New file tab, it takes+ * that tab's place; otherwise it gets a tab of its own.+ */+export function createDocumentTab(kind: DocumentKind): Tab {+ const picker = activeTab.value?.kind === 'new-file' ? activeTab.value : undefined+ const tab = createTab(undefined, createDocumentGraph(kind))+ if (picker) {+ const rest = tabsRef.value.filter((entry) => entry !== tab)+ tabsRef.value = rest.map((entry) => (entry === picker ? tab : entry))+ disposeTabStore(picker.store)+ }+ return tab+}++/** Opens a New file tab, as Figma's + and ⌘T do. */+export function openNewFileTab(): Tab {+ const tab: Tab = { id: generateTabId(), store: createEditorStore(), kind: 'new-file' }+ tabsRef.value = [...tabsRef.value, tab]+ activateTab(tab)+ return tab+}+/*** Shows Home, the one tab pinned first that never closes and never turns into a design, as in* Figma's desktop app; it is made the first time it is asked for.@@ -194,6 +229,11 @@ export async function closeTab(tabId: string, unsaved?: 'save' | 'discard'): Proconst closingTab = tabsRef.value[idx]if (closingTab.kind === 'home') return+ // A New file tab holds no document to save or recover.+ if (closingTab.kind === 'new-file') {+ removeTab(closingTab)+ return+ }const choice = unsaved? await confirmDocumentClose(closingTab.store, async () => unsaved): await requestDocumentClose(closingTab.store, closingTab.store.state.documentName)@@ -515,7 +555,7 @@ export async function openFileInNewTab(const existing = await findTabByFileIdentity(tabsRef.value, identity)if (existing) {switchTab(existing.id)- if (path?.toLowerCase().endsWith('.fig')) {+ if (path && isFigArchiveName(path)) {watchOpenedFigCover(path, existing.store)void cacheOpenedFigCover(path, existing.store).catch((error) => {console.warn('[Recent files] Failed to cache the thumbnail', error)@@ -557,7 +597,7 @@ export async function openFileInNewTab(await yieldToUI()load.update({ phase: 'reading', detail: file.name })- const isFig = file.name.toLowerCase().endsWith('.fig')+ const isFig = isFigArchiveName(file.name)let imported: SceneGraphlet sourceFormat: stringif (isFig) {diff --git a/src/components/TabBar.vue b/src/components/TabBar.vueindex 375cf2939..d4dc12230 100644--- a/src/components/TabBar.vue+++ b/src/components/TabBar.vue@@ -6,7 +6,7 @@ import { computed, useTemplateRef, watch } from 'vue'import { useI18n } from '@open-pencil/vue/i18n'import { animationsEnabled } from '@/app/shell/motion'-import { useTabsStore, createTab } from '@/app/tabs'+import { openNewFileTab, useTabsStore } from '@/app/tabs'import PreparationIndicator from '@/components/preparation/tab/PreparationIndicator.vue'import { useScrollOverflow } from '@/components/ui/list/useScrollOverflow'import Tip from '@/components/ui/overlay/Tip.vue'@@ -46,11 +46,11 @@ const modelValue = computed({set: (id: string) => switchTab(id)})-/** A new design in a tab of its own, as Figma's + does; Home stays pinned first. */+/** A New file tab, as Figma's + opens: what to create, and the recent files. */function createNewTab(event: MouseEvent): void {event.preventDefault()if (event.currentTarget instanceof HTMLElement) event.currentTarget.blur()- createTab()+ openNewFileTab()}function onMiddleClick(e: MouseEvent, tabId: string, isHome: boolean) {@@ -100,18 +100,24 @@ function onClose(e: MouseEvent, tabId: string) {<icon-lucide-house v-if="tab.isHome" :class="baseStyles.icon()" /><PreparationIndicator v-else-if="tab.isPreparing" :progress="tab.preparationProgress" /><icon-lucide-file v-else :class="baseStyles.icon()" />- <span v-if="!tab.isHome" :class="baseStyles.label()">{{ tab.name }}</span>+ <span v-if="!tab.isHome" :class="baseStyles.label()">{{+ tab.isNewFile ? files.newFile : tab.name+ }}</span><Tip v-if="tab.isDirty" :label="files.unsavedChanges" side="bottom"><span role="img" :aria-label="files.unsavedChanges" :class="baseStyles.dirtyDot()" /></Tip></TabsTrigger>- <Tip v-if="!tab.isHome" :label="files.closeTab({ name: tab.name })" side="bottom">+ <Tip+ v-if="!tab.isHome"+ :label="files.closeTab({ name: tab.isNewFile ? files.newFile : tab.name })"+ side="bottom"+ ><buttontype="button"data-test-id="tabbar-close":class="tabBarStyles({ active: tab.isActive }).close()":data-active="tab.isActive || undefined"- :aria-label="files.closeTab({ name: tab.name })"+ :aria-label="files.closeTab({ name: tab.isNewFile ? files.newFile : tab.name })"tabindex="-1"@click="onClose($event, tab.id)">@@ -136,11 +142,11 @@ function onClose(e: MouseEvent, tabId: string) {<icon-lucide-chevron-right v-if="overflowEnd" :class="baseStyles.scrollIcon()" /><icon-lucide-chevron-left v-else :class="baseStyles.scrollIcon()" /></button>- <Tip :label="files.newDesign" side="bottom">+ <Tip :label="files.newFile" side="bottom"><buttontype="button"data-test-id="tabbar-new"- :aria-label="files.newDesign"+ :aria-label="files.newFile":class="baseStyles.newTab()"@click="createNewTab">diff --git a/src/components/home/HomeWorkspace.vue b/src/components/home/HomeWorkspace.vueindex 00976735e..70f502c91 100644--- a/src/components/home/HomeWorkspace.vue+++ b/src/components/home/HomeWorkspace.vue@@ -2,6 +2,7 @@import { useLocalStorage } from '@vueuse/core'import { computed, ref, shallowRef } from 'vue'+import type { DocumentKind } from '@open-pencil/scene-graph'import { useDocumentWorkspace } from '@open-pencil/vue/document/workspace'import { useI18n } from '@open-pencil/vue/i18n'@@ -38,7 +39,7 @@ import HomeSidebar from '@/components/home/sidebar/HomeSidebar.vue'import AppButton from '@/components/ui/button/AppButton.vue'import IconButton from '@/components/ui/button/IconButton.vue'-const emit = defineEmits<{ 'new-document': [] }>()+const emit = defineEmits<{ 'new-document': [kind: DocumentKind] }>()const { locale, storage, files, common, settings, credentials } = useI18n()const view = useLocalStorage<'grid' | 'list'>('open-pencil:home-files-view', 'grid')const query = ref('')@@ -46,11 +47,11 @@ const openError = ref<string | null>(null)const storageConfigured = ref(storagePreferencesComplete(activeStorageProviderID.value))const places = useHomeLocations()-/** A new design lands in the place Home shows: a Cloud workspace, the bucket, or a local file. */-function newDocument() {+/** A new document lands in the place Home shows: a Cloud workspace, the bucket, or a local file. */+function newDocument(kind: DocumentKind) {const target = newDesignTarget.value- if (target) void createStoredDocument(target.location)- else emit('new-document')+ if (target) void createStoredDocument(target.location, kind)+ else emit('new-document', kind)}const workspace = useRecentFilesWorkspace()diff --git a/src/components/home/search/HomeSearchActions.vue b/src/components/home/search/HomeSearchActions.vueindex 22cf89806..2d76d2915 100644--- a/src/components/home/search/HomeSearchActions.vue+++ b/src/components/home/search/HomeSearchActions.vue@@ -1,7 +1,10 @@<script setup lang="ts">import { templateRef } from '@vueuse/core'import { nextTick, watch } from 'vue'+import IconLucidePenTool from '~icons/lucide/pen-tool'+import IconLucideStickyNote from '~icons/lucide/sticky-note'+import type { DocumentKind } from '@open-pencil/scene-graph'import { useViewportKind } from '@open-pencil/vue/editor/viewport-kind'import { useI18n } from '@open-pencil/vue/i18n'@@ -9,12 +12,19 @@ import { openFileDialog } from '@/app/shell/menu/use'import { activeTab } from '@/app/tabs'import AppButton from '@/components/ui/button/AppButton.vue'import AppInput from '@/components/ui/input/AppInput.vue'+import Tip from '@/components/ui/overlay/Tip.vue'import HomeJoinRoom from './HomeJoinRoom.vue'/** The place a new design is created in, when it is not a local file. */const { destination = null } = defineProps<{ destination?: string | null }>()-const emit = defineEmits<{ 'new-document': [] }>()+const emit = defineEmits<{ 'new-document': [kind: DocumentKind] }>()++/** What Home offers to create, side by side, as Figma's Home and New file tab offer theirs. */+const CREATE_CHOICES = [+ { kind: 'design', label: 'createDesign', icon: IconLucidePenTool },+ { kind: 'board', label: 'createBoard', icon: IconLucideStickyNote }+] as const satisfies ReadonlyArray<{ kind: DocumentKind; label: string; icon: unknown }>const query = defineModel<string>({ required: true })const { menu, files } = useI18n()const { isMobile, isTouch } = useViewportKind()@@ -22,8 +32,9 @@ const searchInput = templateRef<{ focus: (options?: FocusOptions) => void }>('sefunction focusSearch(onCleanup: (cleanup: () => void) => void): void {// Focusing the field would raise a touch screen's keyboard over the page.- if (isTouch.value || activeTab.value?.kind !== 'home') return- const tabId = activeTab.value.id+ const tab = activeTab.value+ if (isTouch.value || !tab || tab.kind === 'document') return+ const tabId = tab.idconst previousFocus = document.activeElementif (previousFocus instanceof HTMLElement && previousFocus.closest('[role="tablist"]')) returnlet cancelled = false@@ -67,24 +78,30 @@ watch(<AppButton:size="isTouch ? 'lg' : 'md'"variant="outline"+ class="col-span-2 md:col-span-1"data-test-id="home-open-file"@click="openFileDialog"><template #leading><icon-lucide-folder-open class="size-3.5" /></template>{{ menu.open }}</AppButton>- <AppButton- :size="isTouch ? 'lg' : 'md'"- color="primary"- variant="solid"- data-test-id="home-new-document"- @click="emit('new-document')"+ <Tip+ v-for="choice in CREATE_CHOICES"+ :key="choice.kind"+ :label="destination ? files.createIn({ place: destination }) : ''"+ :disabled="!destination"+ side="bottom">- <template #leading><icon-lucide-plus class="size-3.5" /></template>- <span class="max-w-56 truncate">{{- destination ? files.newDesignIn({ place: destination }) : files.newDesign- }}</span>- </AppButton>+ <AppButton+ :size="isTouch ? 'lg' : 'md'"+ variant="outline"+ :data-test-id="`home-new-${choice.kind}`"+ @click="emit('new-document', choice.kind)"+ >+ <template #leading><component :is="choice.icon" class="size-3.5" /></template>+ {{ files[choice.label] }}+ </AppButton>+ </Tip></div></div></template>diff --git a/src/components/toolbar/EditorToolbar.vue b/src/components/toolbar/EditorToolbar.vueindex 130ec83b8..08e018e04 100644--- a/src/components/toolbar/EditorToolbar.vue+++ b/src/components/toolbar/EditorToolbar.vue@@ -30,13 +30,14 @@ const { menu } = useI18n()const toolLabels = useToolLabels()-const toolShortcuts = toolShortcutLabels()+const profile = computed(() => resolveEditorProfile(store.state))+const toolShortcuts = computed(() => toolShortcutLabels(profile.value.toolKeys))const items = computed(() => {const layout = appPreferences.value.toolbarreturn toolbarItems(- toolbarLayoutFor(layout, resolveEditorProfile(store.state).tools),+ toolbarLayoutFor(layout, profile.value.tools),toolLabels.value,- toolShortcuts+ toolShortcuts.value)})const tools = computed(() =>@@ -50,7 +51,7 @@ const actionItems = computed(() =>* a read-only document leaves them out, as it does the buttons.*/const hiddenActions = computed(() =>- !resolveEditorProfile(store.state).edits+ !profile.value.edits? []: TOOLBAR_ACTIONS.filter((action) => !actionItems.value.includes(action)))diff --git a/src/views/WorkspaceView.vue b/src/views/WorkspaceView.vueindex 16c28586c..63c952386 100644--- a/src/views/WorkspaceView.vue+++ b/src/views/WorkspaceView.vue@@ -25,7 +25,6 @@ import { openWebLinkFromLocation, withoutWebLinkParams } from '@/app/document/ioimport { setActiveEditorStore } from '@/app/editor/active-store'import { focusNodesByName } from '@/app/editor/selection/focus'import { notificationMessages } from '@/app/i18n/notifications'-import { recentFilesAvailable } from '@/app/recent-files/preferences'import { appRuntimeConfig } from '@/app/runtime/config'import { useDocumentDrop } from '@/app/shell/document-drop'import { useKeyboard } from '@/app/shell/keyboard/use'@@ -35,6 +34,7 @@ import {activeTab,createHomeTab,ensureHomeTab,+ createDocumentTab,createTab,getActiveStore,getTabsSnapshot,@@ -54,7 +54,7 @@ import HomeWorkspace from '@/components/home/HomeWorkspace.vue'import RenameSelectionDialog from '@/components/selection/RenameSelectionDialog.vue'import LoadingScreen from '@/components/shell/LoadingScreen.vue'import TabBar from '@/components/TabBar.vue'-import { IS_BROWSER, IS_CLOUD_SITE } from '@/constants'+import { IS_BROWSER } from '@/constants'const route = useRoute()/**@@ -78,10 +78,10 @@ watch()const router = useRouter()const createdInitialTab = tabCount() === 0-// Home is pinned first everywhere but tests and the demo, and opens in front where it lists-// something: recent files, or the workspaces of the Cloud server that serves the editor.+// Home is pinned first everywhere but tests and the demo, and opens in front, as Figma's does:+// it is where a design or a board is started, with or without recent files to list.const pinHome = !appRuntimeConfig.test && !route.meta.demo-const showHomeFirst = route.path === '/' && pinHome && (recentFilesAvailable() || IS_CLOUD_SITE)+const showHomeFirst = route.path === '/' && pinHome// The view stays mounted from /demo to /, so Home is pinned once a route that has it is reached.watch(() => !appRuntimeConfig.test && !route.meta.demo,@@ -301,9 +301,16 @@ onUnmounted(() => {<RenameSelectionDialog /><CommandPalette /><TabBar />- <HomeWorkspace v-show="activeTab?.kind === 'home'" @new-document="createTab()" />+ <HomeWorkspace+ v-show="activeTab && activeTab.kind !== 'document'"+ @new-document="createDocumentTab"+ /><CloudVersionDialog />- <EditorWorkspace v-if="shown && shown.tab.kind !== 'home'" :key="shown.key" :tab="shown.tab" />+ <EditorWorkspace+ v-if="shown && shown.tab.kind === 'document'"+ :key="shown.key"+ :tab="shown.tab"+ /><LoadingScreen v-if="openingCloudLink" /></div></template>diff --git a/tests/app/editor/toolbar/layout.test.ts b/tests/app/editor/toolbar/layout.test.tsindex 01cf9b8fc..33a62f1c5 100644--- a/tests/app/editor/toolbar/layout.test.ts+++ b/tests/app/editor/toolbar/layout.test.ts@@ -1,6 +1,7 @@import { describe, expect, test } from 'bun:test'-import { resolveEditorProfile } from '@open-pencil/core'+import { BOARD_TOOL_SHORTCUTS, resolveEditorProfile, TOOL_SHORTCUTS } from '@open-pencil/core'+import type { DocumentKind } from '@open-pencil/scene-graph'import {combineToolbarEntry,@@ -21,7 +22,7 @@ import {import { toolShortcutLabels } from '@/app/editor/toolbar/shortcuts'const SHAPES: ToolbarEntry[] = ['RECTANGLE', 'LINE', 'ELLIPSE', 'POLYGON', 'STAR']-const SHORTCUTS = toolShortcutLabels('mac')+const SHORTCUTS = toolShortcutLabels(TOOL_SHORTCUTS, 'mac')const LABELS = { ...SHORTCUTS }function layout(groups: ToolbarEntry[][], hidden: ToolbarEntry[] = []): ToolbarLayout {@@ -243,8 +244,12 @@ describe('dragging', () => {})describe('toolbarLayoutFor', () => {- const profileTools = (readOnly: boolean) =>- resolveEditorProfile({ canvasView: { id: 'edit' }, hostRestrictions: { readOnly } }).tools+ const profileTools = (readOnly: boolean, documentKind: DocumentKind = 'design') =>+ resolveEditorProfile({+ documentKind,+ canvasView: { id: 'edit' },+ hostRestrictions: { readOnly }+ }).toolstest('keeps the whole layout when the profile offers every tool', () => {const base = layout([['SELECT', 'HAND'], ['FRAME'], ['insert-icon']])@@ -262,4 +267,34 @@ describe('toolbarLayoutFor', () => {])expect(keys(DEFAULT_TOOLBAR_LAYOUT.groups)).toEqual([['SELECT'], ['HAND']])})++ test('shows every tool a board offers, even those the layout hides', () => {+ const board = toolbarLayoutFor(DEFAULT_TOOLBAR_LAYOUT, profileTools(false, 'board'))+ expect(+ toolbarItems(board, LABELS, SHORTCUTS).map((item) => item.kind === 'tool' && item.tool.key)+ ).toEqual([+ 'SELECT',+ 'SECTION',+ 'TEXT',+ 'STICKY',+ 'SHAPE_WITH_TEXT',+ 'CONNECTOR',+ 'HAND',+ 'COMMENT'+ ])+ })+})++describe('toolShortcutLabels', () => {+ test('names each tool by the first key that picks it in the profile', () => {+ const design = toolShortcutLabels(TOOL_SHORTCUTS, 'mac')+ const board = toolShortcutLabels(BOARD_TOOL_SHORTCUTS, 'mac')+ expect([+ design.RECTANGLE,+ design.STICKY,+ board.RECTANGLE,+ board.STICKY,+ board.SHAPE_WITH_TEXT+ ]).toEqual(['R', '', '', 'S', 'R'])+ })})diff --git a/tests/e2e/app/recent-files.spec.ts b/tests/e2e/app/recent-files.spec.tsindex b56642109..8dced3b89 100644--- a/tests/e2e/app/recent-files.spec.ts+++ b/tests/e2e/app/recent-files.spec.ts@@ -67,7 +67,7 @@ test.describe('on a phone', () => {await expect(search).not.toBeFocused()await expect(search).toHaveAttribute('placeholder', 'Search files…')await expect(page.getByTestId('home-open-file')).toBeVisible()- await expect(page.getByTestId('home-new-document')).toBeVisible()+ await expect(page.getByTestId('home-new-design')).toBeVisible()await expect(page.getByTestId('recent-files-home')).toHaveJSProperty('scrollWidth',await page.getByTestId('recent-files-home').evaluate((element) => element.clientWidth)@@ -93,7 +93,7 @@ test('opens to the recent-files home and starts a new document', async ({ page }await expect(page.getByText('No recent files yet')).toBeVisible()await expect(page.getByTestId('tabbar-tab')).toHaveCount(1)- await page.getByTestId('home-new-document').click()+ await page.getByTestId('home-new-design').click()await expect(page.getByTestId('recent-files-home')).toBeHidden()const tab = page.getByTestId('tabbar-tab')@@ -105,7 +105,7 @@ test('opens to the recent-files home and starts a new document', async ({ page }await expect(page.getByTestId('recent-files-home')).toBeVisible()await expect(page.getByTestId('tabbar-tab')).toHaveCount(2)- await expect(page.getByTestId('tabbar-tab').last()).toContainText('New tab')+ await expect(page.getByTestId('tabbar-tab').last()).toContainText('New file')await expect(page.getByLabel('Search files…')).toBeFocused()await expect(page.getByTestId('tabbar-close')).toHaveCount(2)diff --git a/tests/e2e/canvas/labels/name-editing.spec.ts b/tests/e2e/canvas/labels/name-editing.spec.tsindex 33c6deb80..f63c512ab 100644--- a/tests/e2e/canvas/labels/name-editing.spec.ts+++ b/tests/e2e/canvas/labels/name-editing.spec.ts@@ -86,6 +86,36 @@ test('double-clicking a section title renames it inline', async () => {.toBe('Primitives')})+// Figma shows only the field while a name is renamed: a shorter name leaves none of the old one.+test('a section title being renamed leaves the canvas title to the field', async () => {+ await editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ store.graph.createNode('SECTION', store.state.currentPageId, {+ id: 'section-rename-shorter',+ name: 'Section 1',+ x: 120,+ y: 160,+ width: 280,+ height: 180+ })+ store.requestRender()+ })+ await editor.canvas.waitForRender()++ const canvas = editor.page.getByTestId('canvas-element')+ await canvas.dblclick({ position: { x: 128, y: 142 } })+ const input = editor.page.getByRole('textbox', { name: 'Layer name' })+ await input.fill('Se')+ await editor.canvas.waitForRender()+ const box = await canvas.boundingBox()+ if (!box) throw new Error('Canvas has no box')+ await expect(editor.page).toHaveScreenshot('section-rename-shorter.png', {+ clip: { x: box.x + 110, y: box.y + 126, width: 160, height: 32 }+ })+ await input.press('Escape')+})+// Figma desktop 126: the name above a frame or component renames in place and stays selected.test('double-clicking a frame or component name renames it inline and keeps it selected', async () => {const ids = await editor.page.evaluate(() => {diff --git a/tests/e2e/canvas/labels/name-editing.spec.ts-snapshots/section-rename-shorter-openpencil-darwin.png b/tests/e2e/canvas/labels/name-editing.spec.ts-snapshots/section-rename-shorter-openpencil-darwin.pngnew file mode 100644index 000000000..1bd1aae19Binary files /dev/null and b/tests/e2e/canvas/labels/name-editing.spec.ts-snapshots/section-rename-shorter-openpencil-darwin.png differdiff --git a/tests/e2e/clipboard/tauri-plugin-routing.spec.ts b/tests/e2e/clipboard/tauri-plugin-routing.spec.tsindex 6157b7872..ea7e93475 100644--- a/tests/e2e/clipboard/tauri-plugin-routing.spec.ts+++ b/tests/e2e/clipboard/tauri-plugin-routing.spec.ts@@ -12,7 +12,7 @@ type PageChildSummary = {async function createTauriEditorPage(page: Page) {const clipboard = await installTauriClipboardMock(page)await page.goto('/')- await page.getByTestId('home-new-document').click()+ await page.getByTestId('home-new-design').click()const canvas = new CanvasHelper(page)await canvas.waitForInit()return { canvas, clipboard }diff --git a/tests/engine/app/shell/menu/schema.test.ts b/tests/engine/app/shell/menu/schema.test.tsindex ba01ffb30..ff3c35ff1 100644--- a/tests/engine/app/shell/menu/schema.test.ts+++ b/tests/engine/app/shell/menu/schema.test.ts@@ -49,7 +49,6 @@ describe('APP_MENU_SCHEMA', () => {).filter((entry) => !('type' in entry) && entry.handler === 'shell')expect(shellEntries.map((entry) => ('type' in entry ? '' : entry.id))).toEqual([- 'browse-files','open-tour','diagnostics','settings',@@ -63,13 +62,15 @@ describe('APP_MENU_SCHEMA', () => {])})- test('browses and saves to places from one File menu item each', () => {+ // As in Figma, files are browsed on Home and in a New tab, so the File menu creates and saves.+ test('starts documents and saves to places from the File menu', () => {const fileMenu = APP_MENU_SCHEMA.find((group) => group.label === 'File')const ids = (fileMenu ? actionItems(fileMenu.items) : []).map((entry) =>'type' in entry ? '' : entry.id)- expect(ids).toContain('browse-files')+ expect(ids.slice(0, 3)).toEqual(['new', 'new-tab', 'open'])+ expect(ids).not.toContain('browse-files')expect(ids).toContain('save-to')expect(ids).not.toContain('save-to-cloud')})diff --git a/tests/engine/tauri/document-io.test.ts b/tests/engine/tauri/document-io.test.tsindex 5574559c3..c8de4e3c5 100644--- a/tests/engine/tauri/document-io.test.ts+++ b/tests/engine/tauri/document-io.test.ts@@ -85,6 +85,21 @@ describe('Tauri document IO helpers', () => {return '/tmp/Untitled.fig'})- await expect(chooseTauriFigSavePath()).resolves.toBe('/tmp/Untitled.fig')+ await expect(chooseTauriFigSavePath('design')).resolves.toBe('/tmp/Untitled.fig')+ })++ test('saves a board as a FigJam .jam', async () => {+ await mockTauriIPC((cmd, args) => {+ expect(cmd).toBe('plugin:dialog|save')+ expect(args).toEqual({+ options: {+ defaultPath: 'Untitled.jam',+ filters: [{ name: 'FigJam board', extensions: ['jam'] }]+ }+ })+ return '/tmp/Untitled.jam'+ })++ await expect(chooseTauriFigSavePath('board')).resolves.toBe('/tmp/Untitled.jam')})})diff --git a/tests/engine/tauri/file-actions.test.ts b/tests/engine/tauri/file-actions.test.tsindex 20d3a59ce..fd968868d 100644--- a/tests/engine/tauri/file-actions.test.ts+++ b/tests/engine/tauri/file-actions.test.ts@@ -20,7 +20,18 @@ describe('Tauri file actions', () => {filters: [{name: 'Design file',- extensions: ['fig', 'pen', 'drawio', 'dio', 'mmd', 'mermaid', 'html', 'htm', 'xhtml']+ extensions: [+ 'fig',+ 'jam',+ 'pen',+ 'drawio',+ 'dio',+ 'mmd',+ 'mermaid',+ 'html',+ 'htm',+ 'xhtml'+ ]}],multiple: truediff --git a/tests/engine/text/editor.test.ts b/tests/engine/text/editor.test.tsindex 5db145583..94fe127b3 100644--- a/tests/engine/text/editor.test.ts+++ b/tests/engine/text/editor.test.ts@@ -328,6 +328,37 @@ describe('TextEditor', () => {expect(ranges).toEqual([[1, 3]])})+ // Skia lays out an empty line below a closing line break; typing starts there, so does the caret.+ test('places the caret after a closing line break at the start of the empty line below', () => {+ const lines = (closing: boolean) => [+ asDouble<LineMetrics>({+ baseline: 13,+ ascent: 13,+ height: 17,+ left: 0,+ isHardBreak: true,+ endIncludingNewline: 4+ }),+ asDouble<LineMetrics>({+ baseline: 30,+ ascent: 13,+ height: 17,+ left: 0,+ isHardBreak: true,+ endIndex: closing ? 4 : 7+ })+ ]+ const native = (closing: boolean) => ({+ getHeight: () => 34,+ getGlyphInfoAt: () => null,+ getLineMetrics: () => lines(closing),+ getRectsForRange: () => [asDouble<RectWithDirection>({ rect: [24, 17, 30, 34] })]+ })+ expect(layoutOf(native(true), 4).getCaretRect(4, false)).toEqual({ x: 0, top: 17, bottom: 34 })+ // After text on the last line, the caret follows that text.+ expect(layoutOf(native(false), 7).getCaretRect(7, false)?.x).toBe(30)+ })+test('moveRight at end stays', () => {const { editor } = createEditor()editor.moveRight()diff --git a/tests/engine/vue/input/draw.test.ts b/tests/engine/vue/input/draw.test.tsindex a584c7374..7cad76c9c 100644--- a/tests/engine/vue/input/draw.test.ts+++ b/tests/engine/vue/input/draw.test.ts@@ -50,6 +50,31 @@ describe('draw creation previews', () => {}})+ // FigJam: a drag-drawn shape's box lands on the board's 16-unit dot grid.+ test('rounds both corners to the 16-unit grid on a board', () => {+ const editor = createEditor()+ try {+ editor.setDocumentKind('board')+ editor.setTool('SHAPE_WITH_TEXT')+ const state: { drag: DragState | null } = { drag: null }+ startShapeDraw(3.3, 50.4, editor, (drag) => {+ state.drag = drag+ })+ const drag = state.drag+ if (drag?.type !== 'draw') throw new Error('Expected drawing interaction')+ handleDrawMove(drag, 30.7, 71.8, false)+ drag.commit()+ expect(editor.graph.getNode(drag.nodeId)).toMatchObject({+ x: 0,+ y: 48,+ width: 32,+ height: 16+ })+ } finally {+ editor.dispose()+ }+ })+test('graph replacement discards pending draw batches without replaying or deleting history', () => {const editor = createEditor()try {diff --git a/tests/engine/vue/input/snap-guides.test.ts b/tests/engine/vue/input/snap-guides.test.tsindex a0ec73a61..7bf87c3c1 100644--- a/tests/engine/vue/input/snap-guides.test.ts+++ b/tests/engine/vue/input/snap-guides.test.ts@@ -22,6 +22,21 @@ describe('move snap guide presentation', () => {expect(result.correction.y).toBeCloseTo(0.4)})+ // FigJam ends a move with the top-left on the board's 16-unit dot grid.+ test('a board rounds a move to its 16-unit grid', () => {+ const editor = createEditor()+ editor.setDocumentKind('board')+ editor.state.snappingPreferences = { geometry: false, objects: true, pixelGrid: true }+ const result = resolveObjectPixelSnap(+ new Set(['sticky']),+ { x: 10.4, y: 41, width: 240, height: 240 },+ [],+ editor+ )+ expect(result.correction.x).toBeCloseTo(5.6)+ expect(result.correction.y).toBeCloseTo(7)+ })+test('pixel rounding adjusts a lone frame without drawing self-alignment guides', () => {const pixel = computePixelGridSnap({ x: 10.25, y: 20.4, width: 100, height: 80 })expect(pixel.delta).toEqual({ x: -0.25, y: -0.3999999999999986 })diff --git a/tests/helpers/tauri/fig-export-fixture.ts b/tests/helpers/tauri/fig-export-fixture.tsindex 24e3eab36..faa60f76d 100644--- a/tests/helpers/tauri/fig-export-fixture.ts+++ b/tests/helpers/tauri/fig-export-fixture.ts@@ -6,13 +6,17 @@ installTauriMockWindow()mockIPC((cmd, args) => {if (cmd !== 'build_fig_file') throw new Error(`Unexpected command: ${cmd}`)- const payload = args as {- schemaDeflated: number[]- kiwiData: number[]- thumbnailPng: number[]- metaJson: string- images: Array<{ name: string; data: number[] }>+ const { file: payload } = args as {+ file: {+ schemaDeflated: number[]+ kiwiData: number[]+ thumbnailPng: number[]+ metaJson: string+ images: Array<{ name: string; data: number[] }>+ board: boolean+ }}+ if (payload.board) throw new Error('a new design is no board')if (payload.schemaDeflated.length === 0) throw new Error('schemaDeflated is empty')if (payload.kiwiData.length === 0) throw new Error('kiwiData is empty')if (payload.thumbnailPng.length === 0) throw new Error('thumbnailPng is empty')diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txtindex 5bcdeb482..26a86fd42 100644--- a/tools/checks/i18n/translation-baseline.txt+++ b/tools/checks/i18n/translation-baseline.txt@@ -23,6 +23,8 @@ de:diagnostics.categoryMCPde:diagnostics.categoryRendererde:diagnostics.durationMsde:editor.cornerRadius+de:files.createBoard+de:files.createDesignde:menu.textde:panels.alphade:panels.blendModeNormal@@ -138,6 +140,7 @@ fr:designCheck.scopeDocumentfr:designCheck.scopePagefr:designCheck.suggestionsfr:diagnostics.title+fr:files.createDesignfr:pages.pageNamefr:pages.pagesfr:panels.alpha@@ -216,6 +219,7 @@ it:diagnostics.categoryMCPit:diagnostics.categoryRendererit:diagnostics.categoryRuntimeit:diagnostics.durationMs+it:files.createDesignit:menu.fileit:panels.aiit:panels.autodiff --git a/tools/checks/lint/src/rules/policy.ts b/tools/checks/lint/src/rules/policy.tsindex 3171b84cd..319fcb6cf 100644--- a/tools/checks/lint/src/rules/policy.ts+++ b/tools/checks/lint/src/rules/policy.ts@@ -152,16 +152,33 @@ function fixedKey(key: TSESTree.Node, computed: boolean): string | null {const CORE_PROFILE = ['/packages/core/src/editor/views/', '/packages/core/src/editor/state/']+/** The app's own services, as opposed to its views and components. */+function isAppService(file: string): boolean {+ return file.includes('/src/app/') && !file.includes('/packages/')+}++/** Front ends: the Vue SDK, the app's views and components, and the docs site's theme. */+function isFrontEnd(file: string): boolean {+ return (+ file.includes('/packages/vue/src/') ||+ (!file.includes('/packages/') && file.includes('/src/') && !isAppService(file)) ||+ file.includes('/packages/docs/.vitepress/theme/')+ )+}+/*** 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.+ * own them all, the read-only module applies the restrictions, the app, as the host, sets them,+ * and the document's kind is the graph's own field, which formats save; front ends read the+ * profile instead.*/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/'))+ isAppService(file),+ documentKind: (file) => !isFrontEnd(file)}/** The fixed key a template member expression reads (`a.key`, `a['key']`), or null. */diff --git a/tools/checks/lint/tests/editor-profile-inputs.test.ts b/tools/checks/lint/tests/editor-profile-inputs.test.tsindex b1c09aca2..5bce59dc4 100644--- a/tools/checks/lint/tests/editor-profile-inputs.test.ts+++ b/tools/checks/lint/tests/editor-profile-inputs.test.ts@@ -88,6 +88,23 @@ describe('no-editor-profile-inputs', () => {expect(ruleDiagnostics(await lint(source, rules, path), rule)).toHaveLength(0)})+ const kind = "export const board = editor.state.documentKind === 'board'"++ test.each(['packages/vue/src/canvas/useCanvasInput.ts', 'src/components/toolbar/Toolbar.ts'])(+ 'rejects reading the document kind in the front end %s',+ async (path) => {+ expect(ruleDiagnostics(await lint(kind, rules, path), rule)).toHaveLength(1)+ }+ )++ test.each([+ 'packages/fig/src/archive.ts',+ 'packages/core/src/editor/document-settings.ts',+ 'src/app/editor/session/create.ts'+ ])('accepts reading the document kind in %s, which keeps or saves it', async (path) => {+ expect(ruleDiagnostics(await lint(kind, 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)