Skip to content

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

feat: FigJam's dot grid, click depth, Shift+arrow, and R on boards (#1627)

Danila Poyarkov0e1655e5ae30
diff --git a/changes/1627/added.md b/changes/1627/added.md
new file mode 100644
index 000000000..c64cb1aba
--- /dev/null
+++ b/changes/1627/added.md
@@ -0,0 +1,2 @@
+- Boards draw FigJam's dot grid under their layers and show no pixel grid; a click inside a frame selects the frame, Shift+arrow moves to the next 16-unit grid line, R arms a square shape, a collaboration room shares that a document is a board, and boards have no design lint.
+- Sticky notes, shapes, and connectors keep FigJam's fixed choices: the Design panel offers only their own sections, and design lint leaves them out.
diff --git a/packages/core/src/canvas/page/background.ts b/packages/core/src/canvas/page/background.ts
new file mode 100644
index 000000000..09c2c7c75
--- /dev/null
+++ b/packages/core/src/canvas/page/background.ts
@@ -0,0 +1,75 @@
+import type { Canvas } from 'canvaskit-wasm'
+
+import type { Vector } from '@open-pencil/scene-graph/primitives'
+
+import type { SkiaRenderer } from '#core/canvas/renderer'
+
+/** FigJam's dots, #C4C4C4, as Figma desktop draws them on a board's #F5F5F5 page. */
+const DOT_COLOR = 196 / 255
+
+/** A dot spans 2 canvas units, as in FigJam, but never less than this many screen pixels. */
+const DOT_DIAMETER_UNITS = 2
+const DOT_MIN_DIAMETER = 1.35
+
+/** FigJam doubles the dot spacing as it zooms out, keeping dots at least this far apart on screen. */
+const DOT_MIN_SPACING = 8
+
+/** One dot per grid point, decided per device pixel, so the grid is a single draw at any zoom. */
+const DOT_GRID_SHADER = `
+uniform float2 origin;
+uniform float pitch;
+uniform float radius;
+uniform float shade;
+
+half4 main(float2 position) {
+ float2 offset = position - origin;
+ float2 cell = offset - pitch * floor(offset / pitch + 0.5);
+ float alpha = clamp(radius + 0.5 - length(cell), 0.0, 1.0);
+ return half4(shade * alpha, shade * alpha, shade * alpha, alpha);
+}
+`
+
+/** The spacing FigJam shows at a zoom: the board grid, doubled until the dots stand apart. */
+export function dotGridSpacing(grid: number, zoom: number): number {
+ let spacing = grid
+ while (spacing * zoom < DOT_MIN_SPACING) spacing *= 2
+ return spacing
+}
+
+/**
+ * Paints the page under its layers: its colour and, on a board, FigJam's dots. The canvas is
+ * untransformed, in device pixels; `origin` is where canvas point (0, 0) falls and `scale` how
+ * many device pixels a canvas unit covers.
+ */
+export function paintPageBackground(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ origin: Vector,
+ scale: number
+): void {
+ canvas.clear(r.ck.Color4f(r.pageColor.r, r.pageColor.g, r.pageColor.b, 1))
+ if (r.pageDotGrid === null) return
+ if (!r.shaders.dotGridEffect) {
+ let error = ''
+ r.shaders.dotGridEffect = r.ck.RuntimeEffect.Make(DOT_GRID_SHADER, (message) => {
+ error = message
+ })
+ if (!r.shaders.dotGridEffect) throw new Error(`Cannot compile the dot grid: ${error}`)
+ }
+ const zoom = scale / r.dpr
+ const pitch = dotGridSpacing(r.pageDotGrid, zoom) * scale
+ const diameter = Math.max(DOT_DIAMETER_UNITS * zoom, DOT_MIN_DIAMETER) * r.dpr
+ const shader = r.shaders.dotGridEffect.makeShader([
+ origin.x,
+ origin.y,
+ pitch,
+ diameter / 2,
+ DOT_COLOR
+ ])
+ // Skia scales a shader by the paint's alpha, which earlier drawing may have left translucent.
+ r.auxFill.setAlphaf(1)
+ r.auxFill.setShader(shader)
+ canvas.drawPaint(r.auxFill)
+ r.auxFill.setShader(null)
+ shader.delete()
+}
diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.ts
index fa0ecc382..a8ea42bf6 100644
--- a/packages/core/src/canvas/renderer.ts
+++ b/packages/core/src/canvas/renderer.ts
@@ -144,6 +144,8 @@ export class SkiaRenderer {
worldViewport = { x: 0, y: 0, w: 0, h: 0 }
pageId: string | null = null
pageColor = CANVAS_BG_COLOR
+ /** The board grid the page's dots follow, in canvas units, or null for a page without dots. */
+ pageDotGrid: number | null = null
showRulers = true
rulerTheme: RulerTheme | null = null
/** Selection chrome, set from editor state each frame through {@link setSelectionTheme}. */
diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.ts
index 9a946a70c..6062b6eb9 100644
--- a/packages/core/src/canvas/renderer/pipeline.ts
+++ b/packages/core/src/canvas/renderer/pipeline.ts
@@ -4,10 +4,12 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import { computeDescendantVisualBounds } from '@open-pencil/scene-graph/geometry'
import { needsImagePreviews } from '#core/canvas/images/previews'
+import { paintPageBackground } from '#core/canvas/page/background'
import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'
import { playIslandRoots } from '#core/editor/play/islands'
import type { EditorState } from '#core/editor/types'
import { resolveEditorProfile } from '#core/editor/views/profile'
+import type { EditorProfile } from '#core/editor/views/types'
import { emitNavigationTrace } from '#core/profiler'
import { drawChromePass, drawLabelPass, drawOverlayPass } from './overlay-pass'
@@ -37,6 +39,11 @@ export function renderSceneToCanvas(
export type RenderLayer = 'full' | 'scene' | 'overlays'
+/** Whether the pixel grid shows: on an edited canvas whose profile has one, unless turned off. */
+function showsPixelGrid(profile: EditorProfile, state: EditorState): boolean {
+ return profile.editChrome && profile.pixelGrid && state.showPixelGrid !== false
+}
+
export function renderFromEditorState(
r: SkiaRenderer,
state: EditorState,
@@ -80,7 +87,9 @@ export function renderFromEditorState(
r.pageId = state.currentPageId
r.navigationPhase = state.navigation.phase
r.navigationGeneration = state.navigation.generation
- const { editChrome, live, edits } = resolveEditorProfile(state)
+ const profile = resolveEditorProfile(state)
+ const { editChrome, live, edits } = profile
+ r.pageDotGrid = profile.dotGrid
r.editHandles = edits
render(
r,
@@ -90,7 +99,7 @@ export function renderFromEditorState(
playing: !editChrome,
playIslands: live ? new Set(playIslandRoots(graph, state.currentPageId)) : undefined,
hoveredNodeId: editChrome ? state.hoveredNodeId : null,
- showPixelGrid: editChrome && state.showPixelGrid !== false,
+ showPixelGrid: showsPixelGrid(profile, state),
gradientEdit: state.gradientEdit,
transforming: state.transforming,
measurementMode: state.measurementMode,
@@ -260,7 +269,7 @@ export function render(
if (layer === 'overlays') {
canvas.clear(r.ck.Color4f(0, 0, 0, 0))
} else {
- canvas.clear(r.ck.Color4f(r.pageColor.r, r.pageColor.g, r.pageColor.b, 1))
+ paintPageBackground(r, canvas, { x: r.panX * r.dpr, y: r.panY * r.dpr }, r.zoom * r.dpr)
}
r.worldViewport = {
diff --git a/packages/core/src/canvas/renderer/shaders.ts b/packages/core/src/canvas/renderer/shaders.ts
index fabfbf264..f91d63432 100644
--- a/packages/core/src/canvas/renderer/shaders.ts
+++ b/packages/core/src/canvas/renderer/shaders.ts
@@ -6,6 +6,7 @@ export interface CompiledShaders {
pixelGridEffect: RuntimeEffect | null
/** The pixel grid's shader, kept while its uniforms hold. */
pixelGrid: { key: string; shader: Shader } | null
+ dotGridEffect: RuntimeEffect | null
linearBurn: Blender | null
linearDodge: Blender | null
}
@@ -15,6 +16,7 @@ export function createCompiledShaders(): CompiledShaders {
diamondGradient: null,
pixelGridEffect: null,
pixelGrid: null,
+ dotGridEffect: null,
linearBurn: null,
linearDodge: null
}
@@ -27,6 +29,8 @@ export function releaseCompiledShaders(shaders: CompiledShaders): void {
shaders.pixelGridEffect = null
shaders.pixelGrid?.shader.delete()
shaders.pixelGrid = null
+ shaders.dotGridEffect?.delete()
+ shaders.dotGridEffect = null
shaders.linearBurn?.delete()
shaders.linearBurn = null
shaders.linearDodge?.delete()
diff --git a/packages/core/src/canvas/renderer/tiles/controller.ts b/packages/core/src/canvas/renderer/tiles/controller.ts
index 247911ab7..95ba80951 100644
--- a/packages/core/src/canvas/renderer/tiles/controller.ts
+++ b/packages/core/src/canvas/renderer/tiles/controller.ts
@@ -100,6 +100,8 @@ export class TiledSceneController {
private index: RenderChunkIndex | null = null
private pageId: string | null = null
private contentGeneration = -1
+ /** The dot grid the cached tiles were painted with, which a document kind change replaces. */
+ private dotGrid: number | null = null
private navigationGeneration = -1
private navigationActive = false
private cancelledJobs = 0
@@ -208,6 +210,10 @@ export class TiledSceneController {
): TiledSceneFrameResult {
this.navigationGeneration = navigationGeneration
this.navigationActive = this.isNavigationActive(renderer)
+ if (renderer.pageDotGrid !== this.dotGrid) {
+ this.invalidate()
+ this.dotGrid = renderer.pageDotGrid
+ }
this.prepareGeneration(renderer, graph, contentGeneration, navigationGeneration)
const viewport = {
minX: -renderer.panX / renderer.zoom,
diff --git a/packages/core/src/canvas/renderer/tiles/render.ts b/packages/core/src/canvas/renderer/tiles/render.ts
index f36903126..2ae1524c7 100644
--- a/packages/core/src/canvas/renderer/tiles/render.ts
+++ b/packages/core/src/canvas/renderer/tiles/render.ts
@@ -2,6 +2,7 @@ import type { Image as CKImage } from 'canvaskit-wasm'
import type { SceneGraph } from '@open-pencil/scene-graph'
+import { paintPageBackground } from '#core/canvas/page/background'
import type { SkiaRenderer } from '#core/canvas/renderer'
import {
type RenderChunk,
@@ -62,14 +63,8 @@ export function renderTile(
renderer.images.detailScale = key.level
canvas.save()
try {
- canvas.clear(
- renderer.ck.Color4f(
- renderer.pageColor.r,
- renderer.pageColor.g,
- renderer.pageColor.b,
- renderer.pageColor.a
- )
- )
+ const origin = { x: -bounds.minX * key.level, y: -bounds.minY * key.level }
+ paintPageBackground(renderer, canvas, origin, key.level)
canvas.scale(key.level, key.level)
canvas.translate(-bounds.minX, -bounds.minY)
canvas.clipRect(
diff --git a/packages/core/src/editor/document-settings.ts b/packages/core/src/editor/document-settings.ts
index 52176dcf5..6248a0f2d 100644
--- a/packages/core/src/editor/document-settings.ts
+++ b/packages/core/src/editor/document-settings.ts
@@ -49,16 +49,25 @@ export function createDocumentSettingsActions(ctx: EditorContext) {
}
/**
- * Announces libraries and a color space written to the graph from elsewhere, as a
+ * Announces libraries, a color space, and a kind written to the graph from elsewhere, as a
* collaboration room writes its peers' settings, and draws the document again. It changes
- * nothing itself, so a read-only document offers it, as it does `refreshVariables`.
+ * nothing in the document itself, so a read-only document offers it, as it does
+ * `refreshVariables`.
*/
function refreshDocumentSettings() {
ctx.emitEditorEvent('document:libraries-changed')
ctx.emitEditorEvent('document:color-space-changed', ctx.graph.documentColorSpace)
+ if (ctx.state.documentKind !== ctx.graph.documentKind) showDocumentKind()
ctx.requestRender()
}
+ /** Shows the graph's kind in the editor: its tools, and Move for a tool the kind does not offer. */
+ function showDocumentKind() {
+ ctx.state.documentKind = ctx.graph.documentKind
+ ctx.setActiveTool(offeredTool(ctx.state, ctx.state.activeTool))
+ ctx.emitEditorEvent('document:kind-changed', ctx.graph.documentKind)
+ }
+
/**
* 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.
@@ -66,10 +75,8 @@ export function createDocumentSettingsActions(ctx: EditorContext) {
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()
+ showDocumentKind()
+ ctx.requestRender()
}
return { updateEnabledLibraries, refreshDocumentSettings, setDocumentKind }
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index 664094b7b..4ce156f7c 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -8,6 +8,7 @@ export { ReadOnlyDocumentError } from './read-only'
export { DEFAULT_SNAPPING_PREFERENCES } from './preferences'
export type { SnappingPreferences } from './preferences'
export { createDocumentGraph } from './document-settings'
+export { gridNudge } from './nudge'
export { createDefaultEditorSharedState } from './state/shared'
export { editedGradient, editedGradientLayout } from './gradient-edit'
export type { SelectionSpacing } from './alignment'
diff --git a/packages/core/src/editor/nudge.ts b/packages/core/src/editor/nudge.ts
index 3a718f301..b8817d689 100644
--- a/packages/core/src/editor/nudge.ts
+++ b/packages/core/src/editor/nudge.ts
@@ -9,6 +9,27 @@ import type { EditorContext } from './types'
const NUDGE_COMMIT_DELAY = 300
+/** The step from `position` to the next multiple of `grid` in `direction` (1 or -1). */
+function toNextGridLine(position: number, direction: number, grid: number): number {
+ if (direction === 0) return 0
+ const next =
+ direction > 0
+ ? (Math.floor(position / grid + 1e-9) + 1) * grid
+ : (Math.ceil(position / grid - 1e-9) - 1) * grid
+ return next - position
+}
+
+/**
+ * How far Shift+arrow moves a selection on a board: its top-left corner to the next line of the
+ * board grid that way, as FigJam does, rather than Figma Design's 10 units.
+ */
+export function gridNudge(origin: Vector, direction: Vector, grid: number): Vector {
+ return {
+ x: toNextGridLine(origin.x, direction.x, grid),
+ y: toNextGridLine(origin.y, direction.y, grid)
+ }
+}
+
/** The flow an arrow key moves a layer along: its row or column, or none. */
function flowParent(ctx: EditorContext, node: SceneNode): SceneNode | null {
if (node.layoutPositioning === 'ABSOLUTE' || !node.parentId) return null
diff --git a/packages/core/src/editor/selection/hit-test.ts b/packages/core/src/editor/selection/hit-test.ts
index fb7447b21..aad557c78 100644
--- a/packages/core/src/editor/selection/hit-test.ts
+++ b/packages/core/src/editor/selection/hit-test.ts
@@ -2,6 +2,7 @@ import type { SceneNode } from '@open-pencil/scene-graph'
import { LAYER_HIT_PAD } from '#core/constants'
import type { EditorContext } from '#core/editor/types'
+import { resolveEditorProfile } from '#core/editor/views'
export function createSelectionHitTestActions(
ctx: EditorContext,
@@ -17,7 +18,14 @@ export function createSelectionHitTestActions(
const scope = ctx.state.enteredContainerId ?? ctx.state.currentPageId
return deep
? ctx.graph.hitTestDeep(cx, cy, scope, pad)
- : ctx.graph.hitTestSelectable(cx, cy, scope, ctx.state.selectedIds, pad)
+ : ctx.graph.hitTestSelectable(
+ cx,
+ cy,
+ scope,
+ ctx.state.selectedIds,
+ pad,
+ resolveEditorProfile(ctx.state).framesOpen
+ )
}
/**
diff --git a/packages/core/src/editor/views/profile.ts b/packages/core/src/editor/views/profile.ts
index d6c339442..b38d79658 100644
--- a/packages/core/src/editor/views/profile.ts
+++ b/packages/core/src/editor/views/profile.ts
@@ -11,15 +11,36 @@ 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'])
-/** 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 document's kind decides: its tools and keys, its grids, and how deep a click goes. */
+type DocumentBehaviour = Pick<
+ EditorProfile,
+ 'edits' | 'tools' | 'toolKeys' | 'snapGrid' | 'dotGrid' | 'pixelGrid' | 'framesOpen' | 'lint'
+>
/** 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 }
+ design: {
+ edits: true,
+ tools: null,
+ toolKeys: TOOL_SHORTCUTS,
+ snapGrid: 1,
+ dotGrid: null,
+ pixelGrid: true,
+ framesOpen: true,
+ lint: true
+ },
+ board: {
+ edits: true,
+ tools: BOARD_TOOLS,
+ toolKeys: BOARD_TOOL_SHORTCUTS,
+ snapGrid: BOARD_GRID,
+ dotGrid: BOARD_GRID,
+ pixelGrid: false,
+ framesOpen: false,
+ lint: false
+ }
}
const EDIT_BEHAVIOUR: ViewBehaviour = {
diff --git a/packages/core/src/editor/views/types.ts b/packages/core/src/editor/views/types.ts
index f982b269b..c78877586 100644
--- a/packages/core/src/editor/views/types.ts
+++ b/packages/core/src/editor/views/types.ts
@@ -50,6 +50,17 @@ export interface EditorProfile {
* units: whole pixels in a design, FigJam's 16 on a board.
*/
snapGrid: number
+ /** The grid of dots drawn under the page's layers, in canvas units, as a FigJam board's; null for none. */
+ dotGrid: number | null
+ /** Whether Figma's pixel grid shows when zoomed in far enough; a FigJam board has none. */
+ pixelGrid: boolean
+ /**
+ * Whether a click looks into a top-level frame by itself, as in Figma Design; on a FigJam
+ * board it selects the frame, and double-click or Enter goes inside.
+ */
+ framesOpen: boolean
+ /** Whether design lint checks the document; a FigJam board has none. */
+ lint: boolean
}
/** The state a profile resolves from: the document's kind, the pane's view, and the host's limits. */
diff --git a/packages/core/src/lint/linter.ts b/packages/core/src/lint/linter.ts
index 0b8380ee4..239abcfae 100644
--- a/packages/core/src/lint/linter.ts
+++ b/packages/core/src/lint/linter.ts
@@ -2,6 +2,7 @@ import { uniq } from 'es-toolkit'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { colorToHex } from '@open-pencil/scene-graph/color'
+import { GENERATED_FRAME_TYPES, generatedFrameOwner } from '@open-pencil/scene-graph/generated'
import { presets } from './presets'
import { allRules } from './rules'
@@ -28,6 +29,9 @@ function effectiveTextStyles(node: SceneNode): { fontSize: number; fontWeight: n
return covered < node.text.length || runs.length === 0 ? [base, ...runs] : runs
}
+/** Sticky notes, shapes, and connectors: FigJam's own layers, which lint leaves alone. */
+const GENERATED_TYPES: ReadonlySet<string> = GENERATED_FRAME_TYPES
+
export class Linter {
private rules = new Map<string, Rule>()
private ruleConfigs = new Map<string, { severity: Severity; options?: Record<string, unknown> }>()
@@ -72,7 +76,12 @@ export class Linter {
this.variables = describeVariables(graph)
this.checks = this.ruleChecks()
const roots = rootIds && rootIds.length > 0 ? rootIds : graph.getPages().map((p) => p.id)
- for (const id of outermostRoots(graph, roots)) this.lintNode(id, undefined)
+ for (const id of outermostRoots(graph, roots)) {
+ // A sublayer of a sticky note, shape, or connector is skipped as a root, as in a page's walk.
+ const node = graph.getNode(id)
+ if (node && generatedFrameOwner(graph, node)) continue
+ this.lintNode(id, undefined)
+ }
this.graph = null
this.checks = []
return {
@@ -198,6 +207,9 @@ export class Linter {
private lintNode(id: string, parent: LintNode | undefined) {
const node = this.nodeFor(id, parent)
if (!node) return
+ // A sticky note, shape, or connector is FigJam's own, with its fixed choices: no design
+ // system rule applies to it or to the sublayers it generates.
+ if (GENERATED_TYPES.has(node.type)) return
for (const { rule, context } of this.checks) {
if (rule.match && !rule.match.includes(node.type)) continue
rule.check(node, context)
diff --git a/packages/core/tests/canvas/page/background.test.ts b/packages/core/tests/canvas/page/background.test.ts
new file mode 100644
index 000000000..28ce836ae
--- /dev/null
+++ b/packages/core/tests/canvas/page/background.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, test } from 'bun:test'
+
+import { dotGridSpacing } from '#core/canvas/page/background'
+
+describe('board dot grid', () => {
+ // Figma desktop, FigJam board: dots every 16 units from 50%, doubling below to stay 8 px apart.
+ test('doubles the spacing as FigJam does when zoomed out', () => {
+ const zooms = [4, 1, 0.75, 0.5, 0.4, 0.33, 0.25, 0.2, 0.1]
+ expect(zooms.map((zoom) => dotGridSpacing(16, zoom))).toEqual([
+ 16, 16, 16, 16, 32, 32, 32, 64, 128
+ ])
+ })
+})
diff --git a/packages/core/tests/editor/nudge.test.ts b/packages/core/tests/editor/nudge.test.ts
index ef9eca364..29d292ff8 100644
--- a/packages/core/tests/editor/nudge.test.ts
+++ b/packages/core/tests/editor/nudge.test.ts
@@ -1,6 +1,6 @@
import { describe, test, expect } from 'bun:test'
-import { createEditor } from '@open-pencil/core'
+import { createEditor, gridNudge } from '@open-pencil/core'
import { getNodeOrThrow } from '../helpers/assert'
@@ -193,3 +193,13 @@ describe('arrow keys in an auto layout flow', () => {
editor.dispose()
})
})
+
+describe('Shift+arrow on a board', () => {
+ // FigJam: Shift+arrow moves a layer to the next multiple of 16 that way, not by 10.
+ test('moves the top-left corner to the next grid line in the arrow’s direction', () => {
+ expect(gridNudge({ x: 37, y: 40 }, { x: 1, y: 0 }, 16)).toEqual({ x: 11, y: 0 })
+ expect(gridNudge({ x: 37, y: 40 }, { x: -1, y: 0 }, 16)).toEqual({ x: -5, y: 0 })
+ expect(gridNudge({ x: 32, y: 48 }, { x: 0, y: 1 }, 16)).toEqual({ x: 0, y: 16 })
+ expect(gridNudge({ x: 32, y: 48 }, { x: 0, y: -1 }, 16)).toEqual({ x: 0, y: -16 })
+ })
+})
diff --git a/packages/core/tests/editor/selection/hit-test.test.ts b/packages/core/tests/editor/selection/hit-test.test.ts
index ffcb9ff6d..787d22ef6 100644
--- a/packages/core/tests/editor/selection/hit-test.test.ts
+++ b/packages/core/tests/editor/selection/hit-test.test.ts
@@ -28,4 +28,25 @@ describe('editor scoped hit testing', () => {
expect(editor.hitTestAtPoint(130, 130)?.id).toBe(child.id)
})
+
+ test("selectAtPoint on a board selects the frame over its child", () => {
+ const editor = createEditor()
+ editor.setDocumentKind('board')
+ const pageId = editor.state.currentPageId
+ const frame = editor.graph.createNode('FRAME', pageId, { x: 100, y: 100, width: 200, height: 200 })
+ editor.graph.createNode('RECTANGLE', frame.id, {
+ x: 20,
+ y: 20,
+ width: 40,
+ height: 40,
+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
+ })
+ editor.setCanvasKit(
+ {} as Parameters<typeof editor.setCanvasKit>[0],
+ {} as Parameters<typeof editor.setCanvasKit>[1]
+ )
+
+ editor.selectAtPoint(130, 130)
+ expect([...editor.state.selectedIds]).toEqual([frame.id])
+ })
})
diff --git a/packages/core/tests/editor/views/profile.test.ts b/packages/core/tests/editor/views/profile.test.ts
index a3b890bc1..673239401 100644
--- a/packages/core/tests/editor/views/profile.test.ts
+++ b/packages/core/tests/editor/views/profile.test.ts
@@ -23,7 +23,11 @@ describe('canvas view profiles', () => {
edits: true,
tools: null,
toolKeys: TOOL_SHORTCUTS,
- snapGrid: 1
+ snapGrid: 1,
+ dotGrid: null,
+ pixelGrid: true,
+ framesOpen: true,
+ lint: true
})
})
@@ -40,7 +44,11 @@ describe('canvas view profiles', () => {
edits: true,
tools: null,
toolKeys: TOOL_SHORTCUTS,
- snapGrid: 1
+ snapGrid: 1,
+ dotGrid: null,
+ pixelGrid: true,
+ framesOpen: true,
+ lint: true
})
})
@@ -121,6 +129,13 @@ describe('document kinds', () => {
'COMMENT'
])
expect([profile.toolKeys, profile.snapGrid]).toEqual([BOARD_TOOL_SHORTCUTS, 16])
+ // FigJam draws its dots every 16 units and has no pixel grid.
+ expect([profile.dotGrid, profile.pixelGrid, profile.framesOpen, profile.lint]).toEqual([
+ 16,
+ false,
+ false,
+ false
+ ])
})
test('becoming a board drops a design tool, and refuses picking one', () => {
diff --git a/packages/core/tests/lint/linter.test.ts b/packages/core/tests/lint/linter.test.ts
index 449104cc9..916cd87c4 100644
--- a/packages/core/tests/lint/linter.test.ts
+++ b/packages/core/tests/lint/linter.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, test } from 'bun:test'
+import { createEditor } from '@open-pencil/core'
import { SceneGraph } from '@open-pencil/scene-graph'
import { createLinter } from '#core/lint'
@@ -25,3 +26,24 @@ describe('lintGraph roots', () => {
expect(lint([inner.id, page.id])).toEqual(fromPage)
})
})
+
+describe('FigJam layers', () => {
+ // A sticky note's body, author line, and fill are FigJam's fixed choices, not design decisions.
+ test('leaves sticky notes and what they generate out of every rule', () => {
+ const editor = createEditor()
+ const page = editor.state.currentPageId
+ const sticky = editor.createStickyNote(page, { x: 200, y: 200 })
+ const frame = editor.graph.createNode('FRAME', page, { name: 'Frame 1', width: 50, height: 50 })
+ const linted = createLinter({ preset: 'strict' }).lintGraph(editor.graph).messages
+ const insideSticky = new Set([sticky.id, ...sticky.childIds])
+ expect(linted.filter(({ nodeId }) => insideSticky.has(nodeId))).toEqual([])
+ expect(linted.some(({ nodeId }) => nodeId === frame.id)).toBe(true)
+ })
+
+ test("a sticky note's sublayer is left out when it is a root, as in the page's walk", () => {
+ const editor = createEditor()
+ const sticky = editor.createStickyNote(editor.state.currentPageId, { x: 200, y: 200 })
+ const linted = createLinter({ preset: 'strict' }).lintGraph(editor.graph, [...sticky.childIds])
+ expect(linted.messages).toEqual([])
+ })
+})
diff --git a/packages/scene-graph/src/connectors/sublayers.ts b/packages/scene-graph/src/connectors/sublayers.ts
index 51f906367..3ea72dc78 100644
--- a/packages/scene-graph/src/connectors/sublayers.ts
+++ b/packages/scene-graph/src/connectors/sublayers.ts
@@ -106,7 +106,6 @@ export const CONNECTOR_KIND: GeneratedFrameKind = {
text: (graph, frame) => connectorSublayers(graph, frame)?.label,
rotates: false,
resizes: false,
- strokesAndEffects: true,
namedByText: false
}
diff --git a/packages/scene-graph/src/generated/index.ts b/packages/scene-graph/src/generated/index.ts
index 3b90aebe6..e80f74a43 100644
--- a/packages/scene-graph/src/generated/index.ts
+++ b/packages/scene-graph/src/generated/index.ts
@@ -71,11 +71,6 @@ export function layerResizes(node: Pick<SceneNode, 'type'>): boolean {
return generatedFrameKind(node)?.resizes ?? true
}
-/** Whether a layer takes strokes and effects: any layer but a sticky note. */
-export function layerStrokesAndEffects(node: Pick<SceneNode, 'type'>): boolean {
- return generatedFrameKind(node)?.strokesAndEffects ?? true
-}
-
export type { GeneratedFrameKind } from './kind'
export * from './shape-with-text'
export * from './sticky'
diff --git a/packages/scene-graph/src/generated/kind.ts b/packages/scene-graph/src/generated/kind.ts
index 47b0c8db6..0ee910e81 100644
--- a/packages/scene-graph/src/generated/kind.ts
+++ b/packages/scene-graph/src/generated/kind.ts
@@ -14,8 +14,6 @@ export interface GeneratedFrameKind {
rotates: boolean
/** Whether the frame's resize handles and W and H fields resize it freely. */
resizes: boolean
- /** Whether it takes strokes and effects; a sticky note has neither, its shadow is its own. */
- strokesAndEffects: boolean
/** Whether it takes its name from its text until the user names it, as a sticky note does. */
namedByText: boolean
/**
diff --git a/packages/scene-graph/src/generated/shape-with-text.ts b/packages/scene-graph/src/generated/shape-with-text.ts
index 7a3711f01..b63998db5 100644
--- a/packages/scene-graph/src/generated/shape-with-text.ts
+++ b/packages/scene-graph/src/generated/shape-with-text.ts
@@ -80,7 +80,6 @@ export const SHAPE_WITH_TEXT_KIND: GeneratedFrameKind = {
text: (graph, frame) => shapeWithTextLabel(graph, frame) ?? undefined,
rotates: true,
resizes: true,
- strokesAndEffects: true,
namedByText: true,
sized: ({ height }, shape) =>
height === undefined || height === shape.height
diff --git a/packages/scene-graph/src/generated/sticky.ts b/packages/scene-graph/src/generated/sticky.ts
index d7c3c2907..94f00e76d 100644
--- a/packages/scene-graph/src/generated/sticky.ts
+++ b/packages/scene-graph/src/generated/sticky.ts
@@ -147,7 +147,6 @@ export const STICKY_KIND: GeneratedFrameKind = {
text: (graph, frame) => stickySublayers(graph, frame)?.body,
rotates: false,
resizes: false,
- strokesAndEffects: false,
namedByText: true
}
diff --git a/packages/scene-graph/src/graph.ts b/packages/scene-graph/src/graph.ts
index d01621bcb..2bafd1e80 100644
--- a/packages/scene-graph/src/graph.ts
+++ b/packages/scene-graph/src/graph.ts
@@ -711,9 +711,10 @@ export class SceneGraph {
py: number,
scopeId: string,
selectedIds: ReadonlySet<string>,
- pad = 0
+ pad = 0,
+ framesOpen = true
): SceneNode | null {
- return HitTest.hitTestSelectable(this, px, py, scopeId, selectedIds, pad)
+ return HitTest.hitTestSelectable(this, px, py, scopeId, selectedIds, pad, framesOpen)
}
hitTestOpenContainer(px: number, py: number, scopeId: string): SceneNode | null {
diff --git a/packages/scene-graph/src/hit-test.ts b/packages/scene-graph/src/hit-test.ts
index 2ba950871..53e195b4e 100644
--- a/packages/scene-graph/src/hit-test.ts
+++ b/packages/scene-graph/src/hit-test.ts
@@ -207,13 +207,14 @@ export function hitTestDeep(
/**
* A container a click looks into by itself, as in Figma: a top-level frame (on the page or in a
- * section) or a section that holds layers, and a component set.
+ * section) or a section that holds layers, and a component set. On a FigJam board frames stay
+ * closed (`framesOpen` false): a click inside one selects the frame.
*/
-function opensByItself(graph: SceneGraph, node: SceneNode): boolean {
+function opensByItself(graph: SceneGraph, node: SceneNode, framesOpen = true): boolean {
if (node.type === 'COMPONENT_SET') return true
if (node.childIds.length === 0) return false
if (node.type === 'SECTION') return true
- return node.type === 'FRAME' && isTopLevel(graph, node)
+ return framesOpen && node.type === 'FRAME' && isTopLevel(graph, node)
}
/**
@@ -225,14 +226,15 @@ function frameChildAt(
graph: SceneGraph,
container: SceneNode,
px: number,
- py: number
+ py: number,
+ framesOpen = true
): SceneNode | null {
const transformCache = new Map<string, boolean>()
for (let i = container.childIds.length - 1; i >= 0; i--) {
const child = graph.nodes.get(container.childIds[i])
if (!child || child.internalOnly || !child.visible || child.type !== 'FRAME') continue
// A board, such as a top-level frame in a section, keeps its empty area as background.
- if (opensByItself(graph, child) && !ownsItsEmptyArea(graph, child)) continue
+ if (opensByItself(graph, child, framesOpen) && !ownsItsEmptyArea(graph, child)) continue
if (containsPoint(px, py, child, graph, transformCache)) return child
}
return null
@@ -246,7 +248,8 @@ function frameChildAt(
function openedBySelection(
graph: SceneGraph,
selectedIds: ReadonlySet<string>,
- scopeId: string
+ scopeId: string,
+ framesOpen = true
): Set<string> {
const ancestors = new Set<string>()
for (const id of selectedIds) {
@@ -255,7 +258,9 @@ function openedBySelection(
node &&
node.childIds.length > 0 &&
node.type !== 'GROUP' &&
- node.type !== 'BOOLEAN_OPERATION'
+ node.type !== 'BOOLEAN_OPERATION' &&
+ // A board's frame stays closed when selected: a click inside keeps it selected.
+ (framesOpen || node.type !== 'FRAME' || !isTopLevel(graph, node))
)
ancestors.add(id)
let parentId = node?.parentId
@@ -281,12 +286,13 @@ export function hitTestSelectable(
py: number,
scopeId: string,
selectedIds: ReadonlySet<string>,
- pad = 0
+ pad = 0,
+ framesOpen = true
): SceneNode | null {
const deepest = hitTestChildren(graph, px, py, scopeId, true, new Map(), pad)
if (!deepest) {
const scope = graph.nodes.get(scopeId)
- return scope ? frameChildAt(graph, scope, px, py) : null
+ return scope ? frameChildAt(graph, scope, px, py, framesOpen) : null
}
const chain: SceneNode[] = []
@@ -295,19 +301,19 @@ export function hitTestSelectable(
node = node.parentId ? graph.nodes.get(node.parentId) : undefined
}
- const opened = openedBySelection(graph, selectedIds, scopeId)
+ const opened = openedBySelection(graph, selectedIds, scopeId, framesOpen)
for (const node of chain) {
// A locked layer stands in for everything inside it.
if (node.locked) return node
- if (!opened.has(node.id) && !opensByItself(graph, node)) return node
+ if (!opened.has(node.id) && !opensByItself(graph, node, framesOpen)) return node
}
const last = chain.at(-1)
if (!last) return null
- const frame = frameChildAt(graph, last, px, py)
+ const frame = frameChildAt(graph, last, px, py, framesOpen)
if (frame) return frame
if (ownsItsEmptyArea(graph, last)) return last
- return opened.has(last.id) && !opensByItself(graph, last) ? last : null
+ return opened.has(last.id) && !opensByItself(graph, last, framesOpen) ? last : null
}
/** Whether a click looks into this container rather than selecting it; see `hitTestSelectable`. */
diff --git a/packages/scene-graph/tests/basic/selectable-hit.test.ts b/packages/scene-graph/tests/basic/selectable-hit.test.ts
index b71b1fd5f..7469b8406 100644
--- a/packages/scene-graph/tests/basic/selectable-hit.test.ts
+++ b/packages/scene-graph/tests/basic/selectable-hit.test.ts
@@ -320,4 +320,17 @@ describe('a click just outside a shape', () => {
graph.createNode('FRAME', page, { name: 'Empty', width: 100, height: 100, fills: FILL })
expect(graph.hitTestSelectable(102, 50, page, new Set(), 3.5)).toBeNull()
})
+
+ // FigJam board, Figma desktop: a click on a layer inside a frame selects the frame.
+ test('selects a top-level frame whole when frames stay closed, as on a board', () => {
+ const { graph, page } = scene()
+ const click = (framesOpen: boolean) =>
+ graph.hitTestSelectable(170, 170, page, new Set(), 0, framesOpen)?.name ?? null
+ // In a design the click looks into the top-level frame and takes the frame inside it.
+ expect([click(true), click(false)]).toEqual(['Nested', 'Top'])
+ // Selected, it stays closed: another click inside keeps the frame.
+ const top = [...graph.nodes.values()].find((node) => node.name === 'Top')
+ if (!top) throw new Error('Missing Top')
+ expect(graph.hitTestSelectable(170, 170, page, new Set([top.id]), 0, false)?.name).toBe('Top')
+ })
})
diff --git a/packages/vue/src/shared/input/geometry.ts b/packages/vue/src/shared/input/geometry.ts
index 817241054..b70c8c145 100644
--- a/packages/vue/src/shared/input/geometry.ts
+++ b/packages/vue/src/shared/input/geometry.ts
@@ -1,4 +1,4 @@
-import type { Editor } from '@open-pencil/core'
+import { resolveEditorProfile, type Editor } from '@open-pencil/core'
import { HANDLE_HIT_RADIUS, LAYER_HIT_PAD } from '@open-pencil/core/constants'
import {
createSceneGeometry,
@@ -63,7 +63,14 @@ export function hitTestInEditorScope(
const scope = editor.state.enteredContainerId ?? editor.state.currentPageId
return deep
? editor.graph.hitTestDeep(cx, cy, scope, pad)
- : editor.graph.hitTestSelectable(cx, cy, scope, editor.state.selectedIds, pad)
+ : editor.graph.hitTestSelectable(
+ cx,
+ cy,
+ scope,
+ editor.state.selectedIds,
+ pad,
+ resolveEditorProfile(editor.state).framesOpen
+ )
}
export function isInsideEditorContainerBounds(
diff --git a/src/app/collab/document/sync.ts b/src/app/collab/document/sync.ts
index b43b098fd..e2712d8e4 100644
--- a/src/app/collab/document/sync.ts
+++ b/src/app/collab/document/sync.ts
@@ -6,6 +6,7 @@ import type {
CommentReply,
CommentThread,
DocumentColorSpace,
+ DocumentKind,
EnabledLibraryBinding,
PluginDataEntry
} from '@open-pencil/scene-graph'
@@ -24,6 +25,7 @@ import { readRoot, type YMeta } from '../shared-tree/fields'
const { comments } = OPEN_PENCIL_PLUGIN_DATA
const COLOR_SPACE_KEY = 'colorSpace'
+const KIND_KEY = 'documentKind'
/** A thread's replies are a map of their own by id, so replies written at once all stay. */
const BY_REPLY = new Set(['replies'])
@@ -42,11 +44,12 @@ const bindingSchema = v.object({
enabled: v.boolean()
})
const colorSpaceSchema = v.picklist(['srgb', 'display-p3'] satisfies DocumentColorSpace[])
+const kindSchema = v.picklist(['design', 'board'] satisfies DocumentKind[])
/**
* The room's maps for what the document holds outside its layers: the document node's plugin
* data by plugin and key, its comment threads by id, its libraries by id, and its settings,
- * such as the color space, by name.
+ * such as the color space and whether it is a design or a board, by name.
*/
export type YDocumentData = {
entries: YRecords
@@ -67,6 +70,7 @@ export function roomDocumentData(ydoc: Y.Doc): YDocumentData {
type DocumentData = DocumentNodeData & {
libraries: Map<string, EnabledLibraryBinding>
colorSpace: DocumentColorSpace | undefined
+ kind: DocumentKind | undefined
}
/** The document node's plugin data as the room keeps it: entries by plugin and key, threads by id. */
@@ -114,7 +118,8 @@ function readDocumentData(store: EditorStore): DocumentData {
return {
...documentNodeData(graph.getNode(graph.rootId)?.pluginData ?? []),
libraries: structuredClone(graph.enabledLibraries),
- colorSpace: graph.documentColorSpace
+ colorSpace: graph.documentColorSpace,
+ kind: graph.documentKind
}
}
@@ -192,6 +197,7 @@ export function bindDocumentSync({
writeChanges(data.threads, next.threads, sent.threads, { nested: BY_REPLY })
writeChanges(data.libraries, next.libraries, sent.libraries)
if (next.colorSpace !== sent.colorSpace) data.settings.set(COLOR_SPACE_KEY, next.colorSpace)
+ if (next.kind !== sent.kind) data.settings.set(KIND_KEY, next.kind)
})
sent = structuredClone(next)
}
@@ -221,6 +227,8 @@ export function bindDocumentSync({
if (!ids || ids.settings) {
const colorSpace = v.safeParse(colorSpaceSchema, data.settings.get(COLOR_SPACE_KEY))
if (colorSpace.success) next.colorSpace = colorSpace.output
+ const kind = v.safeParse(kindSchema, data.settings.get(KIND_KEY))
+ if (kind.success) next.kind = kind.output
}
sent = structuredClone(next)
receiving = true
@@ -244,7 +252,9 @@ export function bindDocumentSync({
if (libraries) graph.enabledLibraries = structuredClone(next.libraries)
const colorSpace = next.colorSpace !== undefined && next.colorSpace !== graph.documentColorSpace
if (next.colorSpace !== undefined) graph.documentColorSpace = next.colorSpace
- if (libraries || colorSpace) store.refreshDocumentSettings()
+ const kind = next.kind !== undefined && next.kind !== graph.documentKind
+ if (next.kind !== undefined) graph.documentKind = next.kind
+ if (libraries || colorSpace || kind) store.refreshDocumentSettings()
}
/**
@@ -282,7 +292,8 @@ export function bindDocumentSync({
if (id === store.graph.rootId && 'pluginData' in changes) send()
}),
store.onEditorEvent('document:libraries-changed', send),
- store.onEditorEvent('document:color-space-changed', send)
+ store.onEditorEvent('document:color-space-changed', send),
+ store.onEditorEvent('document:kind-changed', send)
]
data.settings.observe(onSettings)
@@ -294,7 +305,13 @@ export function bindDocumentSync({
share() {
if (store.state.hostRestrictions.readOnly) return
followedRoot = store.graph.rootId
- sent = { entries: new Map(), threads: new Map(), libraries: new Map(), colorSpace: undefined }
+ sent = {
+ entries: new Map(),
+ threads: new Map(),
+ libraries: new Map(),
+ colorSpace: undefined,
+ kind: undefined
+ }
write()
},
follow,
diff --git a/src/app/editor/design-check/session.ts b/src/app/editor/design-check/session.ts
index a9a4be137..713f70fbc 100644
--- a/src/app/editor/design-check/session.ts
+++ b/src/app/editor/design-check/session.ts
@@ -1,7 +1,7 @@
import { useTimeoutFn } from '@vueuse/core'
import { computed, effectScope, ref, shallowRef, watch } from 'vue'
-import type { Editor } from '@open-pencil/core'
+import { resolveEditorProfile, type Editor } from '@open-pencil/core'
import { isFigPagePending } from '@open-pencil/core/io/formats/fig'
import { createLinter, type LintConfig, type LintFixRequest } from '@open-pencil/core/lint'
@@ -50,7 +50,10 @@ export function createDesignCheck(editor: Editor, state: AppEditorState) {
})
const preferences = computed(() => appPreferences.value.designCheck)
- const enabled = computed(() => panelVisible.value || preferences.value.showOnCanvas)
+ // A board has no design lint, as FigJam has none.
+ const enabled = computed(
+ () => resolveEditorProfile(state).lint && (panelVisible.value || preferences.value.showOnCanvas)
+ )
// Primitive keys keep unrelated preference changes, like toggling markers, from rebuilding rules.
const preset = computed(() => preferences.value.preset)
const disabledRules = computed(() => preferences.value.disabledRules.join('\n'))
diff --git a/src/app/shell/keyboard/nudging.ts b/src/app/shell/keyboard/nudging.ts
index c3ac27d9b..59c9320d3 100644
--- a/src/app/shell/keyboard/nudging.ts
+++ b/src/app/shell/keyboard/nudging.ts
@@ -1,5 +1,8 @@
import { useEventListener } from '@vueuse/core'
+import { gridNudge, resolveEditorProfile } from '@open-pencil/core'
+import type { Vector } from '@open-pencil/scene-graph/primitives'
+
import type { EditorStore } from '@/app/editor/active-store'
import { isEditing } from '@/app/shell/keyboard/focus'
import { isReservedModShortcut } from '@/app/shell/keyboard/reserved'
@@ -11,6 +14,19 @@ const NUDGE_DELTAS: Partial<Record<string, [number, number]>> = {
ArrowRight: [1, 0]
}
+/** The top-left corner on the canvas of the selected layers a nudge moves: the unlocked ones. */
+function selectionOrigin(store: EditorStore): Vector {
+ let x = Infinity
+ let y = Infinity
+ for (const id of store.state.selectedIds) {
+ if (store.graph.getNode(id)?.locked) continue
+ const position = store.graph.getAbsolutePosition(id)
+ x = Math.min(x, position.x)
+ y = Math.min(y, position.y)
+ }
+ return { x, y }
+}
+
export function bindNudgeKeys(store: EditorStore) {
useEventListener(window, 'keydown', (e: KeyboardEvent) => {
if (isEditing(e) || store.state.editingTextId) return
@@ -20,8 +36,15 @@ export function bindNudgeKeys(store: EditorStore) {
const delta = NUDGE_DELTAS[e.code]
if (!delta || store.state.selectedIds.size === 0) return
- const step = e.shiftKey ? 10 : 1
- store.nudgeSelected(delta[0] * step, delta[1] * step)
+ const [x, y] = delta
+ const { snapGrid } = resolveEditorProfile(store.state)
+ if (e.shiftKey && snapGrid > 1) {
+ const nudge = gridNudge(selectionOrigin(store), { x, y }, snapGrid)
+ store.nudgeSelected(nudge.x, nudge.y)
+ } else {
+ const step = e.shiftKey ? 10 : 1
+ store.nudgeSelected(x * step, y * step)
+ }
e.preventDefault()
})
}
diff --git a/src/app/shell/keyboard/registry.ts b/src/app/shell/keyboard/registry.ts
index 21a3418c0..daa3295e8 100644
--- a/src/app/shell/keyboard/registry.ts
+++ b/src/app/shell/keyboard/registry.ts
@@ -167,6 +167,8 @@ function bindToolShortcuts(bindings: KeyBindingMap, options: KeyboardShortcutRun
if (!tool) return
event.preventDefault()
options.spaceTool.resetToolBeforeSpace()
+ // FigJam's R always arms a square; the toolbar's shapes keep the kind picked last.
+ if (tool === 'SHAPE_WITH_TEXT') options.store.setShapeWithTextKind('SQUARE')
options.store.setTool(tool)
}
}
diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vue
index 6841e8ed7..34f2e1c63 100644
--- a/src/components/DesignPanel.vue
+++ b/src/components/DesignPanel.vue
@@ -2,7 +2,7 @@
import { computed } from 'vue'
import { getNodeEditCapability } from '@open-pencil/core'
-import { layerResizes, layerStrokesAndEffects } from '@open-pencil/scene-graph/generated'
+import { isGeneratedFrame, layerResizes } from '@open-pencil/scene-graph/generated'
import { readIcon } from '@open-pencil/scene-graph/icons'
import { useEditorCommands } from '@open-pencil/vue/editor/commands'
import { useSelectionState } from '@open-pencil/vue/editor/selection-state'
@@ -94,9 +94,10 @@ const supportsLayoutGuides = useSceneComputed(() => {
const nodes = store.getSelectedNodes()
return nodes.length > 0 && nodes.every((selected) => LAYOUT_GUIDE_TYPES.has(selected.type))
})
-// A sticky note has no strokes or effects, so a selection holding one offers neither.
-const strokesAndEffects = useSceneComputed(() =>
- store.getSelectedNodes().every((selected) => layerStrokesAndEffects(selected))
+// Sticky notes, shapes, and connectors keep FigJam's fixed choices, which their own sections
+// offer, so a selection holding one offers no free-form appearance, type, fill, stroke, or effects.
+const freeStyle = useSceneComputed(() =>
+ store.getSelectedNodes().every((selected) => !isGeneratedFrame(selected))
)
const { panels } = useI18n()
</script>
@@ -132,14 +133,14 @@ const { panels } = useI18n()
<PositionSection />
<ConstraintsSection />
<SelectionLayoutSection />
- <AppearanceSection />
- <TypographySection />
- <FillSection />
- <template v-if="strokesAndEffects">
+ <template v-if="freeStyle">
+ <AppearanceSection />
+ <TypographySection />
+ <FillSection />
<StrokeSection />
<EffectsSection />
+ <SelectionColorsSection />
</template>
- <SelectionColorsSection />
<LayoutGridSection v-if="supportsLayoutGuides" />
<ExportSection />
</div>
@@ -238,18 +239,15 @@ const { panels } = useI18n()
<!-- A sticky note's size follows its text and its scale; Figma leaves W and H read-only. -->
<LayoutSection v-if="layerResizes(node)" />
</template>
- <AppearanceSection />
- <template v-if="node.type !== 'CONNECTOR'">
+ <template v-if="freeStyle">
+ <AppearanceSection />
<MaskSection />
- <!-- A shape with text's typography is its label's, as in Figma. -->
- <TypographySection v-if="node.type === 'TEXT' || node.type === 'SHAPE_WITH_TEXT'" />
+ <TypographySection v-if="node.type === 'TEXT'" />
<FillSection />
- <template v-if="strokesAndEffects">
- <StrokeSection />
- <EffectsSection />
- </template>
+ <StrokeSection />
+ <EffectsSection />
+ <SelectionColorsSection />
</template>
- <SelectionColorsSection />
<LayoutGridSection v-if="supportsLayoutGuides" />
<ExportSection />
diff --git a/src/components/PropertiesPanel.vue b/src/components/PropertiesPanel.vue
index 7a3c5ffe5..9f6ed9fdf 100644
--- a/src/components/PropertiesPanel.vue
+++ b/src/components/PropertiesPanel.vue
@@ -1,8 +1,9 @@
<script setup lang="ts">
import { TabsContent, TabsList, TabsRoot, TabsTrigger } from 'reka-ui'
import { tv } from 'tailwind-variants'
-import { computed } from 'vue'
+import { computed, watchEffect } from 'vue'
+import { resolveEditorProfile } from '@open-pencil/core'
import { useDesignCheckMessages, useI18n } from '@open-pencil/vue/i18n'
import { useAIChat } from '@/app/ai/chat/use'
@@ -32,6 +33,13 @@ const commenting = computed(() => store.state.activeTool === 'COMMENT')
/** Version history takes the sidebar while it is open, for the document and a version alike. */
const history = computed(() => isVersionHistoryOpen(store))
+/** Whether the document has design lint: a board has none, as FigJam has none. */
+const lints = computed(() => resolveEditorProfile(store.state).lint)
+// A board opened on the Lint tab shows Design instead.
+watchEffect(() => {
+ if (!lints.value && activeTab.value === 'lint') activeTab.value = 'design'
+})
+
/** Errors and warnings on the current page; suggestions do not earn an indicator. */
const problemCount = computed(() => {
const snapshot = store.designCheck.snapshot.value
@@ -71,6 +79,7 @@ const problemCount = computed(() => {
<span :class="tabStyles.label()">{{ panels.ai }}</span>
</TabsTrigger>
<TabsTrigger
+ v-if="lints"
value="lint"
data-test-id="properties-tab-lint"
:aria-label="
diff --git a/tests/app/collab/document/sync.test.ts b/tests/app/collab/document/sync.test.ts
index 8a246da5e..10f93dabc 100644
--- a/tests/app/collab/document/sync.test.ts
+++ b/tests/app/collab/document/sync.test.ts
@@ -177,6 +177,21 @@ describe('document data in a room', () => {
})
})
+ test('a board reaches the other peer and a viewer, with its tools', async () => {
+ await withRoom(async ({ host, guest, settle }) => {
+ guest.setTool('RECTANGLE')
+ guest.setReadOnly(true)
+ host.setDocumentKind('board')
+ await settle()
+ expect([guest.graph.documentKind, guest.state.documentKind]).toEqual(['board', 'board'])
+ // The board offers no rectangle: the guest drops it for Move and cannot pick it again.
+ expect(guest.state.activeTool).toBe('SELECT')
+ guest.setReadOnly(false)
+ guest.setTool('RECTANGLE')
+ expect(guest.state.activeTool).toBe('SELECT')
+ })
+ })
+
test('a color space change is an edit the room has not saved', async () => {
await withRoom(async ({ host, hostSession }) => {
hostSession.saves.markSaved(hostSession.saves.counts())
diff --git a/tests/e2e/canvas/board-dots-visual.spec.ts b/tests/e2e/canvas/board-dots-visual.spec.ts
new file mode 100644
index 000000000..1da43615a
--- /dev/null
+++ b/tests/e2e/canvas/board-dots-visual.spec.ts
@@ -0,0 +1,20 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import { boardDriver } from '#tests/helpers/canvas/board-driver'
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+const board = boardDriver(() => editor.page)
+
+// Figma desktop, FigJam board: #C4C4C4 dots, 2 units across, every 16 units from 50% and
+// every 32 at 25%, under the layers.
+for (const zoom of [1, 0.25]) {
+ test(`a board draws FigJam's dots under its layers at ${zoom * 100}%`, async () => {
+ await board.open()
+ await board.addRectangle(40, 40, 96, 64)
+ await board.showAt(zoom)
+ await editor.canvas.waitForRender()
+ editor.canvas.assertNoErrors()
+ expect(await editor.canvas.screenshotCanvasRegion(200, 140)).toMatchSnapshot(
+ `board-dots-${zoom * 100}.png`
+ )
+ })
+}
diff --git a/tests/e2e/canvas/board-dots-visual.spec.ts-snapshots/board-dots-100-openpencil-darwin.png b/tests/e2e/canvas/board-dots-visual.spec.ts-snapshots/board-dots-100-openpencil-darwin.png
new file mode 100644
index 000000000..282bdd9f8
Binary files /dev/null and b/tests/e2e/canvas/board-dots-visual.spec.ts-snapshots/board-dots-100-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/board-dots-visual.spec.ts-snapshots/board-dots-25-openpencil-darwin.png b/tests/e2e/canvas/board-dots-visual.spec.ts-snapshots/board-dots-25-openpencil-darwin.png
new file mode 100644
index 000000000..28e24e2a7
Binary files /dev/null and b/tests/e2e/canvas/board-dots-visual.spec.ts-snapshots/board-dots-25-openpencil-darwin.png differ
diff --git a/tests/e2e/tools/shape-with-text.spec.ts b/tests/e2e/tools/shape-with-text.spec.ts
index 5b5fd8599..0619031e7 100644
--- a/tests/e2e/tools/shape-with-text.spec.ts
+++ b/tests/e2e/tools/shape-with-text.spec.ts
@@ -1,12 +1,14 @@
import type { Vector } from '@open-pencil/scene-graph/primitives'
import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import { boardDriver } from '#tests/helpers/canvas/board-driver'
import { shapeWithTextDriver } from '#tests/helpers/canvas/shape-with-text-driver'
import { propertyField, propertySection } from '#tests/helpers/properties'
import { toolbarToolTestId } from '#tests/helpers/test-ids'
const editor = useEditorSetupWithClear()
const shapes = shapeWithTextDriver(() => editor.page)
+const board = boardDriver(() => editor.page)
test.beforeEach(async () => {
await editor.page.keyboard.press('Escape')
@@ -94,74 +96,30 @@ test('the tool keeps the kind picked last, and a drag draws the shape as large a
expect(await shapes.shapes()).toHaveLength(before)
})
-test('the properties panel switches a shape to another kind, keeping its size', async () => {
+// FigJam: on a board R arms a square, whatever kind the Shapes panel picked last.
+test('R on a board arms a square shape, not the kind picked last', async () => {
await shapes.showTool()
- await shapes.pickKind('Square')
- await clickAt(200, 200)
+ await shapes.pickKind('Cylinder')
await editor.page.keyboard.press('Escape')
- await editor.page.locator('[data-property="shape-kind"]').click()
- await editor.page.getByRole('option', { name: 'Hexagon', exact: true }).click()
- await editor.canvas.waitForRender()
- expect(await lastShape()).toMatchObject({ kind: 'HEXAGON', width: 176, height: 176 })
-
- await editor.page.keyboard.press('ControlOrMeta+z')
- await editor.canvas.waitForRender()
- expect((await lastShape()).kind).toBe('SQUARE')
-})
-
-test("the properties panel paints a shape with FigJam's palette and sizes its text", async () => {
- await shapes.showTool()
- await shapes.pickKind('Square')
- await clickAt(200, 200)
- await editor.page.keyboard.type('Ship it')
+ await board.open()
+ await editor.canvas.click(20, 20)
+ await editor.page.keyboard.press('r')
+ await clickAt(400, 200)
await editor.page.keyboard.press('Escape')
-
- const fill = editor.page.getByRole('radiogroup', { name: 'Fill' })
- await fill.getByRole('radio', { name: 'Violet', exact: true }).click()
- await expect(fill.getByRole('radio', { name: 'Violet', exact: true })).toHaveAttribute(
- 'aria-checked',
- 'true'
- )
- expect(await lastShape()).toMatchObject({ fill: '#874fff', stroke: '#5427b4' })
-
- const dashed = editor.page.locator('[data-property="shape-line-dashed"]')
- await dashed.click()
- await expect(dashed).toHaveAttribute('aria-pressed', 'true')
- const noFill = editor.page
- .getByRole('radiogroup', { name: 'Fill' })
- .getByRole('radio', { name: 'None', exact: true })
- await noFill.click()
- await expect(noFill).toHaveAttribute('aria-checked', 'true')
- await fill.getByRole('radio', { name: 'Violet', exact: true }).click()
- expect(await lastShape()).toMatchObject({ fill: '#874fff' })
-
- await editor.page.locator('[data-property="shape-text-size"]').click()
- await editor.page.getByRole('option', { name: 'Huge', exact: true }).click()
- await editor.canvas.waitForRender()
- await expect(editor.page.locator('[data-property="shape-text-size"]')).toContainText('Huge')
- const huge = await lastShape()
- expect(huge.label?.fontSize).toBe(96)
- expect(huge.height).toBeGreaterThan(176)
+ expect((await lastShape()).kind).toBe('SQUARE')
})
-test("a shape's panel styles its label and rounds its corners, as Figma's does", async () => {
+test("a shape's panel keeps to FigJam's choices, without free-form typography or corners", async () => {
await shapes.showTool()
await shapes.pickKind('Square')
await clickAt(200, 200)
await editor.page.keyboard.type('Ship it')
await editor.page.keyboard.press('Escape')
- await expect(propertySection(editor.page, 'Typography')).toBeVisible()
- await expect(propertyField(editor.page, 'cornerRadius')).toBeVisible()
- const size = propertySection(editor.page, 'Typography').getByRole('spinbutton', {
- name: 'Font size'
- })
- await size.click()
- await editor.page.keyboard.press('ControlOrMeta+a')
- await editor.page.keyboard.type('24')
- await size.press('Enter')
- await editor.canvas.waitForRender()
- expect((await lastShape()).label?.fontSize).toBe(24)
+ for (const section of ['Typography', 'Appearance', 'Fill', 'Stroke', 'Effects']) {
+ await expect(propertySection(editor.page, section)).toHaveCount(0)
+ }
+ await expect(propertyField(editor.page, 'cornerRadius')).toHaveCount(0)
})
test('a shape whose height was set keeps it, and cuts a long label off with "…"', async () => {
diff --git a/tests/e2e/tools/sticky.spec.ts b/tests/e2e/tools/sticky.spec.ts
index 734755474..9c57d7f39 100644
--- a/tests/e2e/tools/sticky.spec.ts
+++ b/tests/e2e/tools/sticky.spec.ts
@@ -131,19 +131,21 @@ test('the Sticky note section recolours a note, sizes its text, and hides its au
})
// Figma keeps a note upright and gives it no strokes or effects: its shadow is part of the note.
-test("a note's panel has its fill and opacity, but no rotation, stroke, or effects", async () => {
+// A note keeps FigJam's fixed choices, which its Sticky note section offers; free-form styling
+// would make notes FigJam itself cannot make.
+test("a note's panel keeps to FigJam's choices: no free-form fill, appearance, stroke, or effects", async () => {
await sticky.add([{ x: 300, y: 200, text: 'Upright' }])
await clickNote(300, 200)
- await expect(propertySection(editor.page, 'Fill')).toBeVisible()
- await expect(propertySection(editor.page, 'Appearance')).toBeVisible()
+ await expect(propertySection(editor.page, 'Sticky note')).toBeVisible()
await expect(propertyField(editor.page, 'x')).toBeVisible()
await expect(propertyField(editor.page, 'rotation')).toHaveCount(0)
- await expect(propertySection(editor.page, 'Stroke')).toHaveCount(0)
- await expect(propertySection(editor.page, 'Effects')).toHaveCount(0)
+ for (const section of ['Fill', 'Appearance', 'Stroke', 'Effects']) {
+ await expect(propertySection(editor.page, section)).toHaveCount(0)
+ }
})
-test('a note selected with a rectangle offers no stroke or effects either', async () => {
+test('a note selected with a rectangle offers no free-form styling either', async () => {
await sticky.add([{ x: 150, y: 150, text: 'One' }])
const from = sticky.point(550, 100)
const to = sticky.point(650, 200)
@@ -154,9 +156,9 @@ test('a note selected with a rectangle offers no stroke or effects either', asyn
await editor.page.keyboard.up('Shift')
await expect(editor.page.getByTestId('design-panel-multi')).toBeVisible()
- await expect(propertySection(editor.page, 'Fill')).toBeVisible()
- await expect(propertySection(editor.page, 'Stroke')).toHaveCount(0)
- await expect(propertySection(editor.page, 'Effects')).toHaveCount(0)
+ for (const section of ['Fill', 'Stroke', 'Effects']) {
+ await expect(propertySection(editor.page, section)).toHaveCount(0)
+ }
})
test('the sticky tool places notes in the colour picked last', async () => {
diff --git a/tests/helpers/canvas/board-driver.ts b/tests/helpers/canvas/board-driver.ts
new file mode 100644
index 000000000..81041e3d9
--- /dev/null
+++ b/tests/helpers/canvas/board-driver.ts
@@ -0,0 +1,39 @@
+import type { Page } from '@playwright/test'
+
+/** A FigJam board in the open document: its kind, its page, and the view it shows. */
+export function boardDriver(page: () => Page) {
+ return {
+ /** Makes the open document a board on FigJam's #F5F5F5 page, as New board starts one. */
+ async open() {
+ await page().evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ store.setDocumentKind('board')
+ store.state.pageColor = { r: 245 / 255, g: 245 / 255, b: 245 / 255, a: 1 }
+ store.requestRender()
+ })
+ },
+
+ /** Shows the board at `zoom` with the canvas origin at the view's top-left corner. */
+ async showAt(zoom: number) {
+ await page().evaluate((zoom) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ store.state.zoom = zoom
+ store.state.panX = 0
+ store.state.panY = 0
+ store.requestRender()
+ }, zoom)
+ },
+
+ /** Adds a rectangle, which a board keeps though its tools draw none. */
+ async addRectangle(x: number, y: number, width: number, height: number) {
+ await page().evaluate(
+ ({ x, y, width, height }) => {
+ window.openPencil?.getStore?.().createShape('RECTANGLE', x, y, width, height)
+ },
+ { x, y, width, height }
+ )
+ }
+ }
+}