@pairdraw/scene-graph 0.20.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/color/index.d.ts +28 -7
- package/dist/color/index.d.ts.map +1 -1
- package/dist/color/index.js +40 -15
- package/dist/color/index.js.map +1 -1
- package/dist/color/management.d.ts +19 -6
- package/dist/color/management.d.ts.map +1 -1
- package/dist/color/management.js +56 -1
- package/dist/color/management.js.map +1 -1
- package/dist/color/profile.d.ts +32 -0
- package/dist/color/profile.d.ts.map +1 -0
- package/dist/color/profile.js +140 -0
- package/dist/color/profile.js.map +1 -0
- package/dist/comments/index.d.ts +2 -2
- package/dist/comments/index.js +2 -2
- package/dist/comments/merge.d.ts.map +1 -1
- package/dist/comments/merge.js +1 -0
- package/dist/comments/merge.js.map +1 -1
- package/dist/comments/schema.d.ts +3 -1
- package/dist/comments/schema.d.ts.map +1 -1
- package/dist/comments/schema.js +19 -2
- package/dist/comments/schema.js.map +1 -1
- package/dist/comments/threads.d.ts +3 -1
- package/dist/comments/threads.d.ts.map +1 -1
- package/dist/comments/threads.js +2 -1
- package/dist/comments/threads.js.map +1 -1
- package/dist/components/properties.d.ts.map +1 -1
- package/dist/components/properties.js +7 -7
- package/dist/components/properties.js.map +1 -1
- package/dist/css/shadows.d.ts +2 -2
- package/dist/css/shadows.d.ts.map +1 -1
- package/dist/css/shadows.js +4 -4
- package/dist/css/shadows.js.map +1 -1
- package/dist/css/values.d.ts +7 -2
- package/dist/css/values.d.ts.map +1 -1
- package/dist/css/values.js +8 -4
- package/dist/css/values.js.map +1 -1
- package/dist/empty-values.js +9 -0
- package/dist/empty-values.js.map +1 -1
- package/dist/graph.d.ts +4 -0
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +11 -2
- package/dist/graph.js.map +1 -1
- package/dist/images.d.ts +3 -2
- package/dist/images.d.ts.map +1 -1
- package/dist/images.js +18 -2
- package/dist/images.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/instances/copies.js +2 -1
- package/dist/instances/copies.js.map +1 -1
- package/dist/instances/index.d.ts.map +1 -1
- package/dist/instances/index.js +12 -11
- package/dist/instances/index.js.map +1 -1
- package/dist/instances/overrides.d.ts +15 -1
- package/dist/instances/overrides.d.ts.map +1 -1
- package/dist/instances/overrides.js +37 -1
- package/dist/instances/overrides.js.map +1 -1
- package/dist/instances/swap-overrides.js +3 -3
- package/dist/instances/swap-overrides.js.map +1 -1
- package/dist/instances/sync.js +9 -7
- package/dist/instances/sync.js.map +1 -1
- package/dist/node-defaults.js +2 -2
- package/dist/node-defaults.js.map +1 -1
- package/dist/plugin-data/fields.d.ts +15 -0
- package/dist/plugin-data/fields.d.ts.map +1 -1
- package/dist/plugin-data/fields.js +15 -23
- package/dist/plugin-data/fields.js.map +1 -1
- package/dist/plugin-data/index.d.ts +2 -2
- package/dist/plugin-data/index.js +2 -2
- package/dist/plugin-data/schema.d.ts +6 -1
- package/dist/plugin-data/schema.d.ts.map +1 -1
- package/dist/plugin-data/schema.js +24 -1
- package/dist/plugin-data/schema.js.map +1 -1
- package/dist/shaders/animation.d.ts +21 -0
- package/dist/shaders/animation.d.ts.map +1 -0
- package/dist/shaders/animation.js +25 -0
- package/dist/shaders/animation.js.map +1 -0
- package/dist/shaders/index.d.ts +2 -1
- package/dist/shaders/index.js +2 -1
- package/dist/slots/content.d.ts.map +1 -1
- package/dist/slots/content.js +4 -4
- package/dist/slots/content.js.map +1 -1
- package/dist/statuses/index.d.ts +2 -2
- package/dist/statuses/index.js +2 -2
- package/dist/statuses/workflow.d.ts +3 -1
- package/dist/statuses/workflow.d.ts.map +1 -1
- package/dist/statuses/workflow.js +6 -2
- package/dist/statuses/workflow.js.map +1 -1
- package/dist/transfer/variables.d.ts.map +1 -1
- package/dist/transfer/variables.js +1 -1
- package/dist/transfer/variables.js.map +1 -1
- package/dist/types.d.ts +34 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/variables/bindings.d.ts +6 -5
- package/dist/variables/bindings.d.ts.map +1 -1
- package/dist/variables/bindings.js +24 -16
- package/dist/variables/bindings.js.map +1 -1
- package/dist/variables/formula/index.d.ts.map +1 -1
- package/dist/variables/formula/index.js +12 -6
- package/dist/variables/formula/index.js.map +1 -1
- package/dist/variables/index.d.ts +14 -1
- package/dist/variables/index.d.ts.map +1 -1
- package/dist/variables/index.js +38 -10
- package/dist/variables/index.js.map +1 -1
- package/dist/variables/paints.d.ts +9 -8
- package/dist/variables/paints.d.ts.map +1 -1
- package/dist/variables/paints.js +35 -26
- package/dist/variables/paints.js.map +1 -1
- package/dist/variables/resolver.d.ts +45 -0
- package/dist/variables/resolver.d.ts.map +1 -0
- package/dist/variables/resolver.js +106 -0
- package/dist/variables/resolver.js.map +1 -0
- package/package.json +1 -1
- package/src/color/index.ts +43 -9
- package/src/color/management.ts +54 -1
- package/src/color/profile.ts +131 -0
- package/src/comments/merge.ts +3 -0
- package/src/comments/schema.ts +32 -2
- package/src/comments/threads.ts +5 -2
- package/src/components/properties.ts +13 -7
- package/src/css/shadows.ts +8 -5
- package/src/css/values.ts +12 -5
- package/src/empty-values.ts +16 -0
- package/src/graph.ts +13 -1
- package/src/images.ts +27 -3
- package/src/instances/copies.ts +2 -1
- package/src/instances/index.ts +19 -11
- package/src/instances/overrides.ts +49 -0
- package/src/instances/swap-overrides.ts +3 -2
- package/src/instances/sync.ts +11 -7
- package/src/node-defaults.ts +2 -2
- package/src/plugin-data/fields.ts +16 -31
- package/src/plugin-data/index.ts +1 -0
- package/src/plugin-data/schema.ts +30 -0
- package/src/shaders/animation.ts +39 -0
- package/src/shaders/index.ts +1 -0
- package/src/slots/content.ts +8 -4
- package/src/statuses/workflow.ts +6 -4
- package/src/transfer/variables.ts +2 -1
- package/src/types.ts +30 -1
- package/src/variables/bindings.ts +35 -18
- package/src/variables/formula/index.ts +19 -18
- package/src/variables/index.ts +49 -10
- package/src/variables/paints.ts +64 -29
- package/src/variables/resolver.ts +178 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"paints.js","names":[],"sources":["../../src/variables/paints.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit/predicate'\n\nimport { copyFills, copyStrokes } from '../copy'\nimport type { SceneGraph } from '../graph'\nimport { hasInstanceOverride } from '../instances/overrides'\nimport type { Color } from '../primitives'\nimport type { Fill, SceneNode, Stroke } from '../types'\nimport { paintBindingTarget, type PaintBindingList } from './fields'\nimport { collectionsResolving, getNodeExplicitVariableModeId } from './resolution'\nimport { subtreeNodes } from './subtree'\n\n/**\n * Figma keeps a bound paint's color and opacity as a cache of its variable: it draws and reads\n * what the paint holds, and writes the variable's color into it again only once the color the\n * variable gives that layer changes, or the mode set for the layer changes, so an edit to the\n * paint sticks until then. The color each binding last gave its paint, and the modes set for the\n * layer then, live here, beside the graph and never saved, by layer and binding field. A layer\n * without an entry, such as one just restored, counts its paint's own color as the last one\n * applied, in the modes it has now.\n */\nexport interface AppliedColor {\n readonly variableId: string\n readonly color: Color\n /** The mode set for the layer, or null, in each collection the variable resolves through. */\n readonly modes: Readonly<Record<string, string | null>>\n}\n\nconst appliedColors = new WeakMap<SceneNode, Map<string, AppliedColor>>()\n\nconst PAINT_LISTS = ['fills', 'strokes'] as const\n\ninterface BoundPaint {\n readonly field: string\n readonly list: PaintBindingList\n readonly index: number\n readonly variableId: string\n}\n\n/** The paints of `node` whose color is bound to a variable, each with a paint there to color. */\nfunction boundPaints(node: SceneNode): BoundPaint[] {\n const paints: BoundPaint[] = []\n for (const [field, variableId] of Object.entries(node.boundVariables)) {\n const target = paintBindingTarget(field)\n if (target && node[target.list].at(target.index)) paints.push({ field, ...target, variableId })\n }\n return paints\n}\n\n/** Whether a layer has a paint whose color is bound to a variable. */\nexport function hasBoundPaints(node: SceneNode): boolean {\n for (const field in node.boundVariables) if (paintBindingTarget(field)) return true\n return false\n}\n\n/**\n * Whether a binding's paint holds a color this graph applied or recorded for it. A layer without\n * an entry, such as one just imported or built with its bindings, has a stored color nothing\n * vouches for: readers show its variable's color until a write or refresh records one.\n */\nexport function paintColorApplied(node: SceneNode, field: string): boolean {\n return appliedColors.get(node)?.has(field) ?? false\n}\n\n/** A paint's color with its opacity as alpha, as a variable's color carries it. */\nfunction paintColor(paint: Fill): Color {\n return { r: paint.color.r, g: paint.color.g, b: paint.color.b, a: paint.opacity }\n}\n\n/** Saved colors are single precision, so a color read back from a file still matches its source. */\nconst COLOR_TOLERANCE = 1e-6\n\nfunction sameColor(a: Color, b: Color): boolean {\n return (\n Math.abs(a.r - b.r) <= COLOR_TOLERANCE &&\n Math.abs(a.g - b.g) <= COLOR_TOLERANCE &&\n Math.abs(a.b - b.b) <= COLOR_TOLERANCE &&\n Math.abs(a.a - b.a) <= COLOR_TOLERANCE\n )\n}\n\n/**\n * The modes set for a layer, or null, in the collections a variable resolves through. Figma\n * refreshes a bound paint whenever one of them changes, even to a mode giving the same color.\n */\nfunction explicitModes(\n graph: SceneGraph,\n node: SceneNode,\n variableId: string\n): Record<string, string | null> {\n const modes: Record<string, string | null> = {}\n for (const collectionId of collectionsResolving(graph, [variableId]))\n modes[collectionId] = getNodeExplicitVariableModeId(graph, node.id, collectionId)\n return modes\n}\n\n/** Whether the color a binding last applied is stale: another color, or set in other modes. */\nfunction staleApplied(\n node: SceneNode,\n bound: BoundPaint,\n paint: Fill,\n color: Color,\n modes: Readonly<Record<string, string | null>>\n): boolean {\n const entry = appliedColors.get(node)?.get(bound.field)\n if (entry?.variableId !== bound.variableId) return !sameColor(paintColor(paint), color)\n return !sameColor(entry.color, color) || !isEqual(entry.modes, modes)\n}\n\n/**\n * A layer copied from another keeps the colors its bindings last applied there, so the copy's\n * paints, edits included, stay as they are until their variables' colors for it change.\n */\nexport function copyAppliedBoundPaints(source: SceneNode, copy: SceneNode): void {\n const entries = appliedColors.get(source)\n if (entries) appliedColors.set(copy, new Map(entries))\n}\n\n/** The colors copied layers' bindings last applied, by layer id, as a copy captured them. */\nexport type AppliedBoundPaints = ReadonlyMap<string, ReadonlyMap<string, AppliedColor>>\n\n/**\n * The colors the bindings of the layers `nodeIds` names last applied, captured when they are\n * copied, so a paste counts what the copied paints were applied from, not what the source has now.\n */\nexport function captureAppliedBoundPaints(\n graph: SceneGraph,\n nodeIds: Iterable<string>\n): AppliedBoundPaints {\n const captured = new Map<string, ReadonlyMap<string, AppliedColor>>()\n for (const id of nodeIds) {\n const node = graph.nodes.get(id)\n const entries = node && appliedColors.get(node)\n if (entries) captured.set(id, new Map(entries))\n }\n return captured\n}\n\n/**\n * Pasted layers keep their paints, edits included, as Figma's copies do. One copied in this\n * document takes the colors its source's bindings had last applied when it was copied, so a paste\n * into another mode refreshes them as a move there would; one from elsewhere counts the colors\n * its variables give it now as applied, as a loaded document does. `copies` maps each copied\n * layer's id to its copy's.\n */\nexport function keepPastedBoundPaints(\n graph: SceneGraph,\n copies: ReadonlyMap<string, string>,\n applied: AppliedBoundPaints\n): void {\n for (const [sourceId, copyId] of copies) {\n const copy = graph.nodes.get(copyId)\n if (!copy || !hasBoundPaints(copy)) continue\n const entries = applied.get(sourceId)\n if (!entries) {\n recordWrittenBoundPaints(graph, copy, { fills: copy.fills, strokes: copy.strokes })\n continue\n }\n appliedColors.set(copy, new Map(entries))\n refresh(graph, copy, NONE_FORCED)\n }\n}\n\nfunction recordApplied(\n node: SceneNode,\n bound: BoundPaint,\n color: Color,\n modes: Readonly<Record<string, string | null>>\n): void {\n let entries = appliedColors.get(node)\n if (!entries) {\n entries = new Map()\n appliedColors.set(node, entries)\n }\n entries.set(bound.field, { variableId: bound.variableId, color: { ...color }, modes })\n}\n\n/** The variable's RGB at full alpha in the paint, and its alpha as the paint's opacity. */\nfunction applyColor(paint: Fill, color: Color): void {\n paint.color = { ...color, a: 1 }\n paint.opacity = color.a\n}\n\n/** Whether `paint` already shows `color` as a bound paint stores it. */\nfunction showsColor(paint: Fill, color: Color): boolean {\n return sameColor(paintColor(paint), color) && paint.color.a === 1\n}\n\ntype PaintLists = Pick<Partial<SceneNode>, 'fills' | 'strokes'>\n\n/**\n * Whether `node` is an instance, or a layer an instance copies from its component, with a paint\n * list neither it nor an instance around it overrides: such paints follow the component, and\n * refreshing them is no edit.\n */\nexport function copiesComponentPaints(\n graph: SceneGraph,\n node: SceneNode,\n list: PaintBindingList\n): boolean {\n const walk = { copied: false }\n const overriding = graph.closest(node.id, (current) => {\n if (current.type !== 'INSTANCE') return false\n walk.copied = true\n return hasInstanceOverride(current.instanceOverrides, current.id, node.id, list)\n })\n return walk.copied && !overriding\n}\n\n/**\n * Writes refreshed paints. A copy's paints that follow its component are derived values that a\n * save leaves to the component, not edits written over it.\n */\nfunction writePaints(graph: SceneGraph, node: SceneNode, changes: PaintLists): void {\n const derived = PAINT_LISTS.every(\n (list) => !changes[list] || copiesComponentPaints(graph, node, list)\n )\n const write = () => graph.updateNode(node.id, changes)\n if (derived) graph.applyComponentDerivedDuring(write)\n else write()\n}\n\n/**\n * Writes into each bound paint the color its variable gives the layer now, where that differs\n * from the color last applied, or wherever `forced` says, and records what each binding gives.\n */\nfunction refresh(graph: SceneGraph, node: SceneNode, forced: (field: string) => boolean): void {\n let fills: Fill[] | undefined\n let strokes: Stroke[] | undefined\n for (const bound of boundPaints(node)) {\n const color = graph.resolveColorVariableForNode(node.id, bound.variableId)\n const paint = node[bound.list].at(bound.index)\n if (!color || !paint) continue\n const modes = explicitModes(graph, node, bound.variableId)\n const stale = staleApplied(node, bound, paint, color, modes)\n recordApplied(node, bound, color, modes)\n if ((!forced(bound.field) && !stale) || showsColor(paint, color)) continue\n if (bound.list === 'fills') {\n fills ??= copyFills(node.fills)\n applyColor(fills[bound.index], color)\n } else {\n strokes ??= copyStrokes(node.strokes)\n applyColor(strokes[bound.index], color)\n }\n }\n const changes: PaintLists = {}\n if (fills) changes.fills = fills\n if (strokes) changes.strokes = strokes\n if (fills || strokes) writePaints(graph, node, changes)\n}\n\nconst NONE_FORCED = (): boolean => false\nconst ALL_FORCED = (): boolean => true\n\n/**\n * Refreshes a layer's bound paints: each takes its variable's color for the layer, alpha as\n * opacity, once that color differs from the one last applied, discarding edits made since, as\n * Figma refreshes them when a variable's value or a layer's mode changes.\n */\nexport function refreshBoundPaints(graph: SceneGraph, node: SceneNode): void {\n if (hasBoundPaints(node)) refresh(graph, node, NONE_FORCED)\n}\n\n/** Gives one bound paint its variable's color for the layer, as binding it does in Figma. */\nexport function applyBoundPaintColor(graph: SceneGraph, node: SceneNode, field: string): void {\n if (paintBindingTarget(field)) refresh(graph, node, (bound) => bound === field)\n}\n\n/**\n * Gives every bound paint in this subtree its variable's color where it sits. A new instance\n * or a layer an instance sync adds is a copy, which shows its variables in its own context rather\n * than whatever its component's paints hold.\n */\nexport function applyBoundPaintColorsIn(graph: SceneGraph, rootId: string): void {\n for (const node of subtreeNodes(graph, [rootId]))\n if (hasBoundPaints(node)) refresh(graph, node, ALL_FORCED)\n}\n\n/** Refreshes the bound paints in this subtree whose variables now give their layers another color. */\nexport function refreshBoundPaintsIn(graph: SceneGraph, rootId: string): void {\n for (const node of subtreeNodes(graph, [rootId])) refreshBoundPaints(graph, node)\n}\n\n/**\n * Records, for the paint lists a write sets, the colors their variables give the layer now, so a\n * paint written with another color or opacity keeps it until that color changes.\n */\nexport function recordWrittenBoundPaints(\n graph: SceneGraph,\n node: SceneNode,\n written: PaintLists\n): void {\n for (const bound of boundPaints(node)) {\n if (!written[bound.list]) continue\n const color = graph.resolveColorVariableForNode(node.id, bound.variableId)\n if (color) recordApplied(node, bound, color, explicitModes(graph, node, bound.variableId))\n }\n}\n\n/**\n * The fills and strokes a layer shows: its stored paints, except a bound paint no applied color\n * vouches for takes its variable's color for the layer, alpha as opacity, as Figma shows a layer\n * whose saved cache is stale on import. Nothing is written or recorded; a copy pasted unlinked\n * keeps the colors it showed.\n */\nexport function shownPaintBindings(\n graph: SceneGraph,\n node: SceneNode\n): Pick<Partial<SceneNode>, 'fills' | 'strokes'> {\n const changes: Pick<Partial<SceneNode>, 'fills' | 'strokes'> = {}\n for (const bound of boundPaints(node)) {\n if (paintColorApplied(node, bound.field)) continue\n const color = graph.resolveColorVariableForNode(node.id, bound.variableId)\n const paint = node[bound.list].at(bound.index)\n if (!color || !paint || showsColor(paint, color)) continue\n if (bound.list === 'fills') {\n changes.fills ??= copyFills(node.fills)\n applyColor(changes.fills[bound.index], color)\n } else {\n changes.strokes ??= copyStrokes(node.strokes)\n applyColor(changes.strokes[bound.index], color)\n }\n }\n return changes\n}\n\n/**\n * Refreshes the bound paints in a moved layer's subtree that resolve through a collection whose\n * mode set the move changed, as Figma does when a layer enters a frame or page that sets another\n * mode, or one where none was. A move between parents setting the same modes, or of layers that\n * bind no paint, costs no more than comparing those modes.\n */\nexport function refreshMovedBoundPaints(\n graph: SceneGraph,\n nodeId: string,\n previousParentId: string | null | undefined\n): void {\n if (graph.isApplyingImportedState || graph.variableCollections.size === 0) return\n const parentId = graph.nodes.get(nodeId)?.parentId\n if (!parentId) return\n const previous = previousParentId && graph.nodes.has(previousParentId) ? previousParentId : null\n const changed = new Set(\n [...graph.variableCollections.keys()].filter(\n (id) =>\n !previous ||\n getNodeExplicitVariableModeId(graph, previous, id) !==\n getNodeExplicitVariableModeId(graph, parentId, id)\n )\n )\n if (changed.size === 0) return\n const reaches = new Map<string, boolean>()\n const reachesChanged = (variableId: string) => {\n let found = reaches.get(variableId)\n if (found === undefined) {\n found = [...collectionsResolving(graph, [variableId])].some((id) => changed.has(id))\n reaches.set(variableId, found)\n }\n return found\n }\n for (const node of subtreeNodes(graph, [nodeId])) {\n if (boundPaints(node).some((bound) => reachesChanged(bound.variableId)))\n refresh(graph, node, NONE_FORCED)\n }\n}\n\nfunction reboundPaint(\n target: SceneNode,\n bindings: Readonly<Record<string, string>>,\n list: PaintBindingList\n): boolean {\n return target[list].some((_, index) => {\n const field = `${list}/${index}/color`\n return field in bindings && bindings[field] !== target.boundVariables[field]\n })\n}\n\n/**\n * A copy's bound paints are its own cache, as Figma keeps them per layer, so a component's edit\n * to its paint's color or opacity does not reach them. An instance sync writing a copy's paints\n * keeps the color and opacity of each one still bound to the same variable, and gives it the\n * variable's color for the copy once that differs from the one last applied, or when it binds\n * anew. `updates` holds what the sync writes, whose paints this sets in place.\n */\nexport function keepCopyBoundPaints(\n graph: SceneGraph,\n target: SceneNode,\n updates: Partial<SceneNode>\n): void {\n const bindings = updates.boundVariables ?? target.boundVariables\n for (const list of PAINT_LISTS) {\n // A paint the component binds anew keeps its own paint otherwise, but takes the new color.\n if (!updates[list] && reboundPaint(target, bindings, list))\n Object.assign(updates, {\n [list]: list === 'fills' ? copyFills(target.fills) : copyStrokes(target.strokes)\n })\n updates[list]?.forEach((paint, index) => {\n const field = `${list}/${index}/color`\n const variableId = bindings[field]\n if (!variableId) return\n const bound = { field, list, index, variableId }\n const own = target[list].at(index)\n const keeps = own !== undefined && target.boundVariables[field] === variableId\n if (keeps) {\n paint.color = { ...own.color }\n paint.opacity = own.opacity\n }\n const color = graph.resolveColorVariableForNode(target.id, variableId)\n if (!color) return\n const modes = explicitModes(graph, target, variableId)\n if (!keeps || staleApplied(target, bound, own, color, modes)) applyColor(paint, color)\n recordApplied(target, bound, color, modes)\n })\n }\n}\n"],"mappings":";;;;;;;AA2BA,MAAM,gCAAgB,IAAI,QAA8C;AAExE,MAAM,cAAc,CAAC,SAAS,SAAS;;AAUvC,SAAS,YAAY,MAA+B;CAClD,MAAM,SAAuB,CAAC;CAC9B,KAAK,MAAM,CAAC,OAAO,eAAe,OAAO,QAAQ,KAAK,cAAc,GAAG;EACrE,MAAM,SAAS,mBAAmB,KAAK;EACvC,IAAI,UAAU,KAAK,OAAO,KAAK,CAAC,GAAG,OAAO,KAAK,GAAG,OAAO,KAAK;GAAE;GAAO,GAAG;GAAQ;EAAW,CAAC;CAChG;CACA,OAAO;AACT;;AAGA,SAAgB,eAAe,MAA0B;CACvD,KAAK,MAAM,SAAS,KAAK,gBAAgB,IAAI,mBAAmB,KAAK,GAAG,OAAO;CAC/E,OAAO;AACT;;;;;;AAOA,SAAgB,k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QAAQ,kBAAkB,OAAO;CAClD,KAAK,MAAM,QAAQ,aAAa;EAE9B,IAAI,CAAC,QAAQ,SAAS,aAAa,QAAQ,UAAU,IAAI,GACvD,OAAO,OAAO,SAAS,GACpB,OAAO,SAAS,UAAU,UAAU,OAAO,KAAK,IAAI,YAAY,OAAO,OAAO,EACjF,CAAC;EACH,QAAQ,KAAK,EAAE,SAAS,OAAO,UAAU;GACvC,MAAM,QAAQ,GAAG,KAAK,GAAG,MAAM;GAC/B,MAAM,aAAa,SAAS;GAC5B,IAAI,CAAC,YAAY;GACjB,MAAM,QAAQ;IAAE;IAAO;IAAM;IAAO;GAAW;GAC/C,MAAM,MAAM,OAAO,KAAK,CAAC,GAAG,KAAK;GACjC,MAAM,QAAQ,QAAQ,KAAA,KAAa,OAAO,eAAe,WAAW;GACpE,IAAI,OAAO;IACT,MAAM,QAAQ,EAAE,GAAG,IAAI,MAAM;IAC7B,MAAM,UAAU,IAAI;GACtB;GACA,MAAM,QAAQ,MAAM,4BAA4B,OAAO,IAAI,UAAU;GACrE,IAAI,CAAC,OAAO;GACZ,MAAM,QAAQ,cAAc,OAAO,QAAQ,UAAU;GACrD,IAAI,CAAC,SAAS,aAAa,QAAQ,OAAO,KAAK,OAAO,KAAK,GAAG,WAAW,OAAO,KAAK;GACrF,cAAc,QAAQ,OAAO,OAAO,KAAK;EAC3C,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"paints.js","names":[],"sources":["../../src/variables/paints.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit/predicate'\n\nimport { copyFills, copyStrokes } from '../copy'\nimport type { SceneGraph } from '../graph'\nimport { hasInstanceOverride } from '../instances/overrides'\nimport type { Color } from '../primitives'\nimport type { Fill, SceneNode, Stroke } from '../types'\nimport { paintBindingTarget, type PaintBindingList } from './fields'\nimport { createVariableResolver, type VariableResolver } from './resolver'\nimport { subtreeNodes } from './subtree'\n\n/**\n * Figma keeps a bound paint's color and opacity as a cache of its variable: it draws and reads\n * what the paint holds, and writes the variable's color into it again only once the color the\n * variable gives that layer changes, or the mode set for the layer changes, so an edit to the\n * paint sticks until then. The color each binding last gave its paint, and the modes set for the\n * layer then, live here, beside the graph and never saved, by layer and binding field. A layer\n * without an entry, such as one just restored, counts its paint's own color as the last one\n * applied, in the modes it has now.\n */\nexport interface AppliedColor {\n readonly variableId: string\n readonly color: Color\n /** The mode set for the layer, or null, in each collection the variable resolves through. */\n readonly modes: Readonly<Record<string, string | null>>\n}\n\nconst appliedColors = new WeakMap<SceneNode, Map<string, AppliedColor>>()\n\nconst PAINT_LISTS = ['fills', 'strokes'] as const\n\ninterface BoundPaint {\n readonly field: string\n readonly list: PaintBindingList\n readonly index: number\n readonly variableId: string\n}\n\n/** The paints of `node` whose color is bound to a variable, each with a paint there to color. */\nfunction boundPaints(node: SceneNode): BoundPaint[] {\n const paints: BoundPaint[] = []\n for (const [field, variableId] of Object.entries(node.boundVariables)) {\n const target = paintBindingTarget(field)\n if (target && node[target.list].at(target.index)) paints.push({ field, ...target, variableId })\n }\n return paints\n}\n\n/** Whether a layer has a paint whose color is bound to a variable. */\nexport function hasBoundPaints(node: SceneNode): boolean {\n for (const field in node.boundVariables) if (paintBindingTarget(field)) return true\n return false\n}\n\n/**\n * Whether a binding's paint holds a color this graph applied or recorded for it. A layer without\n * an entry, such as one just imported or built with its bindings, has a stored color nothing\n * vouches for: readers show its variable's color until a write or refresh records one.\n */\nexport function paintColorApplied(node: SceneNode, field: string): boolean {\n return appliedColors.get(node)?.has(field) ?? false\n}\n\n/** A paint's color with its opacity as alpha, as a variable's color carries it. */\nfunction paintColor(paint: Fill): Color {\n return { r: paint.color.r, g: paint.color.g, b: paint.color.b, a: paint.opacity }\n}\n\n/** Saved colors are single precision, so a color read back from a file still matches its source. */\nconst COLOR_TOLERANCE = 1e-6\n\nfunction sameColor(a: Color, b: Color): boolean {\n return (\n Math.abs(a.r - b.r) <= COLOR_TOLERANCE &&\n Math.abs(a.g - b.g) <= COLOR_TOLERANCE &&\n Math.abs(a.b - b.b) <= COLOR_TOLERANCE &&\n Math.abs(a.a - b.a) <= COLOR_TOLERANCE\n )\n}\n\n/**\n * The modes set for a layer, or null, in the collections a variable resolves through. Figma\n * refreshes a bound paint whenever one of them changes, even to a mode giving the same color.\n */\nfunction explicitModes(\n graph: SceneGraph,\n node: SceneNode,\n variableId: string,\n resolver?: VariableResolver\n): Record<string, string | null> {\n const modes: Record<string, string | null> = {}\n const shared = resolver ?? createVariableResolver(graph)\n for (const collectionId of shared.dependencies([variableId]))\n modes[collectionId] = shared.explicitModeFor(node.id, collectionId)\n return modes\n}\n\n/** Whether the color a binding last applied is stale: another color, or set in other modes. */\nfunction staleApplied(\n node: SceneNode,\n bound: BoundPaint,\n paint: Fill,\n color: Color,\n modes: Readonly<Record<string, string | null>>\n): boolean {\n const entry = appliedColors.get(node)?.get(bound.field)\n if (entry?.variableId !== bound.variableId) return !sameColor(paintColor(paint), color)\n return !sameColor(entry.color, color) || !isEqual(entry.modes, modes)\n}\n\n/**\n * A layer copied from another keeps the colors its bindings last applied there, so the copy's\n * paints, edits included, stay as they are until their variables' colors for it change.\n */\nexport function copyAppliedBoundPaints(source: SceneNode, copy: SceneNode): void {\n const entries = appliedColors.get(source)\n if (entries) appliedColors.set(copy, new Map(entries))\n}\n\n/** The colors copied layers' bindings last applied, by layer id, as a copy captured them. */\nexport type AppliedBoundPaints = ReadonlyMap<string, ReadonlyMap<string, AppliedColor>>\n\n/**\n * The colors the bindings of the layers `nodeIds` names last applied, captured when they are\n * copied, so a paste counts what the copied paints were applied from, not what the source has now.\n */\nexport function captureAppliedBoundPaints(\n graph: SceneGraph,\n nodeIds: Iterable<string>\n): AppliedBoundPaints {\n const captured = new Map<string, ReadonlyMap<string, AppliedColor>>()\n for (const id of nodeIds) {\n const node = graph.nodes.get(id)\n const entries = node && appliedColors.get(node)\n if (entries) captured.set(id, new Map(entries))\n }\n return captured\n}\n\n/**\n * Pasted layers keep their paints, edits included, as Figma's copies do. One copied in this\n * document takes the colors its source's bindings had last applied when it was copied, so a paste\n * into another mode refreshes them as a move there would; one from elsewhere counts the colors\n * its variables give it now as applied, as a loaded document does. `copies` maps each copied\n * layer's id to its copy's.\n */\nexport function keepPastedBoundPaints(\n graph: SceneGraph,\n copies: ReadonlyMap<string, string>,\n applied: AppliedBoundPaints\n): void {\n for (const [sourceId, copyId] of copies) {\n const copy = graph.nodes.get(copyId)\n if (!copy || !hasBoundPaints(copy)) continue\n const entries = applied.get(sourceId)\n if (!entries) {\n recordWrittenBoundPaints(graph, copy, { fills: copy.fills, strokes: copy.strokes })\n continue\n }\n appliedColors.set(copy, new Map(entries))\n refresh(graph, copy, NONE_FORCED)\n }\n}\n\nfunction recordApplied(\n node: SceneNode,\n bound: BoundPaint,\n color: Color,\n modes: Readonly<Record<string, string | null>>\n): void {\n let entries = appliedColors.get(node)\n if (!entries) {\n entries = new Map()\n appliedColors.set(node, entries)\n }\n entries.set(bound.field, { variableId: bound.variableId, color: { ...color }, modes })\n}\n\n/** The variable's RGB at full alpha in the paint, and its alpha as the paint's opacity. */\nfunction applyColor(paint: Fill, color: Color): void {\n paint.color = { ...color, a: 1 }\n paint.opacity = color.a\n}\n\n/** Whether `paint` already shows `color` as a bound paint stores it. */\nfunction showsColor(paint: Fill, color: Color): boolean {\n return sameColor(paintColor(paint), color) && paint.color.a === 1\n}\n\ntype PaintLists = Pick<Partial<SceneNode>, 'fills' | 'strokes'>\n\n/**\n * Whether `node` is an instance, or a layer an instance copies from its component, with a paint\n * list neither it nor an instance around it overrides: such paints follow the component, and\n * refreshing them is no edit.\n */\nexport function copiesComponentPaints(\n graph: SceneGraph,\n node: SceneNode,\n list: PaintBindingList\n): boolean {\n const walk = { copied: false }\n const overriding = graph.closest(node.id, (current) => {\n if (current.type !== 'INSTANCE') return false\n walk.copied = true\n return hasInstanceOverride(current.instanceOverrides, current.id, node.id, list)\n })\n return walk.copied && !overriding\n}\n\n/**\n * Writes refreshed paints. A copy's paints that follow its component are derived values that a\n * save leaves to the component, not edits written over it.\n */\nfunction writePaints(graph: SceneGraph, node: SceneNode, changes: PaintLists): void {\n const derived = PAINT_LISTS.every(\n (list) => !changes[list] || copiesComponentPaints(graph, node, list)\n )\n const write = () => graph.updateNode(node.id, changes)\n if (derived) graph.applyComponentDerivedDuring(write)\n else write()\n}\n\n/**\n * Writes into each bound paint the color its variable gives the layer now, where that differs\n * from the color last applied, or wherever `forced` says, and records what each binding gives.\n */\nfunction refresh(\n graph: SceneGraph,\n node: SceneNode,\n forced: (field: string) => boolean,\n resolver?: VariableResolver\n): void {\n let fills: Fill[] | undefined\n let strokes: Stroke[] | undefined\n const reader = (resolver ?? createVariableResolver(graph)).forNode(node.id)\n for (const bound of boundPaints(node)) {\n const color = reader.color(bound.variableId)\n const paint = node[bound.list].at(bound.index)\n if (!color || !paint) continue\n const modes = explicitModes(graph, node, bound.variableId, resolver)\n const stale = staleApplied(node, bound, paint, color, modes)\n recordApplied(node, bound, color, modes)\n if ((!forced(bound.field) && !stale) || showsColor(paint, color)) continue\n if (bound.list === 'fills') {\n fills ??= copyFills(node.fills)\n applyColor(fills[bound.index], color)\n } else {\n strokes ??= copyStrokes(node.strokes)\n applyColor(strokes[bound.index], color)\n }\n }\n const changes: PaintLists = {}\n if (fills) changes.fills = fills\n if (strokes) changes.strokes = strokes\n if (fills || strokes) writePaints(graph, node, changes)\n}\n\nconst NONE_FORCED = (): boolean => false\nconst ALL_FORCED = (): boolean => true\n\n/**\n * Refreshes a layer's bound paints: each takes its variable's color for the layer, alpha as\n * opacity, once that color differs from the one last applied, discarding edits made since, as\n * Figma refreshes them when a variable's value or a layer's mode changes.\n */\nexport function refreshBoundPaints(\n graph: SceneGraph,\n node: SceneNode,\n resolver?: VariableResolver\n): void {\n if (hasBoundPaints(node)) refresh(graph, node, NONE_FORCED, resolver)\n}\n\n/** Gives one bound paint its variable's color for the layer, as binding it does in Figma. */\nexport function applyBoundPaintColor(\n graph: SceneGraph,\n node: SceneNode,\n field: string,\n resolver?: VariableResolver\n): void {\n if (paintBindingTarget(field)) refresh(graph, node, (bound) => bound === field, resolver)\n}\n\n/**\n * Gives every bound paint in this subtree its variable's color where it sits. A new instance\n * or a layer an instance sync adds is a copy, which shows its variables in its own context rather\n * than whatever its component's paints hold.\n */\nexport function applyBoundPaintColorsIn(\n graph: SceneGraph,\n rootId: string,\n resolver?: VariableResolver\n): void {\n const shared = resolver ?? createVariableResolver(graph)\n for (const node of subtreeNodes(graph, [rootId]))\n if (hasBoundPaints(node)) refresh(graph, node, ALL_FORCED, shared)\n}\n\n/** Refreshes the bound paints in this subtree whose variables now give their layers another color. */\nexport function refreshBoundPaintsIn(\n graph: SceneGraph,\n rootId: string,\n resolver?: VariableResolver\n): void {\n const shared = resolver ?? createVariableResolver(graph)\n for (const node of subtreeNodes(graph, [rootId])) refreshBoundPaints(graph, node, shared)\n}\n\n/**\n * Records, for the paint lists a write sets, the colors their variables give the layer now, so a\n * paint written with another color or opacity keeps it until that color changes.\n */\nexport function recordWrittenBoundPaints(\n graph: SceneGraph,\n node: SceneNode,\n written: PaintLists,\n resolver?: VariableResolver\n): void {\n const reader = (resolver ?? createVariableResolver(graph)).forNode(node.id)\n for (const bound of boundPaints(node)) {\n if (!written[bound.list]) continue\n const color = reader.color(bound.variableId)\n if (color)\n recordApplied(node, bound, color, explicitModes(graph, node, bound.variableId, resolver))\n }\n}\n\n/**\n * The fills and strokes a layer shows: its stored paints, except a bound paint no applied color\n * vouches for takes its variable's color for the layer, alpha as opacity, as Figma shows a layer\n * whose saved cache is stale on import. Nothing is written or recorded; a copy pasted unlinked\n * keeps the colors it showed.\n */\nexport function shownPaintBindings(\n graph: SceneGraph,\n node: SceneNode,\n resolver?: VariableResolver\n): Pick<Partial<SceneNode>, 'fills' | 'strokes'> {\n const changes: Pick<Partial<SceneNode>, 'fills' | 'strokes'> = {}\n const reader = (resolver ?? createVariableResolver(graph)).forNode(node.id)\n for (const bound of boundPaints(node)) {\n if (paintColorApplied(node, bound.field)) continue\n const color = reader.color(bound.variableId)\n const paint = node[bound.list].at(bound.index)\n if (!color || !paint || showsColor(paint, color)) continue\n if (bound.list === 'fills') {\n changes.fills ??= copyFills(node.fills)\n applyColor(changes.fills[bound.index], color)\n } else {\n changes.strokes ??= copyStrokes(node.strokes)\n applyColor(changes.strokes[bound.index], color)\n }\n }\n return changes\n}\n\n/**\n * Refreshes the bound paints in a moved layer's subtree that resolve through a collection whose\n * mode set the move changed, as Figma does when a layer enters a frame or page that sets another\n * mode, or one where none was. A move between parents setting the same modes, or of layers that\n * bind no paint, costs no more than comparing those modes.\n */\nexport function refreshMovedBoundPaints(\n graph: SceneGraph,\n nodeId: string,\n previousParentId: string | null | undefined,\n resolver?: VariableResolver\n): void {\n if (graph.isApplyingImportedState || graph.variableCollections.size === 0) return\n const parentId = graph.nodes.get(nodeId)?.parentId\n if (!parentId) return\n const previous = previousParentId && graph.nodes.has(previousParentId) ? previousParentId : null\n const shared = resolver ?? createVariableResolver(graph)\n const changed = new Set(\n [...graph.variableCollections.keys()].filter(\n (id) =>\n !previous || shared.explicitModeFor(previous, id) !== shared.explicitModeFor(parentId, id)\n )\n )\n if (changed.size === 0) return\n const reaches = new Map<string, boolean>()\n const reachesChanged = (variableId: string) => {\n let found = reaches.get(variableId)\n if (found === undefined) {\n found = [...shared.dependencies([variableId])].some((id) => changed.has(id))\n reaches.set(variableId, found)\n }\n return found\n }\n for (const node of subtreeNodes(graph, [nodeId])) {\n if (boundPaints(node).some((bound) => reachesChanged(bound.variableId)))\n refresh(graph, node, NONE_FORCED, shared)\n }\n}\n\nfunction reboundPaint(\n target: SceneNode,\n bindings: Readonly<Record<string, string>>,\n list: PaintBindingList\n): boolean {\n return target[list].some((_, index) => {\n const field = `${list}/${index}/color`\n return field in bindings && bindings[field] !== target.boundVariables[field]\n })\n}\n\n/**\n * A copy's bound paints are its own cache, as Figma keeps them per layer, so a component's edit\n * to its paint's color or opacity does not reach them. An instance sync writing a copy's paints\n * keeps the color and opacity of each one still bound to the same variable, and gives it the\n * variable's color for the copy once that differs from the one last applied, or when it binds\n * anew. `updates` holds what the sync writes, whose paints this sets in place.\n */\nexport function keepCopyBoundPaints(\n graph: SceneGraph,\n target: SceneNode,\n updates: Partial<SceneNode>,\n resolver?: VariableResolver\n): void {\n const bindings = updates.boundVariables ?? target.boundVariables\n const shared = resolver ?? createVariableResolver(graph)\n const reader = shared.forNode(target.id)\n for (const list of PAINT_LISTS) {\n // A paint the component binds anew keeps its own paint otherwise, but takes the new color.\n if (!updates[list] && reboundPaint(target, bindings, list))\n Object.assign(updates, {\n [list]: list === 'fills' ? copyFills(target.fills) : copyStrokes(target.strokes)\n })\n updates[list]?.forEach((paint, index) => {\n const field = `${list}/${index}/color`\n const variableId = bindings[field]\n if (!variableId) return\n const bound = { field, list, index, variableId }\n const own = target[list].at(index)\n const keeps = own !== undefined && target.boundVariables[field] === variableId\n if (keeps) {\n paint.color = { ...own.color }\n paint.opacity = own.opacity\n }\n const color = reader.color(variableId)\n if (!color) return\n const modes = explicitModes(graph, target, variableId, shared)\n if (!keeps || staleApplied(target, bound, own, color, modes)) applyColor(paint, color)\n recordApplied(target, bound, color, modes)\n })\n }\n}\n"],"mappings":";;;;;;;AA2BA,MAAM,gCAAgB,IAAI,QAA8C;AAExE,MAAM,cAAc,CAAC,SAAS,SAAS;;AAUvC,SAAS,YAAY,MAA+B;CAClD,MAAM,SAAuB,CAAC;CAC9B,KAAK,MAAM,CAAC,OAAO,eAAe,OAAO,QAAQ,KAAK,cAAc,GAAG;EACrE,MAAM,SAAS,mBAAmB,KAAK;EACvC,IAAI,UAAU,KAAK,OAAO,KAAK,CAAC,GAAG,OAAO,KAAK,GAAG,OAAO,KAAK;GAAE;GAAO,GAAG;GAAQ;EAAW,CAAC;CAChG;CACA,OAAO;AACT;;AAGA,SAAgB,eAAe,MAA0B;CACvD,KAAK,MAAM,SAAS,KAAK,gBAAgB,IAAI,mBAAmB,KAAK,GAAG,OAAO;CAC/E,OAAO;AACT;;;;;;AAOA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WAAW,OAAO,KAAK;GACrF,cAAc,QAAQ,OAAO,OAAO,KAAK;EAC3C,CAAC;CACH;AACF"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { Color } from "../primitives/index.js";
|
|
2
|
+
import { VariableModeFallback } from "./resolution.js";
|
|
3
|
+
import { SceneGraph } from "../graph.js";
|
|
4
|
+
import { VariableLiteral, VariableValue } from "../types.js";
|
|
5
|
+
//#region src/variables/resolver.d.ts
|
|
6
|
+
/** One reader per mode context; completed values are shared inside the resolver. */
|
|
7
|
+
interface VariableReader {
|
|
8
|
+
/** Any variable type, following aliases and expressions. Undefined when it cannot resolve. */
|
|
9
|
+
value(variableId: string): VariableLiteral | undefined;
|
|
10
|
+
/** Strict form for formula drafts and diagnostics; throws VariableResolutionError. */
|
|
11
|
+
resolve(variableId: string): VariableLiteral;
|
|
12
|
+
/** Stored value in this context's mode, with no default fallback; aliases are followed. */
|
|
13
|
+
stored(variableId: string): VariableValue | undefined;
|
|
14
|
+
color(variableId: string): Color | undefined;
|
|
15
|
+
number(variableId: string): number | undefined;
|
|
16
|
+
string(variableId: string): string | undefined;
|
|
17
|
+
boolean(variableId: string): boolean | undefined;
|
|
18
|
+
}
|
|
19
|
+
interface VariableResolver {
|
|
20
|
+
forNode(nodeId: string, fallback?: VariableModeFallback): VariableReader;
|
|
21
|
+
active(): VariableReader;
|
|
22
|
+
/**
|
|
23
|
+
* The collection's `modeId`, with every other collection in its active mode. A mode id from
|
|
24
|
+
* another collection is not an explicit mode here, so the collection keeps its active one.
|
|
25
|
+
*/
|
|
26
|
+
forMode(collectionId: string, modeId: string): VariableReader;
|
|
27
|
+
forModes(modeFor: (collectionId: string) => string): VariableReader;
|
|
28
|
+
activeMode(collectionId: string): string;
|
|
29
|
+
modeFor(nodeId: string, collectionId: string, fallback?: VariableModeFallback): string;
|
|
30
|
+
explicitModeFor(nodeId: string, collectionId: string): string | null;
|
|
31
|
+
modesFor(nodeId: string): Record<string, string>;
|
|
32
|
+
dependencies(variableIds: Iterable<string>): Set<string>;
|
|
33
|
+
}
|
|
34
|
+
interface VariableResolverOptions {
|
|
35
|
+
/** Draft values for formula validation; stored reads still use the graph. */
|
|
36
|
+
overrides?: ReadonlyMap<string, VariableValue>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* One value resolver for canvas, editor, exports and tools. Create one per operation: the
|
|
40
|
+
* memo is only valid for the graph state it was built against.
|
|
41
|
+
*/
|
|
42
|
+
declare function createVariableResolver(graph: SceneGraph, options?: VariableResolverOptions): VariableResolver;
|
|
43
|
+
//#endregion
|
|
44
|
+
export { VariableReader, VariableResolver, VariableResolverOptions, createVariableResolver };
|
|
45
|
+
//# sourceMappingURL=resolver.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolver.d.ts","names":[],"sources":["../../src/variables/resolver.ts"],"mappings":";;;;;;UAciB;;EAEf,MAAM,qBAAqB;;EAE3B,QAAQ,qBAAqB;;EAE7B,OAAO,qBAAqB;EAE5B,MAAM,qBAAqB;EAC3B,OAAO;EACP,OAAO;EACP,QAAQ;;UAGO;EACf,QAAQ,gBAAgB,WAAW,uBAAuB;EAC1D,UAAU;;;;;EAKV,QAAQ,sBAAsB,iBAAiB;EAC/C,SAAS,UAAU,kCAAkC;EAErD,WAAW;EACX,QAAQ,gBAAgB,sBAAsB,WAAW;EACzD,gBAAgB,gBAAgB;EAChC,SAAS,iBAAiB;EAC1B,aAAa,aAAa,mBAAmB;;UAG9B;;EAEf,YAAY,oBAAoB;;;;;;iBAgFlB,uBACd,OAAO,YACP,UAAS,0BACR"}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { collectionsResolving, getActiveModeId, getNodeExplicitVariableModeId, getNodeVariableModeId, resolveVariableInModes, resolvedVariableModes } from "./resolution.js";
|
|
2
|
+
//#region src/variables/resolver.ts
|
|
3
|
+
function isColor(value) {
|
|
4
|
+
return typeof value === "object" && "r" in value;
|
|
5
|
+
}
|
|
6
|
+
/** Whether `modeId` names one of the collection's own modes. */
|
|
7
|
+
function collectionHasMode(graph, collectionId, modeId) {
|
|
8
|
+
return graph.variableCollections.get(collectionId)?.modes.some((mode) => mode.modeId === modeId) ?? false;
|
|
9
|
+
}
|
|
10
|
+
function reader(graph, modeFor, overrides) {
|
|
11
|
+
const memo = /* @__PURE__ */ new Map();
|
|
12
|
+
const storedValues = /* @__PURE__ */ new Map();
|
|
13
|
+
const strict = (variableId) => resolveVariableInModes(graph, variableId, modeFor, /* @__PURE__ */ new Set(), memo, overrides);
|
|
14
|
+
const value = (variableId) => {
|
|
15
|
+
try {
|
|
16
|
+
return strict(variableId);
|
|
17
|
+
} catch {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
const stored = (variableId) => {
|
|
22
|
+
if (storedValues.has(variableId)) return storedValues.get(variableId);
|
|
23
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
24
|
+
let id = variableId;
|
|
25
|
+
for (;;) {
|
|
26
|
+
if (visiting.has(id)) return void 0;
|
|
27
|
+
visiting.add(id);
|
|
28
|
+
const variable = graph.variables.get(id);
|
|
29
|
+
if (!variable || !graph.variableCollections.has(variable.collectionId)) return void 0;
|
|
30
|
+
const mode = modeFor(variable.collectionId);
|
|
31
|
+
const valueInMode = variable.valuesByMode[mode];
|
|
32
|
+
if (!Object.hasOwn(variable.valuesByMode, mode)) return void 0;
|
|
33
|
+
if (valueInMode && typeof valueInMode === "object" && "aliasId" in valueInMode) {
|
|
34
|
+
id = valueInMode.aliasId;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
storedValues.set(variableId, valueInMode);
|
|
38
|
+
return valueInMode;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
return {
|
|
42
|
+
value,
|
|
43
|
+
resolve: strict,
|
|
44
|
+
stored,
|
|
45
|
+
color: (variableId) => {
|
|
46
|
+
const resolved = value(variableId);
|
|
47
|
+
return resolved !== void 0 && isColor(resolved) ? resolved : void 0;
|
|
48
|
+
},
|
|
49
|
+
number: (variableId) => {
|
|
50
|
+
const resolved = value(variableId);
|
|
51
|
+
return typeof resolved === "number" ? resolved : void 0;
|
|
52
|
+
},
|
|
53
|
+
string: (variableId) => {
|
|
54
|
+
const resolved = value(variableId);
|
|
55
|
+
return typeof resolved === "string" ? resolved : void 0;
|
|
56
|
+
},
|
|
57
|
+
boolean: (variableId) => {
|
|
58
|
+
const resolved = value(variableId);
|
|
59
|
+
return typeof resolved === "boolean" ? resolved : void 0;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* One value resolver for canvas, editor, exports and tools. Create one per operation: the
|
|
65
|
+
* memo is only valid for the graph state it was built against.
|
|
66
|
+
*/
|
|
67
|
+
function createVariableResolver(graph, options = {}) {
|
|
68
|
+
const readers = /* @__PURE__ */ new Map();
|
|
69
|
+
const overrides = options.overrides;
|
|
70
|
+
const cached = (key, create) => {
|
|
71
|
+
let found = readers.get(key);
|
|
72
|
+
if (!found) {
|
|
73
|
+
found = create();
|
|
74
|
+
readers.set(key, found);
|
|
75
|
+
}
|
|
76
|
+
return found;
|
|
77
|
+
};
|
|
78
|
+
return {
|
|
79
|
+
forNode(nodeId, fallback = "active") {
|
|
80
|
+
return cached(`node:${fallback}:${nodeId}`, () => reader(graph, (collectionId) => getNodeVariableModeId(graph, nodeId, collectionId, fallback), overrides));
|
|
81
|
+
},
|
|
82
|
+
active() {
|
|
83
|
+
return cached("active", () => reader(graph, (id) => getActiveModeId(graph, id), overrides));
|
|
84
|
+
},
|
|
85
|
+
forMode(collectionId, modeId) {
|
|
86
|
+
const mode = collectionHasMode(graph, collectionId, modeId) ? modeId : getActiveModeId(graph, collectionId);
|
|
87
|
+
return cached(JSON.stringify([
|
|
88
|
+
"mode",
|
|
89
|
+
collectionId,
|
|
90
|
+
mode
|
|
91
|
+
]), () => reader(graph, (id) => id === collectionId ? mode : getActiveModeId(graph, id), overrides));
|
|
92
|
+
},
|
|
93
|
+
forModes(modeFor) {
|
|
94
|
+
return reader(graph, modeFor, overrides);
|
|
95
|
+
},
|
|
96
|
+
activeMode: (collectionId) => getActiveModeId(graph, collectionId),
|
|
97
|
+
modeFor: (nodeId, collectionId, fallback = "active") => getNodeVariableModeId(graph, nodeId, collectionId, fallback),
|
|
98
|
+
explicitModeFor: (nodeId, collectionId) => getNodeExplicitVariableModeId(graph, nodeId, collectionId),
|
|
99
|
+
modesFor: (nodeId) => resolvedVariableModes(graph, nodeId),
|
|
100
|
+
dependencies: (variableIds) => collectionsResolving(graph, variableIds)
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
//#endregion
|
|
104
|
+
export { createVariableResolver };
|
|
105
|
+
|
|
106
|
+
//# sourceMappingURL=resolver.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolver.js","names":[],"sources":["../../src/variables/resolver.ts"],"sourcesContent":["import type { SceneGraph } from '../graph'\nimport type { Color } from '../primitives'\nimport type { VariableLiteral, VariableValue } from '../types'\nimport {\n collectionsResolving,\n getActiveModeId,\n getNodeExplicitVariableModeId,\n getNodeVariableModeId,\n resolveVariableInModes,\n resolvedVariableModes,\n type VariableModeFallback\n} from './resolution'\n\n/** One reader per mode context; completed values are shared inside the resolver. */\nexport interface VariableReader {\n /** Any variable type, following aliases and expressions. Undefined when it cannot resolve. */\n value(variableId: string): VariableLiteral | undefined\n /** Strict form for formula drafts and diagnostics; throws VariableResolutionError. */\n resolve(variableId: string): VariableLiteral\n /** Stored value in this context's mode, with no default fallback; aliases are followed. */\n stored(variableId: string): VariableValue | undefined\n\n color(variableId: string): Color | undefined\n number(variableId: string): number | undefined\n string(variableId: string): string | undefined\n boolean(variableId: string): boolean | undefined\n}\n\nexport interface VariableResolver {\n forNode(nodeId: string, fallback?: VariableModeFallback): VariableReader\n active(): VariableReader\n /**\n * The collection's `modeId`, with every other collection in its active mode. A mode id from\n * another collection is not an explicit mode here, so the collection keeps its active one.\n */\n forMode(collectionId: string, modeId: string): VariableReader\n forModes(modeFor: (collectionId: string) => string): VariableReader\n\n activeMode(collectionId: string): string\n modeFor(nodeId: string, collectionId: string, fallback?: VariableModeFallback): string\n explicitModeFor(nodeId: string, collectionId: string): string | null\n modesFor(nodeId: string): Record<string, string>\n dependencies(variableIds: Iterable<string>): Set<string>\n}\n\nexport interface VariableResolverOptions {\n /** Draft values for formula validation; stored reads still use the graph. */\n overrides?: ReadonlyMap<string, VariableValue>\n}\n\nfunction isColor(value: VariableLiteral): value is Color {\n return typeof value === 'object' && 'r' in value\n}\n\n/** Whether `modeId` names one of the collection's own modes. */\nfunction collectionHasMode(graph: SceneGraph, collectionId: string, modeId: string): boolean {\n const collection = graph.variableCollections.get(collectionId)\n return collection?.modes.some((mode) => mode.modeId === modeId) ?? false\n}\n\nfunction reader(\n graph: SceneGraph,\n modeFor: (collectionId: string) => string,\n overrides?: ReadonlyMap<string, VariableValue>\n): VariableReader {\n const memo = new Map<string, VariableLiteral>()\n const storedValues = new Map<string, VariableValue | undefined>()\n\n const strict = (variableId: string) =>\n resolveVariableInModes(graph, variableId, modeFor, new Set(), memo, overrides)\n\n const value = (variableId: string): VariableLiteral | undefined => {\n try {\n return strict(variableId)\n } catch {\n return undefined\n }\n }\n\n const stored = (variableId: string): VariableValue | undefined => {\n if (storedValues.has(variableId)) return storedValues.get(variableId)\n const visiting = new Set<string>()\n let id = variableId\n for (;;) {\n if (visiting.has(id)) return undefined\n visiting.add(id)\n const variable = graph.variables.get(id)\n if (!variable || !graph.variableCollections.has(variable.collectionId)) return undefined\n const mode = modeFor(variable.collectionId)\n const valueInMode = variable.valuesByMode[mode]\n if (!Object.hasOwn(variable.valuesByMode, mode)) return undefined\n if (valueInMode && typeof valueInMode === 'object' && 'aliasId' in valueInMode) {\n id = valueInMode.aliasId\n continue\n }\n storedValues.set(variableId, valueInMode)\n return valueInMode\n }\n }\n\n return {\n value,\n resolve: strict,\n stored,\n color: (variableId) => {\n const resolved = value(variableId)\n return resolved !== undefined && isColor(resolved) ? resolved : undefined\n },\n number: (variableId) => {\n const resolved = value(variableId)\n return typeof resolved === 'number' ? resolved : undefined\n },\n string: (variableId) => {\n const resolved = value(variableId)\n return typeof resolved === 'string' ? resolved : undefined\n },\n boolean: (variableId) => {\n const resolved = value(variableId)\n return typeof resolved === 'boolean' ? resolved : undefined\n }\n }\n}\n\n/**\n * One value resolver for canvas, editor, exports and tools. Create one per operation: the\n * memo is only valid for the graph state it was built against.\n */\nexport function createVariableResolver(\n graph: SceneGraph,\n options: VariableResolverOptions = {}\n): VariableResolver {\n const readers = new Map<string, VariableReader>()\n const overrides = options.overrides\n\n const cached = (key: string, create: () => VariableReader): VariableReader => {\n let found = readers.get(key)\n if (!found) {\n found = create()\n readers.set(key, found)\n }\n return found\n }\n\n return {\n forNode(nodeId, fallback = 'active') {\n return cached(`node:${fallback}:${nodeId}`, () =>\n reader(\n graph,\n (collectionId) => getNodeVariableModeId(graph, nodeId, collectionId, fallback),\n overrides\n )\n )\n },\n active() {\n return cached('active', () => reader(graph, (id) => getActiveModeId(graph, id), overrides))\n },\n forMode(collectionId, modeId) {\n // A mode id is scoped to its collection, so one from another collection selects nothing:\n // it means \"no explicit mode\" for this collection, not that collection's default mode.\n const mode = collectionHasMode(graph, collectionId, modeId)\n ? modeId\n : getActiveModeId(graph, collectionId)\n return cached(JSON.stringify(['mode', collectionId, mode]), () =>\n reader(graph, (id) => (id === collectionId ? mode : getActiveModeId(graph, id)), overrides)\n )\n },\n forModes(modeFor) {\n return reader(graph, modeFor, overrides)\n },\n activeMode: (collectionId) => getActiveModeId(graph, collectionId),\n modeFor: (nodeId, collectionId, fallback = 'active') =>\n getNodeVariableModeId(graph, nodeId, collectionId, fallback),\n explicitModeFor: (nodeId, collectionId) =>\n getNodeExplicitVariableModeId(graph, nodeId, collectionId),\n modesFor: (nodeId) => resolvedVariableModes(graph, nodeId),\n dependencies: (variableIds) => collectionsResolving(graph, variableIds)\n }\n}\n"],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aACzC,sBAAsB,OAAO,QAAQ,cAAc,QAAQ;EAC7D,kBAAkB,QAAQ,iBACxB,8BAA8B,OAAO,QAAQ,YAAY;EAC3D,WAAW,WAAW,sBAAsB,OAAO,MAAM;EACzD,eAAe,gBAAgB,qBAAqB,OAAO,WAAW;CACxE;AACF"}
|
package/package.json
CHANGED
package/src/color/index.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export * from './contrast'
|
|
2
2
|
export * from './management'
|
|
3
|
+
export * from './profile'
|
|
3
4
|
export { normalizeColor } from './normalize'
|
|
4
5
|
export * from './okhcl'
|
|
5
6
|
export { colorSchema } from './schema'
|
|
@@ -8,22 +9,35 @@ import { parse, formatHex, formatHex8, formatRgb, converter, differenceEuclidean
|
|
|
8
9
|
|
|
9
10
|
import { BLACK } from '../constants'
|
|
10
11
|
import type { Color } from '../primitives'
|
|
12
|
+
import type { DocumentColorSpace } from '../types'
|
|
13
|
+
import { fitIntoProfile, SRGB_SYNTAX_MODES } from './management'
|
|
11
14
|
import { normalizeColor } from './normalize'
|
|
15
|
+
import { colorToProfileCSS } from './profile'
|
|
12
16
|
|
|
13
17
|
const toRGB = converter('rgb')
|
|
14
18
|
|
|
15
|
-
/**
|
|
16
|
-
|
|
19
|
+
/**
|
|
20
|
+
* A CSS color as components in `profile`, or null when `input` is not one. Hex and the other sRGB
|
|
21
|
+
* syntaxes give their numbers as they are, as Figma takes typed or imported hex as the document's
|
|
22
|
+
* own numbers in either profile. A color that names its space, such as `color(display-p3 …)` or
|
|
23
|
+
* `oklch()`, is converted into `profile`, and brought inside it by reducing chroma when the profile
|
|
24
|
+
* cannot show it.
|
|
25
|
+
*/
|
|
26
|
+
export function tryParseColor(input: string, profile: DocumentColorSpace = 'srgb'): Color | null {
|
|
17
27
|
const parsed = parse(input)
|
|
18
28
|
if (!parsed) return null
|
|
19
|
-
|
|
29
|
+
// A component written past the float range, such as `1e999`, is no color.
|
|
30
|
+
if (Object.values(parsed).some((value) => typeof value === 'number' && !Number.isFinite(value)))
|
|
31
|
+
return null
|
|
32
|
+
const a = parsed.alpha ?? 1
|
|
20
33
|
// culori leaves a `none` channel out, which normalizing reads as zero.
|
|
21
|
-
return normalizeColor({
|
|
34
|
+
if (SRGB_SYNTAX_MODES.has(parsed.mode)) return normalizeColor({ ...toRGB(parsed), a })
|
|
35
|
+
return fitIntoProfile(parsed, profile).color
|
|
22
36
|
}
|
|
23
37
|
|
|
24
|
-
/** A CSS color
|
|
25
|
-
export function parseColor(input: string): Color {
|
|
26
|
-
return tryParseColor(input) ?? { ...BLACK }
|
|
38
|
+
/** A CSS color as components in `profile`, or black when `input` is not one. */
|
|
39
|
+
export function parseColor(input: string, profile: DocumentColorSpace = 'srgb'): Color {
|
|
40
|
+
return tryParseColor(input, profile) ?? { ...BLACK }
|
|
27
41
|
}
|
|
28
42
|
|
|
29
43
|
export function colorToHex(color: Color): string {
|
|
@@ -60,12 +74,32 @@ export function colorToCSSCompact(color: Color): string {
|
|
|
60
74
|
return `rgba(${r},${g},${b},${a})`
|
|
61
75
|
}
|
|
62
76
|
|
|
77
|
+
/**
|
|
78
|
+
* A stored color as CSS in its document's profile: opaque ones as hex and translucent ones as
|
|
79
|
+
* `rgba()`, which Tailwind matches to its palette, or `color(display-p3 …)` in Display P3, where
|
|
80
|
+
* hex has no room for a component past 1. Colors already in the profile are written as stored.
|
|
81
|
+
*/
|
|
82
|
+
export function colorToDocumentCSS(color: Color, profile: DocumentColorSpace = 'srgb'): string {
|
|
83
|
+
if (profile === 'srgb') return color.a >= 1 ? colorToHex(color) : colorToCSS(color)
|
|
84
|
+
return colorToProfileCSS(color, profile, 'display-p3')
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* A stored color as CSS for a preview of it, such as a swatch or a slider thumb: exactly
|
|
89
|
+
* `colorToCSS` in an sRGB document, so nothing a document already showed changes, and in its own
|
|
90
|
+
* profile otherwise, where `rgb()` cannot show a component past 1.
|
|
91
|
+
*/
|
|
92
|
+
export function colorToPreviewCSS(color: Color, profile: DocumentColorSpace = 'srgb'): string {
|
|
93
|
+
return profile === 'srgb' ? colorToCSS(color) : colorToDocumentCSS(color, profile)
|
|
94
|
+
}
|
|
95
|
+
|
|
63
96
|
export function rgba255ToColor(r: number, g: number, b: number, a = 1): Color {
|
|
64
97
|
return { r: r / 255, g: g / 255, b: b / 255, a }
|
|
65
98
|
}
|
|
66
99
|
|
|
67
|
-
|
|
68
|
-
|
|
100
|
+
/** A solid paint of `color`, a CSS color read into `profile` or components already in it. */
|
|
101
|
+
export function colorToFill(color: string | Color, profile: DocumentColorSpace = 'srgb') {
|
|
102
|
+
const rgba = typeof color === 'string' ? parseColor(color, profile) : color
|
|
69
103
|
return {
|
|
70
104
|
type: 'SOLID' as const,
|
|
71
105
|
color: { r: rgba.r, g: rgba.g, b: rgba.b, a: rgba.a },
|
package/src/color/management.ts
CHANGED
|
@@ -1,4 +1,13 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
clampGamut,
|
|
3
|
+
converter,
|
|
4
|
+
formatCss,
|
|
5
|
+
formatRgb,
|
|
6
|
+
inGamut,
|
|
7
|
+
parse,
|
|
8
|
+
toGamut,
|
|
9
|
+
type Color as CuloriColor
|
|
10
|
+
} from 'culori'
|
|
2
11
|
|
|
3
12
|
import type { Color } from '../primitives'
|
|
4
13
|
import type { DocumentColorSpace, Fill, SceneNode, Stroke } from '../types'
|
|
@@ -150,6 +159,50 @@ export function resolveOkHCLForPreview(
|
|
|
150
159
|
}
|
|
151
160
|
}
|
|
152
161
|
|
|
162
|
+
/**
|
|
163
|
+
* `color`, any culori color, as components in `profile`, past 0 and 1 if need be.
|
|
164
|
+
*/
|
|
165
|
+
function exactlyInProfile(color: CuloriColor, profile: DocumentColorSpace): Color {
|
|
166
|
+
const converted = profile === 'display-p3' ? toP3(color) : toRGB(color)
|
|
167
|
+
return { r: converted.r, g: converted.g, b: converted.b, a: converted.alpha ?? 1 }
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function isInsideProfile(color: Color, profile: DocumentColorSpace): boolean {
|
|
171
|
+
if (profile === 'display-p3')
|
|
172
|
+
return isDisplayableP3({ mode: 'p3', r: color.r, g: color.g, b: color.b, alpha: color.a })
|
|
173
|
+
return isDisplayableRGB({ mode: 'rgb', r: color.r, g: color.g, b: color.b, alpha: color.a })
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* `color`, any culori color, as components in `profile`, brought inside it the way CSS maps
|
|
178
|
+
* out-of-gamut colors — by reducing chroma in OKLCH so lightness and hue hold — and whether it had
|
|
179
|
+
* to be. A color inside already keeps its components, as mapping it would shift them by float
|
|
180
|
+
* noise. A missing (`none`) component reads as zero.
|
|
181
|
+
*/
|
|
182
|
+
export function fitIntoProfile(
|
|
183
|
+
color: CuloriColor,
|
|
184
|
+
profile: DocumentColorSpace
|
|
185
|
+
): { color: Color; clipped: boolean } {
|
|
186
|
+
const exact = normalizeColor(exactlyInProfile(color, profile))
|
|
187
|
+
const clipped = !isInsideProfile(exact, profile)
|
|
188
|
+
const inside = clipped
|
|
189
|
+
? normalizeColor(
|
|
190
|
+
exactlyInProfile(
|
|
191
|
+
profile === 'display-p3' ? toDisplayableP3(color) : toDisplayableRGB(color),
|
|
192
|
+
profile
|
|
193
|
+
)
|
|
194
|
+
)
|
|
195
|
+
: exact
|
|
196
|
+
const clamp = (channel: number) => Math.min(1, Math.max(0, channel))
|
|
197
|
+
return {
|
|
198
|
+
color: { r: clamp(inside.r), g: clamp(inside.g), b: clamp(inside.b), a: color.alpha ?? 1 },
|
|
199
|
+
clipped
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Syntaxes CSS reads as sRGB numbers: hex, `rgb()`, `hsl()`, `hwb()`, names, `color(srgb …)`. */
|
|
204
|
+
export const SRGB_SYNTAX_MODES = new Set(['rgb', 'hsl', 'hwb'])
|
|
205
|
+
|
|
153
206
|
/**
|
|
154
207
|
* A CSS color in any space, mapped into sRGB the way CSS maps out-of-gamut colors: by reducing
|
|
155
208
|
* chroma in OKLCH, so a Display P3 red becomes the nearest sRGB red, not a clipped one. A missing
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { converter, formatCss, formatRgb, toGamut } from 'culori'
|
|
2
|
+
|
|
3
|
+
import type { Color } from '../primitives'
|
|
4
|
+
import type { ColorProfile } from '../types'
|
|
5
|
+
import { normalizeColor } from './normalize'
|
|
6
|
+
|
|
7
|
+
const toRGB = converter('rgb')
|
|
8
|
+
const toP3 = converter('p3')
|
|
9
|
+
const toLinearSRGB = converter('lrgb')
|
|
10
|
+
const toDisplayableRGB = toGamut('rgb', 'oklch')
|
|
11
|
+
const toDisplayableP3 = toGamut('p3', 'oklch')
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* How far past 0 or 1 a component may land and still count as inside a gamut. Conversions round
|
|
15
|
+
* off: P3 red read through OKLCH comes back with a blue of -1e-15, which is the same color.
|
|
16
|
+
*/
|
|
17
|
+
const GAMUT_TOLERANCE = 1e-6
|
|
18
|
+
|
|
19
|
+
type CuloriColor = { mode: 'rgb' | 'p3'; r: number; g: number; b: number; alpha?: number }
|
|
20
|
+
|
|
21
|
+
function culoriColor(color: Color, profile: ColorProfile): CuloriColor {
|
|
22
|
+
const mode = profile === 'display-p3' ? 'p3' : 'rgb'
|
|
23
|
+
return { mode, r: color.r, g: color.g, b: color.b, alpha: color.a }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function sceneColor(
|
|
27
|
+
color: { r: number; g: number; b: number; alpha?: number },
|
|
28
|
+
alpha: number
|
|
29
|
+
): Color {
|
|
30
|
+
return { r: color.r, g: color.g, b: color.b, a: color.alpha ?? alpha }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Whether `color`'s components fit 0 to 1, give or take round-off. */
|
|
34
|
+
export function fitsGamut(color: Pick<Color, 'r' | 'g' | 'b'>): boolean {
|
|
35
|
+
return [color.r, color.g, color.b].every(
|
|
36
|
+
(channel) => channel >= -GAMUT_TOLERANCE && channel <= 1 + GAMUT_TOLERANCE
|
|
37
|
+
)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function clampToGamut(color: Color): Color {
|
|
41
|
+
const clamp = (channel: number) => Math.min(1, Math.max(0, channel))
|
|
42
|
+
return { r: clamp(color.r), g: clamp(color.g), b: clamp(color.b), a: color.a }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* What to do with a color the target profile cannot show: `extend` keeps its components past 0
|
|
47
|
+
* and 1, for a renderer such as Skia that takes extended sRGB; `map` brings it inside by reducing
|
|
48
|
+
* chroma in OKLCH, as CSS maps out-of-gamut colors, keeping its lightness and hue.
|
|
49
|
+
*/
|
|
50
|
+
export type GamutHandling = 'extend' | 'map'
|
|
51
|
+
|
|
52
|
+
/** `color`, whose components are in `from`, as the components in `to` that show the same color. */
|
|
53
|
+
export function convertColor(
|
|
54
|
+
color: Color,
|
|
55
|
+
from: ColorProfile,
|
|
56
|
+
to: ColorProfile,
|
|
57
|
+
gamut: GamutHandling = 'extend'
|
|
58
|
+
): Color {
|
|
59
|
+
if (from === to) return color
|
|
60
|
+
const source = culoriColor(color, from)
|
|
61
|
+
const converted = sceneColor(to === 'display-p3' ? toP3(source) : toRGB(source), color.a)
|
|
62
|
+
if (gamut === 'extend') return converted
|
|
63
|
+
if (fitsGamut(converted)) return clampToGamut(converted)
|
|
64
|
+
const mapped =
|
|
65
|
+
to === 'display-p3' ? toP3(toDisplayableP3(source)) : toRGB(toDisplayableRGB(source))
|
|
66
|
+
return normalizeColor(sceneColor(mapped, color.a))
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* `color`, whose components are in `from`, as CSS showing it in `to`: `color(display-p3 …)` for
|
|
71
|
+
* Display P3, `rgb()` for sRGB, where a color outside sRGB clips per channel as a canvas clips it.
|
|
72
|
+
*/
|
|
73
|
+
export function colorToProfileCSS(color: Color, from: ColorProfile, to: ColorProfile): string {
|
|
74
|
+
const shown = convertColor(color, from, to)
|
|
75
|
+
if (to === 'display-p3') {
|
|
76
|
+
return formatCss({ mode: 'p3', r: shown.r, g: shown.g, b: shown.b, alpha: shown.a })
|
|
77
|
+
}
|
|
78
|
+
return formatRgb({ mode: 'rgb', r: shown.r, g: shown.g, b: shown.b, alpha: shown.a })
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The 3×3 matrix, row by row, taking linear components in `profile` to linear sRGB ones: its
|
|
83
|
+
* columns are the profile's primaries in linear sRGB.
|
|
84
|
+
*/
|
|
85
|
+
export function linearSRGBMatrix(profile: ColorProfile): number[] {
|
|
86
|
+
const mode = profile === 'display-p3' ? 'p3' : 'rgb'
|
|
87
|
+
const columns = [
|
|
88
|
+
{ r: 1, g: 0, b: 0 },
|
|
89
|
+
{ r: 0, g: 1, b: 0 },
|
|
90
|
+
{ r: 0, g: 0, b: 1 }
|
|
91
|
+
].map((primary) => toLinearSRGB({ mode, ...primary }))
|
|
92
|
+
return (['r', 'g', 'b'] as const).flatMap((row) => columns.map((column) => column[row]))
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Display P3's matrix, made once: renderers convert every paint they draw through it. */
|
|
96
|
+
const P3_TO_LINEAR_SRGB = linearSRGBMatrix('display-p3')
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* `color`, whose components are in `profile`, as the sRGB components of the same color: past 0 and
|
|
100
|
+
* 1 where it lies outside sRGB. Skia takes colors this way and converts them into the space of
|
|
101
|
+
* whatever it draws on, so a wide-gamut color reaches it whole.
|
|
102
|
+
*/
|
|
103
|
+
export function toExtendedSRGB(color: Color, profile: ColorProfile): Color {
|
|
104
|
+
if (profile === 'srgb') return color
|
|
105
|
+
// Renderers call this for every paint they draw, so it skips culori's color objects: Display P3
|
|
106
|
+
// shares sRGB's transfer curve, leaving one matrix between the linear components.
|
|
107
|
+
// Indexed reads of a plain array: destructuring costs more than the conversion.
|
|
108
|
+
const m = P3_TO_LINEAR_SRGB
|
|
109
|
+
const r = decodeSRGB(color.r)
|
|
110
|
+
const g = decodeSRGB(color.g)
|
|
111
|
+
const b = decodeSRGB(color.b)
|
|
112
|
+
return {
|
|
113
|
+
r: encodeSRGB(m[0] * r + m[1] * g + m[2] * b),
|
|
114
|
+
g: encodeSRGB(m[3] * r + m[4] * g + m[5] * b),
|
|
115
|
+
b: encodeSRGB(m[6] * r + m[7] * g + m[8] * b),
|
|
116
|
+
a: color.a
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The sRGB transfer curve, mirrored below zero as extended sRGB and culori's `lrgb` take it. */
|
|
121
|
+
function decodeSRGB(channel: number): number {
|
|
122
|
+
const magnitude = Math.abs(channel)
|
|
123
|
+
if (magnitude <= 0.04045) return channel / 12.92
|
|
124
|
+
return (Math.sign(channel) || 1) * ((magnitude + 0.055) / 1.055) ** 2.4
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function encodeSRGB(channel: number): number {
|
|
128
|
+
const magnitude = Math.abs(channel)
|
|
129
|
+
if (magnitude <= 0.0031308) return channel * 12.92
|
|
130
|
+
return (Math.sign(channel) || 1) * (1.055 * magnitude ** (1 / 2.4) - 0.055)
|
|
131
|
+
}
|
package/src/comments/merge.ts
CHANGED
|
@@ -34,6 +34,9 @@ export function mergeCommentThreads(
|
|
|
34
34
|
const newer = thread.updatedAt >= other.updatedAt ? thread : other
|
|
35
35
|
byId.set(thread.id, {
|
|
36
36
|
...newer,
|
|
37
|
+
// A region is only ever set together with its thread, so a copy that lacks one — written by
|
|
38
|
+
// an older build or read before the person drew — does not erase it.
|
|
39
|
+
region: newer.region ?? thread.region ?? other.region,
|
|
37
40
|
deleted: thread.deleted || other.deleted,
|
|
38
41
|
replies: mergeReplies(other.replies, thread.replies)
|
|
39
42
|
})
|
package/src/comments/schema.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as v from 'valibot'
|
|
2
2
|
|
|
3
|
-
import type { CommentThread } from '../types'
|
|
3
|
+
import type { CommentRegion, CommentThread } from '../types'
|
|
4
4
|
|
|
5
5
|
// Lenient on purpose: other tools may write comments, so missing fields get defaults and one
|
|
6
6
|
// malformed thread is skipped instead of hiding every comment.
|
|
@@ -20,6 +20,28 @@ const commentEntry = {
|
|
|
20
20
|
|
|
21
21
|
const commentReplySchema = v.object({ id: v.string(), ...commentEntry })
|
|
22
22
|
|
|
23
|
+
/** Points one thread's region may carry; a file asking for more is not a stroke a person drew. */
|
|
24
|
+
export const MAX_COMMENT_REGION_POINTS = 512
|
|
25
|
+
|
|
26
|
+
const finiteSchema = v.pipe(v.number(), v.finite())
|
|
27
|
+
const commentPointSchema = v.tuple([finiteSchema, finiteSchema])
|
|
28
|
+
|
|
29
|
+
/** The stroke a person circled with: its points and width, and the box they span. */
|
|
30
|
+
const commentRegionSchema: v.GenericSchema<unknown, CommentRegion> = v.object({
|
|
31
|
+
points: v.pipe(
|
|
32
|
+
v.array(commentPointSchema),
|
|
33
|
+
v.minLength(2),
|
|
34
|
+
v.maxLength(MAX_COMMENT_REGION_POINTS)
|
|
35
|
+
),
|
|
36
|
+
width: v.pipe(finiteSchema, v.minValue(0)),
|
|
37
|
+
bounds: v.object({
|
|
38
|
+
minX: finiteSchema,
|
|
39
|
+
minY: finiteSchema,
|
|
40
|
+
maxX: finiteSchema,
|
|
41
|
+
maxY: finiteSchema
|
|
42
|
+
})
|
|
43
|
+
})
|
|
44
|
+
|
|
23
45
|
const commentThreadSchema = v.object({
|
|
24
46
|
id: v.string(),
|
|
25
47
|
pageId: v.string(),
|
|
@@ -45,7 +67,15 @@ export const commentThreadsSchema: v.GenericSchema<unknown, CommentThread[]> = v
|
|
|
45
67
|
const parsed = v.safeParse(commentThreadSchema, item)
|
|
46
68
|
if (!parsed.success) return []
|
|
47
69
|
const thread = parsed.output
|
|
48
|
-
|
|
70
|
+
// A stroke that cannot be read is dropped; the note it was drawn around is still worth keeping.
|
|
71
|
+
const region = v.safeParse(commentRegionSchema, (item as { region?: unknown }).region)
|
|
72
|
+
return [
|
|
73
|
+
{
|
|
74
|
+
...thread,
|
|
75
|
+
updatedAt: thread.updatedAt || thread.createdAt,
|
|
76
|
+
...(region.success ? { region: region.output } : {})
|
|
77
|
+
}
|
|
78
|
+
]
|
|
49
79
|
})
|
|
50
80
|
)
|
|
51
81
|
)
|