Skip to content

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

feat(canvas): sample colors from the canvas with the eyedropper (I) (#1193)

LarryBambelle2d8d71981d1b
diff --git a/changes/1193/added.md b/changes/1193/added.md
new file mode 100644
index 000000000..919ee3633
--- /dev/null
+++ b/changes/1193/added.md
@@ -0,0 +1 @@
+- The Eyedropper tool (I) and the color picker's eyedropper button pick any color shown on the canvas, with a loupe of the pixels under the pointer.
diff --git a/packages/core/src/editor/eyedropper.ts b/packages/core/src/editor/eyedropper.ts
new file mode 100644
index 000000000..1f1b84286
--- /dev/null
+++ b/packages/core/src/editor/eyedropper.ts
@@ -0,0 +1,198 @@
+import type { CanvasKit } from 'canvaskit-wasm'
+import { isEqual } from 'es-toolkit'
+
+import type { Fill, SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'
+import { newStrokeGeometry } from '@open-pencil/scene-graph/node-defaults'
+import type { Color } from '@open-pencil/scene-graph/primitives'
+import type { UndoManager } from '@open-pencil/scene-graph/undo'
+
+import type { SkiaRenderer } from '#core/canvas/renderer'
+import { getPageColor } from '#core/figma-api/page-backgrounds'
+
+/** Which paint of the selection a sampled colour replaces. Alt samples into the stroke. */
+export type EyedropperTarget = 'fill' | 'stroke'
+
+type SampleRenderer = Pick<
+ SkiaRenderer,
+ 'worldViewport' | 'viewportImageRendering' | 'presentationColorSpace' | 'renderNode'
+>
+
+/** A square of the document's pixels: RGBA rows, `size` pixels a side, the centre one sampled. */
+export interface ScenePixels {
+ size: number
+ data: Uint8Array
+}
+
+/**
+ * The document's pixels in a square of `size` (odd) pixels centred on a world point, each
+ * `1 / scale` world units wide, composited over the page background, so at the view's zoom they
+ * are the pixels the screen shows there.
+ *
+ * Renders only what intersects the square into a raster surface, so selection chrome, rulers and
+ * the screen's colour profile never leak into the result, unlike `window.EyeDropper`, which
+ * samples the screen. Components come back in the document's own colour space: the renderer
+ * presents in that space and the surface is not converted.
+ */
+export function sampleScenePixels(
+ ck: CanvasKit,
+ renderer: SampleRenderer,
+ graph: SceneGraph,
+ pageId: string,
+ x: number,
+ y: number,
+ size = 1,
+ scale = 1
+): ScenePixels | null {
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return null
+ if (!Number.isInteger(size) || size < 1 || size % 2 === 0 || !(scale > 0)) return null
+ const page = graph.getNode(pageId)
+ if (!page) return null
+ const surface = ck.MakeSurface(size, size)
+ if (!surface) return null
+ const previousViewport = renderer.worldViewport
+ const previousImageRendering = renderer.viewportImageRendering
+ const previousColorSpace = renderer.presentationColorSpace
+ try {
+ const canvas = surface.getCanvas()
+ const background = getPageColor(page)
+ canvas.clear(ck.Color4f(background.r, background.g, background.b, 1))
+ // Pixel (i, j) covers [i, i + 1); put the sampled point at the centre pixel's centre.
+ const half = (size - 1) / 2
+ canvas.translate(half + 0.5, half + 0.5)
+ canvas.scale(scale, scale)
+ canvas.translate(-x, -y)
+ const reach = (half + 1) / scale
+ renderer.worldViewport = { x: x - reach, y: y - reach, w: reach * 2, h: reach * 2 }
+ renderer.viewportImageRendering = false
+ renderer.presentationColorSpace = graph.documentColorSpace
+ for (const childId of page.childIds) renderer.renderNode(canvas, graph, childId, {})
+ surface.flush()
+ const data = canvas.readPixels(0, 0, {
+ width: size,
+ height: size,
+ alphaType: ck.AlphaType.Unpremul,
+ colorType: ck.ColorType.RGBA_8888,
+ colorSpace: ck.ColorSpace.SRGB
+ })
+ if (!(data instanceof Uint8Array) || data.length < size * size * 4) return null
+ return { size, data }
+ } finally {
+ renderer.worldViewport = previousViewport
+ renderer.viewportImageRendering = previousImageRendering
+ renderer.presentationColorSpace = previousColorSpace
+ surface.delete()
+ }
+}
+
+/** The opaque colour of one pixel of a sample, by column and row. */
+export function scenePixelColor(pixels: ScenePixels, column: number, row: number): Color {
+ const at = (row * pixels.size + column) * 4
+ const { data } = pixels
+ return { r: data[at] / 255, g: data[at + 1] / 255, b: data[at + 2] / 255, a: 1 }
+}
+
+/** The colour the document shows at a world point, one `1 / scale`-wide pixel of it. */
+export function sampleSceneColor(
+ ck: CanvasKit,
+ renderer: SampleRenderer,
+ graph: SceneGraph,
+ pageId: string,
+ x: number,
+ y: number,
+ scale = 1
+): Color | null {
+ const pixels = sampleScenePixels(ck, renderer, graph, pageId, x, y, 1, scale)
+ return pixels ? scenePixelColor(pixels, 0, 0) : null
+}
+
+function solidPaint(color: Color): Fill {
+ return { type: 'SOLID', color: { ...color, a: 1 }, opacity: 1, visible: true }
+}
+
+/**
+ * Replaces the top solid paint's colour, keeping its opacity, or adds an opaque solid paint. A
+ * solid paint's alpha is its opacity, as the colour picker writes them, so the alpha stays too.
+ */
+function withSampledPaint<T extends Fill>(
+ paints: readonly T[],
+ color: Color,
+ create: (paint: Fill) => T
+): { paints: T[]; index: number } {
+ const next = paints.map((paint) => ({ ...paint }))
+ for (let index = next.length - 1; index >= 0; index--) {
+ if (next[index].type !== 'SOLID') continue
+ next[index] = { ...next[index], color: { ...color, a: next[index].color.a } }
+ return { paints: next, index }
+ }
+ next.push(create(solidPaint(color)))
+ return { paints: next, index: next.length - 1 }
+}
+
+export function eyedropperChanges(
+ node: SceneNode,
+ color: Color,
+ target: EyedropperTarget
+): Partial<SceneNode> {
+ const boundVariables = { ...node.boundVariables }
+ if (target === 'stroke') {
+ // A first stroke takes the weight and alignment the node keeps for its strokes.
+ const { paints, index } = withSampledPaint<Stroke>(node.strokes, color, (paint) => ({
+ ...paint,
+ ...newStrokeGeometry(node)
+ }))
+ delete boundVariables[`strokes/${index}/color`]
+ return { strokes: paints, boundVariables }
+ }
+ const { paints, index } = withSampledPaint<Fill>(node.fills, color, (paint) => paint)
+ delete boundVariables[`fills/${index}/color`]
+ const changes: Partial<SceneNode> = { fills: paints, boundVariables }
+ // Text colour lives in the node fills; per-character fills would hide the sample.
+ if (node.type === 'TEXT' && node.styleRuns.some((run) => run.style.fills)) {
+ changes.styleRuns = node.styleRuns.map((run) => {
+ const style = { ...run.style }
+ delete style.fills
+ return { ...run, style }
+ })
+ }
+ return changes
+}
+
+interface EyedropperEditor {
+ graph: SceneGraph
+ undo: UndoManager
+ state: { selectedIds: ReadonlySet<string> }
+ updateNodeWithUndo: (id: string, changes: Partial<SceneNode>, label?: string) => void
+}
+
+/** Whether the changes would leave the layer as it is, as when it already has the colour. */
+function changesNothing(node: SceneNode, changes: Partial<SceneNode>): boolean {
+ return Object.entries(changes).every(([key, value]) =>
+ isEqual(node[key as keyof SceneNode], value)
+ )
+}
+
+/**
+ * Applies a sampled colour to every selected layer that can take a paint, as one undo step.
+ * Layers that already show it are left alone, so a sample that changes nothing records nothing.
+ * Returns how many layers changed.
+ */
+export function applySampledColor(
+ editor: EyedropperEditor,
+ color: Color,
+ target: EyedropperTarget = 'fill'
+): number {
+ const nodes = [...editor.state.selectedIds]
+ .map((id) => editor.graph.getNode(id))
+ .filter((node): node is SceneNode => node !== undefined && !node.locked)
+ .filter((node) => node.type !== 'GROUP')
+ const edits = nodes
+ .map((node) => ({ node, changes: eyedropperChanges(node, color, target) }))
+ .filter(({ node, changes }) => !changesNothing(node, changes))
+ if (edits.length === 0) return 0
+ editor.undo.runBatch('Eyedropper', () => {
+ for (const { node, changes } of edits) {
+ editor.updateNodeWithUndo(node.id, changes, 'Eyedropper')
+ }
+ })
+ return edits.length
+}
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index 329143277..9335808d1 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -58,6 +58,14 @@ export { opacityFromBuffer } from './nodes'
export { layerTypeOptions, type LayerType } from './structure/layer-type'
export type { NodePreview } from './node-preview'
export { BOARD_TOOL_SHORTCUTS, BOARD_TOOLS, EDITOR_TOOLS, TOOL_SHORTCUTS } from './tool-registry'
+export {
+ applySampledColor,
+ eyedropperChanges,
+ sampleSceneColor,
+ sampleScenePixels,
+ scenePixelColor
+} from './eyedropper'
+export type { EyedropperTarget, ScenePixels } from './eyedropper'
export type { RenameSelectionOptions, RenameSelectionPreview } from './structure/rename'
export type { EditorToolDef } from './tool-registry'
export type {
diff --git a/packages/core/src/editor/tool-registry.ts b/packages/core/src/editor/tool-registry.ts
index 5e9299f2f..4b40d30ce 100644
--- a/packages/core/src/editor/tool-registry.ts
+++ b/packages/core/src/editor/tool-registry.ts
@@ -40,7 +40,8 @@ export const TOOL_SHORTCUTS: Partial<Record<string, Tool>> = {
KeyP: 'PEN',
'Shift+KeyP': 'PENCIL',
KeyH: 'HAND',
- KeyC: 'COMMENT'
+ KeyC: 'COMMENT',
+ KeyI: 'EYEDROPPER'
}
/**
diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.ts
index 205b52141..b8de39e7a 100644
--- a/packages/core/src/editor/types.ts
+++ b/packages/core/src/editor/types.ts
@@ -52,6 +52,7 @@ export type Tool =
| 'PENCIL'
| 'HAND'
| 'COMMENT'
+ | 'EYEDROPPER'
/** The gradient whose handles the canvas shows while its paint picker is open. */
export interface GradientEdit {
diff --git a/packages/core/tests/editor/eyedropper.test.ts b/packages/core/tests/editor/eyedropper.test.ts
new file mode 100644
index 000000000..445490e5a
--- /dev/null
+++ b/packages/core/tests/editor/eyedropper.test.ts
@@ -0,0 +1,245 @@
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
+
+import { expectDefined, getNodeOrThrow } from '#core-tests/helpers/assert'
+import type { CanvasKit } from 'canvaskit-wasm'
+
+import type { Fill, SceneNode } from '@open-pencil/scene-graph'
+import type { Color } from '@open-pencil/scene-graph/primitives'
+
+import { SkiaRenderer } from '#core/canvas/renderer'
+import { createEditor } from '#core/editor/create'
+import {
+ applySampledColor,
+ eyedropperChanges,
+ sampleSceneColor,
+ sampleScenePixels,
+ scenePixelColor
+} from '#core/editor/eyedropper'
+import { TOOL_SHORTCUTS } from '#core/editor/tool-registry'
+import { getPageColor } from '#core/figma-api/page-backgrounds'
+import { initCanvasKit } from '#core/io/formats/raster/headless'
+
+function solid(color: Color): Fill {
+ return { type: 'SOLID', color, opacity: 1, visible: true }
+}
+
+const RED = { r: 1, g: 0, b: 0, a: 1 }
+const GREEN = { r: 0, g: 1, b: 0, a: 1 }
+const BLUE = { r: 0, g: 0, b: 1, a: 1 }
+const WHITE = { r: 1, g: 1, b: 1, a: 1 }
+
+describe('sampleSceneColor', () => {
+ let ck: CanvasKit
+ let renderer: SkiaRenderer
+
+ beforeAll(async () => {
+ ck = await initCanvasKit()
+ renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))
+ })
+ afterAll(() => renderer.destroy())
+
+ function scene() {
+ const editor = createEditor()
+ const pageId = editor.graph.getPages()[0].id
+ const cells: Array<[number, number, Color]> = [
+ [0, 0, RED],
+ [1, 0, GREEN],
+ [0, 1, BLUE],
+ [1, 1, WHITE]
+ ]
+ for (const [x, y, color] of cells) {
+ editor.graph.createNode('RECTANGLE', pageId, {
+ x,
+ y,
+ width: 1,
+ height: 1,
+ fills: [solid(color)]
+ })
+ }
+ return { graph: editor.graph, pageId }
+ }
+
+ function bytes(color: Color | null) {
+ const c = expectDefined(color)
+ return [c.r, c.g, c.b, c.a].map((v) => Math.round(v * 255))
+ }
+
+ test('reads the exact RGBA of each pixel of a rendered 2x2 scene', () => {
+ const { graph, pageId } = scene()
+ expect(bytes(sampleSceneColor(ck, renderer, graph, pageId, 0.5, 0.5))).toEqual([255, 0, 0, 255])
+ expect(bytes(sampleSceneColor(ck, renderer, graph, pageId, 1.5, 0.5))).toEqual([0, 255, 0, 255])
+ expect(bytes(sampleSceneColor(ck, renderer, graph, pageId, 0.5, 1.5))).toEqual([0, 0, 255, 255])
+ expect(bytes(sampleSceneColor(ck, renderer, graph, pageId, 1.5, 1.5))).toEqual([
+ 255, 255, 255, 255
+ ])
+ })
+
+ test('outside every layer it returns the page background', () => {
+ const { graph, pageId } = scene()
+ const background = getPageColor(getNodeOrThrow(graph, pageId))
+ expect(bytes(sampleSceneColor(ck, renderer, graph, pageId, 50, 50))).toEqual(
+ bytes({ ...background, a: 1 })
+ )
+ })
+
+ test('composites translucent layers over what is below', () => {
+ const { graph, pageId } = scene()
+ graph.createNode('RECTANGLE', pageId, {
+ x: 0,
+ y: 0,
+ width: 1,
+ height: 1,
+ fills: [{ ...solid(BLUE), opacity: 0.5 }]
+ })
+ const [r, g, b] = bytes(sampleSceneColor(ck, renderer, graph, pageId, 0.5, 0.5))
+ expect(Math.abs(r - 128)).toBeLessThanOrEqual(1)
+ expect(g).toBe(0)
+ expect(Math.abs(b - 128)).toBeLessThanOrEqual(1)
+ })
+
+ test('restores the renderer viewport it borrowed', () => {
+ const { graph, pageId } = scene()
+ renderer.worldViewport = { x: 10, y: 20, w: 30, h: 40 }
+ sampleSceneColor(ck, renderer, graph, pageId, 0.5, 0.5)
+ expect(renderer.worldViewport).toEqual({ x: 10, y: 20, w: 30, h: 40 })
+ })
+
+ test('rejects non-finite points and unknown pages', () => {
+ const { graph, pageId } = scene()
+ expect(sampleSceneColor(ck, renderer, graph, pageId, Number.NaN, 0)).toBeNull()
+ expect(sampleSceneColor(ck, renderer, graph, 'missing', 0, 0)).toBeNull()
+ })
+
+ test('a square of pixels has the sampled one at its centre and its neighbours around it', () => {
+ const { graph, pageId } = scene()
+ const background = bytes({ ...getPageColor(getNodeOrThrow(graph, pageId)), a: 1 })
+ const pixels = expectDefined(sampleScenePixels(ck, renderer, graph, pageId, 0.5, 0.5, 3))
+ const at = (column: number, row: number) => bytes(scenePixelColor(pixels, column, row))
+ expect(at(1, 1)).toEqual([255, 0, 0, 255])
+ expect(at(2, 1)).toEqual([0, 255, 0, 255])
+ expect(at(1, 2)).toEqual([0, 0, 255, 255])
+ expect(at(2, 2)).toEqual([255, 255, 255, 255])
+ expect(at(0, 0)).toEqual(background)
+ })
+
+ test('at a zoom each pixel spans that fraction of a world unit, as the screen shows it', () => {
+ const { graph, pageId } = scene()
+ const background = bytes({ ...getPageColor(getNodeOrThrow(graph, pageId)), a: 1 })
+ const pixels = expectDefined(sampleScenePixels(ck, renderer, graph, pageId, 0.25, 0.25, 3, 2))
+ const row = [0, 1, 2].map((column) => bytes(scenePixelColor(pixels, column, 1)))
+ expect(row).toEqual([background, [255, 0, 0, 255], [255, 0, 0, 255]])
+ })
+
+ test('rejects even and empty squares', () => {
+ const { graph, pageId } = scene()
+ expect(sampleScenePixels(ck, renderer, graph, pageId, 0.5, 0.5, 2)).toBeNull()
+ expect(sampleScenePixels(ck, renderer, graph, pageId, 0.5, 0.5, 0)).toBeNull()
+ expect(sampleScenePixels(ck, renderer, graph, pageId, 0.5, 0.5, 3, 0)).toBeNull()
+ })
+})
+
+describe('applySampledColor', () => {
+ function setup(overrides: Partial<SceneNode> = {}) {
+ const editor = createEditor()
+ const pageId = editor.graph.getPages()[0].id
+ const rect = editor.graph.createNode('RECTANGLE', pageId, {
+ width: 10,
+ height: 10,
+ fills: [solid(BLUE)],
+ ...overrides
+ })
+ editor.select([rect.id])
+ return { editor, rect }
+ }
+
+ test('replaces the top solid fill and undo reverts in one step', () => {
+ const { editor, rect } = setup()
+ expect(applySampledColor(editor, RED)).toBe(1)
+ expect(getNodeOrThrow(editor.graph, rect.id).fills[0].color).toEqual(RED)
+ editor.undoAction()
+ expect(getNodeOrThrow(editor.graph, rect.id).fills[0].color).toEqual(BLUE)
+ })
+
+ test('keeps the fill opacity and its alpha, and drops a colour variable binding', () => {
+ const { editor, rect } = setup({
+ fills: [{ ...solid({ ...BLUE, a: 0.4 }), opacity: 0.4 }],
+ boundVariables: { 'fills/0/color': 'VariableID:1:2' }
+ })
+ applySampledColor(editor, RED)
+ const node = getNodeOrThrow(editor.graph, rect.id)
+ expect(node.fills[0]).toMatchObject({ color: { ...RED, a: 0.4 }, opacity: 0.4 })
+ expect(node.boundVariables['fills/0/color']).toBeUndefined()
+ })
+
+ test('adds a solid fill above a gradient', () => {
+ const { editor, rect } = setup({
+ fills: [{ ...solid(BLUE), type: 'GRADIENT_LINEAR', gradientStops: [] }]
+ })
+ applySampledColor(editor, GREEN)
+ const fills = getNodeOrThrow(editor.graph, rect.id).fills
+ expect(fills).toHaveLength(2)
+ expect(fills[1]).toMatchObject({ type: 'SOLID', color: GREEN })
+ })
+
+ test('Alt target paints the stroke, adding one with the weight and alignment the node keeps', () => {
+ const { editor, rect } = setup({ strokeWeight: 3, strokeAlign: 'OUTSIDE' })
+ applySampledColor(editor, RED, 'stroke')
+ const node = getNodeOrThrow(editor.graph, rect.id)
+ expect(node.strokes).toHaveLength(1)
+ expect(node.strokes[0]).toMatchObject({
+ type: 'SOLID',
+ color: RED,
+ weight: 3,
+ align: 'OUTSIDE'
+ })
+ expect(node.fills[0].color).toEqual(BLUE)
+ })
+
+ test('text drops per-character fills so the whole text takes the colour', () => {
+ const editor = createEditor()
+ const pageId = editor.graph.getPages()[0].id
+ const text = editor.graph.createNode('TEXT', pageId, {
+ text: 'Hello',
+ fills: [solid(BLUE)],
+ styleRuns: [{ start: 0, length: 2, style: { fills: [solid(GREEN)], fontWeight: 700 } }]
+ })
+ const changes = eyedropperChanges(text, RED, 'fill')
+ expect(changes.styleRuns?.[0].style).toEqual({ fontWeight: 700 })
+ expect(changes.fills?.[0].color).toEqual(RED)
+ })
+
+ test('redo brings back the colour, and undo the binding it dropped', () => {
+ const { editor, rect } = setup({ boundVariables: { 'fills/0/color': 'VariableID:1:2' } })
+ applySampledColor(editor, RED)
+ editor.undoAction()
+ expect(getNodeOrThrow(editor.graph, rect.id).boundVariables['fills/0/color']).toBe(
+ 'VariableID:1:2'
+ )
+ editor.redoAction()
+ const node = getNodeOrThrow(editor.graph, rect.id)
+ expect(node.fills[0].color).toEqual(RED)
+ expect(node.boundVariables['fills/0/color']).toBeUndefined()
+ })
+
+ test('a colour the layer already has records no undo step', () => {
+ const { editor } = setup()
+ const before = editor.undo.peekUndo()
+ expect(applySampledColor(editor, BLUE)).toBe(0)
+ expect(editor.undo.peekUndo()).toBe(before)
+ })
+
+ test('does nothing without a selection', () => {
+ const { editor } = setup()
+ editor.clearSelection()
+ expect(applySampledColor(editor, RED)).toBe(0)
+ })
+})
+
+describe('tool registry', () => {
+ test('I selects the eyedropper and no other key does', () => {
+ const keys = Object.entries(TOOL_SHORTCUTS)
+ .filter(([, tool]) => tool === 'EYEDROPPER')
+ .map(([key]) => key)
+ expect(keys).toEqual(['KeyI'])
+ })
+})
diff --git a/packages/docs/de/reference/figma-compatibility.md b/packages/docs/de/reference/figma-compatibility.md
index fffa45ed8..bc0390d8c 100644
--- a/packages/docs/de/reference/figma-compatibility.md
+++ b/packages/docs/de/reference/figma-compatibility.md
@@ -22,7 +22,7 @@ Vergleich der Funktionen von Figma Design mit dem aktuellen Stand von OpenPencil
| Hilfslinien | ✅ | Aus den Linealen auf die Arbeitsfläche oder in Rahmen ziehen; auswählen, verschieben, duplizieren, löschen und rückgängig machen; in `.fig` gespeichert |
| Befehlspalette | ✅ | <kbd>⌘</kbd><kbd>K</kbd> öffnet eine durchsuchbare Liste der Editor- und App-Aktionen |
| Kontextmenü | ✅ | Zwischenablage, Reihenfolge, Gruppen, Komponenten, Sichtbarkeit, Sperre und Seitenwechsel |
-| Tastenkürzel | 🟡 | Werkzeuge, Bearbeitung, boolesche Operationen, Abflachen, Masken, Komponenten, Ausrichtung, Reihenfolge, Navigation und Textformatierung; kein Skalieren (<kbd>K</kbd>), Pfeil, Pipette (<kbd>I</kbd>) oder Zoomwerkzeug |
+| Tastenkürzel | 🟡 | Werkzeuge, Bearbeitung, boolesche Operationen, Abflachen, Masken, Komponenten, Ausrichtung, Reihenfolge, Navigation und Textformatierung; kein Skalieren (<kbd>K</kbd>), Pfeil oder Zoomwerkzeug |
| Suchen und Ersetzen | 🔲 | Keine dokumentweite Textsuche |
| Ebenenkonturen | 🔲 | Keine Drahtgitteransicht |
| Eigene Miniatur | 🔲 | Gespeicherte Dateien zeigen ihre erste Seite, wie Figma ohne Cover-Seite; keine eigene Auswahl |
@@ -68,7 +68,7 @@ Direkte Textbearbeitung, CanvasKit Paragraph, Systemschriften, Schriftwahl, Grö
## Farben, Verläufe und Bilder
-Volltonfarben, lineare, radiale, Winkel- und Diamantverläufe, Bildfüllungen, Mischmodi, Auswahlfarben für Mehrfachauswahlen sowie Hex-, RGB-, HSL-, HSB- und OkHCL-Felder werden unterstützt. Teilweise umgesetzt sind Musterfüllungen (aus Figma importierte werden dargestellt, lassen sich aber nicht erstellen), das Hinzufügen von Bildern (Ablegen oder Einfügen, kein Video) und Zuschnitt (Modus Crop, keine Griffe auf der Arbeitsfläche). Bildkorrekturen und Pipette fehlen.
+Volltonfarben, lineare, radiale, Winkel- und Diamantverläufe, Bildfüllungen, Mischmodi, Auswahlfarben für Mehrfachauswahlen sowie Hex-, RGB-, HSL-, HSB- und OkHCL-Felder werden unterstützt. Teilweise umgesetzt sind Musterfüllungen (aus Figma importierte werden dargestellt, lassen sich aber nicht erstellen), das Hinzufügen von Bildern (Ablegen oder Einfügen, kein Video) und Zuschnitt (Modus Crop, keine Griffe auf der Arbeitsfläche). Bildkorrekturen fehlen.
## Effekte und Eigenschaften
diff --git a/packages/docs/reference/figma-compatibility.md b/packages/docs/reference/figma-compatibility.md
index b7ef1741c..49a67a6dc 100644
--- a/packages/docs/reference/figma-compatibility.md
+++ b/packages/docs/reference/figma-compatibility.md
@@ -22,7 +22,7 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu
| Canvas guides | ✅ | Drag guides from rulers onto the canvas or frames; select, move, duplicate, delete, and undo; saved in `.fig` |
| Actions menu / command palette | ✅ | <kbd>⌘</kbd><kbd>K</kbd> opens a searchable palette of editor and app actions |
| Context menu | ✅ | Right-click with clipboard, z-order, grouping, component, visibility, lock, move-to-page actions |
-| Keyboard shortcuts | 🟡 | Tools, editing, booleans, flatten, masks, components, align, z-order, navigation, text formatting; no Scale (<kbd>K</kbd>), Arrow, Eyedropper (<kbd>I</kbd>), or zoom tool |
+| Keyboard shortcuts | 🟡 | Tools, editing, booleans, flatten, masks, components, align, z-order, navigation, text formatting; no Scale (<kbd>K</kbd>), Arrow, or zoom tool |
| Find and replace | 🔲 | Text search/replace across document |
| Layer outlines view | 🔲 | Wireframe view of all layers |
| Custom file thumbnails | 🔲 | Saved files preview their first page, as Figma's do without a Cover page; no thumbnail picker |
@@ -113,7 +113,7 @@ Feature-by-feature comparison of Figma Design capabilities with Open Pencil's cu
| Add images & videos | 🟡 | Drop or paste PNG, JPEG, GIF, WebP, AVIF, and SVG onto the canvas; no video |
| Image property adjustment | 🔲 | Exposure, contrast, saturation, etc. |
| Crop an image | 🟡 | The Crop mode in the image fill picker keeps a crop; no on-canvas crop handles |
-| Eyedropper tool | 🔲 | Sample colors from canvas |
+| Eyedropper tool | ✅ | <kbd>I</kbd> or the color picker button; samples the rendered canvas with a loupe of the pixels under the pointer, <kbd>Alt</kbd> targets the stroke |
| Mixed selection color editing | ✅ | Selection colors changes a color everywhere across a multi-selection |
| Color models (RGB, HSL, HSB, Hex) | ✅ | Hex, RGB, HSL, HSB, and OkHCL fields with gamut warnings |
diff --git a/packages/docs/reference/keyboard-shortcuts.md b/packages/docs/reference/keyboard-shortcuts.md
index d9415fea0..5de925a3c 100644
--- a/packages/docs/reference/keyboard-shortcuts.md
+++ b/packages/docs/reference/keyboard-shortcuts.md
@@ -32,7 +32,7 @@ Full Figma-compatible shortcut map. ✅ = implemented.
| — | Sticky note (FigJam) | ✅ (toolbar, hidden by default) |
| — | Connector (FigJam) | ✅ (toolbar, hidden by default) |
| <kbd>C</kbd> | Comment | ✅ |
-| <kbd>I</kbd> | Eyedropper | 🔲 |
+| <kbd>I</kbd> | Eyedropper | ✅ |
## File
diff --git a/packages/vue/package.json b/packages/vue/package.json
index 2d5a1d1d0..8e3063cd8 100644
--- a/packages/vue/package.json
+++ b/packages/vue/package.json
@@ -19,6 +19,11 @@
"import": "./dist/canvas/drop/index.js",
"default": "./dist/canvas/drop/index.js"
},
+ "./canvas/eyedropper": {
+ "types": "./dist/canvas/eyedropper/index.d.ts",
+ "import": "./dist/canvas/eyedropper/index.js",
+ "default": "./dist/canvas/eyedropper/index.js"
+ },
"./canvas/issues": {
"types": "./dist/canvas/issues/index.d.ts",
"import": "./dist/canvas/issues/index.js",
diff --git a/packages/vue/src/canvas/eyedropper/index.ts b/packages/vue/src/canvas/eyedropper/index.ts
new file mode 100644
index 000000000..84cc465bd
--- /dev/null
+++ b/packages/vue/src/canvas/eyedropper/index.ts
@@ -0,0 +1,77 @@
+import { applySampledColor, resolveEditorProfile, scenePixelColor } from '@open-pencil/core'
+import type { Editor, EyedropperTarget } from '@open-pencil/core'
+import type { Color } from '@open-pencil/scene-graph/primitives'
+
+import { sampleEyedropperPixels } from './sample'
+
+interface SampleRequest {
+ resolve: (color: Color | null) => void
+ stop: () => void
+}
+
+/** The request a color picker waits on, per editor; a new request replaces the old one. */
+const requests = new WeakMap<Editor, SampleRequest>()
+
+function settle(editor: Editor, color: Color | null) {
+ const request = requests.get(editor)
+ if (!request) return
+ requests.delete(editor)
+ request.stop()
+ request.resolve(color)
+}
+
+/** Whether the editor's profile offers the eyedropper; boards and read-only documents do not. */
+export function offersEyedropper(editor: Editor): boolean {
+ const { tools } = resolveEditorProfile(editor.state)
+ return !tools || tools.has('EYEDROPPER')
+}
+
+/**
+ * Switches to the eyedropper and resolves with the next color picked on the canvas instead of
+ * applying it to the selection; `null` when the user leaves the tool or the request is cancelled.
+ */
+export function requestEyedropperSample(editor: Editor): Promise<Color | null> {
+ settle(editor, null)
+ editor.setTool('EYEDROPPER')
+ if (editor.state.activeTool !== 'EYEDROPPER') return Promise.resolve(null)
+ return new Promise((resolve) => {
+ // Subscribed after switching, so the switch to the eyedropper itself does not cancel.
+ const stop = editor.onEditorEvent('tool:changed', () => settle(editor, null))
+ requests.set(editor, { resolve, stop })
+ })
+}
+
+/** Gives up a waiting request, as when its picker closes, and leaves the eyedropper. */
+export function cancelEyedropperSample(editor: Editor) {
+ if (!requests.has(editor)) return
+ settle(editor, null)
+ if (editor.state.activeTool === 'EYEDROPPER') editor.setTool('SELECT')
+}
+
+/**
+ * Whether a press answers a picker's request: one on the canvas while a request waits. A picker
+ * passes it as `keepOpen`, so the press that samples does not dismiss it.
+ */
+export function pressAnswersEyedropper(editor: Editor, event: PointerEvent): boolean {
+ return requests.has(editor) && event.target instanceof HTMLCanvasElement
+}
+
+/**
+ * A click with the eyedropper: answers a waiting picker request, otherwise paints the selection's
+ * fill (Alt: stroke) in one undo step. Either way the Move tool comes back.
+ */
+export function handleEyedropperDown(editor: Editor, cx: number, cy: number, altKey: boolean) {
+ const pixels = sampleEyedropperPixels(editor, cx, cy, 1)
+ const color = pixels ? scenePixelColor(pixels, 0, 0) : null
+ if (requests.has(editor)) {
+ // Resolve before the tool switch, which would otherwise cancel the request.
+ settle(editor, color)
+ } else if (color) {
+ const target: EyedropperTarget = altKey ? 'stroke' : 'fill'
+ applySampledColor(editor, color, target)
+ }
+ editor.setTool('SELECT')
+}
+
+export { EYEDROPPER_LOUPE_PIXELS, useEyedropperLoupe } from './use'
+export type { EyedropperLoupe } from './use'
diff --git a/packages/vue/src/canvas/eyedropper/sample.ts b/packages/vue/src/canvas/eyedropper/sample.ts
new file mode 100644
index 000000000..7b4991ff3
--- /dev/null
+++ b/packages/vue/src/canvas/eyedropper/sample.ts
@@ -0,0 +1,15 @@
+import { sampleScenePixels } from '@open-pencil/core'
+import type { Editor, ScenePixels } from '@open-pencil/core'
+
+/** The screen pixels around a world point at the view's zoom, the centre one sampled. */
+export function sampleEyedropperPixels(
+ editor: Editor,
+ cx: number,
+ cy: number,
+ size: number
+): ScenePixels | null {
+ const renderer = editor.renderer
+ if (!renderer) return null
+ const { currentPageId, zoom } = editor.state
+ return sampleScenePixels(renderer.ck, renderer, editor.graph, currentPageId, cx, cy, size, zoom)
+}
diff --git a/packages/vue/src/canvas/eyedropper/use.ts b/packages/vue/src/canvas/eyedropper/use.ts
new file mode 100644
index 000000000..388c25ee9
--- /dev/null
+++ b/packages/vue/src/canvas/eyedropper/use.ts
@@ -0,0 +1,96 @@
+import { useElementHover, useMouseInElement, useRafFn } from '@vueuse/core'
+import {
+ computed,
+ shallowRef,
+ toValue,
+ watch,
+ type ComputedRef,
+ type MaybeRefOrGetter,
+ type Ref,
+ type ShallowRef
+} from 'vue'
+
+import { scenePixelColor } from '@open-pencil/core'
+import type { Editor, ScenePixels } from '@open-pencil/core'
+import type { Color } from '@open-pencil/scene-graph/primitives'
+
+import { sampleEyedropperPixels } from './sample'
+
+/** How many screen pixels a side the loupe shows; odd, so one pixel is the centre. */
+export const EYEDROPPER_LOUPE_PIXELS = 9
+
+/**
+ * A loupe that stands in for the cursor while the eyedropper is active over the canvas: centred
+ * on the pointer, so the outlined centre pixel is the one a click picks. The pointer cursor
+ * itself should be hidden while it shows, or the cursor, drawn by the system ahead of the page,
+ * appears to run ahead of the loupe.
+ */
+export interface EyedropperLoupe {
+ /** Whether the loupe has pixels to show: the eyedropper is active with the pointer on the canvas. */
+ visible: ComputedRef<boolean>
+ /** The pointer in viewport (client) coordinates, updated with each move. */
+ clientX: ShallowRef<number>
+ clientY: ShallowRef<number>
+ /** The screen pixels around the pointer, sampled once a frame from the document alone. */
+ pixels: ShallowRef<ScenePixels | null>
+ /** The centre pixel's colour: what a click picks. */
+ color: ComputedRef<Color | null>
+}
+
+/**
+ * Tracks the pointer over a canvas while the eyedropper is active. The position follows each
+ * move at once; the pixels are sampled on the next frame, and again only when the pointer, the
+ * view, or the page changed, so a still pointer costs nothing. `enabled` is false for a canvas
+ * that takes no input, such as a split view's inactive pane.
+ */
+export function useEyedropperLoupe(
+ editor: Editor,
+ canvas: Readonly<Ref<HTMLElement | null | undefined>>,
+ enabled: MaybeRefOrGetter<boolean> = true
+): EyedropperLoupe {
+ const pointer = useMouseInElement(canvas, { handleOutside: false, type: 'client' })
+ const hovered = useElementHover(canvas)
+ const active = computed(
+ () => toValue(enabled) && hovered.value && editor.state.activeTool === 'EYEDROPPER'
+ )
+ const pixels = shallowRef<ScenePixels | null>(null)
+ let sampledAt = ''
+
+ const { pause, resume } = useRafFn(
+ () => {
+ const sx = pointer.elementX.value
+ const sy = pointer.elementY.value
+ const { zoom, panX, panY, currentPageId } = editor.state
+ const at = `${sx} ${sy} ${zoom} ${panX} ${panY} ${currentPageId}`
+ if (at === sampledAt) return
+ sampledAt = at
+ const { x, y } = editor.screenToCanvas(sx, sy)
+ pixels.value = sampleEyedropperPixels(editor, x, y, EYEDROPPER_LOUPE_PIXELS)
+ },
+ { immediate: false }
+ )
+
+ watch(
+ active,
+ (shown) => {
+ if (shown) return resume()
+ pause()
+ pixels.value = null
+ sampledAt = ''
+ },
+ { immediate: true }
+ )
+
+ const centre = (EYEDROPPER_LOUPE_PIXELS - 1) / 2
+ const color = computed(() =>
+ pixels.value ? scenePixelColor(pixels.value, centre, centre) : null
+ )
+
+ return {
+ visible: computed(() => active.value && color.value !== null),
+ clientX: pointer.x,
+ clientY: pointer.y,
+ pixels,
+ color
+ }
+}
diff --git a/packages/vue/src/canvas/tools/registry.ts b/packages/vue/src/canvas/tools/registry.ts
index dcaa6dff6..8ad18af33 100644
--- a/packages/vue/src/canvas/tools/registry.ts
+++ b/packages/vue/src/canvas/tools/registry.ts
@@ -2,6 +2,7 @@ import type { Ref } from 'vue'
import type { Editor, Tool } from '@open-pencil/core'
+import { handleEyedropperDown } from '#vue/canvas/eyedropper'
import { startPenInput, updatePenHover } from '#vue/canvas/pen/input'
import { startPencilInput } from '#vue/canvas/pencil/input'
import { HAND_GRAB_CURSOR } from '#vue/editor/tool-cursor'
@@ -76,6 +77,11 @@ export const CANVAS_TOOLS: Readonly<Record<Tool, CanvasTool>> = {
HAND: pan,
// Comments are placed by the app's comments layer above the canvas.
COMMENT: { press: () => undefined },
+ EYEDROPPER: {
+ press: ({ event, cx, cy }, { editor }) => {
+ if (event.button === 0) handleEyedropperDown(editor, cx, cy, event.altKey)
+ }
+ },
PEN: {
press: ({ event, cx, cy }, { editor, setDrag, cursorOverride }) =>
startPenInput(event, cx, cy, editor, setDrag, cursorOverride),
diff --git a/packages/vue/src/editor/tool-cursor/index.ts b/packages/vue/src/editor/tool-cursor/index.ts
index cd43d7df1..e155174ce 100644
--- a/packages/vue/src/editor/tool-cursor/index.ts
+++ b/packages/vue/src/editor/tool-cursor/index.ts
@@ -1,6 +1,7 @@
import type { Tool } from '@open-pencil/core'
import commentCursorSVG from '#vue/shared/assets/cursors/comment.svg?raw'
+import eyedropperCursorSVG from '#vue/shared/assets/cursors/eyedropper.svg?raw'
import handGrabCursorSVG from '#vue/shared/assets/cursors/hand-grab.svg?raw'
import handCursorSVG from '#vue/shared/assets/cursors/hand.svg?raw'
import penCursorSVG from '#vue/shared/assets/cursors/pen.svg?raw'
@@ -14,6 +15,8 @@ function svgCursor(svg: string, x: number, y: number, fallback: string): string
export const PEN_CURSOR = svgCursor(penCursorSVG, 4, 4, 'crosshair')
/** The pencil, pointing at its tip in the lower left. */
const PENCIL_CURSOR = svgCursor(pencilCursorSVG, 4, 20, 'crosshair')
+/** The eyedropper, pointing at its tip in the lower left. */
+const EYEDROPPER_CURSOR = svgCursor(eyedropperCursorSVG, 4, 20, 'crosshair')
/** A speech bubble whose tail tip places the comment pin. */
const COMMENT_CURSOR = svgCursor(commentCursorSVG, 5, 24, 'crosshair')
/** The open hand of the hand tool. */
@@ -37,7 +40,8 @@ const TOOL_CURSORS: Record<Tool, string> = {
PEN: PEN_CURSOR,
PENCIL: PENCIL_CURSOR,
HAND: HAND_CURSOR,
- COMMENT: COMMENT_CURSOR
+ COMMENT: COMMENT_CURSOR,
+ EYEDROPPER: EYEDROPPER_CURSOR
}
export function toolCursor(tool: Tool, override?: string | null): string {
diff --git a/packages/vue/src/i18n/locales/de/tools.json b/packages/vue/src/i18n/locales/de/tools.json
index e6c358915..91e9fbfe8 100644
--- a/packages/vue/src/i18n/locales/de/tools.json
+++ b/packages/vue/src/i18n/locales/de/tools.json
@@ -14,5 +14,7 @@
"shape": "Form",
"connector": "Verbinder",
"hand": "Hand",
- "comment": "Kommentar"
+ "comment": "Kommentar",
+ "eyedropper": "Pipette",
+ "eyedropperSample": "Farbe von der Arbeitsfläche aufnehmen"
}
diff --git a/packages/vue/src/i18n/locales/es/tools.json b/packages/vue/src/i18n/locales/es/tools.json
index 1e938a304..6a4125665 100644
--- a/packages/vue/src/i18n/locales/es/tools.json
+++ b/packages/vue/src/i18n/locales/es/tools.json
@@ -14,5 +14,7 @@
"shape": "Forma",
"connector": "Conector",
"hand": "Mano",
- "comment": "Comentario"
+ "comment": "Comentario",
+ "eyedropper": "Cuentagotas",
+ "eyedropperSample": "Tomar un color del lienzo"
}
diff --git a/packages/vue/src/i18n/locales/fr/tools.json b/packages/vue/src/i18n/locales/fr/tools.json
index 5c07dad4e..6e1c01ca0 100644
--- a/packages/vue/src/i18n/locales/fr/tools.json
+++ b/packages/vue/src/i18n/locales/fr/tools.json
@@ -14,5 +14,7 @@
"shape": "Forme",
"connector": "Connecteur",
"hand": "Main",
- "comment": "Commentaire"
+ "comment": "Commentaire",
+ "eyedropper": "Pipette",
+ "eyedropperSample": "Prélever une couleur sur le canevas"
}
diff --git a/packages/vue/src/i18n/locales/it/tools.json b/packages/vue/src/i18n/locales/it/tools.json
index 421aba957..40403e249 100644
--- a/packages/vue/src/i18n/locales/it/tools.json
+++ b/packages/vue/src/i18n/locales/it/tools.json
@@ -14,5 +14,7 @@
"shape": "Forma",
"connector": "Connettore",
"hand": "Mano",
- "comment": "Commento"
+ "comment": "Commento",
+ "eyedropper": "Contagocce",
+ "eyedropperSample": "Preleva un colore dalla tela"
}
diff --git a/packages/vue/src/i18n/locales/ja/tools.json b/packages/vue/src/i18n/locales/ja/tools.json
index 289e657d1..10ec05402 100644
--- a/packages/vue/src/i18n/locales/ja/tools.json
+++ b/packages/vue/src/i18n/locales/ja/tools.json
@@ -14,5 +14,7 @@
"shape": "シェイプ",
"connector": "コネクタ",
"hand": "手のひらツール",
- "comment": "コメント"
+ "comment": "コメント",
+ "eyedropper": "スポイト",
+ "eyedropperSample": "キャンバスから色を取得"
}
diff --git a/packages/vue/src/i18n/locales/pl/tools.json b/packages/vue/src/i18n/locales/pl/tools.json
index 56bc842b0..96b0a2bf2 100644
--- a/packages/vue/src/i18n/locales/pl/tools.json
+++ b/packages/vue/src/i18n/locales/pl/tools.json
@@ -14,5 +14,7 @@
"shape": "Kształt",
"connector": "Łącznik",
"hand": "Dłoń",
- "comment": "Komentarz"
+ "comment": "Komentarz",
+ "eyedropper": "Zakraplacz",
+ "eyedropperSample": "Pobierz kolor z kanwy"
}
diff --git a/packages/vue/src/i18n/locales/ru/tools.json b/packages/vue/src/i18n/locales/ru/tools.json
index 86114e3b3..6298c0f1d 100644
--- a/packages/vue/src/i18n/locales/ru/tools.json
+++ b/packages/vue/src/i18n/locales/ru/tools.json
@@ -14,5 +14,7 @@
"shape": "Фигура",
"connector": "Соединитель",
"hand": "Рука",
- "comment": "Комментарий"
+ "comment": "Комментарий",
+ "eyedropper": "Пипетка",
+ "eyedropperSample": "Взять цвет с холста"
}
diff --git a/packages/vue/src/i18n/locales/zh-cn/tools.json b/packages/vue/src/i18n/locales/zh-cn/tools.json
index cf4b87360..006c6567d 100644
--- a/packages/vue/src/i18n/locales/zh-cn/tools.json
+++ b/packages/vue/src/i18n/locales/zh-cn/tools.json
@@ -14,5 +14,7 @@
"shape": "形状",
"connector": "连接线",
"hand": "抓手",
- "comment": "评论"
+ "comment": "评论",
+ "eyedropper": "吸管",
+ "eyedropperSample": "从画布拾取颜色"
}
diff --git a/packages/vue/src/i18n/messages/tools.ts b/packages/vue/src/i18n/messages/tools.ts
index 1988bf763..0a08ae387 100644
--- a/packages/vue/src/i18n/messages/tools.ts
+++ b/packages/vue/src/i18n/messages/tools.ts
@@ -16,7 +16,9 @@ export const toolMessageDefaults = {
shape: 'Shape',
connector: 'Connector',
hand: 'Hand',
- comment: 'Comment'
+ comment: 'Comment',
+ eyedropper: 'Eyedropper',
+ eyedropperSample: 'Pick a color from the canvas'
} as const
export const toolMessages = i18n('tools', toolMessageDefaults)
diff --git a/packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vue b/packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vue
index 6644adc32..c17290a5d 100644
--- a/packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vue
+++ b/packages/vue/src/primitives/ColorPicker/ColorPickerRoot.vue
@@ -7,6 +7,8 @@ import type { Color } from '@open-pencil/scene-graph/primitives'
import { useRetainedPopup } from '#vue/lifecycle/retention/popup'
+import { pickerOutsideHandlers, type PickerKeepOpen } from './outside'
+
export interface ColorPickerUI {
content?: string
swatch?: string
@@ -15,11 +17,14 @@ export interface ColorPickerUI {
const {
color,
label = 'Edit color',
- ui
+ ui,
+ keepOpen
} = defineProps<{
color: Color
label?: string
ui?: ColorPickerUI
+ /** Whether a press outside the picker should leave it open, such as one that samples the canvas. */
+ keepOpen?: PickerKeepOpen
}>()
const emit = defineEmits<{
@@ -34,6 +39,8 @@ const { open: popupOpen, portalActive } = useRetainedPopup(undefined, () => {
emit('openChange', false)
})
+const outside = pickerOutsideHandlers(() => keepOpen)
+
function cancelFromEscape(event: KeyboardEvent) {
event.stopPropagation()
emit('cancel')
@@ -60,6 +67,8 @@ function cancelFromEscape(event: KeyboardEvent) {
side="left"
data-picker-content
@escape-key-down="cancelFromEscape"
+ @pointer-down-outside="outside.onPointerDownOutside"
+ @focus-outside="outside.onFocusOutside"
>
<slot :color="color" />
</PopoverContent>
diff --git a/packages/vue/src/primitives/ColorPicker/index.ts b/packages/vue/src/primitives/ColorPicker/index.ts
index 51586bcfc..d08483b71 100644
--- a/packages/vue/src/primitives/ColorPicker/index.ts
+++ b/packages/vue/src/primitives/ColorPicker/index.ts
@@ -1,2 +1,3 @@
export { default as ColorInputRoot } from '#vue/primitives/ColorPicker/ColorInputRoot.vue'
export { default as ColorPickerRoot } from '#vue/primitives/ColorPicker/ColorPickerRoot.vue'
+export { pickerOutsideHandlers, type PickerKeepOpen } from '#vue/primitives/ColorPicker/outside'
diff --git a/packages/vue/src/primitives/ColorPicker/outside.ts b/packages/vue/src/primitives/ColorPicker/outside.ts
new file mode 100644
index 000000000..a80070a0f
--- /dev/null
+++ b/packages/vue/src/primitives/ColorPicker/outside.ts
@@ -0,0 +1,21 @@
+import type { FocusOutsideEvent, PointerDownOutsideEvent } from 'reka-ui'
+
+/** Whether a press outside a picker leaves it open, such as one on a gradient handle. */
+export type PickerKeepOpen = (event: PointerEvent) => boolean
+
+/**
+ * Outside-dismissal handlers for a picker's `PopoverContent`: the press decides through
+ * `keepOpen`. Reka reports the canvas taking focus a couple of ticks after that press, so a focus
+ * move to the canvas never dismisses on its own.
+ */
+export function pickerOutsideHandlers(keepOpen: () => PickerKeepOpen | undefined) {
+ return {
+ onPointerDownOutside(event: PointerDownOutsideEvent) {
+ if (keepOpen()?.(event.detail.originalEvent)) event.preventDefault()
+ },
+ onFocusOutside(event: FocusOutsideEvent) {
+ if (keepOpen() && event.detail.originalEvent.target instanceof HTMLCanvasElement)
+ event.preventDefault()
+ }
+ }
+}
diff --git a/packages/vue/src/shared/assets/cursors/eyedropper.svg b/packages/vue/src/shared/assets/cursors/eyedropper.svg
new file mode 100644
index 000000000..51f86182a
--- /dev/null
+++ b/packages/vue/src/shared/assets/cursors/eyedropper.svg
@@ -0,0 +1,17 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
+ <filter id="shadow" x="-50%" y="-50%" width="200%" height="200%">
+ <feDropShadow dx="0" dy="1.25" stdDeviation="1" flood-opacity="0.5"/>
+ </filter>
+ <g filter="url(#shadow)" stroke-linecap="round" stroke-linejoin="round">
+ <g transform="translate(2.16 2.16) scale(0.8)">
+ <g fill="#fff" stroke="#fff" stroke-width="3.75">
+ <path d="m12 9-8.414 8.414A2 2 0 0 0 3 18.828v1.344a2 2 0 0 1-.586 1.414A2 2 0 0 1 3.828 21h1.344a2 2 0 0 0 1.414-.586L15 12"/>
+ <path d="m18 9 .4.4a1 1 0 1 1-3 3l-3.8-3.8a1 1 0 1 1 3-3l.4.4 3.4-3.4a1 1 0 1 1 3 3z"/>
+ </g>
+ <g fill="none" stroke="#000" stroke-width="1.25">
+ <path d="m12 9-8.414 8.414A2 2 0 0 0 3 18.828v1.344a2 2 0 0 1-.586 1.414A2 2 0 0 1 3.828 21h1.344a2 2 0 0 0 1.414-.586L15 12"/>
+ <path d="m18 9 .4.4a1 1 0 1 1-3 3l-3.8-3.8a1 1 0 1 1 3-3l.4.4 3.4-3.4a1 1 0 1 1 3 3zM2 22l.414-.414"/>
+ </g>
+ </g>
+ </g>
+</svg>
diff --git a/packages/vue/tests/canvas/eyedropper/request.test.ts b/packages/vue/tests/canvas/eyedropper/request.test.ts
new file mode 100644
index 000000000..8890e2713
--- /dev/null
+++ b/packages/vue/tests/canvas/eyedropper/request.test.ts
@@ -0,0 +1,68 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { createEditor, type Editor } from '@open-pencil/core'
+
+import {
+ cancelEyedropperSample,
+ handleEyedropperDown,
+ offersEyedropper,
+ requestEyedropperSample
+} from '#vue/canvas/eyedropper'
+
+let editor: Editor
+
+afterEach(() => editor.dispose())
+
+describe('requestEyedropperSample', () => {
+ test('switches to the eyedropper while it waits', () => {
+ editor = createEditor()
+ void requestEyedropperSample(editor)
+ expect(editor.state.activeTool).toBe('EYEDROPPER')
+ })
+
+ test('resolves null when the user leaves the eyedropper', async () => {
+ editor = createEditor()
+ const sample = requestEyedropperSample(editor)
+ editor.setTool('SELECT')
+ expect(await sample).toBeNull()
+ })
+
+ test('a click without a renderer answers the request with no color and returns to Move', async () => {
+ editor = createEditor()
+ const sample = requestEyedropperSample(editor)
+ handleEyedropperDown(editor, 10, 10, false)
+ expect(await sample).toBeNull()
+ expect(editor.state.activeTool).toBe('SELECT')
+ })
+
+ test('a new request cancels the one still waiting', async () => {
+ editor = createEditor()
+ const first = requestEyedropperSample(editor)
+ void requestEyedropperSample(editor)
+ expect(await first).toBeNull()
+ expect(editor.state.activeTool).toBe('EYEDROPPER')
+ })
+
+ test('cancelling resolves null and brings Move back', async () => {
+ editor = createEditor()
+ const sample = requestEyedropperSample(editor)
+ cancelEyedropperSample(editor)
+ expect(await sample).toBeNull()
+ expect(editor.state.activeTool).toBe('SELECT')
+ })
+
+ test('cancelling without a waiting request leaves the tool alone', () => {
+ editor = createEditor()
+ editor.setTool('EYEDROPPER')
+ cancelEyedropperSample(editor)
+ expect(editor.state.activeTool).toBe('EYEDROPPER')
+ })
+
+ test('a board does not offer the eyedropper and resolves at once', async () => {
+ editor = createEditor()
+ editor.setDocumentKind('board')
+ expect(offersEyedropper(editor)).toBe(false)
+ expect(await requestEyedropperSample(editor)).toBeNull()
+ expect(editor.state.activeTool).toBe('SELECT')
+ })
+})
diff --git a/packages/vue/tsdown.config.ts b/packages/vue/tsdown.config.ts
index 63b6999ee..ae69b65c8 100644
--- a/packages/vue/tsdown.config.ts
+++ b/packages/vue/tsdown.config.ts
@@ -59,6 +59,7 @@ export default defineConfig({
index: './src/index.ts',
'canvas/index': './src/canvas/index.ts',
'canvas/drop/index': './src/canvas/drop/index.ts',
+ 'canvas/eyedropper/index': './src/canvas/eyedropper/index.ts',
'canvas/issues/index': './src/canvas/issues/index.ts',
'canvas/labels/index': './src/canvas/labels/index.ts',
'canvas/overlays/index': './src/canvas/overlays/index.ts',
diff --git a/src/app/editor/toolbar/shortcuts.ts b/src/app/editor/toolbar/shortcuts.ts
index de17da74a..37828a462 100644
--- a/src/app/editor/toolbar/shortcuts.ts
+++ b/src/app/editor/toolbar/shortcuts.ts
@@ -28,7 +28,8 @@ const UNKEYED: Readonly<Record<Tool, string>> = {
SHAPE_WITH_TEXT: '',
CONNECTOR: '',
HAND: '',
- COMMENT: ''
+ COMMENT: '',
+ EYEDROPPER: ''
}
/**
diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.ts
index 2ada5f7d1..efdf3ab9e 100644
--- a/src/app/shell/keyboard/actions.ts
+++ b/src/app/shell/keyboard/actions.ts
@@ -77,6 +77,11 @@ export function createKeyboardActions({
store.setRotationPreview(null)
return
}
+ // Esc leaves the eyedropper without touching the selection or a waiting color picker.
+ if (store.state.activeTool === 'EYEDROPPER') {
+ store.setTool('SELECT')
+ return
+ }
if (store.state.nodeEditState) {
store.exitNodeEditMode(true)
return
diff --git a/src/components/ColorPicker/ColorPicker.vue b/src/components/ColorPicker/ColorPicker.vue
index 1677d8273..8bd73aa8b 100644
--- a/src/components/ColorPicker/ColorPicker.vue
+++ b/src/components/ColorPicker/ColorPicker.vue
@@ -7,10 +7,20 @@ import { useI18n } from '@open-pencil/vue/i18n'
import { ColorPickerRoot } from '@open-pencil/vue/primitives/ColorPicker'
import ColorPickerPanel from '@/components/color-picker-panel/ColorPickerPanel.vue'
+import { useEyedropperKeepOpen } from '@/components/color-picker-panel/eyedropper'
import { usePopoverUI } from '@/components/ui/overlay/popover'
const { panels } = useI18n()
-const { color, okhcl = null } = defineProps<{ color: Color; okhcl?: OkHCLControls | null }>()
+const {
+ color,
+ okhcl = null,
+ eyedropper = true
+} = defineProps<{
+ color: Color
+ okhcl?: OkHCLControls | null
+ /** Offers sampling the canvas; off where no document color is edited, as in Settings. */
+ eyedropper?: boolean
+}>()
defineSlots<{
trigger?(props: { style: { background: string } }): VNode[]
}>()
@@ -20,12 +30,15 @@ const emit = defineEmits<{
cancel: []
}>()
const cls = usePopoverUI({ content: 'w-56 p-2' })
+// Settings has no document behind it to sample, nor always an editor to sample with.
+const keepOpen = eyedropper ? useEyedropperKeepOpen() : undefined
</script>
<template>
<ColorPickerRoot
:color="color"
:label="panels.editColor"
+ :keep-open="keepOpen"
:ui="{
content: cls.content,
swatch: 'size-5 shrink-0 cursor-pointer rounded border border-border p-0'
@@ -38,7 +51,12 @@ const cls = usePopoverUI({ content: 'w-56 p-2' })
<slot name="trigger" v-bind="trigger" />
</template>
<template #default="{ color: currentColor }">
- <ColorPickerPanel :color="currentColor" :okhcl="okhcl" @update="emit('update', $event)" />
+ <ColorPickerPanel
+ :color="currentColor"
+ :okhcl="okhcl"
+ :eyedropper="eyedropper"
+ @update="emit('update', $event)"
+ />
</template>
</ColorPickerRoot>
</template>
diff --git a/src/components/EditorCanvas.vue b/src/components/EditorCanvas.vue
index 318422e86..d57f1ada5 100644
--- a/src/components/EditorCanvas.vue
+++ b/src/components/EditorCanvas.vue
@@ -28,6 +28,7 @@ import {
import type { ViewportTransform } from '@open-pencil/core/geometry'
import { PlayIslands, useCanvasInput } from '@open-pencil/vue/canvas'
import { useCanvasDrop } from '@open-pencil/vue/canvas/drop'
+import { useEyedropperLoupe } from '@open-pencil/vue/canvas/eyedropper'
import { useCanvasIssueMarkers } from '@open-pencil/vue/canvas/issues'
import { useCanvasVirtualReference } from '@open-pencil/vue/canvas/overlays'
import { useCanvasStatusLabels } from '@open-pencil/vue/canvas/statuses'
@@ -44,6 +45,7 @@ import { canvasOverlayObstacles } from '@/app/editor/canvas/obstacles'
import { useFollowView } from '@/app/presence/follow-view'
import { appRuntimeConfig } from '@/app/runtime/config'
import { appPreferences } from '@/app/settings/preferences/store'
+import CanvasEyedropperLoupe from '@/components/canvas/CanvasEyedropperLoupe.vue'
import CommentsLayer from '@/components/comments/CommentsLayer.vue'
import IssueMarkerTooltip from '@/components/design-check/IssueMarkerTooltip.vue'
import SelectionToolbar from '@/components/figjam/SelectionToolbar.vue'
@@ -288,11 +290,16 @@ const valueEditorIcon = computed(() => {
: IconLucideAlignHorizontalSpaceBetween
})
+const eyedropperLoupe = useEyedropperLoupe(store, canvasRef, () => isActivePane.value)
+
+// The eyedropper's loupe stands in for the cursor while it shows.
const cursor = computed(() =>
- toolCursor(
- store.state.activeTool,
- issueMarkerCursor.value ?? statusLabelCursor.value ?? cursorOverride.value
- )
+ eyedropperLoupe.visible.value
+ ? 'none'
+ : toolCursor(
+ store.state.activeTool,
+ issueMarkerCursor.value ?? statusLabelCursor.value ?? cursorOverride.value
+ )
)
</script>
@@ -328,6 +335,7 @@ const cursor = computed(() =>
<PlayIslands :view="paneView" :drawn="drawnView" :canvas="canvasRef" />
<AppDropOverlay :visible="isDraggingOver" />
<IssueMarkerTooltip :marker="hoveredIssueMarker" :canvas="canvasRef" />
+ <CanvasEyedropperLoupe :loupe="eyedropperLoupe" />
<StatusLabelMenu
:label="openStatusLabel"
:canvas="canvasRef"
diff --git a/src/components/canvas/CanvasEyedropperLoupe.vue b/src/components/canvas/CanvasEyedropperLoupe.vue
new file mode 100644
index 000000000..b1c94b588
--- /dev/null
+++ b/src/components/canvas/CanvasEyedropperLoupe.vue
@@ -0,0 +1,56 @@
+<script setup lang="ts">
+/**
+ * The eyedropper's loupe, standing in for the cursor: centred on the pointer, so the outlined
+ * pixel is the one a click picks. The canvas hides the system cursor while it shows; next to a
+ * cursor the system draws ahead of the page, any overlay looks a few frames behind.
+ */
+import { tv } from 'tailwind-variants'
+import { computed, useTemplateRef, watchEffect } from 'vue'
+
+import { colorToCSS, colorToHexRaw } from '@open-pencil/scene-graph/color'
+import type { EyedropperLoupe } from '@open-pencil/vue/canvas/eyedropper'
+
+import { remToPx } from '@/app/shell/root-font-size'
+import theme from '@/theme/canvas/eyedropper-loupe'
+
+const loupeTheme = tv(theme)
+
+/** From the card's corner to the centre pixel's centre: 0.375rem padding and 4.5 pixels of 0.5rem. */
+const LOUPE_CENTRE_OFFSET_REM = 0.375 + 4.5 * 0.5
+
+const { loupe } = defineProps<{ loupe: EyedropperLoupe }>()
+
+const styles = loupeTheme()
+const pixelsCanvas = useTemplateRef<HTMLCanvasElement>('pixels')
+
+const transform = computed(() => {
+ const offset = remToPx(LOUPE_CENTRE_OFFSET_REM)
+ return `translate(${loupe.clientX.value - offset}px, ${loupe.clientY.value - offset}px)`
+})
+
+watchEffect(() => {
+ const target = pixelsCanvas.value
+ const pixels = loupe.pixels.value
+ if (!target || !pixels) return
+ target.width = pixels.size
+ target.height = pixels.size
+ const image = new ImageData(new Uint8ClampedArray(pixels.data), pixels.size, pixels.size)
+ target.getContext('2d')?.putImageData(image, 0, 0)
+})
+</script>
+
+<template>
+ <Teleport v-if="loupe.visible.value && loupe.color.value" to="body">
+ <div :class="styles.content()" :style="{ transform }" data-test-id="eyedropper-loupe">
+ <div :class="styles.loupe()">
+ <canvas ref="pixels" :class="styles.pixels()" />
+ <span :class="styles.grid()" />
+ <span :class="styles.centre()" />
+ </div>
+ <div :class="styles.value()">
+ <span :class="styles.swatch()" :style="{ background: colorToCSS(loupe.color.value) }" />
+ <span data-test-id="eyedropper-loupe-value">{{ colorToHexRaw(loupe.color.value) }}</span>
+ </div>
+ </div>
+ </Teleport>
+</template>
diff --git a/src/components/canvas/CanvasPaneHeader.vue b/src/components/canvas/CanvasPaneHeader.vue
index f693e0ec9..a96df8b02 100644
--- a/src/components/canvas/CanvasPaneHeader.vue
+++ b/src/components/canvas/CanvasPaneHeader.vue
@@ -16,7 +16,7 @@ import type { SplitDirection } from '@/app/editor/panes/split-tree'
import IconButton from '@/components/ui/button/IconButton.vue'
import { menuItem, useMenuUI } from '@/components/ui/menu/menu'
import MenuScrollArea from '@/components/ui/menu/MenuScrollArea.vue'
-import canvasPaneHeaderTheme from '@/theme/canvas-pane-header'
+import canvasPaneHeaderTheme from '@/theme/canvas/pane-header'
const { paneId } = defineProps<{
paneId: string
diff --git a/src/components/color-picker-panel/ColorPickerPanel.vue b/src/components/color-picker-panel/ColorPickerPanel.vue
index 3d584c230..8a74c8208 100644
--- a/src/components/color-picker-panel/ColorPickerPanel.vue
+++ b/src/components/color-picker-panel/ColorPickerPanel.vue
@@ -7,9 +7,15 @@ import { provideColorPickerPanel } from '@/components/color-picker-panel/context
import FormatControls from '@/components/color-picker-panel/FormatControls.vue'
import HueAlphaSliders from '@/components/color-picker-panel/HueAlphaSliders.vue'
-const { color, okhcl = null } = defineProps<{
+const {
+ color,
+ okhcl = null,
+ eyedropper = false
+} = defineProps<{
color: Color
okhcl?: OkHCLControls | null
+ /** Offers sampling the canvas, for pickers that edit a document's colors. */
+ eyedropper?: boolean
}>()
const emit = defineEmits<{
@@ -23,6 +29,9 @@ provideColorPickerPanel(
},
get okhcl() {
return okhcl
+ },
+ get eyedropper() {
+ return eyedropper
}
},
emit
diff --git a/src/components/color-picker-panel/EyedropperButton.vue b/src/components/color-picker-panel/EyedropperButton.vue
new file mode 100644
index 000000000..4e767b339
--- /dev/null
+++ b/src/components/color-picker-panel/EyedropperButton.vue
@@ -0,0 +1,54 @@
+<script setup lang="ts">
+import { computed, onScopeDispose, ref } from 'vue'
+
+import { useEditor } from '@open-pencil/vue'
+import {
+ cancelEyedropperSample,
+ offersEyedropper,
+ requestEyedropperSample
+} from '@open-pencil/vue/canvas/eyedropper'
+import { useI18n } from '@open-pencil/vue/i18n'
+
+import { useColorPickerPanelContext } from '@/components/color-picker-panel/context'
+import IconButton from '@/components/ui/button/IconButton.vue'
+
+const ctx = useColorPickerPanelContext()
+const editor = useEditor()
+const { tools } = useI18n()
+const offered = computed(() => offersEyedropper(editor))
+const sampling = ref(false)
+
+/** Starts sampling, or, pressed again while it samples, gives the sample up. */
+async function pick() {
+ if (sampling.value) {
+ cancelEyedropperSample(editor)
+ return
+ }
+ sampling.value = true
+ try {
+ const sampled = await requestEyedropperSample(editor)
+ // The picker keeps its own opacity; the sample only brings the color.
+ if (sampled) ctx.updateColor({ ...sampled, a: ctx.color.a })
+ } finally {
+ sampling.value = false
+ }
+}
+
+// Closing the picker gives up the sample it still waits on.
+onScopeDispose(() => {
+ if (sampling.value) cancelEyedropperSample(editor)
+})
+</script>
+
+<template>
+ <IconButton
+ v-if="offered"
+ :label="tools.eyedropperSample"
+ :active="sampling"
+ toggle
+ data-test-id="color-eyedropper"
+ @click="pick"
+ >
+ <icon-lucide-pipette class="size-3.5" />
+ </IconButton>
+</template>
diff --git a/src/components/color-picker-panel/FormatControls.vue b/src/components/color-picker-panel/FormatControls.vue
index 6673f8174..9232c4a9b 100644
--- a/src/components/color-picker-panel/FormatControls.vue
+++ b/src/components/color-picker-panel/FormatControls.vue
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { useColorPickerPanelContext } from '@/components/color-picker-panel/context'
+import EyedropperButton from '@/components/color-picker-panel/EyedropperButton.vue'
import HsbFields from '@/components/color-picker-panel/HsbFields.vue'
import HslFields from '@/components/color-picker-panel/HslFields.vue'
import OkhclFields from '@/components/color-picker-panel/OkhclFields.vue'
@@ -11,13 +12,16 @@ const ctx = useColorPickerPanelContext()
<template>
<div class="flex flex-col gap-2">
- <AppSelect
- class="w-30"
- data-test-id="color-format-select"
- :model-value="ctx.fieldFormat"
- :options="ctx.fieldOptions"
- @update:model-value="ctx.setFieldFormat"
- />
+ <div class="flex items-center justify-between gap-2">
+ <AppSelect
+ class="w-30"
+ data-test-id="color-format-select"
+ :model-value="ctx.fieldFormat"
+ :options="ctx.fieldOptions"
+ @update:model-value="ctx.setFieldFormat"
+ />
+ <EyedropperButton v-if="ctx.eyedropper" />
+ </div>
<div class="min-w-0 flex flex-col gap-2">
<RGBFields v-if="ctx.fieldFormat === 'rgb'" />
diff --git a/src/components/color-picker-panel/context.ts b/src/components/color-picker-panel/context.ts
index 8e87d99f0..b072fa034 100644
--- a/src/components/color-picker-panel/context.ts
+++ b/src/components/color-picker-panel/context.ts
@@ -8,6 +8,8 @@ import { useI18n } from '@open-pencil/vue/i18n'
interface ColorPanelProps {
color: Color
okhcl?: OkHCLControls | null
+ /** Offers sampling the canvas, for pickers that edit a document's colors. */
+ eyedropper?: boolean
}
type ColorPanelEmit = (event: 'update', color: Color) => void
@@ -60,7 +62,9 @@ function createColorPickerPanelContext(props: ColorPanelProps, emit: ColorPanelE
updateRGBChannelValue: colorModel.updateRGBChannel,
updateHSLChannelValue: colorModel.updateHSLChannel,
updateHSBChannelValue: colorModel.updateHSBChannel,
- updateOkHCLChannel: colorModel.updateOkHCLChannel
+ updateOkHCLChannel: colorModel.updateOkHCLChannel,
+ updateColor: colorModel.updateColor,
+ eyedropper: computed(() => props.eyedropper ?? false)
}
}
diff --git a/src/components/color-picker-panel/eyedropper.ts b/src/components/color-picker-panel/eyedropper.ts
new file mode 100644
index 000000000..506be9ae3
--- /dev/null
+++ b/src/components/color-picker-panel/eyedropper.ts
@@ -0,0 +1,14 @@
+import { useEditor } from '@open-pencil/vue'
+import { pressAnswersEyedropper } from '@open-pencil/vue/canvas/eyedropper'
+import type { PickerKeepOpen } from '@open-pencil/vue/primitives/ColorPicker'
+
+/**
+ * A document color picker's `keepOpen`: the caller's own rule, plus the canvas press that answers
+ * the picker's eyedropper, so sampling a color does not close the picker.
+ */
+export function useEyedropperKeepOpen(
+ keepOpen: () => PickerKeepOpen | undefined = () => undefined
+): PickerKeepOpen {
+ const editor = useEditor()
+ return (event) => keepOpen()?.(event) === true || pressAnswersEyedropper(editor, event)
+}
diff --git a/src/components/fill-picker/FillPicker.vue b/src/components/fill-picker/FillPicker.vue
index 9819a02d1..338916a7c 100644
--- a/src/components/fill-picker/FillPicker.vue
+++ b/src/components/fill-picker/FillPicker.vue
@@ -1,6 +1,5 @@
<script setup lang="ts">
import { PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'
-import type { FocusOutsideEvent, PointerDownOutsideEvent } from 'reka-ui'
import { tv } from 'tailwind-variants'
import { computed } from 'vue'
@@ -10,9 +9,11 @@ import { applySolidFillColor, type OkHCLControls } from '@open-pencil/vue/contro
import { DEFAULT_SHADER_PRESET } from '@open-pencil/vue/controls/shader'
import { useI18n } from '@open-pencil/vue/i18n'
import { useRetainedPopup } from '@open-pencil/vue/lifecycle/retention'
+import { pickerOutsideHandlers, type PickerKeepOpen } from '@open-pencil/vue/primitives/ColorPicker'
import { FillRoot } from '@open-pencil/vue/primitives/Fill'
import ColorPickerPanel from '@/components/color-picker-panel/ColorPickerPanel.vue'
+import { useEyedropperKeepOpen } from '@/components/color-picker-panel/eyedropper'
import GradientEditor from '@/components/fill-picker/GradientEditor.vue'
import ImageFillPicker from '@/components/fill-picker/ImageFillPicker.vue'
import ShaderFillPicker from '@/components/fill-picker/shader/ShaderFillPicker.vue'
@@ -45,7 +46,7 @@ const {
/** Names the trigger for a paint that is not a fill, such as a stroke. */
label?: string
/** Whether a press outside the picker should leave it open, such as on a gradient handle. */
- keepOpen?: (event: PointerEvent) => boolean
+ keepOpen?: PickerKeepOpen
/** The one layer the paint is on, which an image crop starts by covering. */
layerSize?: { width: number; height: number } | null
}>()
@@ -70,16 +71,9 @@ const cls = usePopoverUI({
})
const { panels } = useI18n()
-/** Dragging a gradient handle on the canvas leaves the picker open, as in Figma. */
-function keepOpenOnPress(event: PointerDownOutsideEvent) {
- if (keepOpen?.(event.detail.originalEvent)) event.preventDefault()
-}
-
-/** A press focuses the canvas before the press itself reaches the picker, so the press decides. */
-function keepOpenOnFocus(event: FocusOutsideEvent) {
- if (keepOpen && event.detail.originalEvent.target instanceof HTMLCanvasElement)
- event.preventDefault()
-}
+/** Dragging a gradient handle or sampling a color on the canvas leaves the picker open. */
+const keepPickerOpen = useEyedropperKeepOpen(() => keepOpen)
+const outside = pickerOutsideHandlers(() => keepPickerOpen)
function cancelFromEscape(event: KeyboardEvent) {
event.stopPropagation()
@@ -113,8 +107,8 @@ function cancelFromEscape(event: KeyboardEvent) {
side="left"
data-picker-content
@escape-key-down="cancelFromEscape"
- @pointer-down-outside="keepOpenOnPress"
- @focus-outside="keepOpenOnFocus"
+ @pointer-down-outside="outside.onPointerDownOutside"
+ @focus-outside="outside.onFocusOutside"
>
<div class="mb-2 flex items-center gap-0.5">
<Tip :label="panels.solid">
@@ -167,6 +161,7 @@ function cancelFromEscape(event: KeyboardEvent) {
v-if="root.category === 'SOLID'"
:color="root.fill.color"
:okhcl="okhcl"
+ eyedropper
@update="emit('update', applySolidFillColor(root.fill, $event))"
/>
diff --git a/src/components/fill-picker/GradientEditor.vue b/src/components/fill-picker/GradientEditor.vue
index 922eb9d86..7532978b0 100644
--- a/src/components/fill-picker/GradientEditor.vue
+++ b/src/components/fill-picker/GradientEditor.vue
@@ -146,7 +146,11 @@ function listStopClass(active: boolean) {
</GradientEditorStop>
</div>
- <ColorPickerPanel :color="root.activeColor" @update="root.actions.updateActiveColor" />
+ <ColorPickerPanel
+ :color="root.activeColor"
+ eyedropper
+ @update="root.actions.updateActiveColor"
+ />
</div>
</GradientEditorRoot>
</template>
diff --git a/src/components/icons/index.ts b/src/components/icons/index.ts
index c7c986f86..71307cb94 100644
--- a/src/components/icons/index.ts
+++ b/src/components/icons/index.ts
@@ -14,6 +14,7 @@ import IconMinus from '~icons/lucide/minus'
import IconMousePointer from '~icons/lucide/mouse-pointer'
import IconPenTool from '~icons/lucide/pen-tool'
import IconPencil from '~icons/lucide/pencil'
+import IconPipette from '~icons/lucide/pipette'
import IconRows from '~icons/lucide/rows-3'
import IconShapes from '~icons/lucide/shapes'
import IconSmile from '~icons/lucide/smile'
@@ -52,7 +53,8 @@ export const toolIcons: Record<Tool, Component> = {
SHAPE_WITH_TEXT: IconShapes,
CONNECTOR: IconSpline,
HAND: IconHand,
- COMMENT: IconMessageCircle
+ COMMENT: IconMessageCircle,
+ EYEDROPPER: IconPipette
}
export const NODE_ICONS: Partial<Record<string, typeof IconSquare>> = {
diff --git a/src/components/settings/general/AccentColorPicker.vue b/src/components/settings/general/AccentColorPicker.vue
index e312f7a2a..cf0508e4b 100644
--- a/src/components/settings/general/AccentColorPicker.vue
+++ b/src/components/settings/general/AccentColorPicker.vue
@@ -82,6 +82,7 @@ function onCancel(): void {
<Tip :label="messages.accentCustom">
<ColorPicker
:color="customColor"
+ :eyedropper="false"
@update="onCustomColor"
@open-change="onPickerOpenChange"
@cancel="onCancel"
diff --git a/src/components/toolbar/labels.ts b/src/components/toolbar/labels.ts
index 6b58dd967..ab78e0f62 100644
--- a/src/components/toolbar/labels.ts
+++ b/src/components/toolbar/labels.ts
@@ -25,7 +25,8 @@ export function useToolLabels() {
SHAPE_WITH_TEXT: tools.value.shape,
CONNECTOR: tools.value.connector,
HAND: tools.value.hand,
- COMMENT: tools.value.comment
+ COMMENT: tools.value.comment,
+ EYEDROPPER: tools.value.eyedropper
}))
}
diff --git a/src/theme/button/icon-button.ts b/src/theme/button/icon-button.ts
index 61d08641c..bce95a86a 100644
--- a/src/theme/button/icon-button.ts
+++ b/src/theme/button/icon-button.ts
@@ -1,5 +1,8 @@
export default {
- base: 'flex cursor-pointer items-center justify-center bg-transparent text-muted outline-none hover:bg-hover hover:text-surface focus-visible:border-panel-focus',
+ // The icon passes the pointer to the button: Reka's Splitter only sees that a control covers
+ // its resize handle when the event target is an HTML element, so a press or hover on an SVG
+ // icon over a handle, as in a picker beside the properties panel, reached the handle.
+ base: 'flex cursor-pointer items-center justify-center bg-transparent text-muted outline-none hover:bg-hover hover:text-surface focus-visible:border-panel-focus [&_svg]:pointer-events-none',
variants: {
size: {
xs: 'size-6 rounded border border-transparent text-sm leading-none',
diff --git a/src/theme/canvas/eyedropper-loupe.ts b/src/theme/canvas/eyedropper-loupe.ts
new file mode 100644
index 000000000..388f74134
--- /dev/null
+++ b/src/theme/canvas/eyedropper-loupe.ts
@@ -0,0 +1,19 @@
+/**
+ * The eyedropper's loupe, centred on the pointer in place of the cursor: the screen pixels around
+ * it, enlarged on a grid with the picked one outlined, and that pixel's colour below. Nine pixels
+ * a side at 0.5rem each (`EYEDROPPER_LOUPE_PIXELS`) inside 0.375rem of padding, so the centre
+ * pixel starts at 2rem and its centre sits 2.625rem from the card's corner
+ * (`LOUPE_CENTRE_OFFSET_REM`).
+ */
+export default {
+ slots: {
+ content:
+ 'pointer-events-none fixed top-0 left-0 z-50 flex flex-col gap-1.5 rounded-lg bg-panel p-1.5 text-surface shadow-[0_0_0_1px_var(--color-border),0_8px_30px_rgb(0_0_0/0.4)]',
+ loupe: 'relative size-18 overflow-hidden rounded-md',
+ pixels: 'block size-full [image-rendering:pixelated]',
+ grid: 'absolute inset-0 bg-[image:linear-gradient(to_right,rgb(0_0_0/0.12)_0.0625rem,transparent_0.0625rem),linear-gradient(to_bottom,rgb(0_0_0/0.12)_0.0625rem,transparent_0.0625rem)] bg-[size:0.5rem_0.5rem]',
+ centre: 'absolute top-8 left-8 size-2 shadow-[0_0_0_1px_rgb(0_0_0),0_0_0_2px_rgb(255_255_255)]',
+ value: 'flex items-center gap-1.5 px-0.5 font-mono text-2xs leading-4',
+ swatch: 'size-3 shrink-0 rounded-sm shadow-[inset_0_0_0_1px_rgb(0_0_0/0.15)]'
+ }
+} as const
diff --git a/src/theme/canvas-pane-header.ts b/src/theme/canvas/pane-header.ts
similarity index 100%
rename from src/theme/canvas-pane-header.ts
rename to src/theme/canvas/pane-header.ts
diff --git a/tests/e2e/tools/eyedropper.spec.ts b/tests/e2e/tools/eyedropper.spec.ts
new file mode 100644
index 000000000..2e25fbc31
--- /dev/null
+++ b/tests/e2e/tools/eyedropper.spec.ts
@@ -0,0 +1,158 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import { eyedropperDriver } from '#tests/helpers/canvas/eyedropper-driver'
+import { getSelectedNode } from '#tests/helpers/store'
+
+const editor = useEditorSetupWithClear('/?test')
+const eyedropper = eyedropperDriver(() => editor.page)
+
+const SOURCE = { r: 1, g: 0, b: 0, a: 1 }
+const TARGET = { r: 0.2, g: 0.4, b: 0.8, a: 1 }
+
+/** A red source rectangle left of a blue target rectangle; the target ends up selected. */
+async function sourceAndTarget() {
+ const { canvas } = editor
+ await canvas.drawRect(100, 120, 100, 100)
+ const source = await eyedropper.selectedId()
+ if (!source) throw new Error('Drawing the source rectangle selected nothing')
+ await eyedropper.setFill(source, SOURCE)
+ await canvas.drawRect(300, 120, 100, 100)
+ const target = await eyedropper.selectedId()
+ if (!target) throw new Error('Drawing the target rectangle selected nothing')
+ await eyedropper.setFill(target, TARGET)
+ return target
+}
+
+test('I then a click paints the selection with the sampled color in one undo step', async () => {
+ const { canvas } = editor
+ const target = await sourceAndTarget()
+
+ await canvas.pressKey('i')
+ await canvas.click(150, 170)
+ await expect.poll(() => eyedropper.topPaint(target, 'fills')).toEqual({ color: SOURCE })
+ expect(await eyedropper.selectedId()).toBe(target)
+ expect(await eyedropper.activeTool()).toBe('SELECT')
+
+ await canvas.undo()
+ await expect.poll(() => eyedropper.topPaint(target, 'fills')).toEqual({ color: TARGET })
+})
+
+test('hovering shows the loupe with the color a click picks, until the pointer leaves', async () => {
+ const { page, canvas } = editor
+ await sourceAndTarget()
+ const loupe = page.getByTestId('eyedropper-loupe')
+
+ await canvas.pressKey('i')
+ await canvas.hover(150, 170)
+ await expect(loupe).toBeVisible()
+ await expect(page.getByTestId('eyedropper-loupe-value')).toHaveText('FF0000')
+
+ await page.mouse.move(0, 0)
+ await expect(loupe).toBeHidden()
+ await canvas.hover(150, 170)
+ await expect(loupe).toBeVisible()
+ await canvas.pressKey('Escape')
+ await expect(loupe).toBeHidden()
+})
+
+test('Alt-click samples into the stroke and keeps the fill', async () => {
+ const { page, canvas } = editor
+ const target = await sourceAndTarget()
+
+ await canvas.pressKey('i')
+ await page.keyboard.down('Alt')
+ await canvas.click(150, 170)
+ await page.keyboard.up('Alt')
+
+ await expect.poll(() => eyedropper.topPaint(target, 'strokes')).toEqual({ color: SOURCE })
+ expect(await eyedropper.topPaint(target, 'fills')).toEqual({ color: TARGET })
+})
+
+test('Escape leaves the eyedropper without changing the selection', async () => {
+ const { canvas } = editor
+ const target = await sourceAndTarget()
+
+ await canvas.pressKey('i')
+ await canvas.pressKey('Escape')
+ // With the Move tool back, the same click selects the source rectangle instead of sampling it.
+ await canvas.click(150, 170)
+ await expect.poll(() => eyedropper.selectedId()).not.toBe(target)
+ expect(await eyedropper.topPaint(target, 'fills')).toEqual({ color: TARGET })
+})
+
+test('I types a letter while editing text', async () => {
+ const { page, canvas } = editor
+ await canvas.pressKey('t')
+ await canvas.click(200, 300)
+ await page.keyboard.type('AIB')
+ await canvas.pressKey('Escape')
+
+ expect((await getSelectedNode(page))?.text).toBe('AIB')
+})
+
+test('the color picker button samples the canvas and the picker stays open', async () => {
+ const { page, canvas } = editor
+ const target = await sourceAndTarget()
+
+ await page.getByTestId('fill-picker-swatch').first().click()
+ const pick = page.getByTestId('color-eyedropper')
+ await pick.click()
+ await expect(pick).toHaveAttribute('aria-pressed', 'true')
+ await canvas.hover(150, 170)
+ await expect(page.getByTestId('eyedropper-loupe')).toBeVisible()
+ await canvas.click(150, 170)
+
+ await expect.poll(() => eyedropper.topPaint(target, 'fills')).toEqual({ color: SOURCE })
+ await expect(pick).toBeVisible()
+ await expect(pick).toHaveAttribute('aria-pressed', 'false')
+ expect(await eyedropper.activeTool()).toBe('SELECT')
+})
+
+test('a color sampled into the picker undoes and redoes as one step', async () => {
+ const { page, canvas } = editor
+ const target = await sourceAndTarget()
+
+ await page.getByTestId('fill-picker-swatch').first().click()
+ await page.getByTestId('color-eyedropper').click()
+ await canvas.click(150, 170)
+ await expect.poll(() => eyedropper.topPaint(target, 'fills')).toEqual({ color: SOURCE })
+
+ await page.keyboard.press('ControlOrMeta+z')
+ await expect.poll(() => eyedropper.topPaint(target, 'fills')).toEqual({ color: TARGET })
+ await page.keyboard.press('ControlOrMeta+Shift+z')
+ await expect.poll(() => eyedropper.topPaint(target, 'fills')).toEqual({ color: SOURCE })
+ await expect(page.getByTestId('color-eyedropper')).toBeVisible()
+})
+
+test('pressing the picker button again stops sampling', async () => {
+ const { page, canvas } = editor
+ const target = await sourceAndTarget()
+
+ await page.getByTestId('fill-picker-swatch').first().click()
+ const pick = page.getByTestId('color-eyedropper')
+ await pick.click()
+ await expect(pick).toHaveAttribute('aria-pressed', 'true')
+ await pick.click()
+
+ await expect(pick).toHaveAttribute('aria-pressed', 'false')
+ await expect.poll(() => eyedropper.activeTool()).toBe('SELECT')
+ // The picker stays open, and the next canvas click samples nothing.
+ await expect(pick).toBeVisible()
+ await canvas.click(150, 170)
+ expect(await eyedropper.topPaint(target, 'fills')).toEqual({ color: TARGET })
+})
+
+test('closing the picker while it samples leaves the eyedropper', async () => {
+ const { page, canvas } = editor
+ const target = await sourceAndTarget()
+
+ await page.getByTestId('fill-picker-swatch').first().click()
+ await page.getByTestId('color-eyedropper').click()
+ await page.keyboard.press('Escape')
+
+ await expect(page.getByTestId('color-eyedropper')).toBeHidden()
+ await expect.poll(() => eyedropper.activeTool()).toBe('SELECT')
+ // The next click selects as usual instead of answering a request no picker waits on.
+ await canvas.click(150, 170)
+ await expect.poll(() => eyedropper.selectedId()).not.toBe(target)
+ expect(await eyedropper.topPaint(target, 'fills')).toEqual({ color: TARGET })
+})
diff --git a/tests/engine/app/document/io/changes.test.ts b/tests/engine/app/document/io/changes.test.ts
index 5253bd859..83617ed84 100644
--- a/tests/engine/app/document/io/changes.test.ts
+++ b/tests/engine/app/document/io/changes.test.ts
@@ -2,7 +2,7 @@ import { expect, test } from 'bun:test'
import { computed, effectScope } from 'vue'
-import { createEditor } from '@open-pencil/core'
+import { applySampledColor, createEditor } from '@open-pencil/core'
import { exportFigFile, parseFigFile, populateFigPage } from '@open-pencil/core/io/formats/fig'
import { computeAllLayouts } from '@open-pencil/core/layout'
import { fontManager } from '@open-pencil/core/text'
@@ -155,6 +155,27 @@ test('undoing or redoing back to the saved state saves the document again', asyn
})
})
+test('an eyedropper sample is one saved-state step, and one that changes nothing is none', async () => {
+ await withSavedRectangle(async (editor, id, changes) => {
+ const red = { r: 1, g: 0, b: 0, a: 1 }
+ editor.select([id])
+ const states: boolean[] = []
+ const record = async () => {
+ await settle()
+ states.push(changes.hasUnsavedChanges())
+ }
+ applySampledColor(editor, red)
+ await record()
+ editor.undoAction()
+ await record()
+ editor.redoAction()
+ changes.markSaved()
+ applySampledColor(editor, red)
+ await record()
+ expect(states).toEqual([true, false, false])
+ })
+})
+
test('a change outside the history keeps the document unsaved after undoing back', async () => {
await withSavedRectangle(async (editor, id, changes) => {
// A collaborator's change reaches the graph without a step of this tab's history.
diff --git a/tests/helpers/canvas/eyedropper-driver.ts b/tests/helpers/canvas/eyedropper-driver.ts
new file mode 100644
index 000000000..9a11764ee
--- /dev/null
+++ b/tests/helpers/canvas/eyedropper-driver.ts
@@ -0,0 +1,49 @@
+import type { Page } from '@playwright/test'
+
+import type { Color } from '@open-pencil/scene-graph/primitives'
+
+/** Layers to sample from and paint into, and the paints the eyedropper leaves on them. */
+export function eyedropperDriver(page: () => Page) {
+ return {
+ /** The first selected layer's id, if any. */
+ selectedId() {
+ return page().evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ return [...store.state.selectedIds][0] ?? null
+ })
+ },
+
+ /** The layer's top paint of the kind, which the eyedropper replaces. */
+ topPaint(id: string, kind: 'fills' | 'strokes') {
+ return page().evaluate(
+ ([nodeId, key]) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const paint = store.graph.getNode(nodeId)?.[key].at(-1)
+ return paint?.type === 'SOLID' ? { color: paint.color } : null
+ },
+ [id, kind] as const
+ )
+ },
+
+ /** Setup: gives the layer one opaque solid fill. */
+ setFill(id: string, color: Color) {
+ return page().evaluate(
+ ([nodeId, value]) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ store.updateNodeWithUndo(nodeId, {
+ fills: [{ type: 'SOLID', color: value, opacity: 1, visible: true }]
+ })
+ },
+ [id, color] as const
+ )
+ },
+
+ /** The tool the editor has armed. */
+ activeTool() {
+ return page().evaluate(() => window.openPencil?.getStore?.().state.activeTool ?? null)
+ }
+ }
+}