Skip to content

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

fix: board colour, snap, and text-size follow-ups, with shared grid shaders (#1669)

Danila Poyarkov8551818f8fa0
diff --git a/changes/1629/added.md b/changes/1629/added.md
index 6fa218ea0..4c59bc2da 100644
--- a/changes/1629/added.md
+++ b/changes/1629/added.md
@@ -1 +1 @@
-- Boards open on the canvas and their tools alone, as FigJam shows them, with no rulers, the panels a click away, and the AI chat floating over the canvas; while the panels are hidden, every selection gets FigJam's selection toolbar, with colour, outline, text, alignment and wrap-in-section menus for sticky notes, shapes, connectors, text, sections and other layers.
+- Boards open on the canvas and their tools alone, as FigJam shows them, with no rulers, the panels a click away, and the AI chat floating over the canvas; while the panels are hidden, every selection but a lone image gets FigJam's selection toolbar, with colour, outline, text, alignment and wrap-in-section menus for sticky notes, shapes, connectors, text, sections and other layers.
diff --git a/packages/core/src/canvas/gradients/diamond.ts b/packages/core/src/canvas/gradients/diamond.ts
index e9dfb9f0b..6df49c3e1 100644
--- a/packages/core/src/canvas/gradients/diamond.ts
+++ b/packages/core/src/canvas/gradients/diamond.ts
@@ -1,6 +1,7 @@
import type { InputMatrix, Shader } from 'canvaskit-wasm'
import type { SkiaRenderer } from '#core/canvas/renderer'
+import { compiledEffect } from '#core/canvas/renderer/shaders'
const DIAMOND_GRADIENT = `
uniform shader ramp;
@@ -17,14 +18,13 @@ export function makeDiamondGradient(
positions: number[],
localMatrix: InputMatrix
): Shader {
- if (!r.shaders.diamondGradient) {
- let error = ''
- const effect = r.ck.RuntimeEffect.Make(DIAMOND_GRADIENT, (message) => {
- error = message
- })
- if (!effect) throw new Error(`Cannot compile diamond gradient: ${error}`)
- r.shaders.diamondGradient = effect
- }
+ const effect = compiledEffect(
+ r.ck,
+ r.shaders,
+ 'diamondGradient',
+ DIAMOND_GRADIENT,
+ 'diamond gradient'
+ )
const ramp = r.ck.Shader.MakeLinearGradient(
[0, 0],
[1, 0],
@@ -33,7 +33,7 @@ export function makeDiamondGradient(
r.ck.TileMode.Clamp
)
try {
- return r.shaders.diamondGradient.makeShaderWithChildren([], [ramp], localMatrix)
+ return effect.makeShaderWithChildren([], [ramp], localMatrix)
} finally {
ramp.delete()
}
diff --git a/packages/core/src/canvas/overlays/pixel-grid.ts b/packages/core/src/canvas/overlays/pixel-grid.ts
index 067998c5f..da8910a26 100644
--- a/packages/core/src/canvas/overlays/pixel-grid.ts
+++ b/packages/core/src/canvas/overlays/pixel-grid.ts
@@ -3,6 +3,7 @@ import type { Canvas } from 'canvaskit-wasm'
import type { Color } from '@open-pencil/scene-graph/primitives'
import type { SkiaRenderer } from '#core/canvas/renderer'
+import { compiledEffect, fillWithShader, keptShader } from '#core/canvas/renderer/shaders'
/** Device pixels one document pixel must cover before Figma shows the pixel grid: 800% at 1×. */
export const PIXEL_GRID_MIN_DEVICE_PIXELS = 8
@@ -52,13 +53,7 @@ function lineColor(page: Color): Color {
/** Figma's pixel grid: a line at every document pixel once zoomed in far enough to tell them apart. */
export function drawPixelGrid(r: SkiaRenderer, canvas: Canvas): void {
if (!pixelGridVisible(r.zoom, r.dpr)) return
- if (!r.shaders.pixelGridEffect) {
- let error = ''
- r.shaders.pixelGridEffect = r.ck.RuntimeEffect.Make(PIXEL_GRID_SHADER, (message) => {
- error = message
- })
- if (!r.shaders.pixelGridEffect) throw new Error(`Cannot compile the pixel grid: ${error}`)
- }
+ const effect = compiledEffect(r.ck, r.shaders, 'pixelGridEffect', PIXEL_GRID_SHADER, 'pixel grid')
const color = lineColor(r.pageColor)
const step = r.zoom * r.dpr
const uniforms = [
@@ -72,15 +67,6 @@ export function drawPixelGrid(r: SkiaRenderer, canvas: Canvas): void {
color.a,
r.dpr
]
- // The shader holds only these uniforms, so a hover repaint at the same view reuses it.
- const key = uniforms.join(',')
- if (r.shaders.pixelGrid?.key !== key) {
- r.shaders.pixelGrid?.shader.delete()
- r.shaders.pixelGrid = { key, shader: r.shaders.pixelGridEffect.makeShader(uniforms) }
- }
- // Skia scales a shader by the paint's alpha, which earlier overlays may have left translucent.
- r.auxFill.setAlphaf(1)
- r.auxFill.setShader(r.shaders.pixelGrid.shader)
- canvas.drawRect(r.ck.LTRBRect(0, 0, r.viewportWidth, r.viewportHeight), r.auxFill)
- r.auxFill.setShader(null)
+ const shader = keptShader(r.shaders, 'pixelGrid', effect, uniforms)
+ fillWithShader(canvas, r.auxFill, shader, r.ck.LTRBRect(0, 0, r.viewportWidth, r.viewportHeight))
}
diff --git a/packages/core/src/canvas/page/background.ts b/packages/core/src/canvas/page/background.ts
index 09c2c7c75..343d2a93b 100644
--- a/packages/core/src/canvas/page/background.ts
+++ b/packages/core/src/canvas/page/background.ts
@@ -3,6 +3,7 @@ import type { Canvas } from 'canvaskit-wasm'
import type { Vector } from '@open-pencil/scene-graph/primitives'
import type { SkiaRenderer } from '#core/canvas/renderer'
+import { compiledEffect, fillWithShader, keptShader } from '#core/canvas/renderer/shaders'
/** FigJam's dots, #C4C4C4, as Figma desktop draws them on a board's #F5F5F5 page. */
const DOT_COLOR = 196 / 255
@@ -14,16 +15,17 @@ 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. */
+/**
+ * One dot per grid point, decided per device pixel, so the grid is a single draw at any zoom. It
+ * puts a dot at its own origin, where the canvas is moved to draw it, so tiles at one zoom share it.
+ */
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);
+ float2 cell = position - pitch * floor(position / pitch + 0.5);
float alpha = clamp(radius + 0.5 - length(cell), 0.0, 1.0);
return half4(shade * alpha, shade * alpha, shade * alpha, alpha);
}
@@ -49,27 +51,13 @@ export function paintPageBackground(
): 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 effect = compiledEffect(r.ck, r.shaders, 'dotGridEffect', DOT_GRID_SHADER, 'dot grid')
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()
+ const shader = keptShader(r.shaders, 'dotGrid', effect, [pitch, diameter / 2, DOT_COLOR])
+ canvas.save()
+ canvas.translate(origin.x, origin.y)
+ fillWithShader(canvas, r.auxFill, shader)
+ canvas.restore()
}
diff --git a/packages/core/src/canvas/renderer/shaders.ts b/packages/core/src/canvas/renderer/shaders.ts
index f91d63432..1c6390893 100644
--- a/packages/core/src/canvas/renderer/shaders.ts
+++ b/packages/core/src/canvas/renderer/shaders.ts
@@ -1,22 +1,32 @@
-import type { Blender, RuntimeEffect, Shader } from 'canvaskit-wasm'
+import type { Blender, Canvas, CanvasKit, Paint, Rect, RuntimeEffect, Shader } from 'canvaskit-wasm'
+
+/** A shader kept while the uniforms it was made with, joined as `key`, still hold. */
+interface KeptShader {
+ key: string
+ shader: Shader
+}
/** Skia programs a renderer compiles on first use and keeps for the surface's lifetime. */
export interface CompiledShaders {
diamondGradient: RuntimeEffect | null
pixelGridEffect: RuntimeEffect | null
- /** The pixel grid's shader, kept while its uniforms hold. */
- pixelGrid: { key: string; shader: Shader } | null
+ pixelGrid: KeptShader | null
dotGridEffect: RuntimeEffect | null
+ dotGrid: KeptShader | null
linearBurn: Blender | null
linearDodge: Blender | null
}
+type EffectSlot = 'diamondGradient' | 'pixelGridEffect' | 'dotGridEffect'
+type ShaderSlot = 'pixelGrid' | 'dotGrid'
+
export function createCompiledShaders(): CompiledShaders {
return {
diamondGradient: null,
pixelGridEffect: null,
pixelGrid: null,
dotGridEffect: null,
+ dotGrid: null,
linearBurn: null,
linearDodge: null
}
@@ -31,8 +41,61 @@ export function releaseCompiledShaders(shaders: CompiledShaders): void {
shaders.pixelGrid = null
shaders.dotGridEffect?.delete()
shaders.dotGridEffect = null
+ shaders.dotGrid?.shader.delete()
+ shaders.dotGrid = null
shaders.linearBurn?.delete()
shaders.linearBurn = null
shaders.linearDodge?.delete()
shaders.linearDodge = null
}
+
+/** The program in `slot`, compiled from `source` the first time; `name` says what failed to compile. */
+export function compiledEffect(
+ ck: CanvasKit,
+ shaders: CompiledShaders,
+ slot: EffectSlot,
+ source: string,
+ name: string
+): RuntimeEffect {
+ const kept = shaders[slot]
+ if (kept) return kept
+ let error = ''
+ const effect = ck.RuntimeEffect.Make(source, (message) => {
+ error = message
+ })
+ if (!effect) throw new Error(`Cannot compile the ${name}: ${error}`)
+ shaders[slot] = effect
+ return effect
+}
+
+/**
+ * The shader in `slot`, made again from `effect` only when `uniforms` change, so repaints at the
+ * same view, or tiles at the same zoom, share one.
+ */
+export function keptShader(
+ shaders: CompiledShaders,
+ slot: ShaderSlot,
+ effect: RuntimeEffect,
+ uniforms: number[]
+): Shader {
+ const key = uniforms.join(',')
+ const kept = shaders[slot]
+ if (kept?.key === key) return kept.shader
+ kept?.shader.delete()
+ const shader = effect.makeShader(uniforms)
+ shaders[slot] = { key, shader }
+ return shader
+}
+
+/**
+ * Fills `rect`, or the whole clip without one, with `shader` through `paint`. The paint is made
+ * opaque first, since Skia scales a shader by the paint's alpha and earlier drawing may have left
+ * it translucent, and gives the shader up after.
+ */
+export function fillWithShader(canvas: Canvas, paint: Paint, shader: Shader, rect?: Rect): void {
+ paint.setAlphaf(1)
+ paint.setShader(shader)
+ if (rect) canvas.drawRect(rect, paint)
+ else canvas.drawPaint(paint)
+ paint.setShader(null)
+}
diff --git a/packages/core/src/editor/figjam/colors.ts b/packages/core/src/editor/figjam/colors.ts
index 8bdb7fa53..38d780d16 100644
--- a/packages/core/src/editor/figjam/colors.ts
+++ b/packages/core/src/editor/figjam/colors.ts
@@ -8,10 +8,9 @@ import {
type FigJamColorName,
type FigJamLineStyle
} from '@open-pencil/scene-graph/figjam'
-import { isGeneratedFrame } from '@open-pencil/scene-graph/generated'
import { recordSubtreeEdit } from '#core/editor/components/slots/history'
-import { showsImage } from '#core/editor/figjam/toolbar'
+import { figJamColoredLayers } from '#core/editor/figjam/toolbar'
import type { NodeActions } from '#core/editor/nodes'
import type { EditorContext } from '#core/editor/types'
@@ -38,28 +37,23 @@ export function createFigJamColorActions(ctx: EditorContext, nodes: NodeActions)
)
}
- /** The layers a colour lands on: a group's contents, as FigJam colours a group. */
- function painted(layer: SceneNode): SceneNode[] {
- if (layer.type !== 'GROUP') return [layer]
- return ctx.graph.getChildren(layer.id).flatMap(painted)
- }
-
/**
* Paints the sections and plain layers among `ids` in palette colour `name`, as FigJam's colour
* menu does: a section takes a pale tint outlined in the colour, other layers the colour itself.
+ * A layer with nothing to paint, such as a group of images, records no step.
*/
function setFigJamColor(ids: Iterable<string>, name: FigJamColorName) {
- const layers = layersAmong(ids, (node) => !isGeneratedFrame(node))
+ const layers = layersAmong(
+ ids,
+ (node) => node.type === 'SECTION' || figJamColoredLayers(ctx.graph, node).length > 0
+ )
edit('Change color', layers, (layer) => {
if (layer.type === 'SECTION') {
nodes.updateNode(layer.id, figJamSectionColorFields(layer, name))
return
}
- // An image in a group keeps its picture, as a lone image has no colour menu.
- for (const target of painted(layer)) {
- if (!isGeneratedFrame(target) && !showsImage(target))
- nodes.updateNode(target.id, figJamLayerColorFields(target, name))
- }
+ for (const target of figJamColoredLayers(ctx.graph, layer))
+ nodes.updateNode(target.id, figJamLayerColorFields(target, name))
})
}
diff --git a/packages/core/src/editor/figjam/toolbar.ts b/packages/core/src/editor/figjam/toolbar.ts
index 7f0805c8b..8be1f37e4 100644
--- a/packages/core/src/editor/figjam/toolbar.ts
+++ b/packages/core/src/editor/figjam/toolbar.ts
@@ -1,4 +1,5 @@
-import type { NodeType, SceneNode } from '@open-pencil/scene-graph'
+import type { NodeType, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { isGeneratedFrame } from '@open-pencil/scene-graph/generated'
/**
* Which of FigJam's selection toolbars a selection gets: one per kind of layer, a text toolbar for
@@ -39,7 +40,19 @@ const KIND_BY_TYPE: Partial<Record<NodeType, FigJamToolbarKind>> = {
/** Whether a layer shows an image, which FigJam's colour menu leaves alone. */
export function showsImage(node: Pick<SceneNode, 'fills'>): boolean {
- return node.fills.some((fill) => fill.type === 'IMAGE' && fill.visible)
+ return node.fills.some((fill) => fill.type === 'IMAGE' && fill.visible && fill.opacity > 0)
+}
+
+/**
+ * The layers FigJam's colour menu paints for `layer`: a group's contents at any depth, leaving
+ * out images and generated frames, which keep colours of their own. Reading a colour back takes
+ * the same layers.
+ */
+export function figJamColoredLayers(graph: SceneGraph, layer: SceneNode): SceneNode[] {
+ if (layer.type === 'GROUP') {
+ return graph.getChildren(layer.id).flatMap((child) => figJamColoredLayers(graph, child))
+ }
+ return isGeneratedFrame(layer) || showsImage(layer) ? [] : [layer]
}
function layerKind(node: Pick<SceneNode, 'type' | 'fills'>): FigJamToolbarKind {
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index 70cee2053..329143277 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -9,7 +9,7 @@ export { DEFAULT_SNAPPING_PREFERENCES } from './preferences'
export type { SnappingPreferences } from './preferences'
export { createDocumentGraph } from './document-settings'
export { gridNudge } from './nudge'
-export { figJamToolbarKind, type FigJamToolbarKind } from './figjam/toolbar'
+export { figJamColoredLayers, figJamToolbarKind, type FigJamToolbarKind } from './figjam/toolbar'
export { createDefaultEditorSharedState } from './state/shared'
export { editedGradient, editedGradientLayout } from './gradient-edit'
export type { SelectionSpacing } from './alignment'
diff --git a/packages/core/src/editor/read-only/actions.ts b/packages/core/src/editor/read-only/actions.ts
index 3a2750e1b..8a472487e 100644
--- a/packages/core/src/editor/read-only/actions.ts
+++ b/packages/core/src/editor/read-only/actions.ts
@@ -9,6 +9,7 @@ export const READ_ONLY_ACTIONS: ReadonlySet<string> = new Set([
'acceptingParent',
'acceptsChildren',
'canDistributeNodes',
+ 'canWrapSelectionInSection',
'collectVariantOptions',
'findVariantByValues',
'getChildren',
diff --git a/packages/core/src/editor/shapes/with-text.ts b/packages/core/src/editor/shapes/with-text.ts
index 54a9084d9..f0f7f706f 100644
--- a/packages/core/src/editor/shapes/with-text.ts
+++ b/packages/core/src/editor/shapes/with-text.ts
@@ -18,6 +18,7 @@ import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text
import { recordSubtreeEdit } from '#core/editor/components/slots/history'
import type { NodeActions } from '#core/editor/nodes'
import type { EditorContext } from '#core/editor/types'
+import { textStyleChanges } from '#core/text/character-style'
const FILL_OPACITY: Record<FigJamFillMode, number> = { fill: 1, transparent: 0.5, none: 0 }
@@ -119,7 +120,11 @@ export function createShapeWithTextActions(ctx: EditorContext, nodes: NodeAction
editShapes('Change shape text size', ids, (shape) => {
const label = shapeWithTextLabel(ctx.graph, shape)
if (label) {
- nodes.updateNode(label.id, figJamTextSizeFields(size, figJamTypeface(label) ?? 'simple'))
+ // Characters sized on their own take the size too, as text layers do.
+ nodes.updateNode(
+ label.id,
+ textStyleChanges(label, figJamTextSizeFields(size, figJamTypeface(label) ?? 'simple'))
+ )
}
})
}
diff --git a/packages/core/src/editor/stickies.ts b/packages/core/src/editor/stickies.ts
index f69aa1642..6abb356d9 100644
--- a/packages/core/src/editor/stickies.ts
+++ b/packages/core/src/editor/stickies.ts
@@ -18,6 +18,7 @@ import { rescaleNodeTree } from '@open-pencil/scene-graph/scaling'
import { recordSubtreeEdit } from '#core/editor/components/slots/history'
import type { EditorContext } from '#core/editor/types'
import { pushCreatedSubtreesUndo } from '#core/editor/undo'
+import { textStyleChanges } from '#core/text/character-style'
import type { NodeActions } from './nodes'
@@ -86,7 +87,11 @@ export function createStickyActions(ctx: EditorContext, nodes: NodeActions) {
editStickies('Change sticky text size', ids, (sticky) => {
const body = stickySublayers(ctx.graph, sticky)?.body
if (body) {
- nodes.updateNode(body.id, figJamTextSizeFields(size, figJamTypeface(body) ?? 'simple'))
+ // Characters sized on their own take the size too, as text layers do.
+ nodes.updateNode(
+ body.id,
+ textStyleChanges(body, figJamTextSizeFields(size, figJamTypeface(body) ?? 'simple'))
+ )
}
})
}
diff --git a/packages/core/tests/editor/figjam/colors.test.ts b/packages/core/tests/editor/figjam/colors.test.ts
index 71446b778..2a14a68eb 100644
--- a/packages/core/tests/editor/figjam/colors.test.ts
+++ b/packages/core/tests/editor/figjam/colors.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'
import { expectDefined } from '#core-tests/helpers/assert'
-import { createEditor } from '@open-pencil/core'
+import { createEditor, figJamColoredLayers } from '@open-pencil/core'
import { colorToHex } from '@open-pencil/scene-graph/color'
import { createSticky } from '@open-pencil/scene-graph/generated'
@@ -53,6 +53,32 @@ describe("FigJam's colour menu", () => {
expect(hex(editor.graph.getNode(b)?.fills[0])).toBe('#3dadff')
expect(editor.graph.getNode(photo)?.fills).toEqual([image])
expect(hex(editor.graph.getNode(sticky.id)?.fills[0])).toBe(before)
+ const colored = figJamColoredLayers(editor.graph, expectDefined(editor.graph.getNode(group)))
+ expect(colored.map((layer) => layer.id)).toEqual([a, b])
+ })
+
+ test('a group of images takes no colour and records no undo step', () => {
+ const { editor, pageId } = setup()
+ const photo = editor.createShape('RECTANGLE', 0, 0, 100, 100, pageId)
+ editor.graph.updateNode(photo, {
+ fills: [
+ {
+ type: 'IMAGE',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ imageHash: 'hash',
+ imageScaleMode: 'FILL',
+ opacity: 1,
+ visible: true
+ }
+ ]
+ })
+ const other = editor.createShape('RECTANGLE', 200, 0, 100, 100, pageId)
+ editor.select([photo, other])
+ const group = expectDefined(editor.groupSelected())
+ editor.graph.deleteNode(other)
+ const label = editor.undo.undoLabel
+ editor.setFigJamColor([group], 'blue')
+ expect(editor.undo.undoLabel).toBe(label)
})
test("dashes a section's outline, giving it one first if it has none", () => {
diff --git a/packages/core/tests/editor/figjam/toolbar.test.ts b/packages/core/tests/editor/figjam/toolbar.test.ts
index c0d30fc13..bab808151 100644
--- a/packages/core/tests/editor/figjam/toolbar.test.ts
+++ b/packages/core/tests/editor/figjam/toolbar.test.ts
@@ -21,6 +21,7 @@ describe("FigJam's selection toolbars", () => {
expect(figJamToolbarKind([layer('RECTANGLE'), layer('FRAME'), layer('LINE')])).toBe('layer')
expect(figJamToolbarKind([layer('RECTANGLE', [image])])).toBe('image')
expect(figJamToolbarKind([layer('RECTANGLE', [{ ...image, visible: false }])])).toBe('layer')
+ expect(figJamToolbarKind([layer('RECTANGLE', [{ ...image, opacity: 0 }])])).toBe('layer')
expect(figJamToolbarKind([layer('SECTION', [image])])).toBe('section')
expect(figJamToolbarKind([layer('TEXT', [image])])).toBe('text')
expect(figJamToolbarKind([])).toBeNull()
diff --git a/packages/core/tests/editor/selection/hit-test.test.ts b/packages/core/tests/editor/selection/hit-test.test.ts
index 787d22ef6..fd185253c 100644
--- a/packages/core/tests/editor/selection/hit-test.test.ts
+++ b/packages/core/tests/editor/selection/hit-test.test.ts
@@ -49,4 +49,26 @@ describe('editor scoped hit testing', () => {
editor.selectAtPoint(130, 130)
expect([...editor.state.selectedIds]).toEqual([frame.id])
})
+
+ test("selectAtPoint inside an entered board frame selects 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 })
+ const child = 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.state.enteredContainerId = frame.id
+ editor.selectAtPoint(130, 130)
+ expect([...editor.state.selectedIds]).toEqual([child.id])
+ })
})
diff --git a/packages/scene-graph/src/figjam/palette.ts b/packages/scene-graph/src/figjam/palette.ts
index 159140b9b..eaba6d0fd 100644
--- a/packages/scene-graph/src/figjam/palette.ts
+++ b/packages/scene-graph/src/figjam/palette.ts
@@ -232,6 +232,18 @@ export function figJamColorName(color: Color | undefined): FigJamColorName | nul
return FIGJAM_COLOR_NAMES.find((name) => sameColor(color, figJamColor(name))) ?? null
}
+/**
+ * The palette colour an outline is drawn in: a colour itself, or the outline a section of that
+ * colour takes, which is darker for black and lighter for white.
+ */
+export function figJamOutlineColorName(color: Color | undefined): FigJamColorName | null {
+ return (
+ figJamColorName(color) ??
+ FIGJAM_COLOR_NAMES.find((name) => sameColor(color, parseColor(PALETTE[name].sectionStroke))) ??
+ null
+ )
+}
+
/** The fill mode a shape's first fill shows. */
export function figJamFillMode(fill: Fill | undefined): FigJamFillMode {
if (!fill || !fill.visible || fill.opacity === 0) return 'none'
@@ -375,9 +387,12 @@ export function figJamSectionColorFields(
}
}
-/** The first of `paints` the canvas draws: a hidden or fully transparent one shows nothing. */
+/**
+ * The paint of `paints` the canvas shows on top: the last it draws, skipping hidden and fully
+ * transparent ones, which show nothing.
+ */
function drawnPaint<P extends Fill>(paints: readonly P[]): P | undefined {
- return paints.find((paint) => paint.visible && paint.opacity > 0)
+ return paints.findLast((paint) => paint.visible && paint.opacity > 0)
}
/** The palette colour a section is painted, by its tint. */
diff --git a/packages/scene-graph/tests/figjam/palette.test.ts b/packages/scene-graph/tests/figjam/palette.test.ts
index a4219296c..b49ddedb7 100644
--- a/packages/scene-graph/tests/figjam/palette.test.ts
+++ b/packages/scene-graph/tests/figjam/palette.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, test } from 'bun:test'
import { createShapeWithText, shapeWithTextLabel } from '@open-pencil/scene-graph/generated'
-import { figJamColor, figJamColorName, figJamLayerColorFields, figJamLayerColorName, figJamLineColorFields, figJamLineStyle, figJamLineStyleFields, figJamSectionColorFields, figJamSectionColorName, figJamShapePaint } from '@open-pencil/scene-graph/figjam'
+import { figJamColor, figJamColorName, figJamLayerColorFields, figJamLayerColorName, figJamLineColorFields, figJamLineStyle, figJamLineStyleFields, figJamOutlineColorName, figJamSectionColorFields, figJamSectionColorName, figJamShapePaint } from '@open-pencil/scene-graph/figjam'
import { SceneGraph } from '@open-pencil/scene-graph'
import { colorToHex } from '@open-pencil/scene-graph/color'
@@ -94,6 +94,13 @@ describe("FigJam's shape colours", () => {
expect(figJamSectionColorName({ fills: [hidden, ...(red.fills ?? [])] })).toBe('red')
})
+ test("a section's outline reads as its colour, darker for black and lighter for white", () => {
+ for (const name of ['black', 'white', 'red'] as const) {
+ const outline = figJamSectionColorFields({ strokes: [] }, name).strokes?.[0]?.color
+ expect(figJamOutlineColorName(outline)).toBe(name)
+ }
+ })
+
test('the colour menu paints text, a line, and other layers as FigJam does', () => {
const text = figJamLayerColorFields({ type: 'TEXT', fills: [], strokes: [], styleRuns: [] }, 'red')
expect(hexes(text.fills)).toEqual(['#f24822'])
@@ -120,7 +127,7 @@ describe("FigJam's shape colours", () => {
test('a layer shows the colour of its first paint the canvas draws', () => {
const paint = (name: 'red' | 'green' | 'blue', visible: boolean, opacity = 1) => ({ type: 'SOLID' as const, color: figJamColor(name), opacity, visible })
- const fills = [paint('red', false), paint('green', true, 0), paint('blue', true)]
+ const fills = [paint('red', true), paint('blue', true), paint('green', true, 0), paint('red', false)]
expect(figJamLayerColorName({ type: 'RECTANGLE', fills, strokes: [] })).toBe('blue')
})
diff --git a/packages/vue/src/controls/figjam-style/use.ts b/packages/vue/src/controls/figjam-style/use.ts
index ca6686e32..c83baf3ed 100644
--- a/packages/vue/src/controls/figjam-style/use.ts
+++ b/packages/vue/src/controls/figjam-style/use.ts
@@ -1,10 +1,11 @@
import { uniq } from 'es-toolkit'
import { computed } from 'vue'
+import { figJamColoredLayers } from '@open-pencil/core'
import type { SceneNode } from '@open-pencil/scene-graph'
import {
- figJamColorName,
figJamLayerColorName,
+ figJamOutlineColorName,
figJamLineStyle,
figJamSectionColorName,
figJamTextSize,
@@ -39,16 +40,10 @@ export function useFigJamStyle() {
)
const ids = computed(() => layers.value.map((layer) => layer.id))
- /** The layers a group's colour is read from: its contents, as its colour paints them. */
- function painted(layer: SceneNode): SceneNode[] {
- if (layer.type !== 'GROUP') return [layer]
- return editor.graph.getChildren(layer.id).flatMap(painted)
- }
-
- /** The palette colour a layer shows, a group's when its contents share one. */
+ /** The palette colour a layer shows, a group's when the layers its colour paints share one. */
function layerColor(layer: SceneNode): FigJamColorName | null {
if (layer.type === 'SECTION') return figJamSectionColorName(layer)
- const names = uniq(painted(layer).map(figJamLayerColorName))
+ const names = uniq(figJamColoredLayers(editor.graph, layer).map(figJamLayerColorName))
return names.length === 1 ? (names[0] ?? null) : null
}
@@ -59,7 +54,7 @@ export function useFigJamStyle() {
return {
color: layerColor(first),
lineStyle: figJamLineStyle(first),
- lineColor: figJamColorName(first.strokes.at(0)?.color),
+ lineColor: figJamOutlineColorName(first.strokes.at(0)?.color),
textSize: text ? figJamTextSize(text) : null,
typeface: text ? figJamTypeface(text) : null,
font: text?.fontFamily ?? null
diff --git a/packages/vue/src/shared/input/resize/snap.ts b/packages/vue/src/shared/input/resize/snap.ts
index 0c7e7ae00..f4188bc65 100644
--- a/packages/vue/src/shared/input/resize/snap.ts
+++ b/packages/vue/src/shared/input/resize/snap.ts
@@ -120,7 +120,8 @@ export function applyResizeSnap(
const dx = horizontal ? localCorrection.x : 0
const dy = vertical ? localCorrection.y : 0
- state.snapGuides = snap.guides
+ // Only the axes the handle moves snap, so only their guides show.
+ state.snapGuides = snap.guides.filter((guide) => (guide.axis === 'x' ? horizontal : vertical))
return applyEdgeDelta(drag.handle, rect, dx, dy)
}
@@ -147,6 +148,29 @@ const DRIVING_EDGE: Record<HandlePosition, Record<AspectDriver, HandlePosition>>
* lands on the grid and on other layers' edges as a free resize's edge would, and the other side
* follows the ratio, rounded to a whole pixel in a design and left as it falls on a board.
*/
+/** The size a drag gives the box before its ratio is kept. */
+function draggedSize(handle: HandlePosition, origRect: Rect, dx: number, dy: number) {
+ return {
+ width: origRect.width + edgeGrowth(dx, movesRight(handle), movesLeft(handle)),
+ height: origRect.height + edgeGrowth(dy, movesBottom(handle), movesTop(handle))
+ }
+}
+
+/**
+ * The side that drives a ratio-locked resize, which {@link proportionalResizeRect} snaps; the
+ * other follows it and may be rounded.
+ */
+export function proportionalResizeDriver(
+ handle: HandlePosition,
+ origRect: Rect,
+ dx: number,
+ dy: number,
+ aspect: number
+): AspectDriver {
+ const { width, height } = draggedSize(handle, origRect, dx, dy)
+ return aspectDriver(handle, width, height, aspect)
+}
+
export function proportionalResizeRect(
drag: ResizeSnapTarget,
origRect: Rect,
@@ -159,14 +183,13 @@ export function proportionalResizeRect(
const { handle } = drag
const constrained = calculateResizeRect(handle, origRect, dx, dy, aspect)
const state = optionalEditorState(editor)
- const width = origRect.width + edgeGrowth(dx, movesRight(handle), movesLeft(handle))
- const height = origRect.height + edgeGrowth(dy, movesBottom(handle), movesTop(handle))
+ const { width, height } = draggedSize(handle, origRect, dx, dy)
// A handle dragged past the opposite edge flips the box; it lands where the pointer puts it.
if (disableSnapping || !state || width <= 0 || height <= 0) {
if (state) state.snapGuides = []
return constrained
}
- const driver = aspectDriver(handle, width, height, aspect)
+ const driver = proportionalResizeDriver(handle, origRect, dx, dy, aspect)
const snapped = applyResizeSnap(
{ nodeId: drag.nodeId, handle: DRIVING_EDGE[handle][driver] },
constrained,
diff --git a/packages/vue/src/shared/input/sticky/scale.ts b/packages/vue/src/shared/input/sticky/scale.ts
index 0194bb017..82898de91 100644
--- a/packages/vue/src/shared/input/sticky/scale.ts
+++ b/packages/vue/src/shared/input/sticky/scale.ts
@@ -12,7 +12,7 @@ import { scaleNodeChanges } from '@open-pencil/scene-graph/scaling'
import { getHitHandleByMatrix } from '#vue/shared/input/geometry'
import { constrainToAspectRatio } from '#vue/shared/input/resize/rect'
-import { proportionalResizeRect } from '#vue/shared/input/resize/snap'
+import { proportionalResizeDriver, proportionalResizeRect } from '#vue/shared/input/resize/snap'
import type { DragStickyScale } from '#vue/shared/input/types'
/** The smallest scale a corner drag takes a note to, so it never folds away. */
@@ -113,30 +113,25 @@ export function applyStickyScale(
const { origRect } = d
// The note keeps its proportions, anchored and snapped as a Shift-resize from the same handle.
const aspect = origRect.width / origRect.height
- const rect = proportionalResizeRect(
- d,
+ const [dx, dy] = [cx - d.startX, cy - d.startY]
+ const rect = proportionalResizeRect(d, origRect, dx, dy, aspect, editor, disableSnapping)
+ // The scale comes from the side that snapped; the other follows it, rounded or not.
+ const driver = proportionalResizeDriver(d.handle, origRect, dx, dy, aspect)
+ const snappedScale = rect[driver] / origRect[driver]
+ d.scale = Math.max(MIN_STICKY_SCALE, snappedScale)
+ const clamped = d.scale !== snappedScale
+ // At its smallest the note no longer meets the edge it snapped to, so no guide shows one.
+ if (clamped) editor.setSnapGuides([])
+ // The note lands at the size its scale gives, anchored as the handle anchors it, so its edges
+ // meet the size it records and the snapped one stays on its guide.
+ const placed = constrainToAspectRatio(
+ d.handle,
origRect,
- cx - d.startX,
- cy - d.startY,
+ origRect.width * d.scale,
+ origRect.height * d.scale,
aspect,
- editor,
- disableSnapping
+ driver
)
- d.scale = Math.max(MIN_STICKY_SCALE, rect.width / origRect.width)
- const clamped = d.scale !== rect.width / origRect.width
- // At its smallest the note no longer meets the edge it snapped to, so no guide shows one.
- if (clamped) editor.setSnapGuides([])
- // A note scaled down to its smallest stays anchored as the handle anchors it.
- const placed = !clamped
- ? rect
- : constrainToAspectRatio(
- d.handle,
- origRect,
- origRect.width * d.scale,
- origRect.height * d.scale,
- aspect,
- 'width'
- )
d.position = { x: placed.x, y: placed.y }
for (const [id, original] of d.originals) {
const changes = scaleNodeChanges(original, d.scale, id !== d.nodeId)
diff --git a/packages/vue/tests/shared/input/sticky/scale.test.ts b/packages/vue/tests/shared/input/sticky/scale.test.ts
index 43c3b79ab..4ac1d2431 100644
--- a/packages/vue/tests/shared/input/sticky/scale.test.ts
+++ b/packages/vue/tests/shared/input/sticky/scale.test.ts
@@ -82,6 +82,25 @@ describe('scaling a sticky note by a corner on a board', () => {
expect(editor.graph.getNode(note.id)?.width).toBe(24)
})
+ // A wide note in a design file keeps its ratio with the following side rounded to pixels.
+ test('keeps a snapped bottom edge on its guide when the width is rounded', () => {
+ const editor = createEditor()
+ editor.state.snappingPreferences = { geometry: true, objects: true, pixelGrid: true }
+ const pageId = editor.state.currentPageId
+ const note = editor.createStickyNote(pageId, { x: 0, y: 0 })
+ editor.graph.updateNode(note.id, { x: 0, y: 0, width: 480, height: 240 })
+ editor.graph.createNode('RECTANGLE', pageId, { x: 700, y: 301.3, width: 20, height: 50 })
+ editor.select([note.id])
+ const drag = tryStartStickyScale(240, 240, editor)
+ if (!drag) throw new Error('No s handle')
+ applyStickyScale(drag, 240, 300, editor)
+ const guide = editor.state.snapGuides.find((line) => line.axis === 'y')
+ drag.commit()
+ const scaled = editor.graph.getNode(note.id)
+ expect(guide?.position).toBeCloseTo(301.3)
+ expect((scaled?.y ?? 0) + (scaled?.height ?? 0)).toBeCloseTo(301.3)
+ })
+
test('Control scales it freely, off the grid', () => {
expect(scaleNote({ x: 1264, y: 400 }, 'se', 37, 37, undefined, true)).toMatchObject({ width: 277 })
})
diff --git a/tests/engine/vue/input/snap-guides.test.ts b/tests/engine/vue/input/snap-guides.test.ts
index 7bf87c3c1..f60a21bc9 100644
--- a/tests/engine/vue/input/snap-guides.test.ts
+++ b/tests/engine/vue/input/snap-guides.test.ts
@@ -4,6 +4,7 @@ import { createEditor } from '@open-pencil/core'
import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'
import { computeSnap } from '@open-pencil/scene-graph/snap'
+import { applyResizeSnap } from '#vue/shared/input/resize/snap'
import { computePixelGridSnap, resolveObjectPixelSnap } from '#vue/shared/input/snap'
describe('move snap guide presentation', () => {
@@ -72,6 +73,23 @@ describe('move snap guide presentation', () => {
expect(result.guides.some((guide) => guide.axis === 'x' && guide.position === 200)).toBe(true)
})
+ test('a resize shows only the guides of the axes its handle moves', () => {
+ const editor = createEditor()
+ editor.state.snappingPreferences = { geometry: false, objects: true, pixelGrid: true }
+ const pageId = editor.state.currentPageId
+ const box = editor.graph.createNode('FRAME', pageId, { x: 0, y: 20, width: 100, height: 80 })
+ editor.graph.createNode('FRAME', pageId, { x: 150, y: 20, width: 100, height: 80 })
+ const rect = applyResizeSnap(
+ { nodeId: box.id, handle: 'e' },
+ { x: 0, y: 20, width: 148, height: 80 },
+ editor,
+ false
+ )
+ expect(rect.width).toBe(150)
+ expect(editor.state.snapGuides.map((guide) => guide.axis)).not.toContain('y')
+ expect(editor.state.snapGuides.length).toBeGreaterThan(0)
+ })
+
test('multiple moving nodes are excluded from object targets', () => {
const nodes = [
createDefaultNode(() => 'first', 'FRAME', { x: 0, y: 0, width: 50, height: 50, rotation: 0 }),