@open-pencil/scene-graph 0.17.0-beta.1 → 0.17.0-beta.2

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.
Files changed (236) hide show
  1. package/dist/arrow-caps.d.ts.map +1 -1
  2. package/dist/arrow-caps.js +2 -5
  3. package/dist/arrow-caps.js.map +1 -1
  4. package/dist/behaviours/index.d.ts +2 -2
  5. package/dist/behaviours/index.js +2 -2
  6. package/dist/behaviours/kinds.d.ts +11 -5
  7. package/dist/behaviours/kinds.d.ts.map +1 -1
  8. package/dist/behaviours/kinds.js +76 -75
  9. package/dist/behaviours/kinds.js.map +1 -1
  10. package/dist/behaviours/layers.d.ts.map +1 -1
  11. package/dist/behaviours/layers.js +3 -2
  12. package/dist/behaviours/layers.js.map +1 -1
  13. package/dist/behaviours/model.d.ts +7 -4
  14. package/dist/behaviours/model.d.ts.map +1 -1
  15. package/dist/behaviours/model.js +16 -9
  16. package/dist/behaviours/model.js.map +1 -1
  17. package/dist/behaviours/schema.d.ts +118 -4
  18. package/dist/behaviours/schema.d.ts.map +1 -1
  19. package/dist/behaviours/schema.js +18 -3
  20. package/dist/behaviours/schema.js.map +1 -1
  21. package/dist/behaviours/spec.d.ts.map +1 -1
  22. package/dist/behaviours/spec.js +3 -2
  23. package/dist/behaviours/spec.js.map +1 -1
  24. package/dist/bindings.js +9 -1
  25. package/dist/bindings.js.map +1 -1
  26. package/dist/checkpoint.d.ts +31 -2
  27. package/dist/checkpoint.d.ts.map +1 -1
  28. package/dist/checkpoint.js +176 -5
  29. package/dist/checkpoint.js.map +1 -1
  30. package/dist/components/index.d.ts +3 -3
  31. package/dist/components/index.js +3 -3
  32. package/dist/components/properties.d.ts +13 -1
  33. package/dist/components/properties.d.ts.map +1 -1
  34. package/dist/components/properties.js +58 -3
  35. package/dist/components/properties.js.map +1 -1
  36. package/dist/components/variants.d.ts +16 -10
  37. package/dist/components/variants.d.ts.map +1 -1
  38. package/dist/components/variants.js +39 -13
  39. package/dist/components/variants.js.map +1 -1
  40. package/dist/connectors/hit.d.ts.map +1 -1
  41. package/dist/connectors/hit.js +1 -7
  42. package/dist/connectors/hit.js.map +1 -1
  43. package/dist/connectors/pieces.d.ts.map +1 -1
  44. package/dist/connectors/pieces.js +2 -5
  45. package/dist/connectors/pieces.js.map +1 -1
  46. package/dist/copy.d.ts.map +1 -1
  47. package/dist/copy.js +9 -15
  48. package/dist/copy.js.map +1 -1
  49. package/dist/css/blend.d.ts +11 -0
  50. package/dist/css/blend.d.ts.map +1 -0
  51. package/dist/css/blend.js +30 -0
  52. package/dist/css/blend.js.map +1 -0
  53. package/dist/css/index.d.ts +2 -1
  54. package/dist/css/index.js +2 -1
  55. package/dist/cubic.d.ts +7 -0
  56. package/dist/cubic.d.ts.map +1 -0
  57. package/dist/cubic.js +17 -0
  58. package/dist/cubic.js.map +1 -0
  59. package/dist/export-format.d.ts +14 -1
  60. package/dist/export-format.d.ts.map +1 -1
  61. package/dist/export-format.js +26 -1
  62. package/dist/export-format.js.map +1 -1
  63. package/dist/fields/text.d.ts +2 -2
  64. package/dist/fields/text.d.ts.map +1 -1
  65. package/dist/fields/text.js +2 -1
  66. package/dist/fields/text.js.map +1 -1
  67. package/dist/figjam/index.d.ts +2 -2
  68. package/dist/figjam/index.js +2 -2
  69. package/dist/figjam/palette.d.ts +13 -2
  70. package/dist/figjam/palette.d.ts.map +1 -1
  71. package/dist/figjam/palette.js +30 -2
  72. package/dist/figjam/palette.js.map +1 -1
  73. package/dist/generated/index.d.ts +2 -2
  74. package/dist/generated/index.js +2 -2
  75. package/dist/generated/shape-with-text.d.ts +7 -2
  76. package/dist/generated/shape-with-text.d.ts.map +1 -1
  77. package/dist/generated/shape-with-text.js +20 -3
  78. package/dist/generated/shape-with-text.js.map +1 -1
  79. package/dist/geometry.d.ts +30 -46
  80. package/dist/geometry.d.ts.map +1 -1
  81. package/dist/geometry.js +63 -131
  82. package/dist/geometry.js.map +1 -1
  83. package/dist/graph.d.ts +1 -0
  84. package/dist/graph.d.ts.map +1 -1
  85. package/dist/graph.js +15 -3
  86. package/dist/graph.js.map +1 -1
  87. package/dist/guides.d.ts +3 -1
  88. package/dist/guides.d.ts.map +1 -1
  89. package/dist/guides.js +5 -1
  90. package/dist/guides.js.map +1 -1
  91. package/dist/hit-test.d.ts.map +1 -1
  92. package/dist/hit-test.js +42 -29
  93. package/dist/hit-test.js.map +1 -1
  94. package/dist/index.d.ts +2 -2
  95. package/dist/instances/fields.d.ts +2 -2
  96. package/dist/instances/fields.d.ts.map +1 -1
  97. package/dist/instances/fields.js +8 -0
  98. package/dist/instances/fields.js.map +1 -1
  99. package/dist/instances/index.d.ts +1 -3
  100. package/dist/instances/index.d.ts.map +1 -1
  101. package/dist/instances/index.js +36 -30
  102. package/dist/instances/index.js.map +1 -1
  103. package/dist/instances/kept-overrides.js +204 -0
  104. package/dist/instances/kept-overrides.js.map +1 -0
  105. package/dist/instances/main-component.d.ts +3 -1
  106. package/dist/instances/main-component.d.ts.map +1 -1
  107. package/dist/instances/main-component.js +10 -2
  108. package/dist/instances/main-component.js.map +1 -1
  109. package/dist/instances/overrides.d.ts +4 -1
  110. package/dist/instances/overrides.d.ts.map +1 -1
  111. package/dist/instances/overrides.js +18 -2
  112. package/dist/instances/overrides.js.map +1 -1
  113. package/dist/instances/swap.js +288 -0
  114. package/dist/instances/swap.js.map +1 -0
  115. package/dist/instances/sync.js +84 -32
  116. package/dist/instances/sync.js.map +1 -1
  117. package/dist/node-defaults.d.ts.map +1 -1
  118. package/dist/node-defaults.js +1 -1
  119. package/dist/node-defaults.js.map +1 -1
  120. package/dist/outline/flatten.d.ts +15 -0
  121. package/dist/outline/flatten.d.ts.map +1 -0
  122. package/dist/outline/flatten.js +189 -0
  123. package/dist/outline/flatten.js.map +1 -0
  124. package/dist/outline/heads.js +34 -0
  125. package/dist/outline/heads.js.map +1 -0
  126. package/dist/outline/hit.d.ts +21 -0
  127. package/dist/outline/hit.d.ts.map +1 -0
  128. package/dist/outline/hit.js +276 -0
  129. package/dist/outline/hit.js.map +1 -0
  130. package/dist/outline/index.d.ts +5 -0
  131. package/dist/outline/index.js +5 -0
  132. package/dist/outline/point.d.ts +16 -0
  133. package/dist/outline/point.d.ts.map +1 -0
  134. package/dist/outline/point.js +42 -0
  135. package/dist/outline/point.js.map +1 -0
  136. package/dist/outline/shapes.d.ts +35 -0
  137. package/dist/outline/shapes.d.ts.map +1 -0
  138. package/dist/outline/shapes.js +181 -0
  139. package/dist/outline/shapes.js.map +1 -0
  140. package/dist/plugin-data/fields.d.ts +2 -1
  141. package/dist/plugin-data/fields.d.ts.map +1 -1
  142. package/dist/plugin-data/fields.js +19 -4
  143. package/dist/plugin-data/fields.js.map +1 -1
  144. package/dist/scaling/tree.js +1 -1
  145. package/dist/shared-styles.d.ts +14 -1
  146. package/dist/shared-styles.d.ts.map +1 -1
  147. package/dist/shared-styles.js +63 -2
  148. package/dist/shared-styles.js.map +1 -1
  149. package/dist/slots/content.d.ts.map +1 -1
  150. package/dist/slots/content.js +2 -0
  151. package/dist/slots/content.js.map +1 -1
  152. package/dist/slots/frames.d.ts +2 -0
  153. package/dist/slots/frames.d.ts.map +1 -1
  154. package/dist/slots/frames.js +7 -2
  155. package/dist/slots/frames.js.map +1 -1
  156. package/dist/text/index.d.ts +2 -2
  157. package/dist/text/index.js +3 -3
  158. package/dist/text/lengths.d.ts +6 -1
  159. package/dist/text/lengths.d.ts.map +1 -1
  160. package/dist/text/lengths.js +10 -1
  161. package/dist/text/lengths.js.map +1 -1
  162. package/dist/text/overflow.d.ts +2 -2
  163. package/dist/text/overflow.js.map +1 -1
  164. package/dist/text/picture.d.ts +1 -2
  165. package/dist/text/picture.d.ts.map +1 -1
  166. package/dist/text/picture.js +1 -4
  167. package/dist/text/picture.js.map +1 -1
  168. package/dist/transfer/index.js +1 -1
  169. package/dist/transfer/nodes.js +9 -5
  170. package/dist/transfer/nodes.js.map +1 -1
  171. package/dist/types.d.ts +27 -1
  172. package/dist/types.d.ts.map +1 -1
  173. package/dist/types.js.map +1 -1
  174. package/dist/variables/bindings.d.ts +28 -5
  175. package/dist/variables/bindings.d.ts.map +1 -1
  176. package/dist/variables/bindings.js +104 -14
  177. package/dist/variables/bindings.js.map +1 -1
  178. package/dist/variables/fields.d.ts +19 -1
  179. package/dist/variables/fields.d.ts.map +1 -1
  180. package/dist/variables/fields.js +36 -1
  181. package/dist/variables/fields.js.map +1 -1
  182. package/dist/variables/index.d.ts +3 -3
  183. package/dist/variables/index.d.ts.map +1 -1
  184. package/dist/variables/index.js +23 -8
  185. package/dist/variables/index.js.map +1 -1
  186. package/package.json +7 -1
  187. package/src/arrow-caps.ts +2 -5
  188. package/src/behaviours/kinds.ts +51 -34
  189. package/src/behaviours/layers.ts +4 -2
  190. package/src/behaviours/model.ts +22 -11
  191. package/src/behaviours/schema.ts +20 -4
  192. package/src/behaviours/spec.ts +8 -2
  193. package/src/bindings.ts +11 -2
  194. package/src/checkpoint.ts +251 -4
  195. package/src/components/properties.ts +92 -2
  196. package/src/components/variants.ts +51 -30
  197. package/src/connectors/hit.ts +1 -12
  198. package/src/connectors/pieces.ts +2 -5
  199. package/src/copy.ts +9 -15
  200. package/src/css/blend.ts +27 -0
  201. package/src/css/index.ts +1 -0
  202. package/src/cubic.ts +14 -0
  203. package/src/export-format.ts +29 -0
  204. package/src/fields/text.ts +3 -1
  205. package/src/figjam/palette.ts +29 -1
  206. package/src/generated/shape-with-text.ts +28 -2
  207. package/src/geometry.ts +78 -198
  208. package/src/graph.ts +27 -3
  209. package/src/guides.ts +5 -0
  210. package/src/hit-test.ts +67 -54
  211. package/src/instances/fields.ts +8 -0
  212. package/src/instances/index.ts +58 -31
  213. package/src/instances/kept-overrides.ts +280 -0
  214. package/src/instances/main-component.ts +12 -0
  215. package/src/instances/overrides.ts +27 -1
  216. package/src/instances/swap.ts +451 -0
  217. package/src/instances/sync.ts +141 -42
  218. package/src/node-defaults.ts +2 -1
  219. package/src/outline/flatten.ts +190 -0
  220. package/src/outline/heads.ts +52 -0
  221. package/src/outline/hit.ts +369 -0
  222. package/src/outline/index.ts +4 -0
  223. package/src/outline/point.ts +59 -0
  224. package/src/outline/shapes.ts +207 -0
  225. package/src/plugin-data/fields.ts +15 -2
  226. package/src/shared-styles.ts +82 -1
  227. package/src/slots/content.ts +2 -0
  228. package/src/slots/frames.ts +9 -7
  229. package/src/text/lengths.ts +10 -0
  230. package/src/text/overflow.ts +2 -2
  231. package/src/text/picture.ts +0 -4
  232. package/src/transfer/nodes.ts +7 -5
  233. package/src/types.ts +28 -0
  234. package/src/variables/bindings.ts +125 -14
  235. package/src/variables/fields.ts +46 -1
  236. package/src/variables/index.ts +35 -2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shapes.js","names":[],"sources":["../../src/outline/shapes.ts"],"sourcesContent":["import { polygonOutline } from '../polygon'\nimport type { Vector } from '../primitives'\nimport type { SceneNode, WindingRule } from '../types'\nimport {\n arcPoints,\n blobContours,\n commandContours,\n loopPoints,\n segmentPoints,\n segmentRuns\n} from './flatten'\n\n/** Contours filled together under one winding rule. */\nexport interface OutlineArea {\n windingRule: WindingRule\n contours: Vector[][]\n}\n\n/**\n * A shape's geometry in its own coordinates, curves flattened: the areas its fills cover and the\n * lines its strokes follow, closed contours ending where they began.\n */\nexport interface ShapeOutline {\n areas: OutlineArea[]\n lines: Vector[][]\n /** Each line's own stroke weight, where sides differ, as a rectangle's independent borders. */\n lineWeights?: number[]\n /**\n * Strokes centre on the lines whatever their alignment, as on a network without regions that is\n * open or has no saved stroke geometry.\n */\n strokeCentered?: boolean\n /** For each line, whether its start and its end are open ends, where a stroke's cap is drawn. */\n lineEnds?: Array<[boolean, boolean]>\n /** The saved outline a stroke fills, for a shape whose stroke has no lines to follow. */\n strokeAreas?: OutlineArea[]\n}\n\nfunction closed(contour: Vector[]): Vector[] {\n const first = contour.at(0)\n const last = contour.at(-1)\n if (!first || !last || (first.x === last.x && first.y === last.y)) return contour\n return [...contour, first]\n}\n\nfunction fromContours(contours: Vector[][], windingRule: WindingRule = 'NONZERO'): ShapeOutline {\n return { areas: [{ windingRule, contours }], lines: contours.map(closed) }\n}\n\nfunction cornerRadii(node: SceneNode): [number, number, number, number] {\n const radii: [number, number, number, number] = node.independentCorners\n ? [node.topLeftRadius, node.topRightRadius, node.bottomRightRadius, node.bottomLeftRadius]\n : [node.cornerRadius, node.cornerRadius, node.cornerRadius, node.cornerRadius]\n const limit = Math.min(node.width, node.height) / 2\n return radii.map((radius) => Math.max(0, Math.min(radius, limit))) as typeof radii\n}\n\nfunction rectangleContour(node: SceneNode, tolerance: number): Vector[] {\n const { width: w, height: h } = node\n const [tl, tr, br, bl] = cornerRadii(node)\n const corner = (cx: number, cy: number, r: number, from: number): Vector[] =>\n r > 0 ? arcPoints(cx, cy, r, r, from, from + Math.PI / 2, tolerance) : [{ x: cx, y: cy }]\n return [\n ...corner(w - tr, tr, tr, -Math.PI / 2),\n ...corner(w - br, h - br, br, 0),\n ...corner(bl, h - bl, bl, Math.PI / 2),\n ...corner(tl, tl, tl, Math.PI)\n ]\n}\n\n/**\n * A rectangle's four sides with the weight each draws its border at: top, right, bottom, left.\n * Each side runs from the middle of one rounded corner to the middle of the next, as its border\n * is drawn round them.\n */\nfunction rectangleSides(\n node: SceneNode,\n tolerance: number\n): Pick<ShapeOutline, 'lines' | 'lineWeights'> {\n const { width: w, height: h } = node\n const [tl, tr, br, bl] = cornerRadii(node)\n const quarter = Math.PI / 4\n const arc = (cx: number, cy: number, r: number, from: number): Vector[] =>\n r > 0 ? arcPoints(cx, cy, r, r, from, from + quarter, tolerance) : [{ x: cx, y: cy }]\n return {\n lines: [\n [...arc(tl, tl, tl, 5 * quarter), ...arc(w - tr, tr, tr, -2 * quarter)],\n [...arc(w - tr, tr, tr, -quarter), ...arc(w - br, h - br, br, 0)],\n [...arc(w - br, h - br, br, quarter), ...arc(bl, h - bl, bl, 2 * quarter)],\n [...arc(bl, h - bl, bl, 3 * quarter), ...arc(tl, tl, tl, 4 * quarter)]\n ],\n lineWeights: [\n node.borderTopWeight,\n node.borderRightWeight,\n node.borderBottomWeight,\n node.borderLeftWeight\n ]\n }\n}\n\nconst FULL_TURN = Math.PI * 2\n\nfunction ellipseContours(node: SceneNode, tolerance: number): Vector[][] {\n const rx = node.width / 2\n const ry = node.height / 2\n const arc = node.arcData\n const start = arc?.startingAngle ?? 0\n const end = arc?.endingAngle ?? FULL_TURN\n const inner = arc?.innerRadius ?? 0\n const whole = Math.abs(end - start) >= FULL_TURN - 1e-6\n const outer = arcPoints(rx, ry, rx, ry, start, whole ? start + FULL_TURN : end, tolerance)\n if (inner <= 0) return [whole ? outer : [{ x: rx, y: ry }, ...outer]]\n const hole = arcPoints(\n rx,\n ry,\n rx * inner,\n ry * inner,\n whole ? start + FULL_TURN : end,\n start,\n tolerance\n )\n // A whole ring is two loops wound opposite ways; a part ring is one outline across its ends.\n return whole ? [outer, hole] : [[...outer, ...hole]]\n}\n\nfunction vectorOutline(node: SceneNode, tolerance: number): ShapeOutline | null {\n const network = node.vectorNetwork\n const geometry = node.fillGeometry.map((path) => ({\n windingRule: path.windingRule,\n contours: path.commandsBlob.length > 0 ? blobContours(path.commandsBlob, tolerance) : []\n }))\n if (!network) {\n if (geometry.length === 0 && node.strokeGeometry.length === 0) return null\n // Without a network the renderer fills the saved stroke geometry, or draws no stroke.\n const strokeAreas = node.strokeGeometry.map((path) => ({\n windingRule: path.windingRule,\n contours: path.commandsBlob.length > 0 ? blobContours(path.commandsBlob, tolerance) : []\n }))\n return { areas: geometry, lines: [], strokeAreas }\n }\n // A vertex on one segment only is an open end.\n const degree = new Map<number, number>()\n for (const segment of network.segments) {\n degree.set(segment.start, (degree.get(segment.start) ?? 0) + 1)\n degree.set(segment.end, (degree.get(segment.end) ?? 0) + 1)\n }\n const lines: Vector[][] = []\n const lineEnds: Array<[boolean, boolean]> = []\n for (const [index, segment] of network.segments.entries()) {\n const points = segmentPoints(network, index, tolerance)\n if (!points) continue\n lines.push(points)\n lineEnds.push([degree.get(segment.start) === 1, degree.get(segment.end) === 1])\n }\n // Without regions the stroke draws centred on each segment, unless a closed network carries\n // saved stroke geometry, which the renderer draws with its alignment.\n const open = lineEnds.some(([start, end]) => start || end)\n const strokeCentered = network.regions.length === 0 && (open || node.strokeGeometry.length === 0)\n if (geometry.length > 0) return { areas: geometry, lines, lineEnds, strokeCentered }\n const areas =\n network.regions.length > 0\n ? network.regions.map((region) => ({\n windingRule: region.windingRule,\n contours: region.loops.map((loop) => loopPoints(network, loop, tolerance))\n }))\n : // Without regions a fill closes each run of segments, as a path fill does.\n [{ windingRule: 'NONZERO' as const, contours: segmentRuns(network, tolerance) }]\n return { areas, lines, lineEnds, strokeCentered }\n}\n\n/**\n * The outline a click is tested against, in the node's own coordinates, with curves within\n * `tolerance` of the shape; null for layers tested by their box, such as text.\n */\nexport function shapeOutline(node: SceneNode, tolerance: number): ShapeOutline | null {\n switch (node.type) {\n case 'RECTANGLE':\n case 'ROUNDED_RECTANGLE': {\n const outline = fromContours([rectangleContour(node, tolerance)])\n return node.independentStrokeWeights\n ? { ...outline, ...rectangleSides(node, tolerance) }\n : outline\n }\n case 'ELLIPSE': {\n if (node.fillGeometry.length > 0) return vectorOutline(node, tolerance)\n return fromContours(ellipseContours(node, tolerance))\n }\n case 'POLYGON':\n case 'STAR':\n return fromContours(commandContours(polygonOutline(node), tolerance))\n case 'LINE':\n return {\n areas: [],\n lines: [\n [\n { x: 0, y: 0 },\n { x: node.width, y: node.height }\n ]\n ],\n lineEnds: [[true, true]]\n }\n case 'VECTOR':\n return vectorOutline(node, tolerance)\n default:\n return null\n }\n}\n"],"mappings":";;;AAsCA,SAAS,OAAO,SAA6B;CAC3C,MAAM,QAAQ,QAAQ,GAAG,CAAC;CAC1B,MAAM,OAAO,QAAQ,GAAG,EAAE;CAC1B,IAAI,CAAC,SAAS,CAAC,QAAS,MAAM,MAAM,KAAK,KAAK,MAAM,MAAM,KAAK,GAAI,OAAO;CAC1E,OAAO,CAAC,GAAG,S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;CACzD,MAAM,iBAAiB,QAAQ,QAAQ,WAAW,MAAM,QAAQ,KAAK,eAAe,WAAW;CAC/F,IAAI,SAAS,SAAS,GAAG,OAAO;EAAE,OAAO;EAAU;EAAO;EAAU;CAAe;CASnF,OAAO;EAAE,OAPP,QAAQ,QAAQ,SAAS,IACrB,QAAQ,QAAQ,KAAK,YAAY;GAC/B,aAAa,OAAO;GACpB,UAAU,OAAO,MAAM,KAAK,SAAS,WAAW,SAAS,MAAM,SAAS,CAAC;EAC3E,EAAE,IAEF,CAAC;GAAE,aAAa;GAAoB,UAAU,YAAY,SAAS,SAAS;EAAE,CAAC;EACrE;EAAO;EAAU;CAAe;AAClD;;;;;AAMA,SAAgB,aAAa,MAAiB,WAAwC;CACpF,QAAQ,KAAK,MAAb;EACE,KAAK;EACL,KAAK,qBAAqB;GACxB,MAAM,UAAU,aAAa,CAAC,iBAAiB,MAAM,SAAS,CAAC,CAAC;GAChE,OAAO,KAAK,2BACR;IAAE,GAAG;IAAS,GAAG,eAAe,MAAM,SAAS;GAAE,IACjD;EACN;EACA,KAAK;GACH,IAAI,KAAK,aAAa,SAAS,GAAG,OAAO,cAAc,MAAM,SAAS;GACtE,OAAO,aAAa,gBAAgB,MAAM,SAAS,CAAC;EAEtD,KAAK;EACL,KAAK,QACH,OAAO,aAAa,gBAAgB,eAAe,IAAI,GAAG,SAAS,CAAC;EACtE,KAAK,QACH,OAAO;GACL,OAAO,CAAC;GACR,OAAO,CACL,CACE;IAAE,GAAG;IAAG,GAAG;GAAE,GACb;IAAE,GAAG,KAAK;IAAO,GAAG,KAAK;GAAO,CAClC,CACF;GACA,UAAU,CAAC,CAAC,MAAM,IAAI,CAAC;EACzB;EACF,KAAK,UACH,OAAO,cAAc,MAAM,SAAS;EACtC,SACE,OAAO;CACX;AACF"}
@@ -74,7 +74,7 @@ declare const OPEN_PENCIL_PLUGIN_DATA: {
74
74
  okhcl: PluginDataField<OkHCLPayload>;
75
75
  /** How a main component or component set behaves as a control in preview. */
76
76
  behaviour: PluginDataField<{
77
- kind: "button" | "textField" | "textarea" | "numberField" | "toggle" | "switch" | "checkbox" | "radio" | "radioGroup" | "toggleGroup" | "slider" | "progress" | "tabs" | "collapsible" | "accordion";
77
+ kind: "button" | "textField" | "textarea" | "numberField" | "toggle" | "switch" | "checkbox" | "radio" | "radioGroup" | "toggleGroup" | "slider" | "progress" | "tabs" | "tab" | "collapsible" | "accordion";
78
78
  booleans: {
79
79
  [x: string]: {
80
80
  propertyId: string;
@@ -104,6 +104,7 @@ declare const OPEN_PENCIL_PLUGIN_DATA: {
104
104
  pressed?: string | undefined;
105
105
  focus?: string | undefined;
106
106
  disabled?: string | undefined;
107
+ invalid?: string | undefined;
107
108
  propertyId: string;
108
109
  } | undefined;
109
110
  }>;
@@ -1 +1 @@
1
- {"version":3,"file":"fields.d.ts","names":[],"sources":["../../src/plugin-data/fields.ts"],"mappings":";;;;;;;UAyGiB;EACf,OAAO;EACP,cAAc;IAAiB;IAAa;;;;;;;;cAuCjC;;iBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA0EG,kBAAkB,kBAAkB,oBAAoB"}
1
+ {"version":3,"file":"fields.d.ts","names":[],"sources":["../../src/plugin-data/fields.ts"],"mappings":";;;;;;;UAsHiB;EACf,OAAO;EACP,cAAc;IAAiB;IAAa;;;;;;;;cAuCjC;;iBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA0EG,kBAAkB,kBAAkB,oBAAoB"}
@@ -26,10 +26,25 @@ const boundVariablesSchema = v.pipe(v.custom((value) => typeof value === "object
26
26
  /** Every entry must be valid, or the whole value is ignored in favour of native settings. */
27
27
  const exportSettingsSchema = v.array(v.pipe(v.object({
28
28
  scale: v.pipe(v.number(), v.finite()),
29
- format: v.custom(isExportFormatId)
30
- }), v.transform(({ scale, format }) => ({
31
- scale: clampExportScale(scale),
32
- format
29
+ format: v.custom(isExportFormatId),
30
+ suffix: v.optional(v.string()),
31
+ size: v.optional(v.object({
32
+ type: v.picklist(["WIDTH", "HEIGHT"]),
33
+ value: v.pipe(v.number(), v.finite())
34
+ })),
35
+ contentsOnly: v.optional(v.boolean()),
36
+ useAbsoluteBounds: v.optional(v.boolean()),
37
+ colorProfile: v.optional(v.picklist([
38
+ "DOCUMENT",
39
+ "SRGB",
40
+ "DISPLAY_P3_V4"
41
+ ])),
42
+ svgOutlineText: v.optional(v.boolean()),
43
+ svgIdAttribute: v.optional(v.boolean()),
44
+ svgSimplifyStroke: v.optional(v.boolean())
45
+ }), v.transform((setting) => ({
46
+ ...setting,
47
+ scale: clampExportScale(setting.scale)
33
48
  }))));
34
49
  const librarySourceSchema = v.pipe(v.object({
35
50
  identity: v.object({
@@ -1 +1 @@
1
- {"version":3,"file":"fields.js","names":[],"sources":["../../src/plugin-data/fields.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { behaviourSchema } from '../behaviours/schema'\nimport type { OkHCLPayload } from '../color/okhcl'\nimport { commentThreadsSchema } from '../comments/schema'\nimport { isExportFormatId, type ExportFormatId } from '../export-format'\nimport { clampExportScale } from '../export-scale'\nimport { FIG_COMPRESSIONS } from '../fig-compression'\nimport { iconSchema, iconTintSchema } from '../icons/schema'\nimport type { Rect } from '../primitives'\nimport { shaderPaintSchema } from '../shaders/schema'\nimport { nodeStatusSchema, statusWorkflowSchema } from '../statuses/schema'\nimport {\n MODE_ATTRIBUTE_PATTERN,\n TOKEN_UNITS,\n type EnabledLibraryBinding,\n type ExportSetting,\n type LayoutDirection,\n type LibraryAssetSource,\n type PluginDataEntry,\n type SourceLibraryPublication,\n type TextDirection,\n type TokenUnit\n} from '../types'\nimport {\n jsonPluginDataField,\n textPluginDataField,\n withoutPluginData,\n type PluginDataKey\n} from './field'\n\nconst DIRECTIONS = ['AUTO', 'LTR', 'RTL'] as const satisfies readonly (\n | TextDirection\n | LayoutDirection\n)[]\n\nconst textPathBoxSchema: v.GenericSchema<unknown, Rect> = v.pipe(\n v.object({ x: v.number(), y: v.number(), width: v.number(), height: v.number() }),\n v.check(\n ({ x, y, width, height }) => Number.isFinite(x + y + width + height) && width > 0 && height > 0\n )\n)\n\n/** String-valued entries of a JSON object; other entries are dropped, not rejected. */\nconst boundVariablesSchema = v.pipe(\n v.custom<Record<string, unknown>>(\n (value) => typeof value === 'object' && value !== null && !Array.isArray(value)\n ),\n v.transform((value) =>\n Object.fromEntries(\n Object.entries(value).filter(\n (entry): entry is [string, string] => typeof entry[1] === 'string'\n )\n )\n )\n)\n\n/** Every entry must be valid, or the whole value is ignored in favour of native settings. */\nconst exportSettingsSchema: v.GenericSchema<unknown, ExportSetting[]> = v.array(\n v.pipe(\n v.object({\n scale: v.pipe(v.number(), v.finite()),\n format: v.custom<ExportFormatId>(isExportFormatId)\n }),\n // Clamp at the file boundary: imported plugin data may carry a scale the UI never produces.\n v.transform(({ scale, format }) => ({ scale: clampExportScale(scale), format }))\n )\n)\n\nconst librarySourceSchema: v.GenericSchema<unknown, LibraryAssetSource> = v.pipe(\n v.object({\n identity: v.object({ libraryId: v.string(), assetKey: v.string(), revisionId: v.string() }),\n sourceNodeId: v.optional(v.unknown()),\n readOnly: v.optional(v.unknown())\n }),\n v.transform(({ identity, sourceNodeId, readOnly }) => ({\n identity,\n sourceNodeId: typeof sourceNodeId === 'string' ? sourceNodeId : null,\n readOnly: readOnly === true\n }))\n)\n\nconst enabledLibrarySchema = v.object({\n libraryId: v.string(),\n revisionId: v.string(),\n enabled: v.optional(v.unknown())\n})\n\n/** Invalid entries are skipped one by one, so one bad binding keeps the others. */\nconst enabledLibrariesSchema: v.GenericSchema<unknown, EnabledLibraryBinding[]> = v.pipe(\n v.array(v.unknown()),\n v.transform((items) =>\n items.flatMap((item) => {\n const parsed = v.safeParse(enabledLibrarySchema, item)\n if (!parsed.success) return []\n const { libraryId, revisionId, enabled } = parsed.output\n return [{ libraryId, revisionId, enabled: enabled === true }]\n })\n )\n)\n\n// Shape only. Whether a string is valid CSS is checked where it is written into a stylesheet.\nconst cssTextSchema = v.pipe(v.string(), v.trim(), v.nonEmpty(), v.maxLength(1000))\n\n/** Token fields Figma has no slot for, with mode ids as the file spells them. */\nexport interface StoredToken {\n unit?: TokenUnit\n expressions?: Record<string, { css: string; resolved?: number }>\n}\n\nconst tokenSchema: v.GenericSchema<unknown, StoredToken> = v.object({\n unit: v.optional(v.picklist(TOKEN_UNITS)),\n expressions: v.optional(\n v.record(\n v.string(),\n v.object({ css: cssTextSchema, resolved: v.optional(v.pipe(v.number(), v.finite())) })\n )\n )\n})\n\nconst okhclSchema: v.GenericSchema<unknown, OkHCLPayload> = v.object({\n version: v.literal(1),\n kind: v.picklist(['fill', 'stroke']),\n index: v.number(),\n color: v.object({\n h: v.number(),\n c: v.number(),\n l: v.number(),\n a: v.fallback(v.optional(v.number()), undefined)\n })\n})\n\nconst sourceLibraryPublicationSchema: v.GenericSchema<unknown, SourceLibraryPublication> = v.object(\n {\n libraryId: v.string(),\n revisionId: v.string(),\n name: v.string(),\n catalogSource: v.optional(v.string())\n }\n)\n\n/**\n * Every plugin-data entry OpenPencil writes under {@link OPEN_PENCIL_PLUGIN_ID}: state Figma's\n * format has no field for. Add a key here, never as a string elsewhere, so reading and writing\n * it share one schema.\n */\nexport const OPEN_PENCIL_PLUGIN_DATA = {\n /** A text node's direction, on TEXT nodes. */\n textDirection: textPluginDataField('textDirection', 'format', DIRECTIONS),\n /** An auto-layout frame's direction. */\n layoutDirection: textPluginDataField('layoutDirection', 'format', DIRECTIONS),\n /** Marks a component set Figma would read as a plain frame. */\n nodeType: textPluginDataField('nodeType', 'format', ['COMPONENT_SET']),\n /** Variable bindings by field path, including those Figma cannot store natively. */\n boundVariables: jsonPluginDataField('boundVariables', 'format', boundVariablesSchema),\n exportSettings: jsonPluginDataField('exportSettings', 'format', exportSettingsSchema),\n /** The node-local rect a TEXT_PATH layout maps onto, which Kiwi has no field for. */\n textPathBox: jsonPluginDataField('textPathBox', 'format', textPathBoxSchema),\n /** The library asset a node was inserted from. */\n librarySource: jsonPluginDataField('librarySource', 'bookkeeping', librarySourceSchema),\n /**\n * The document root's id, on the DOCUMENT node, whose own GUID is always Figma's `0:0`; the\n * root keeps it across a save as every layer keeps its GUID.\n */\n documentId: jsonPluginDataField(\n 'documentId',\n 'bookkeeping',\n v.pipe(v.string(), v.nonEmpty(), v.maxLength(64))\n ),\n /** Libraries enabled for the document, on the DOCUMENT node. */\n enabledLibraries: jsonPluginDataField('enabledLibraries', 'bookkeeping', enabledLibrariesSchema),\n /** The library this document publishes as, on the DOCUMENT node. */\n sourceLibraryPublication: jsonPluginDataField(\n 'sourceLibraryPublication',\n 'bookkeeping',\n sourceLibraryPublicationSchema\n ),\n /** Canvas comment threads, deleted ones included, on the DOCUMENT node. */\n comments: jsonPluginDataField('comments', 'bookkeeping', commentThreadsSchema),\n /** The statuses layers can be in, on the DOCUMENT node. */\n statuses: jsonPluginDataField('statuses', 'bookkeeping', statusWorkflowSchema),\n /** How tightly the document's `.fig` data is compressed, on the DOCUMENT node. */\n figCompression: textPluginDataField('figCompression', 'bookkeeping', FIG_COMPRESSIONS),\n /** A layer's status, any state of the workflow; Figma's `sectionStatusInfo` knows only two. */\n status: jsonPluginDataField('status', 'format', nodeStatusSchema),\n /** Unit and CSS expressions, on each VARIABLE. */\n token: jsonPluginDataField('token', 'format', tokenSchema),\n /** Mode conditions by mode id, on each VARIABLE_SET. */\n modeConditions: jsonPluginDataField(\n 'modeConditions',\n 'format',\n v.record(v.string(), cssTextSchema)\n ),\n /** The attribute that switches manual modes, on each VARIABLE_SET. */\n modeAttribute: jsonPluginDataField(\n 'modeAttribute',\n 'format',\n v.pipe(v.string(), v.trim(), v.maxLength(100), v.regex(MODE_ATTRIBUTE_PATTERN))\n ),\n /** One entry per paint picked in OkHCL, so the picker reopens on the same coordinates. */\n okhcl: jsonPluginDataField('okhcl', 'content', okhclSchema),\n /** How a main component or component set behaves as a control in preview. */\n behaviour: jsonPluginDataField('behaviour', 'content', behaviourSchema),\n /** The icon a frame draws, such as `lucide:home`, on the frame its paths are in. */\n icon: jsonPluginDataField('icon', 'content', iconSchema),\n /** Which of an icon path's paints its icon's color sets, on each path the source drew in it. */\n iconTint: jsonPluginDataField('iconTint', 'content', iconTintSchema),\n /** One entry per paint that draws a shader, matched to its image paint by the frame's hash. */\n shader: jsonPluginDataField('shader', 'content', shaderPaintSchema)\n} satisfies Record<string, PluginDataKey>\n\nconst NOT_CONTENT = Object.values(OPEN_PENCIL_PLUGIN_DATA).filter(\n (field) => field.role !== 'content'\n)\n\n/**\n * A node's plugin data that is part of its content, in a stable order: OpenPencil's content\n * fields and every other plugin's entries, which the node carries wherever it goes. Format\n * copies of node fields and bookkeeping are left out.\n */\nexport function contentPluginData(entries: readonly PluginDataEntry[]): PluginDataEntry[] {\n return withoutPluginData(entries, NOT_CONTENT).sort(\n (a, b) => a.pluginId.localeCompare(b.pluginId) || a.key.localeCompare(b.key)\n )\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,MAAM,aAAa;CAAC;CAAQ;CAAO;AAAK;AAKxC,MAAM,oBAAoD,EAAE,KAC1D,EAAE,OAAO;CAAE,GAAG,EAAE,OAAO;CAAG,GAAG,EAAE,OAAO;CAAG,OAAO,EAAE,OAAO;CAAG,QAAQ,EAAE,OAAO;AAAE,CAAC,GAChF,EAAE,OACC,EAAE,GAAG,GAAG,OAAO,aAAa,OAAO,SAAS,IAAI,IAAI,QAAQ,MAAM,KAAK,QAAQ,KAAK,SAAS,CAChG,CACF;;AAGA,MAAM,uBAAuB,EAAE,KAC7B,EAAE,QACC,UAAU,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,CAChF,GACA,EAAE,WAAW,U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GAAG,EAAE,UAAU,EAAE,CAAC,CAClD;;CAEA,kBAAkB,oBAAoB,oBAAoB,eAAe,sBAAsB;;CAE/F,0BAA0B,oBACxB,4BACA,eACA,8BACF;;CAEA,UAAU,oBAAoB,YAAY,eAAe,oBAAoB;;CAE7E,UAAU,oBAAoB,YAAY,eAAe,oBAAoB;;CAE7E,gBAAgB,oBAAoB,kBAAkB,eAAe,gBAAgB;;CAErF,QAAQ,oBAAoB,UAAU,UAAU,gBAAgB;;CAEhE,OAAO,oBAAoB,SAAS,UAAU,WAAW;;CAEzD,gBAAgB,oBACd,kBACA,UACA,EAAE,OAAO,EAAE,OAAO,GAAG,aAAa,CACpC;;CAEA,eAAe,oBACb,iBACA,UACA,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,KAAK,GAAG,EAAE,UAAU,GAAG,GAAG,EAAE,MAAM,sBAAsB,CAAC,CAChF;;CAEA,OAAO,oBAAoB,SAAS,WAAW,WAAW;;CAE1D,WAAW,oBAAoB,aAAa,WAAW,eAAe;;CAEtE,MAAM,oBAAoB,QAAQ,WAAW,UAAU;;CAEvD,UAAU,oBAAoB,YAAY,WAAW,cAAc;;CAEnE,QAAQ,oBAAoB,UAAU,WAAW,iBAAiB;AACpE;AAEA,MAAM,cAAc,OAAO,OAAO,uBAAuB,CAAC,CAAC,QACxD,UAAU,MAAM,SAAS,SAC5B;;;;;;AAOA,SAAgB,kBAAkB,SAAwD;CACxF,OAAO,kBAAkB,SAAS,WAAW,CAAC,CAAC,MAC5C,GAAG,MAAM,EAAE,SAAS,cAAc,EAAE,QAAQ,KAAK,EAAE,IAAI,cAAc,EAAE,GAAG,CAC7E;AACF"}
1
+ {"version":3,"file":"fields.js","names":[],"sources":["../../src/plugin-data/fields.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { behaviourSchema } from '../behaviours/schema'\nimport type { OkHCLPayload } from '../color/okhcl'\nimport { commentThreadsSchema } from '../comments/schema'\nimport { isExportFormatId, type ExportFormatId } from '../export-format'\nimport { clampExportScale } from '../export-scale'\nimport { FIG_COMPRESSIONS } from '../fig-compression'\nimport { iconSchema, iconTintSchema } from '../icons/schema'\nimport type { Rect } from '../primitives'\nimport { shaderPaintSchema } from '../shaders/schema'\nimport { nodeStatusSchema, statusWorkflowSchema } from '../statuses/schema'\nimport {\n MODE_ATTRIBUTE_PATTERN,\n TOKEN_UNITS,\n type EnabledLibraryBinding,\n type ExportSetting,\n type LayoutDirection,\n type LibraryAssetSource,\n type PluginDataEntry,\n type SourceLibraryPublication,\n type TextDirection,\n type TokenUnit\n} from '../types'\nimport {\n jsonPluginDataField,\n textPluginDataField,\n withoutPluginData,\n type PluginDataKey\n} from './field'\n\nconst DIRECTIONS = ['AUTO', 'LTR', 'RTL'] as const satisfies readonly (\n | TextDirection\n | LayoutDirection\n)[]\n\nconst textPathBoxSchema: v.GenericSchema<unknown, Rect> = v.pipe(\n v.object({ x: v.number(), y: v.number(), width: v.number(), height: v.number() }),\n v.check(\n ({ x, y, width, height }) => Number.isFinite(x + y + width + height) && width > 0 && height > 0\n )\n)\n\n/** String-valued entries of a JSON object; other entries are dropped, not rejected. */\nconst boundVariablesSchema = v.pipe(\n v.custom<Record<string, unknown>>(\n (value) => typeof value === 'object' && value !== null && !Array.isArray(value)\n ),\n v.transform((value) =>\n Object.fromEntries(\n Object.entries(value).filter(\n (entry): entry is [string, string] => typeof entry[1] === 'string'\n )\n )\n )\n)\n\n/** Every entry must be valid, or the whole value is ignored in favour of native settings. */\nconst exportSettingsSchema: v.GenericSchema<unknown, ExportSetting[]> = v.array(\n v.pipe(\n v.object({\n scale: v.pipe(v.number(), v.finite()),\n format: v.custom<ExportFormatId>(isExportFormatId),\n suffix: v.optional(v.string()),\n size: v.optional(\n v.object({\n type: v.picklist(['WIDTH', 'HEIGHT']),\n value: v.pipe(v.number(), v.finite())\n })\n ),\n contentsOnly: v.optional(v.boolean()),\n useAbsoluteBounds: v.optional(v.boolean()),\n colorProfile: v.optional(v.picklist(['DOCUMENT', 'SRGB', 'DISPLAY_P3_V4'])),\n svgOutlineText: v.optional(v.boolean()),\n svgIdAttribute: v.optional(v.boolean()),\n svgSimplifyStroke: v.optional(v.boolean())\n }),\n // Clamp at the file boundary: imported plugin data may carry a scale the UI never produces.\n v.transform((setting) => ({ ...setting, scale: clampExportScale(setting.scale) }))\n )\n)\n\nconst librarySourceSchema: v.GenericSchema<unknown, LibraryAssetSource> = v.pipe(\n v.object({\n identity: v.object({ libraryId: v.string(), assetKey: v.string(), revisionId: v.string() }),\n sourceNodeId: v.optional(v.unknown()),\n readOnly: v.optional(v.unknown())\n }),\n v.transform(({ identity, sourceNodeId, readOnly }) => ({\n identity,\n sourceNodeId: typeof sourceNodeId === 'string' ? sourceNodeId : null,\n readOnly: readOnly === true\n }))\n)\n\nconst enabledLibrarySchema = v.object({\n libraryId: v.string(),\n revisionId: v.string(),\n enabled: v.optional(v.unknown())\n})\n\n/** Invalid entries are skipped one by one, so one bad binding keeps the others. */\nconst enabledLibrariesSchema: v.GenericSchema<unknown, EnabledLibraryBinding[]> = v.pipe(\n v.array(v.unknown()),\n v.transform((items) =>\n items.flatMap((item) => {\n const parsed = v.safeParse(enabledLibrarySchema, item)\n if (!parsed.success) return []\n const { libraryId, revisionId, enabled } = parsed.output\n return [{ libraryId, revisionId, enabled: enabled === true }]\n })\n )\n)\n\n// Shape only. Whether a string is valid CSS is checked where it is written into a stylesheet.\nconst cssTextSchema = v.pipe(v.string(), v.trim(), v.nonEmpty(), v.maxLength(1000))\n\n/** Token fields Figma has no slot for, with mode ids as the file spells them. */\nexport interface StoredToken {\n unit?: TokenUnit\n expressions?: Record<string, { css: string; resolved?: number }>\n}\n\nconst tokenSchema: v.GenericSchema<unknown, StoredToken> = v.object({\n unit: v.optional(v.picklist(TOKEN_UNITS)),\n expressions: v.optional(\n v.record(\n v.string(),\n v.object({ css: cssTextSchema, resolved: v.optional(v.pipe(v.number(), v.finite())) })\n )\n )\n})\n\nconst okhclSchema: v.GenericSchema<unknown, OkHCLPayload> = v.object({\n version: v.literal(1),\n kind: v.picklist(['fill', 'stroke']),\n index: v.number(),\n color: v.object({\n h: v.number(),\n c: v.number(),\n l: v.number(),\n a: v.fallback(v.optional(v.number()), undefined)\n })\n})\n\nconst sourceLibraryPublicationSchema: v.GenericSchema<unknown, SourceLibraryPublication> = v.object(\n {\n libraryId: v.string(),\n revisionId: v.string(),\n name: v.string(),\n catalogSource: v.optional(v.string())\n }\n)\n\n/**\n * Every plugin-data entry OpenPencil writes under {@link OPEN_PENCIL_PLUGIN_ID}: state Figma's\n * format has no field for. Add a key here, never as a string elsewhere, so reading and writing\n * it share one schema.\n */\nexport const OPEN_PENCIL_PLUGIN_DATA = {\n /** A text node's direction, on TEXT nodes. */\n textDirection: textPluginDataField('textDirection', 'format', DIRECTIONS),\n /** An auto-layout frame's direction. */\n layoutDirection: textPluginDataField('layoutDirection', 'format', DIRECTIONS),\n /** Marks a component set Figma would read as a plain frame. */\n nodeType: textPluginDataField('nodeType', 'format', ['COMPONENT_SET']),\n /** Variable bindings by field path, including those Figma cannot store natively. */\n boundVariables: jsonPluginDataField('boundVariables', 'format', boundVariablesSchema),\n exportSettings: jsonPluginDataField('exportSettings', 'format', exportSettingsSchema),\n /** The node-local rect a TEXT_PATH layout maps onto, which Kiwi has no field for. */\n textPathBox: jsonPluginDataField('textPathBox', 'format', textPathBoxSchema),\n /** The library asset a node was inserted from. */\n librarySource: jsonPluginDataField('librarySource', 'bookkeeping', librarySourceSchema),\n /**\n * The document root's id, on the DOCUMENT node, whose own GUID is always Figma's `0:0`; the\n * root keeps it across a save as every layer keeps its GUID.\n */\n documentId: jsonPluginDataField(\n 'documentId',\n 'bookkeeping',\n v.pipe(v.string(), v.nonEmpty(), v.maxLength(64))\n ),\n /** Libraries enabled for the document, on the DOCUMENT node. */\n enabledLibraries: jsonPluginDataField('enabledLibraries', 'bookkeeping', enabledLibrariesSchema),\n /** The library this document publishes as, on the DOCUMENT node. */\n sourceLibraryPublication: jsonPluginDataField(\n 'sourceLibraryPublication',\n 'bookkeeping',\n sourceLibraryPublicationSchema\n ),\n /** Canvas comment threads, deleted ones included, on the DOCUMENT node. */\n comments: jsonPluginDataField('comments', 'bookkeeping', commentThreadsSchema),\n /** The statuses layers can be in, on the DOCUMENT node. */\n statuses: jsonPluginDataField('statuses', 'bookkeeping', statusWorkflowSchema),\n /** How tightly the document's `.fig` data is compressed, on the DOCUMENT node. */\n figCompression: textPluginDataField('figCompression', 'bookkeeping', FIG_COMPRESSIONS),\n /** A layer's status, any state of the workflow; Figma's `sectionStatusInfo` knows only two. */\n status: jsonPluginDataField('status', 'format', nodeStatusSchema),\n /** Unit and CSS expressions, on each VARIABLE. */\n token: jsonPluginDataField('token', 'format', tokenSchema),\n /** Mode conditions by mode id, on each VARIABLE_SET. */\n modeConditions: jsonPluginDataField(\n 'modeConditions',\n 'format',\n v.record(v.string(), cssTextSchema)\n ),\n /** The attribute that switches manual modes, on each VARIABLE_SET. */\n modeAttribute: jsonPluginDataField(\n 'modeAttribute',\n 'format',\n v.pipe(v.string(), v.trim(), v.maxLength(100), v.regex(MODE_ATTRIBUTE_PATTERN))\n ),\n /** One entry per paint picked in OkHCL, so the picker reopens on the same coordinates. */\n okhcl: jsonPluginDataField('okhcl', 'content', okhclSchema),\n /** How a main component or component set behaves as a control in preview. */\n behaviour: jsonPluginDataField('behaviour', 'content', behaviourSchema),\n /** The icon a frame draws, such as `lucide:home`, on the frame its paths are in. */\n icon: jsonPluginDataField('icon', 'content', iconSchema),\n /** Which of an icon path's paints its icon's color sets, on each path the source drew in it. */\n iconTint: jsonPluginDataField('iconTint', 'content', iconTintSchema),\n /** One entry per paint that draws a shader, matched to its image paint by the frame's hash. */\n shader: jsonPluginDataField('shader', 'content', shaderPaintSchema)\n} satisfies Record<string, PluginDataKey>\n\nconst NOT_CONTENT = Object.values(OPEN_PENCIL_PLUGIN_DATA).filter(\n (field) => field.role !== 'content'\n)\n\n/**\n * A node's plugin data that is part of its content, in a stable order: OpenPencil's content\n * fields and every other plugin's entries, which the node carries wherever it goes. Format\n * copies of node fields and bookkeeping are left out.\n */\nexport function contentPluginData(entries: readonly PluginDataEntry[]): PluginDataEntry[] {\n return withoutPluginData(entries, NOT_CONTENT).sort(\n (a, b) => a.pluginId.localeCompare(b.pluginId) || a.key.localeCompare(b.key)\n )\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,MAAM,aAAa;CAAC;CAAQ;CAAO;AAAK;AAKxC,MAAM,oBAAoD,EAAE,KAC1D,EAAE,OAAO;CAAE,GAAG,EAAE,OAAO;CAAG,GAAG,EAAE,OAAO;CAAG,OAAO,EAAE,OAAO;CAAG,QAAQ,EAAE,OAAO;AAAE,CAAC,GAChF,EAAE,OACC,EAAE,GAAG,GAAG,OAAO,aAAa,OAAO,SAAS,IAAI,IAAI,QAAQ,MAAM,KAAK,QAAQ,KAAK,SAAS,CAChG,CACF;;AAGA,MAAM,uBAAuB,EAAE,KAC7B,EAAE,QACC,UAAU,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,CAChF,GACA,EAAE,WAAW,UACX,OAAO,YACL,OAAO,QAAQ,KAAK,CAAC,CAAC,QACnB,UAAqC,OAAO,MAAM,OAAO,QAC5D,CACF,CACF,CACF;;AAGA,MAAM,uBAAkE,EAAE,MACxE,EAAE,KACA,EAAE,OAAO;CACP,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC;CACpC,QAAQ,EAAE,OAAuB,gBAAgB;CACjD,QAAQ,EAAE,SAAS,EAAE,OAAO,CAAC;CAC7B,MAAM,EAAE,SACN,EAAE,OAAO;EACP,MAAM,EAAE,SAAS,CAAC,SAAS,QAAQ,CAAC;EACpC,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC;CACtC,CAAC,CACH;CACA,cAAc,EAAE,SAAS,EAAE,QAAQ,CAAC;CACpC,mBAAmB,EAAE,SAAS,EAAE,QAAQ,CAAC;CACzC,cAA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BAAkB,oBAAoB,oBAAoB,eAAe,sBAAsB;;CAE/F,0BAA0B,oBACxB,4BACA,eACA,8BACF;;CAEA,UAAU,oBAAoB,YAAY,eAAe,oBAAoB;;CAE7E,UAAU,oBAAoB,YAAY,eAAe,oBAAoB;;CAE7E,gBAAgB,oBAAoB,kBAAkB,eAAe,gBAAgB;;CAErF,QAAQ,oBAAoB,UAAU,UAAU,gBAAgB;;CAEhE,OAAO,oBAAoB,SAAS,UAAU,WAAW;;CAEzD,gBAAgB,oBACd,kBACA,UACA,EAAE,OAAO,EAAE,OAAO,GAAG,aAAa,CACpC;;CAEA,eAAe,oBACb,iBACA,UACA,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,KAAK,GAAG,EAAE,UAAU,GAAG,GAAG,EAAE,MAAM,sBAAsB,CAAC,CAChF;;CAEA,OAAO,oBAAoB,SAAS,WAAW,WAAW;;CAE1D,WAAW,oBAAoB,aAAa,WAAW,eAAe;;CAEtE,MAAM,oBAAoB,QAAQ,WAAW,UAAU;;CAEvD,UAAU,oBAAoB,YAAY,WAAW,cAAc;;CAEnE,QAAQ,oBAAoB,UAAU,WAAW,iBAAiB;AACpE;AAEA,MAAM,cAAc,OAAO,OAAO,uBAAuB,CAAC,CAAC,QACxD,UAAU,MAAM,SAAS,SAC5B;;;;;;AAOA,SAAgB,kBAAkB,SAAwD;CACxF,OAAO,kBAAkB,SAAS,WAAW,CAAC,CAAC,MAC5C,GAAG,MAAM,EAAE,SAAS,cAAc,EAAE,QAAQ,KAAK,EAAE,IAAI,cAAc,EAAE,GAAG,CAC7E;AACF"}
@@ -1,6 +1,6 @@
1
+ import { findInstanceAncestor } from "../instances/main-component.js";
1
2
  import { scaleNodeChanges } from "./node.js";
2
3
  import { scaleVariableBindingUnits } from "../variables/units.js";
3
- import { findInstanceAncestor } from "../instances/index.js";
4
4
  //#region src/scaling/tree.ts
5
5
  const MIN_SCALE = .01;
6
6
  const RESCALABLE_NODE_TYPES = /* @__PURE__ */ new Set([
@@ -33,6 +33,19 @@ declare function sharedStyleRefKey(kind: SharedStyleKind): (typeof STYLE_REF_KEY
33
33
  declare function sharedStyleTypeForKind(kind: SharedStyleKind): SharedStyleType;
34
34
  declare function getSharedStyles(graph: SceneGraph, kind: SharedStyleKind): SharedStyle[];
35
35
  declare function styleDetachmentChanges(node: SceneNode, changes: Partial<SceneNode>): Partial<SceneNode>;
36
+ /** The node of the shared style with `id`, when the document holds one of `type`. */
37
+ declare function findSharedStyle(graph: SceneGraph, id: string, type: SharedStyleType): SceneNode | undefined;
38
+ /** A new local style's ID, in the shape Figma gives one: `S:` and a 40-digit hex key. */
39
+ declare function newSharedStyleId(): string;
40
+ /** The page that holds the document's styles out of view, as a `.fig` file keeps them; made once. */
41
+ declare function internalCanvas(graph: SceneGraph): SceneNode;
42
+ /**
43
+ * What a layer takes from a shared style it starts using: the style's fields and the reference
44
+ * that keeps it attached. Without the style's node, the reference alone.
45
+ */
46
+ declare function sharedStylePatch(kind: SharedStyleKind, target: SceneNode, styleId: string, style: SceneNode | null): Partial<SceneNode>;
47
+ /** A layer leaving a shared style: it keeps the style's values, without the reference. */
48
+ declare function sharedStyleDetachPatch(kind: SharedStyleKind): Partial<SceneNode>;
36
49
  //#endregion
37
- export { FACE_KEYS, SHARED_STYLE_FIELDS, SHARED_TEXT_STYLE_FIELDS, STYLE_LINK_FIELDS, getSharedStyles, rangeFontStyle, referencedStyleIds, sharedStyleRefKey, sharedStyleTypeForKind, styleDetachmentChanges };
50
+ export { FACE_KEYS, SHARED_STYLE_FIELDS, SHARED_TEXT_STYLE_FIELDS, STYLE_LINK_FIELDS, findSharedStyle, getSharedStyles, internalCanvas, newSharedStyleId, rangeFontStyle, referencedStyleIds, sharedStyleDetachPatch, sharedStylePatch, sharedStyleRefKey, sharedStyleTypeForKind, styleDetachmentChanges };
38
51
  //# sourceMappingURL=shared-styles.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared-styles.d.ts","names":[],"sources":["../src/shared-styles.ts"],"mappings":";;;cAaM;;;;;;;;cASO;;iBAGG,mBAAmB,MAAM;;cAiB5B;;cAwBA;;;;;;;;cASA;;;;;iBAUG,eACd,MAAM,KAAK,yBACX,OAAO;iBAMO,kBAAkB,MAAM,0BAA0B,gBAAgB;iBAIlE,uBAAuB,MAAM,kBAAkB;iBAI/C,gBAAgB,OAAO,YAAY,MAAM,kBAAkB;iBA0B3D,uBACd,MAAM,WACN,SAAS,QAAQ,aAChB,QAAQ"}
1
+ {"version":3,"file":"shared-styles.d.ts","names":[],"sources":["../src/shared-styles.ts"],"mappings":";;;cAiBM;;;;;;;;cASO;;iBAGG,mBAAmB,MAAM;;cAiB5B;;cAwBA;;;;;;;;cASA;;;;;iBAUG,eACd,MAAM,KAAK,yBACX,OAAO;iBAMO,kBAAkB,MAAM,0BAA0B,gBAAgB;iBAIlE,uBAAuB,MAAM,kBAAkB;iBAI/C,gBAAgB,OAAO,YAAY,MAAM,kBAAkB;iBA0B3D,uBACd,MAAM,WACN,SAAS,QAAQ,aAChB,QAAQ;;iBAmBK,gBACd,OAAO,YACP,YACA,MAAM,kBACL;;iBASa;;iBAOA,eAAe,OAAO,aAAa;;;;;iBAmCnC,iBACd,MAAM,iBACN,QAAQ,WACR,iBACA,OAAO,mBACN,QAAQ;;iBAYK,uBAAuB,MAAM,kBAAkB,QAAQ"}
@@ -1,5 +1,9 @@
1
+ import { BLACK } from "./constants.js";
2
+ import { newStrokeGeometry } from "./node-defaults.js";
3
+ import { copyEffects, copyFills, copyLayoutGrids } from "./copy.js";
4
+ import { randomHex } from "./random.js";
1
5
  import { styleRunReferences } from "./text/references.js";
2
- import { compact, isEqual, omit } from "es-toolkit";
6
+ import { compact, isEqual, omit, pick } from "es-toolkit";
3
7
  //#region src/shared-styles.ts
4
8
  const STYLE_REF_KEYS = {
5
9
  fill: "fillStyleId",
@@ -119,7 +123,64 @@ function styleDetachmentChanges(node, changes) {
119
123
  if (FACE_KEYS.some((key) => key in changes && changes[key] !== node[key]) && !("fontStyle" in changes) && node.fontStyle) next.fontStyle = null;
120
124
  return next;
121
125
  }
126
+ /** The node of the shared style with `id`, when the document holds one of `type`. */
127
+ function findSharedStyle(graph, id, type) {
128
+ if (!id) return void 0;
129
+ for (const node of graph.getAllNodes()) if (node.sharedStyleType === type && node.source.id === id) return node;
130
+ }
131
+ /** A new local style's ID, in the shape Figma gives one: `S:` and a 40-digit hex key. */
132
+ function newSharedStyleId() {
133
+ return `S:${randomHex(20)},`;
134
+ }
135
+ const INTERNAL_CANVAS_NAME = "Internal Only Canvas";
136
+ /** The page that holds the document's styles out of view, as a `.fig` file keeps them; made once. */
137
+ function internalCanvas(graph) {
138
+ const existing = graph.getPages(true).find((page) => page.internalOnly);
139
+ if (existing) return existing;
140
+ return graph.createNode("CANVAS", graph.rootId, {
141
+ name: INTERNAL_CANVAS_NAME,
142
+ width: 0,
143
+ height: 0,
144
+ internalOnly: true
145
+ });
146
+ }
147
+ /**
148
+ * A paint style's paints as a layer's strokes: every paint, each keeping the weight, alignment,
149
+ * and line style of the stroke it replaces, or of the layer's first; no paints clear the strokes
150
+ * (Figma desktop 126).
151
+ */
152
+ function strokesFromStyle(target, style) {
153
+ const fallback = target.strokes[0] ?? {
154
+ type: "SOLID",
155
+ color: BLACK,
156
+ opacity: 1,
157
+ visible: true,
158
+ ...newStrokeGeometry(target)
159
+ };
160
+ return copyFills(style.fills).map((paint, index) => ({
161
+ ...paint,
162
+ ...pick(target.strokes[index] ?? fallback, STROKE_LINE_KEYS)
163
+ }));
164
+ }
165
+ /**
166
+ * What a layer takes from a shared style it starts using: the style's fields and the reference
167
+ * that keeps it attached. Without the style's node, the reference alone.
168
+ */
169
+ function sharedStylePatch(kind, target, styleId, style) {
170
+ const patch = { [STYLE_REF_KEYS[kind]]: styleId };
171
+ if (!style) return patch;
172
+ if (kind === "fill") patch.fills = copyFills(style.fills);
173
+ else if (kind === "stroke") patch.strokes = strokesFromStyle(target, style);
174
+ else if (kind === "effect") patch.effects = copyEffects(style.effects);
175
+ else if (kind === "grid") patch.layoutGrids = copyLayoutGrids(style.layoutGrids);
176
+ else Object.assign(patch, structuredClone(pick(style, SHARED_STYLE_FIELDS.text)));
177
+ return patch;
178
+ }
179
+ /** A layer leaving a shared style: it keeps the style's values, without the reference. */
180
+ function sharedStyleDetachPatch(kind) {
181
+ return { [STYLE_REF_KEYS[kind]]: null };
182
+ }
122
183
  //#endregion
123
- export { FACE_KEYS, SHARED_STYLE_FIELDS, SHARED_TEXT_STYLE_FIELDS, STYLE_LINK_FIELDS, getSharedStyles, rangeFontStyle, referencedStyleIds, sharedStyleRefKey, sharedStyleTypeForKind, styleDetachmentChanges };
184
+ export { FACE_KEYS, SHARED_STYLE_FIELDS, SHARED_TEXT_STYLE_FIELDS, STYLE_LINK_FIELDS, findSharedStyle, getSharedStyles, internalCanvas, newSharedStyleId, rangeFontStyle, referencedStyleIds, sharedStyleDetachPatch, sharedStylePatch, sharedStyleRefKey, sharedStyleTypeForKind, styleDetachmentChanges };
124
185
 
125
186
  //# sourceMappingURL=shared-styles.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared-styles.js","names":[],"sources":["../src/shared-styles.ts"],"sourcesContent":["import { compact, isEqual, omit } from 'es-toolkit'\n\nimport type { SceneGraph } from './graph'\nimport { styleRunReferences } from './text/references'\nimport type {\n CharacterStyleOverride,\n SceneNode,\n SharedStyle,\n SharedStyleKind,\n SharedStyleType,\n Stroke\n} from './types'\n\nconst STYLE_REF_KEYS = {\n fill: 'fillStyleId',\n stroke: 'strokeStyleId',\n text: 'textStyleId',\n effect: 'effectStyleId',\n grid: 'gridStyleId'\n} as const satisfies Record<SharedStyleKind, keyof SceneNode>\n\n/** The fields that link a layer to its shared styles. */\nexport const STYLE_LINK_FIELDS = Object.values(STYLE_REF_KEYS)\n\n/** The shared styles a layer uses: its own, its text ranges', and its vector regions'. */\nexport function referencedStyleIds(node: SceneNode): string[] {\n return compact([\n ...STYLE_LINK_FIELDS.map((field) => node[field]),\n ...styleRunReferences(node.styleRuns).styles,\n ...(node.vectorNetwork?.regions ?? []).map((region) => region.fillStyleId)\n ])\n}\n\nconst STYLE_TYPES = {\n fill: 'FILL',\n stroke: 'FILL',\n text: 'TEXT',\n effect: 'EFFECT',\n grid: 'GRID'\n} as const satisfies Record<SharedStyleKind, SharedStyleType>\n\n/** The fields a text style gives what uses it; changing one leaves the style. */\nexport const SHARED_TEXT_STYLE_FIELDS = [\n 'fontFamily',\n 'fontWeight',\n 'italic',\n 'fontStyle',\n 'fontSize',\n 'lineHeight',\n 'letterSpacing',\n 'textDecoration',\n 'textCase',\n 'fontFeatures'\n] as const satisfies readonly (keyof SceneNode)[]\n\n/**\n * The paragraph fields a text style also gives the whole text; a range takes only the character\n * ones. Changing one leaves the style, and a cleared style resets them (live-verified).\n */\nconst TEXT_STYLE_PARAGRAPH_FIELDS = [\n 'paragraphSpacing',\n 'paragraphIndent',\n 'listSpacing'\n] as const satisfies readonly (keyof SceneNode)[]\n\n/** The fields each kind of shared style gives what uses it; changing one leaves the style. */\nexport const SHARED_STYLE_FIELDS = {\n fill: ['fills'],\n stroke: ['strokes'],\n text: [...SHARED_TEXT_STYLE_FIELDS, ...TEXT_STYLE_PARAGRAPH_FIELDS],\n effect: ['effects'],\n grid: ['layoutGrids']\n} as const satisfies Record<SharedStyleKind, readonly (keyof SceneNode)[]>\n\n/** The fields that pick a text's face, which its style name names. */\nexport const FACE_KEYS = [\n 'fontFamily',\n 'fontWeight',\n 'italic'\n] as const satisfies readonly (keyof SceneNode)[]\n\n/**\n * The face name of characters with `style` over the text: their own, none where they set another\n * face without one (as ranges from HTML or `.pen` do), else the text's.\n */\nexport function rangeFontStyle(\n node: Pick<SceneNode, 'fontStyle'>,\n style: CharacterStyleOverride\n): string | null {\n if (style.fontStyle !== undefined) return style.fontStyle\n return FACE_KEYS.some((key) => style[key] !== undefined) ? null : node.fontStyle\n}\n\nexport function sharedStyleRefKey(kind: SharedStyleKind): (typeof STYLE_REF_KEYS)[SharedStyleKind] {\n return STYLE_REF_KEYS[kind]\n}\n\nexport function sharedStyleTypeForKind(kind: SharedStyleKind): SharedStyleType {\n return STYLE_TYPES[kind]\n}\n\nexport function getSharedStyles(graph: SceneGraph, kind: SharedStyleKind): SharedStyle[] {\n const type = sharedStyleTypeForKind(kind)\n const styles: SharedStyle[] = []\n for (const node of graph.getAllNodes()) {\n if (node.sharedStyleType !== type || !node.source.id) continue\n styles.push({ id: node.source.id, nodeId: node.id, name: node.name, type })\n }\n return styles.sort((left, right) => left.name.localeCompare(right.name))\n}\n\n/** What a stroke draws along beside its paint: the layer's, not its stroke style's. */\nconst STROKE_LINE_KEYS = ['weight', 'align', 'cap', 'join', 'dashPattern'] as const\n\n/**\n * Whether new strokes only change how their lines run, keeping every paint. A stroke style gives\n * paints only, so such a write keeps it; any other strokes write leaves it, as setting even the\n * same paints does in Figma (live-verified).\n */\nfunction restylesStrokeLines(current: readonly Stroke[], next: readonly Stroke[]): boolean {\n const paints = (strokes: readonly Stroke[]) =>\n strokes.map((stroke) => omit(stroke, STROKE_LINE_KEYS))\n const lines = (strokes: readonly Stroke[]) =>\n strokes.map((stroke) => STROKE_LINE_KEYS.map((key) => stroke[key]))\n return isEqual(paints(current), paints(next)) && !isEqual(lines(current), lines(next))\n}\n\nexport function styleDetachmentChanges(\n node: SceneNode,\n changes: Partial<SceneNode>\n): Partial<SceneNode> {\n const next = { ...changes }\n for (const [kind, fields] of Object.entries(SHARED_STYLE_FIELDS)) {\n const reference = STYLE_REF_KEYS[kind as SharedStyleKind]\n if (reference in changes || !node[reference]) continue\n if (!fields.some((field) => field in changes)) continue\n if (kind === 'stroke' && changes.strokes && restylesStrokeLines(node.strokes, changes.strokes))\n continue\n next[reference] = null\n }\n // A face named for another family, weight, or slant names none; the new one takes its own name.\n const changesFace = FACE_KEYS.some((key) => key in changes && changes[key] !== node[key])\n if (changesFace && !('fontStyle' in changes) && node.fontStyle) {\n next.fontStyle = null\n }\n return next\n}\n"],"mappings":";;;AAaA,MAAM,iBA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GAAE,IAAI,KAAK,OAAO;GAAI,QAAQ,KAAK;GAAI,MAAM,KAAK;GAAM;EAAK,CAAC;CAC5E;CACA,OAAO,OAAO,MAAM,MAAM,UAAU,KAAK,KAAK,cAAc,MAAM,IAAI,CAAC;AACzE;;AAGA,MAAM,mBAAmB;CAAC;CAAU;CAAS;CAAO;CAAQ;AAAa;;;;;;AAOzE,SAAS,oBAAoB,SAA4B,MAAkC;CACzF,MAAM,UAAU,YACd,QAAQ,KAAK,WAAW,KAAK,QAAQ,gBAAgB,CAAC;CACxD,MAAM,SAAS,YACb,QAAQ,KAAK,WAAW,iBAAiB,KAAK,QAAQ,OAAO,IAAI,CAAC;CACpE,OAAO,QAAQ,OAAO,OAAO,GAAG,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC;AACvF;AAEA,SAAgB,uBACd,MACA,SACoB;CACpB,MAAM,OAAO,EAAE,GAAG,QAAQ;CAC1B,KAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,mBAAmB,GAAG;EAChE,MAAM,YAAY,eAAe;EACjC,IAAI,aAAa,WAAW,CAAC,KAAK,YAAY;EAC9C,IAAI,CAAC,OAAO,MAAM,UAAU,SAAS,OAAO,GAAG;EAC/C,IAAI,SAAS,YAAY,QAAQ,WAAW,oBAAoB,KAAK,SAAS,QAAQ,OAAO,GAC3F;EACF,KAAK,aAAa;CACpB;CAGA,IADoB,UAAU,MAAM,QAAQ,OAAO,WAAW,QAAQ,SAAS,KAAK,IACtE,KAAK,EAAE,eAAe,YAAY,KAAK,WACnD,KAAK,YAAY;CAEnB,OAAO;AACT"}
1
+ {"version":3,"file":"shared-styles.js","names":[],"sources":["../src/shared-styles.ts"],"sourcesContent":["import { compact, isEqual, omit, pick } from 'es-toolkit'\n\nimport { BLACK } from './constants'\nimport { copyEffects, copyFills, copyLayoutGrids } from './copy'\nimport type { SceneGraph } from './graph'\nimport { newStrokeGeometry } from './node-defaults'\nimport { randomHex } from './random'\nimport { styleRunReferences } from './text/references'\nimport type {\n CharacterStyleOverride,\n SceneNode,\n SharedStyle,\n SharedStyleKind,\n SharedStyleType,\n Stroke\n} from './types'\n\nconst STYLE_REF_KEYS = {\n fill: 'fillStyleId',\n stroke: 'strokeStyleId',\n text: 'textStyleId',\n effect: 'effectStyleId',\n grid: 'gridStyleId'\n} as const satisfies Record<SharedStyleKind, keyof SceneNode>\n\n/** The fields that link a layer to its shared styles. */\nexport const STYLE_LINK_FIELDS = Object.values(STYLE_REF_KEYS)\n\n/** The shared styles a layer uses: its own, its text ranges', and its vector regions'. */\nexport function referencedStyleIds(node: SceneNode): string[] {\n return compact([\n ...STYLE_LINK_FIELDS.map((field) => node[field]),\n ...styleRunReferences(node.styleRuns).styles,\n ...(node.vectorNetwork?.regions ?? []).map((region) => region.fillStyleId)\n ])\n}\n\nconst STYLE_TYPES = {\n fill: 'FILL',\n stroke: 'FILL',\n text: 'TEXT',\n effect: 'EFFECT',\n grid: 'GRID'\n} as const satisfies Record<SharedStyleKind, SharedStyleType>\n\n/** The fields a text style gives what uses it; changing one leaves the style. */\nexport const SHARED_TEXT_STYLE_FIELDS = [\n 'fontFamily',\n 'fontWeight',\n 'italic',\n 'fontStyle',\n 'fontSize',\n 'lineHeight',\n 'letterSpacing',\n 'textDecoration',\n 'textCase',\n 'fontFeatures'\n] as const satisfies readonly (keyof SceneNode)[]\n\n/**\n * The paragraph fields a text style also gives the whole text; a range takes only the character\n * ones. Changing one leaves the style, and a cleared style resets them (live-verified).\n */\nconst TEXT_STYLE_PARAGRAPH_FIELDS = [\n 'paragraphSpacing',\n 'paragraphIndent',\n 'listSpacing'\n] as const satisfies readonly (keyof SceneNode)[]\n\n/** The fields each kind of shared style gives what uses it; changing one leaves the style. */\nexport const SHARED_STYLE_FIELDS = {\n fill: ['fills'],\n stroke: ['strokes'],\n text: [...SHARED_TEXT_STYLE_FIELDS, ...TEXT_STYLE_PARAGRAPH_FIELDS],\n effect: ['effects'],\n grid: ['layoutGrids']\n} as const satisfies Record<SharedStyleKind, readonly (keyof SceneNode)[]>\n\n/** The fields that pick a text's face, which its style name names. */\nexport const FACE_KEYS = [\n 'fontFamily',\n 'fontWeight',\n 'italic'\n] as const satisfies readonly (keyof SceneNode)[]\n\n/**\n * The face name of characters with `style` over the text: their own, none where they set another\n * face without one (as ranges from HTML or `.pen` do), else the text's.\n */\nexport function rangeFontStyle(\n node: Pick<SceneNode, 'fontStyle'>,\n style: CharacterStyleOverride\n): string | null {\n if (style.fontStyle !== undefined) return style.fontStyle\n return FACE_KEYS.some((key) => style[key] !== undefined) ? null : node.fontStyle\n}\n\nexport function sharedStyleRefKey(kind: SharedStyleKind): (typeof STYLE_REF_KEYS)[SharedStyleKind] {\n return STYLE_REF_KEYS[kind]\n}\n\nexport function sharedStyleTypeForKind(kind: SharedStyleKind): SharedStyleType {\n return STYLE_TYPES[kind]\n}\n\nexport function getSharedStyles(graph: SceneGraph, kind: SharedStyleKind): SharedStyle[] {\n const type = sharedStyleTypeForKind(kind)\n const styles: SharedStyle[] = []\n for (const node of graph.getAllNodes()) {\n if (node.sharedStyleType !== type || !node.source.id) continue\n styles.push({ id: node.source.id, nodeId: node.id, name: node.name, type })\n }\n return styles.sort((left, right) => left.name.localeCompare(right.name))\n}\n\n/** What a stroke draws along beside its paint: the layer's, not its stroke style's. */\nconst STROKE_LINE_KEYS = ['weight', 'align', 'cap', 'join', 'dashPattern'] as const\n\n/**\n * Whether new strokes only change how their lines run, keeping every paint. A stroke style gives\n * paints only, so such a write keeps it; any other strokes write leaves it, as setting even the\n * same paints does in Figma (live-verified).\n */\nfunction restylesStrokeLines(current: readonly Stroke[], next: readonly Stroke[]): boolean {\n const paints = (strokes: readonly Stroke[]) =>\n strokes.map((stroke) => omit(stroke, STROKE_LINE_KEYS))\n const lines = (strokes: readonly Stroke[]) =>\n strokes.map((stroke) => STROKE_LINE_KEYS.map((key) => stroke[key]))\n return isEqual(paints(current), paints(next)) && !isEqual(lines(current), lines(next))\n}\n\nexport function styleDetachmentChanges(\n node: SceneNode,\n changes: Partial<SceneNode>\n): Partial<SceneNode> {\n const next = { ...changes }\n for (const [kind, fields] of Object.entries(SHARED_STYLE_FIELDS)) {\n const reference = STYLE_REF_KEYS[kind as SharedStyleKind]\n if (reference in changes || !node[reference]) continue\n if (!fields.some((field) => field in changes)) continue\n if (kind === 'stroke' && changes.strokes && restylesStrokeLines(node.strokes, changes.strokes))\n continue\n next[reference] = null\n }\n // A face named for another family, weight, or slant names none; the new one takes its own name.\n const changesFace = FACE_KEYS.some((key) => key in changes && changes[key] !== node[key])\n if (changesFace && !('fontStyle' in changes) && node.fontStyle) {\n next.fontStyle = null\n }\n return next\n}\n\n/** The node of the shared style with `id`, when the document holds one of `type`. */\nexport function findSharedStyle(\n graph: SceneGraph,\n id: string,\n type: SharedStyleType\n): SceneNode | undefined {\n if (!id) return undefined\n for (const node of graph.getAllNodes()) {\n if (node.sharedStyleType === type && node.source.id === id) return node\n }\n return undefined\n}\n\n/** A new local style's ID, in the shape Figma gives one: `S:` and a 40-digit hex key. */\nexport function newSharedStyleId(): string {\n return `S:${randomHex(20)},`\n}\n\nconst INTERNAL_CANVAS_NAME = 'Internal Only Canvas'\n\n/** The page that holds the document's styles out of view, as a `.fig` file keeps them; made once. */\nexport function internalCanvas(graph: SceneGraph): SceneNode {\n const existing = graph.getPages(true).find((page) => page.internalOnly)\n if (existing) return existing\n return graph.createNode('CANVAS', graph.rootId, {\n name: INTERNAL_CANVAS_NAME,\n width: 0,\n height: 0,\n internalOnly: true\n })\n}\n\n/**\n * A paint style's paints as a layer's strokes: every paint, each keeping the weight, alignment,\n * and line style of the stroke it replaces, or of the layer's first; no paints clear the strokes\n * (Figma desktop 126).\n */\nfunction strokesFromStyle(target: SceneNode, style: SceneNode): SceneNode['strokes'] {\n // Without strokes, the layer keeps the weight and alignment a new stroke takes.\n const fallback: Stroke = target.strokes[0] ?? {\n type: 'SOLID',\n color: BLACK,\n opacity: 1,\n visible: true,\n ...newStrokeGeometry(target)\n }\n return copyFills(style.fills).map((paint, index) => ({\n ...paint,\n ...pick(target.strokes[index] ?? fallback, STROKE_LINE_KEYS)\n }))\n}\n\n/**\n * What a layer takes from a shared style it starts using: the style's fields and the reference\n * that keeps it attached. Without the style's node, the reference alone.\n */\nexport function sharedStylePatch(\n kind: SharedStyleKind,\n target: SceneNode,\n styleId: string,\n style: SceneNode | null\n): Partial<SceneNode> {\n const patch: Partial<SceneNode> = { [STYLE_REF_KEYS[kind]]: styleId }\n if (!style) return patch\n if (kind === 'fill') patch.fills = copyFills(style.fills)\n else if (kind === 'stroke') patch.strokes = strokesFromStyle(target, style)\n else if (kind === 'effect') patch.effects = copyEffects(style.effects)\n else if (kind === 'grid') patch.layoutGrids = copyLayoutGrids(style.layoutGrids)\n else Object.assign(patch, structuredClone(pick(style, SHARED_STYLE_FIELDS.text)))\n return patch\n}\n\n/** A layer leaving a shared style: it keeps the style's values, without the reference. */\nexport function sharedStyleDetachPatch(kind: SharedStyleKind): Partial<SceneNode> {\n return { [STYLE_REF_KEYS[kind]]: null }\n}\n"],"mappings":";;;;;;;AAiBA,MAAM,iBAAiB;CACrB,MAAM;CACN,QAAQ;CACR,MAAM;CACN,QAAQ;CACR,MAAM;AACR;;AAGA,MAAa,oBAAoB,OAAO,OAAO,cAAc;;AAG7D,SAAgB,mBAAmB,MAA2B;CAC5D,OAAO,QAAQ;EACb,GAAG,kBAAkB,KAAK,UAAU,KAAK,MAAM;EAC/C,GAAG,mBAAmB,KAAK,SAAS,CAAC,CAAC;EACtC,IAAI,KAAK,eAAe,WAAW,CAAC,EAAA,CAAG,KAAK,WAAW,OAAO,WAAW;CAC3E,CAAC;AACH;AAEA,MAAM,cAAc;CAClB,MAAM;CACN,QAAQ;CACR,MAAM;CACN,QAAQ;CACR,MAAM;AACR;;AAGA,MAAa,2BAA2B;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAMA,MAAM,8BAA8B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AG;EACH,GAAG,KAAK,OAAO,QAAQ,UAAU,UAAU,gBAAgB;CAC7D,EAAE;AACJ;;;;;AAMA,SAAgB,iBACd,MACA,QACA,SACA,OACoB;CACpB,MAAM,QAA4B,GAAG,eAAe,QAAQ,QAAQ;CACpE,IAAI,CAAC,OAAO,OAAO;CACnB,IAAI,SAAS,QAAQ,MAAM,QAAQ,UAAU,MAAM,KAAK;MACnD,IAAI,SAAS,UAAU,MAAM,UAAU,iBAAiB,QAAQ,KAAK;MACrE,IAAI,SAAS,UAAU,MAAM,UAAU,YAAY,MAAM,OAAO;MAChE,IAAI,SAAS,QAAQ,MAAM,cAAc,gBAAgB,MAAM,WAAW;MAC1E,OAAO,OAAO,OAAO,gBAAgB,KAAK,OAAO,oBAAoB,IAAI,CAAC,CAAC;CAChF,OAAO;AACT;;AAGA,SAAgB,uBAAuB,MAA2C;CAChF,OAAO,GAAG,eAAe,QAAQ,KAAK;AACxC"}
@@ -1 +1 @@
1
- {"version":3,"file":"content.d.ts","names":[],"sources":["../../src/slots/content.ts"],"mappings":";;;;;;;;;;KAcY;EACN;;EACA;EAAc,OAAO;EAAW,UAAU;EAAW;;EACrD;EAAgB,OAAO;;iBAYb,UAAU,OAAO,YAAY,mBAAmB;;;;;;iBAmChD,iBACd,OAAO,YACP,OAAO,QAAQ;EAAa;;;iBAwCd,iBACd,OAAO,YACP,OAAO,QAAQ;EAAa;;;iBAYd,iBACd,OAAO,YACP,OAAO,QAAQ;EAAa"}
1
+ {"version":3,"file":"content.d.ts","names":[],"sources":["../../src/slots/content.ts"],"mappings":";;;;;;;;;;KAcY;EACN;;EACA;EAAc,OAAO;EAAW,UAAU;EAAW;;EACrD;EAAgB,OAAO;;iBAYb,UAAU,OAAO,YAAY,mBAAmB;;;;;;iBAmChD,iBACd,OAAO,YACP,OAAO,QAAQ;EAAa;;;iBA0Cd,iBACd,OAAO,YACP,OAAO,QAAQ;EAAa;;;iBAYd,iBACd,OAAO,YACP,OAAO,QAAQ;EAAa"}
@@ -54,6 +54,7 @@ function descendants(graph, node, enterInstances) {
54
54
  function claimSlotContent(graph, scope) {
55
55
  const { frame, instance, propertyId } = scope;
56
56
  if (ownsSlotContent(graph, frame, propertyId)) return;
57
+ graph.willChangeNode(instance);
57
58
  const overrides = instance.instanceOverrides;
58
59
  for (const node of descendants(graph, frame, false)) {
59
60
  overrides.descendants.delete(node.id);
@@ -61,6 +62,7 @@ function claimSlotContent(graph, scope) {
61
62
  graph.updateNode(node.id, { componentId: null });
62
63
  continue;
63
64
  }
65
+ graph.willChangeNode(node);
64
66
  for (const inner of descendants(graph, node, true)) {
65
67
  const fields = overrides.descendants.get(inner.id);
66
68
  if (!fields) continue;
@@ -1 +1 @@
1
- {"version":3,"file":"content.js","names":[],"sources":["../../src/slots/content.ts"],"sourcesContent":["import { isGeneratedFrame } from '../generated'\nimport type { SceneGraph } from '../graph'\nimport { getInstanceOverride, setInstanceOverride } from '../instances/overrides'\nimport { cloneChildrenWithMapping } from '../instances/sync'\nimport type { SceneNode } from '../types'\nimport { ownsSlotContent, slotPropertyId } from './frames'\n\n/**\n * Where layers may be added, moved, or removed under a parent:\n * - `free`: outside any instance, or inside a component definition;\n * - `slot`: inside a slot of an instance, whose content the instance owns or can claim;\n * - `locked`: anywhere else inside an instance, whose layers come from its component, or inside a\n * generated frame such as a sticky note, whose layers come from its template.\n */\nexport type SlotScope =\n | { kind: 'free' }\n | { kind: 'slot'; frame: SceneNode; instance: SceneNode; propertyId: string }\n | { kind: 'locked'; owner: SceneNode }\n\nfunction parentOf(graph: SceneGraph, node: SceneNode): SceneNode | undefined {\n return node.parentId ? graph.nodes.get(node.parentId) : undefined\n}\n\nfunction nearestInstance(graph: SceneGraph, node: SceneNode): SceneNode | undefined {\n let current = parentOf(graph, node)\n while (current && current.type !== 'INSTANCE') current = parentOf(graph, current)\n return current\n}\n\nexport function slotScope(graph: SceneGraph, parentId: string): SlotScope {\n let current = graph.nodes.get(parentId)\n while (current) {\n const propertyId = slotPropertyId(current)\n if (propertyId) {\n const instance = nearestInstance(graph, current)\n return instance ? { kind: 'slot', frame: current, instance, propertyId } : { kind: 'free' }\n }\n if (current.type === 'INSTANCE' || isGeneratedFrame(current))\n return { kind: 'locked', owner: current }\n current = parentOf(graph, current)\n }\n return { kind: 'free' }\n}\n\n/** Every layer below `node`; `enterInstances` also walks the layers of nested instances. */\nfunction descendants(graph: SceneGraph, node: SceneNode, enterInstances: boolean): SceneNode[] {\n const result: SceneNode[] = []\n const visit = (parent: SceneNode): void => {\n for (const childId of parent.childIds) {\n const child = graph.nodes.get(childId)\n if (!child) continue\n result.push(child)\n if (enterInstances || child.type !== 'INSTANCE') visit(child)\n }\n }\n visit(node)\n return result\n}\n\n/**\n * Make the instance own its slot's content, as Figma does on the first edit: the layers\n * stay where they are, but stop following the component. Overrides the instance held for\n * them become their own values, or move to the nested instance they belong to.\n */\nexport function claimSlotContent(\n graph: SceneGraph,\n scope: Extract<SlotScope, { kind: 'slot' }>\n): void {\n const { frame, instance, propertyId } = scope\n if (ownsSlotContent(graph, frame, propertyId)) return\n const overrides = instance.instanceOverrides\n for (const node of descendants(graph, frame, false)) {\n overrides.descendants.delete(node.id)\n if (node.type !== 'INSTANCE') {\n graph.updateNode(node.id, { componentId: null })\n continue\n }\n // A nested instance keeps the overrides its former owner applied inside it.\n for (const inner of descendants(graph, node, true)) {\n const fields = overrides.descendants.get(inner.id)\n if (!fields) continue\n for (const [field, value] of fields)\n if (field !== 'sourceComponentId')\n setInstanceOverride(node.instanceOverrides, node.id, inner.id, field, value)\n overrides.descendants.delete(inner.id)\n }\n graph.updateNode(node.id, { instanceOverrides: node.instanceOverrides })\n }\n graph.updateNode(instance.id, {\n instanceOverrides: overrides,\n componentPropertyAssignments: { ...instance.componentPropertyAssignments, [propertyId]: '' }\n })\n}\n\n/** The component layer an instance layer was cloned from. */\nfunction componentSource(instance: SceneNode, node: SceneNode): string | null {\n const mapped = getInstanceOverride(\n instance.instanceOverrides,\n instance.id,\n node.id,\n 'sourceComponentId'\n )\n return typeof mapped === 'string' ? mapped : node.componentId\n}\n\n/** Return the slot to its component's content: the instance stops owning it. */\nexport function resetSlotContent(\n graph: SceneGraph,\n scope: Extract<SlotScope, { kind: 'slot' }>\n): void {\n const { frame, instance, propertyId } = scope\n for (const childId of Array.from(frame.childIds)) graph.deleteNode(childId)\n const assignments = { ...instance.componentPropertyAssignments }\n Reflect.deleteProperty(assignments, propertyId)\n graph.updateNode(instance.id, { componentPropertyAssignments: assignments })\n const source = componentSource(instance, frame)\n if (source && graph.nodes.has(source)) cloneChildrenWithMapping(graph, source, frame.id)\n}\n\n/** Remove everything from the slot; the instance keeps owning it, now empty. */\nexport function clearSlotContent(\n graph: SceneGraph,\n scope: Extract<SlotScope, { kind: 'slot' }>\n): void {\n claimSlotContent(graph, scope)\n for (const childId of Array.from(scope.frame.childIds)) graph.deleteNode(childId)\n}\n"],"mappings":";;;;;AAmBA,SAAS,SAAS,OAAmB,MAAwC;CAC3E,OAAO,KAAK,WAAW,MAAM,MAAM,IAAI,KAAK,QAAQ,IAAI,KAAA;AAC1D;AAEA,SAAS,gBAAgB,OAAmB,MAAwC;CAClF,IAAI,UAAU,SAAS,OAAO,IAAI;CAClC,OAAO,WAAW,QAAQ,SAAS,YAAY,UAAU,SAAS,OAAO,OAAO;CAChF,OAAO;AACT;AAEA,SAAgB,UAAU,OAAmB,UAA6B;CACxE,IAAI,UAAU,MAAM,MAAM,IAAI,QAAQ;CACtC,OAAO,SAAS;EACd,MAAM,aAAa,eAAe,OAAO;EACzC,IAAI,YAAY;GACd,MAAM,WAAW,gBAAgB,OAAO,OAAO;GAC/C,OAAO,WAAW;IAAE,MAAM;IAAQ,OAAO;IAAS;IAAU;GAAW,IAAI,EAAE,MAAM,OAAO;EAC5F;EACA,IAAI,QAAQ,SAAS,cAAc,iBAAiB,OAAO,GACzD,OAAO;GAAE,MAAM;GAAU,OAAO;EAAQ;EAC1C,UAAU,SAAS,OAAO,OAAO;CACnC;CACA,OAAO,EAA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,IACL,mBACF;CACA,OAAO,OAAO,WAAW,WAAW,SAAS,KAAK;AACpD;;AAGA,SAAgB,iBACd,OACA,OACM;CACN,MAAM,EAAE,OAAO,UAAU,eAAe;CACxC,KAAK,MAAM,WAAW,MAAM,KAAK,MAAM,QAAQ,GAAG,MAAM,WAAW,OAAO;CAC1E,MAAM,cAAc,EAAE,GAAG,SAAS,6BAA6B;CAC/D,QAAQ,eAAe,aAAa,UAAU;CAC9C,MAAM,WAAW,SAAS,IAAI,EAAE,8BAA8B,YAAY,CAAC;CAC3E,MAAM,SAAS,gBAAgB,UAAU,KAAK;CAC9C,IAAI,UAAU,MAAM,MAAM,IAAI,MAAM,GAAG,yBAAyB,OAAO,QAAQ,MAAM,EAAE;AACzF;;AAGA,SAAgB,iBACd,OACA,OACM;CACN,iBAAiB,OAAO,KAAK;CAC7B,KAAK,MAAM,WAAW,MAAM,KAAK,MAAM,MAAM,QAAQ,GAAG,MAAM,WAAW,OAAO;AAClF"}
1
+ {"version":3,"file":"content.js","names":[],"sources":["../../src/slots/content.ts"],"sourcesContent":["import { isGeneratedFrame } from '../generated'\nimport type { SceneGraph } from '../graph'\nimport { getInstanceOverride, setInstanceOverride } from '../instances/overrides'\nimport { cloneChildrenWithMapping } from '../instances/sync'\nimport type { SceneNode } from '../types'\nimport { ownsSlotContent, slotPropertyId } from './frames'\n\n/**\n * Where layers may be added, moved, or removed under a parent:\n * - `free`: outside any instance, or inside a component definition;\n * - `slot`: inside a slot of an instance, whose content the instance owns or can claim;\n * - `locked`: anywhere else inside an instance, whose layers come from its component, or inside a\n * generated frame such as a sticky note, whose layers come from its template.\n */\nexport type SlotScope =\n | { kind: 'free' }\n | { kind: 'slot'; frame: SceneNode; instance: SceneNode; propertyId: string }\n | { kind: 'locked'; owner: SceneNode }\n\nfunction parentOf(graph: SceneGraph, node: SceneNode): SceneNode | undefined {\n return node.parentId ? graph.nodes.get(node.parentId) : undefined\n}\n\nfunction nearestInstance(graph: SceneGraph, node: SceneNode): SceneNode | undefined {\n let current = parentOf(graph, node)\n while (current && current.type !== 'INSTANCE') current = parentOf(graph, current)\n return current\n}\n\nexport function slotScope(graph: SceneGraph, parentId: string): SlotScope {\n let current = graph.nodes.get(parentId)\n while (current) {\n const propertyId = slotPropertyId(current)\n if (propertyId) {\n const instance = nearestInstance(graph, current)\n return instance ? { kind: 'slot', frame: current, instance, propertyId } : { kind: 'free' }\n }\n if (current.type === 'INSTANCE' || isGeneratedFrame(current))\n return { kind: 'locked', owner: current }\n current = parentOf(graph, current)\n }\n return { kind: 'free' }\n}\n\n/** Every layer below `node`; `enterInstances` also walks the layers of nested instances. */\nfunction descendants(graph: SceneGraph, node: SceneNode, enterInstances: boolean): SceneNode[] {\n const result: SceneNode[] = []\n const visit = (parent: SceneNode): void => {\n for (const childId of parent.childIds) {\n const child = graph.nodes.get(childId)\n if (!child) continue\n result.push(child)\n if (enterInstances || child.type !== 'INSTANCE') visit(child)\n }\n }\n visit(node)\n return result\n}\n\n/**\n * Make the instance own its slot's content, as Figma does on the first edit: the layers\n * stay where they are, but stop following the component. Overrides the instance held for\n * them become their own values, or move to the nested instance they belong to.\n */\nexport function claimSlotContent(\n graph: SceneGraph,\n scope: Extract<SlotScope, { kind: 'slot' }>\n): void {\n const { frame, instance, propertyId } = scope\n if (ownsSlotContent(graph, frame, propertyId)) return\n graph.willChangeNode(instance)\n const overrides = instance.instanceOverrides\n for (const node of descendants(graph, frame, false)) {\n overrides.descendants.delete(node.id)\n if (node.type !== 'INSTANCE') {\n graph.updateNode(node.id, { componentId: null })\n continue\n }\n // A nested instance keeps the overrides its former owner applied inside it.\n graph.willChangeNode(node)\n for (const inner of descendants(graph, node, true)) {\n const fields = overrides.descendants.get(inner.id)\n if (!fields) continue\n for (const [field, value] of fields)\n if (field !== 'sourceComponentId')\n setInstanceOverride(node.instanceOverrides, node.id, inner.id, field, value)\n overrides.descendants.delete(inner.id)\n }\n graph.updateNode(node.id, { instanceOverrides: node.instanceOverrides })\n }\n graph.updateNode(instance.id, {\n instanceOverrides: overrides,\n componentPropertyAssignments: { ...instance.componentPropertyAssignments, [propertyId]: '' }\n })\n}\n\n/** The component layer an instance layer was cloned from. */\nfunction componentSource(instance: SceneNode, node: SceneNode): string | null {\n const mapped = getInstanceOverride(\n instance.instanceOverrides,\n instance.id,\n node.id,\n 'sourceComponentId'\n )\n return typeof mapped === 'string' ? mapped : node.componentId\n}\n\n/** Return the slot to its component's content: the instance stops owning it. */\nexport function resetSlotContent(\n graph: SceneGraph,\n scope: Extract<SlotScope, { kind: 'slot' }>\n): void {\n const { frame, instance, propertyId } = scope\n for (const childId of Array.from(frame.childIds)) graph.deleteNode(childId)\n const assignments = { ...instance.componentPropertyAssignments }\n Reflect.deleteProperty(assignments, propertyId)\n graph.updateNode(instance.id, { componentPropertyAssignments: assignments })\n const source = componentSource(instance, frame)\n if (source && graph.nodes.has(source)) cloneChildrenWithMapping(graph, source, frame.id)\n}\n\n/** Remove everything from the slot; the instance keeps owning it, now empty. */\nexport function clearSlotContent(\n graph: SceneGraph,\n scope: Extract<SlotScope, { kind: 'slot' }>\n): void {\n claimSlotContent(graph, scope)\n for (const childId of Array.from(scope.frame.childIds)) graph.deleteNode(childId)\n}\n"],"mappings":";;;;;AAmBA,SAAS,SAAS,OAAmB,MAAwC;CAC3E,OAAO,KAAK,WAAW,MAAM,MAAM,IAAI,KAAK,QAAQ,IAAI,KAAA;AAC1D;AAEA,SAAS,gBAAgB,OAAmB,MAAwC;CAClF,IAAI,UAAU,SAAS,OAAO,IAAI;CAClC,OAAO,WAAW,QAAQ,SAAS,YAAY,UAAU,SAAS,OAAO,OAAO;CAChF,OAAO;AACT;AAEA,SAAgB,UAAU,OAAmB,UAA6B;CACxE,IAAI,UAAU,MAAM,MAAM,IAAI,QAAQ;CACtC,OAAO,SAAS;EACd,MAAM,aAAa,eAAe,OAAO;EACzC,IAAI,YAAY;GACd,MAAM,WAAW,gBAAgB,OAAO,OAAO;GAC/C,OAAO,WAAW;IAAE,MAAM;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K,IAAI,EAAE,mBAAmB,KAAK,kBAAkB,CAAC;CACzE;CACA,MAAM,WAAW,SAAS,IAAI;EAC5B,mBAAmB;EACnB,8BAA8B;GAAE,GAAG,SAAS;IAA+B,aAAa;EAAG;CAC7F,CAAC;AACH;;AAGA,SAAS,gBAAgB,UAAqB,MAAgC;CAC5E,MAAM,SAAS,oBACb,SAAS,mBACT,SAAS,IACT,KAAK,IACL,mBACF;CACA,OAAO,OAAO,WAAW,WAAW,SAAS,KAAK;AACpD;;AAGA,SAAgB,iBACd,OACA,OACM;CACN,MAAM,EAAE,OAAO,UAAU,eAAe;CACxC,KAAK,MAAM,WAAW,MAAM,KAAK,MAAM,QAAQ,GAAG,MAAM,WAAW,OAAO;CAC1E,MAAM,cAAc,EAAE,GAAG,SAAS,6BAA6B;CAC/D,QAAQ,eAAe,aAAa,UAAU;CAC9C,MAAM,WAAW,SAAS,IAAI,EAAE,8BAA8B,YAAY,CAAC;CAC3E,MAAM,SAAS,gBAAgB,UAAU,KAAK;CAC9C,IAAI,UAAU,MAAM,MAAM,IAAI,MAAM,GAAG,yBAAyB,OAAO,QAAQ,MAAM,EAAE;AACzF;;AAGA,SAAgB,iBACd,OACA,OACM;CACN,iBAAiB,OAAO,KAAK;CAC7B,KAAK,MAAM,WAAW,MAAM,KAAK,MAAM,MAAM,QAAQ,GAAG,MAAM,WAAW,OAAO;AAClF"}
@@ -18,6 +18,8 @@ interface ParkedSlot {
18
18
  name: string;
19
19
  /** Content layer ids, in layer order. */
20
20
  content: string[];
21
+ ownerId: string;
22
+ propertyId: string;
21
23
  }
22
24
  /** Owned slot content parked under an instance while its component changes. */
23
25
  interface ParkedSlotContent {
@@ -1 +1 @@
1
- {"version":3,"file":"frames.d.ts","names":[],"sources":["../../src/slots/frames.ts"],"mappings":";;;;iBAKgB,eAAe,MAAM;;;;;iBASrB,gBACd,OAAO,YACP,MAAM,WACN;;iBAmBc,mBAAmB,OAAO,YAAY,UAAU,YAAY;;UAelE;;EAER;;EAEA;;EAEA;;;UAIe;EACf,OAAO;;EAEP;;;;;;;iBAoCc,uBAAuB,OAAO,YAAY,UAAU,YAAY;;iBAsBhE,wBACd,OAAO,YACP,UAAU,WACV,QAAQ"}
1
+ {"version":3,"file":"frames.d.ts","names":[],"sources":["../../src/slots/frames.ts"],"mappings":";;;;iBAKgB,eAAe,MAAM;;;;;iBASrB,gBACd,OAAO,YACP,MAAM,WACN;;iBAmBc,mBAAmB,OAAO,YAAY,UAAU,YAAY;;UAelE;;EAER;;EAEA;;EAEA;EACA;EACA;;;UAIe;EACf,OAAO;;EAEP;;;;;;;iBAoCc,uBAAuB,OAAO,YAAY,UAAU,YAAY;;iBA2BhE,wBACd,OAAO,YACP,UAAU,WACV,QAAQ"}
@@ -77,13 +77,18 @@ function detachOwnedSlotContent(graph, instance) {
77
77
  parked.slots.push({
78
78
  path,
79
79
  name,
80
- content
80
+ content,
81
+ ownerId: owner.id,
82
+ propertyId
81
83
  });
82
84
  }
83
85
  };
84
86
  visit(instance, []);
85
87
  return parked;
86
88
  }
89
+ function assignsOtherContent(owner, propertyId, slot) {
90
+ return !(owner.id === slot.ownerId && propertyId === slot.propertyId) && Object.hasOwn(owner.componentPropertyAssignments, propertyId);
91
+ }
87
92
  /** Move parked content into the slots of the same names and paths, and reassign them. */
88
93
  function restoreOwnedSlotContent(graph, instance, parked) {
89
94
  if (parked.slots.length === 0 && parked.propertyIds.length === 0) return;
@@ -95,7 +100,7 @@ function restoreOwnedSlotContent(graph, instance, parked) {
95
100
  return !!propertyId && slotName(graph, owner, propertyId) === slot.name;
96
101
  });
97
102
  const propertyId = frame && slotPropertyId(frame);
98
- if (!owner || !frame || !propertyId || Object.hasOwn(owner.componentPropertyAssignments, propertyId)) {
103
+ if (!owner || !frame || !propertyId || assignsOtherContent(owner, propertyId, slot)) {
99
104
  for (const id of slot.content) graph.deleteNode(id);
100
105
  continue;
101
106
  }
@@ -1 +1 @@
1
- {"version":3,"file":"frames.js","names":[],"sources":["../../src/slots/frames.ts"],"sourcesContent":["import type { SceneGraph } from '../graph'\nimport { instanceMainComponent } from '../instances/main-component'\nimport type { SceneNode } from '../types'\n\n/** The slot property a frame holds the content of, if it is a slot. */\nexport function slotPropertyId(node: SceneNode): string | undefined {\n return node.componentPropertyReferences.find((reference) => reference.field === 'SLOT_CONTENT')\n ?.propertyId\n}\n\n/**\n * Whether this slot frame's children belong to its instance rather than its component: the\n * nearest enclosing instance assigns the slot. Such content is never synced from the component.\n */\nexport function ownsSlotContent(\n graph: SceneGraph,\n node: SceneNode,\n propertyId = slotPropertyId(node)\n): boolean {\n if (!propertyId) return false\n let owner = node.parentId ? graph.nodes.get(node.parentId) : undefined\n while (owner && owner.type !== 'INSTANCE')\n owner = owner.parentId ? graph.nodes.get(owner.parentId) : undefined\n return !!owner && Object.hasOwn(owner.componentPropertyAssignments, propertyId)\n}\n\n/** The name of a slot property as the instance's component (or the component's set) defines it. */\nfunction slotName(graph: SceneGraph, instance: SceneNode, propertyId: string) {\n const component = instanceMainComponent(graph, instance)\n const set = component?.parentId ? graph.nodes.get(component.parentId) : undefined\n return [component, set]\n .flatMap((node) => node?.componentPropertyDefinitions ?? [])\n .find((definition) => definition.id === propertyId && definition.type === 'SLOT')?.name\n}\n\n/** An instance's slot frames, without entering nested instances, whose slots are their own. */\nexport function instanceSlotFrames(graph: SceneGraph, instance: SceneNode): SceneNode[] {\n const frames: SceneNode[] = []\n const visit = (node: SceneNode): void => {\n for (const childId of node.childIds) {\n const child = graph.nodes.get(childId)\n if (!child) continue\n if (slotPropertyId(child)) frames.push(child)\n else if (child.type !== 'INSTANCE') visit(child)\n }\n }\n visit(instance)\n return frames\n}\n\n/** One slot's owned content, parked while the instance it belongs to is rebuilt. */\ninterface ParkedSlot {\n /** Names of the nested instances leading to the slot's owner; empty for the instance itself. */\n path: string[]\n /** The slot property's name, which the replacement must share. */\n name: string\n /** Content layer ids, in layer order. */\n content: string[]\n}\n\n/** Owned slot content parked under an instance while its component changes. */\nexport interface ParkedSlotContent {\n slots: ParkedSlot[]\n /** The instance's own slot assignments the content was parked from. */\n propertyIds: string[]\n}\n\n/** Instances directly inside this one: not inside another nested instance or a slot. */\nfunction nestedInstances(graph: SceneGraph, owner: SceneNode): SceneNode[] {\n const found: SceneNode[] = []\n const visit = (node: SceneNode): void => {\n for (const childId of node.childIds) {\n const child = graph.nodes.get(childId)\n if (!child || slotPropertyId(child)) continue\n if (child.type === 'INSTANCE') found.push(child)\n else visit(child)\n }\n }\n visit(owner)\n return found\n}\n\n/** The nested instance a name path leads to from `root`, matched by layer name as Figma does. */\nfunction instanceAtPath(\n graph: SceneGraph,\n root: SceneNode,\n path: readonly string[]\n): SceneNode | undefined {\n let current: SceneNode | undefined = root\n for (const name of path) {\n current = current && nestedInstances(graph, current).find((node) => node.name === name)\n }\n return current\n}\n\n/**\n * Park the slot content an instance and the instances nested in it own, by slot name and the\n * nested instance's name path, directly under the instance, so its component can be replaced.\n * Figma keeps that content when a variant switch or swap leads to slots of the same names.\n */\nexport function detachOwnedSlotContent(graph: SceneGraph, instance: SceneNode): ParkedSlotContent {\n const parked: ParkedSlotContent = { slots: [], propertyIds: [] }\n const visit = (owner: SceneNode, path: string[]): void => {\n for (const nested of nestedInstances(graph, owner)) visit(nested, [...path, nested.name])\n for (const frame of instanceSlotFrames(graph, owner)) {\n const propertyId = slotPropertyId(frame)\n if (!propertyId || !Object.hasOwn(owner.componentPropertyAssignments, propertyId)) continue\n if (owner.id === instance.id) parked.propertyIds.push(propertyId)\n const name = slotName(graph, owner, propertyId)\n const key = [...path, name].join('\\u0000')\n if (!name || parked.slots.some((slot) => [...slot.path, slot.name].join('\\u0000') === key))\n continue\n const content = [...frame.childIds]\n for (const id of content) graph.insertChildAt(id, instance.id, instance.childIds.length)\n parked.slots.push({ path, name, content })\n }\n }\n visit(instance, [])\n return parked\n}\n\n/** Move parked content into the slots of the same names and paths, and reassign them. */\nexport function restoreOwnedSlotContent(\n graph: SceneGraph,\n instance: SceneNode,\n parked: ParkedSlotContent\n): void {\n if (parked.slots.length === 0 && parked.propertyIds.length === 0) return\n graph.updateNode(instance.id, {\n componentPropertyAssignments: Object.fromEntries(\n Object.entries(instance.componentPropertyAssignments).filter(\n ([id]) => !parked.propertyIds.includes(id)\n )\n )\n })\n for (const slot of parked.slots) {\n const owner = instanceAtPath(graph, instance, slot.path)\n const frame =\n owner &&\n instanceSlotFrames(graph, owner).find((candidate) => {\n const propertyId = slotPropertyId(candidate)\n return !!propertyId && slotName(graph, owner, propertyId) === slot.name\n })\n const propertyId = frame && slotPropertyId(frame)\n if (\n !owner ||\n !frame ||\n !propertyId ||\n Object.hasOwn(owner.componentPropertyAssignments, propertyId)\n ) {\n for (const id of slot.content) graph.deleteNode(id)\n continue\n }\n for (const id of Array.from(frame.childIds)) graph.deleteNode(id)\n for (const [index, id] of slot.content.entries()) graph.insertChildAt(id, frame.id, index)\n graph.updateNode(owner.id, {\n componentPropertyAssignments: { ...owner.componentPropertyAssignments, [propertyId]: '' }\n })\n }\n}\n"],"mappings":";;;AAKA,SAAgB,eAAe,MAAqC;CAClE,OAAO,KAAK,4BAA4B,MAAM,cAAc,UAAU,UAAU,cAAc,CAAC,EAC3F;AACN;;;;;AAMA,SAAgB,gBACd,OACA,MACA,aAAa,eAAe,IAAI,GACvB;CACT,IAAI,CAAC,YAAY,OAAO;CACxB,IAAI,QAAQ,KAAK,WAAW,MAAM,MAAM,IAAI,KAAK,QAAQ,IAAI,KAAA;CAC7D,OAAO,SAAS,MAAM,SAAS,YAC7B,QAAQ,MAAM,WAAW,MAAM,MAAM,IAAI,MAAM,QAAQ,IAAI,KAAA;CAC7D,OAAO,CAAC,CAAC,SAAS,OAAO,OAAO,MAAM,8BAA8B,UAAU;AAChF;;AAGA,SAAS,SAAS,OAAmB,UAAqB,YAAoB;CAC5E,MAAM,YAAY,sBAAsB,OAAO,QAAQ;CAEvD,OAAO,CAAC,WADI,WAAW,WAAW,MAAM,MAAM,IAAI,UAAU,QAAQ,IAAI,KAAA,CAClD,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ACD,CAAC,cACD,OAAO,OAAO,MAAM,8BAA8B,UAAU,GAC5D;GACA,KAAK,MAAM,MAAM,KAAK,SAAS,MAAM,WAAW,EAAE;GAClD;EACF;EACA,KAAK,MAAM,MAAM,MAAM,KAAK,MAAM,QAAQ,GAAG,MAAM,WAAW,EAAE;EAChE,KAAK,MAAM,CAAC,OAAO,OAAO,KAAK,QAAQ,QAAQ,GAAG,MAAM,cAAc,IAAI,MAAM,IAAI,KAAK;EACzF,MAAM,WAAW,MAAM,IAAI,EACzB,8BAA8B;GAAE,GAAG,MAAM;IAA+B,aAAa;EAAG,EAC1F,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"frames.js","names":[],"sources":["../../src/slots/frames.ts"],"sourcesContent":["import type { SceneGraph } from '../graph'\nimport { instanceMainComponent } from '../instances/main-component'\nimport type { SceneNode } from '../types'\n\n/** The slot property a frame holds the content of, if it is a slot. */\nexport function slotPropertyId(node: SceneNode): string | undefined {\n return node.componentPropertyReferences.find((reference) => reference.field === 'SLOT_CONTENT')\n ?.propertyId\n}\n\n/**\n * Whether this slot frame's children belong to its instance rather than its component: the\n * nearest enclosing instance assigns the slot. Such content is never synced from the component.\n */\nexport function ownsSlotContent(\n graph: SceneGraph,\n node: SceneNode,\n propertyId = slotPropertyId(node)\n): boolean {\n if (!propertyId) return false\n let owner = node.parentId ? graph.nodes.get(node.parentId) : undefined\n while (owner && owner.type !== 'INSTANCE')\n owner = owner.parentId ? graph.nodes.get(owner.parentId) : undefined\n return !!owner && Object.hasOwn(owner.componentPropertyAssignments, propertyId)\n}\n\n/** The name of a slot property as the instance's component (or the component's set) defines it. */\nfunction slotName(graph: SceneGraph, instance: SceneNode, propertyId: string) {\n const component = instanceMainComponent(graph, instance)\n const set = component?.parentId ? graph.nodes.get(component.parentId) : undefined\n return [component, set]\n .flatMap((node) => node?.componentPropertyDefinitions ?? [])\n .find((definition) => definition.id === propertyId && definition.type === 'SLOT')?.name\n}\n\n/** An instance's slot frames, without entering nested instances, whose slots are their own. */\nexport function instanceSlotFrames(graph: SceneGraph, instance: SceneNode): SceneNode[] {\n const frames: SceneNode[] = []\n const visit = (node: SceneNode): void => {\n for (const childId of node.childIds) {\n const child = graph.nodes.get(childId)\n if (!child) continue\n if (slotPropertyId(child)) frames.push(child)\n else if (child.type !== 'INSTANCE') visit(child)\n }\n }\n visit(instance)\n return frames\n}\n\n/** One slot's owned content, parked while the instance it belongs to is rebuilt. */\ninterface ParkedSlot {\n /** Names of the nested instances leading to the slot's owner; empty for the instance itself. */\n path: string[]\n /** The slot property's name, which the replacement must share. */\n name: string\n /** Content layer ids, in layer order. */\n content: string[]\n ownerId: string\n propertyId: string\n}\n\n/** Owned slot content parked under an instance while its component changes. */\nexport interface ParkedSlotContent {\n slots: ParkedSlot[]\n /** The instance's own slot assignments the content was parked from. */\n propertyIds: string[]\n}\n\n/** Instances directly inside this one: not inside another nested instance or a slot. */\nfunction nestedInstances(graph: SceneGraph, owner: SceneNode): SceneNode[] {\n const found: SceneNode[] = []\n const visit = (node: SceneNode): void => {\n for (const childId of node.childIds) {\n const child = graph.nodes.get(childId)\n if (!child || slotPropertyId(child)) continue\n if (child.type === 'INSTANCE') found.push(child)\n else visit(child)\n }\n }\n visit(owner)\n return found\n}\n\n/** The nested instance a name path leads to from `root`, matched by layer name as Figma does. */\nfunction instanceAtPath(\n graph: SceneGraph,\n root: SceneNode,\n path: readonly string[]\n): SceneNode | undefined {\n let current: SceneNode | undefined = root\n for (const name of path) {\n current = current && nestedInstances(graph, current).find((node) => node.name === name)\n }\n return current\n}\n\n/**\n * Park the slot content an instance and the instances nested in it own, by slot name and the\n * nested instance's name path, directly under the instance, so its component can be replaced.\n * Figma keeps that content when a variant switch or swap leads to slots of the same names.\n */\nexport function detachOwnedSlotContent(graph: SceneGraph, instance: SceneNode): ParkedSlotContent {\n const parked: ParkedSlotContent = { slots: [], propertyIds: [] }\n const visit = (owner: SceneNode, path: string[]): void => {\n for (const nested of nestedInstances(graph, owner)) visit(nested, [...path, nested.name])\n for (const frame of instanceSlotFrames(graph, owner)) {\n const propertyId = slotPropertyId(frame)\n if (!propertyId || !Object.hasOwn(owner.componentPropertyAssignments, propertyId)) continue\n if (owner.id === instance.id) parked.propertyIds.push(propertyId)\n const name = slotName(graph, owner, propertyId)\n const key = [...path, name].join('\\u0000')\n if (!name || parked.slots.some((slot) => [...slot.path, slot.name].join('\\u0000') === key))\n continue\n const content = [...frame.childIds]\n for (const id of content) graph.insertChildAt(id, instance.id, instance.childIds.length)\n parked.slots.push({ path, name, content, ownerId: owner.id, propertyId })\n }\n }\n visit(instance, [])\n return parked\n}\n\nfunction assignsOtherContent(owner: SceneNode, propertyId: string, slot: ParkedSlot): boolean {\n const parkedFromHere = owner.id === slot.ownerId && propertyId === slot.propertyId\n return !parkedFromHere && Object.hasOwn(owner.componentPropertyAssignments, propertyId)\n}\n\n/** Move parked content into the slots of the same names and paths, and reassign them. */\nexport function restoreOwnedSlotContent(\n graph: SceneGraph,\n instance: SceneNode,\n parked: ParkedSlotContent\n): void {\n if (parked.slots.length === 0 && parked.propertyIds.length === 0) return\n graph.updateNode(instance.id, {\n componentPropertyAssignments: Object.fromEntries(\n Object.entries(instance.componentPropertyAssignments).filter(\n ([id]) => !parked.propertyIds.includes(id)\n )\n )\n })\n for (const slot of parked.slots) {\n const owner = instanceAtPath(graph, instance, slot.path)\n const frame =\n owner &&\n instanceSlotFrames(graph, owner).find((candidate) => {\n const propertyId = slotPropertyId(candidate)\n return !!propertyId && slotName(graph, owner, propertyId) === slot.name\n })\n const propertyId = frame && slotPropertyId(frame)\n if (!owner || !frame || !propertyId || assignsOtherContent(owner, propertyId, slot)) {\n for (const id of slot.content) graph.deleteNode(id)\n continue\n }\n for (const id of Array.from(frame.childIds)) graph.deleteNode(id)\n for (const [index, id] of slot.content.entries()) graph.insertChildAt(id, frame.id, index)\n graph.updateNode(owner.id, {\n componentPropertyAssignments: { ...owner.componentPropertyAssignments, [propertyId]: '' }\n })\n }\n}\n"],"mappings":";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_PARAGRAPH_SPACING_FIELDS, TextParagraphRange, hasParagraphSpacing, hasTextList, paragraphCount, paragraphIndexAt, paragraphSpacingAt, paragraphStyleAt, paragraphStylesAfterEdit, paragraphStylesAfterTextChange, paragraphStylesInRange, paragraphStylesWithoutSpacing, sharedParagraphSpacing, textParagraphRanges, trimParagraphStyles, withIndentation, withListType, withParagraphSpacing } from "./paragraphs.js";
2
2
  import { LIST_BULLET, ListNumberFormat, TextListItem, formatListNumber, listNumberFormat, textListItems, topLevelNumberDigits } from "./lists.js";
3
3
  import { StyleRunReferences, remapStyleRunReferences, styleRunReferences } from "./references.js";
4
- import { NO_LETTER_SPACING, formatTextLength, lineHeightPixels, percentLength, pixelLength, scaledTextLength, textLengthPixels } from "./lengths.js";
4
+ import { NO_LETTER_SPACING, formatTextLength, lineHeightPixels, lineStepPixels, percentLength, pixelLength, scaledTextLength, textLengthPixels } from "./lengths.js";
5
5
  import { textLinesOverflow } from "./overflow.js";
6
6
  import { textLengthSchema } from "./schema.js";
7
- export { LIST_BULLET, ListNumberFormat, MAX_LIST_INDENTATION, NO_LETTER_SPACING, PLAIN_PARAGRAPH, StyleRunReferences, TEXT_PARAGRAPH_SPACING_FIELDS, TextListItem, TextParagraphRange, formatListNumber, formatTextLength, hasParagraphSpacing, hasTextList, lineHeightPixels, listNumberFormat, paragraphCount, paragraphIndexAt, paragraphSpacingAt, paragraphStyleAt, paragraphStylesAfterEdit, paragraphStylesAfterTextChange, paragraphStylesInRange, paragraphStylesWithoutSpacing, percentLength, pixelLength, remapStyleRunReferences, scaledTextLength, sharedParagraphSpacing, styleRunReferences, textLengthPixels, textLengthSchema, textLinesOverflow, textListItems, textParagraphRanges, topLevelNumberDigits, trimParagraphStyles, withIndentation, withListType, withParagraphSpacing };
7
+ export { LIST_BULLET, ListNumberFormat, MAX_LIST_INDENTATION, NO_LETTER_SPACING, PLAIN_PARAGRAPH, StyleRunReferences, TEXT_PARAGRAPH_SPACING_FIELDS, TextListItem, TextParagraphRange, formatListNumber, formatTextLength, hasParagraphSpacing, hasTextList, lineHeightPixels, lineStepPixels, listNumberFormat, paragraphCount, paragraphIndexAt, paragraphSpacingAt, paragraphStyleAt, paragraphStylesAfterEdit, paragraphStylesAfterTextChange, paragraphStylesInRange, paragraphStylesWithoutSpacing, percentLength, pixelLength, remapStyleRunReferences, scaledTextLength, sharedParagraphSpacing, styleRunReferences, textLengthPixels, textLengthSchema, textLinesOverflow, textListItems, textParagraphRanges, topLevelNumberDigits, trimParagraphStyles, withIndentation, withListType, withParagraphSpacing };
@@ -1,7 +1,7 @@
1
- import { NO_LETTER_SPACING, formatTextLength, lineHeightPixels, percentLength, pixelLength, scaledTextLength, textLengthPixels } from "./lengths.js";
2
- import { textLinesOverflow } from "./overflow.js";
1
+ import { NO_LETTER_SPACING, formatTextLength, lineHeightPixels, lineStepPixels, percentLength, pixelLength, scaledTextLength, textLengthPixels } from "./lengths.js";
3
2
  import { remapStyleRunReferences, styleRunReferences } from "./references.js";
4
3
  import { MAX_LIST_INDENTATION, PLAIN_PARAGRAPH, TEXT_PARAGRAPH_SPACING_FIELDS, hasParagraphSpacing, hasTextList, paragraphCount, paragraphIndexAt, paragraphSpacingAt, paragraphStyleAt, paragraphStylesAfterEdit, paragraphStylesAfterTextChange, paragraphStylesInRange, paragraphStylesWithoutSpacing, sharedParagraphSpacing, textParagraphRanges, trimParagraphStyles, withIndentation, withListType, withParagraphSpacing } from "./paragraphs.js";
5
4
  import { LIST_BULLET, formatListNumber, listNumberFormat, textListItems, topLevelNumberDigits } from "./lists.js";
5
+ import { textLinesOverflow } from "./overflow.js";
6
6
  import { textLengthSchema } from "./schema.js";
7
- export { LIST_BULLET, MAX_LIST_INDENTATION, NO_LETTER_SPACING, PLAIN_PARAGRAPH, TEXT_PARAGRAPH_SPACING_FIELDS, formatListNumber, formatTextLength, hasParagraphSpacing, hasTextList, lineHeightPixels, listNumberFormat, paragraphCount, paragraphIndexAt, paragraphSpacingAt, paragraphStyleAt, paragraphStylesAfterEdit, paragraphStylesAfterTextChange, paragraphStylesInRange, paragraphStylesWithoutSpacing, percentLength, pixelLength, remapStyleRunReferences, scaledTextLength, sharedParagraphSpacing, styleRunReferences, textLengthPixels, textLengthSchema, textLinesOverflow, textListItems, textParagraphRanges, topLevelNumberDigits, trimParagraphStyles, withIndentation, withListType, withParagraphSpacing };
7
+ export { LIST_BULLET, MAX_LIST_INDENTATION, NO_LETTER_SPACING, PLAIN_PARAGRAPH, TEXT_PARAGRAPH_SPACING_FIELDS, formatListNumber, formatTextLength, hasParagraphSpacing, hasTextList, lineHeightPixels, lineStepPixels, listNumberFormat, paragraphCount, paragraphIndexAt, paragraphSpacingAt, paragraphStyleAt, paragraphStylesAfterEdit, paragraphStylesAfterTextChange, paragraphStylesInRange, paragraphStylesWithoutSpacing, percentLength, pixelLength, remapStyleRunReferences, scaledTextLength, sharedParagraphSpacing, styleRunReferences, textLengthPixels, textLengthSchema, textLinesOverflow, textListItems, textParagraphRanges, topLevelNumberDigits, trimParagraphStyles, withIndentation, withListType, withParagraphSpacing };
@@ -6,6 +6,11 @@ declare const NO_LETTER_SPACING: TextLength;
6
6
  declare function textLengthPixels(length: TextLength, fontSize: number): number;
7
7
  /** A line height in pixels at `fontSize`, or null when it is automatic. */
8
8
  declare function lineHeightPixels(lineHeight: TextLength | null, fontSize: number): number | null;
9
+ /**
10
+ * How far apart a line height sets lines at `fontSize`, as Figma steps them: a height in pixels
11
+ * as it is, a percent one to whole pixels (Figma desktop 126); null when it is automatic.
12
+ */
13
+ declare function lineStepPixels(lineHeight: TextLength | null, fontSize: number): number | null;
9
14
  /** A length in pixels, as a bound number variable and most authored formats give one. */
10
15
  declare function pixelLength(value: number): TextLength;
11
16
  /** A length as a percent of the font size. */
@@ -15,5 +20,5 @@ declare function scaledTextLength(length: TextLength, factor: number): TextLengt
15
20
  /** `length` as people read it: `24px` or `150%`. */
16
21
  declare function formatTextLength(length: TextLength): string;
17
22
  //#endregion
18
- export { NO_LETTER_SPACING, formatTextLength, lineHeightPixels, percentLength, pixelLength, scaledTextLength, textLengthPixels };
23
+ export { NO_LETTER_SPACING, formatTextLength, lineHeightPixels, lineStepPixels, percentLength, pixelLength, scaledTextLength, textLengthPixels };
19
24
  //# sourceMappingURL=lengths.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"lengths.d.ts","names":[],"sources":["../../src/text/lengths.ts"],"mappings":";;;cAGa,mBAAmB;;iBAGhB,iBAAiB,QAAQ,YAAY;;iBAKrC,iBAAiB,YAAY,mBAAmB;;iBAKhD,YAAY,gBAAgB;;iBAK5B,cAAc,gBAAgB;;iBAK9B,iBAAiB,QAAQ,YAAY,iBAAiB;;iBAKtD,iBAAiB,QAAQ"}
1
+ {"version":3,"file":"lengths.d.ts","names":[],"sources":["../../src/text/lengths.ts"],"mappings":";;;cAGa,mBAAmB;;iBAGhB,iBAAiB,QAAQ,YAAY;;iBAKrC,iBAAiB,YAAY,mBAAmB;;;;;iBAQhD,eAAe,YAAY,mBAAmB;;iBAO9C,YAAY,gBAAgB;;iBAK5B,cAAc,gBAAgB;;iBAK9B,iBAAiB,QAAQ,YAAY,iBAAiB;;iBAKtD,iBAAiB,QAAQ"}
@@ -12,6 +12,15 @@ function textLengthPixels(length, fontSize) {
12
12
  function lineHeightPixels(lineHeight, fontSize) {
13
13
  return lineHeight ? textLengthPixels(lineHeight, fontSize) : null;
14
14
  }
15
+ /**
16
+ * How far apart a line height sets lines at `fontSize`, as Figma steps them: a height in pixels
17
+ * as it is, a percent one to whole pixels (Figma desktop 126); null when it is automatic.
18
+ */
19
+ function lineStepPixels(lineHeight, fontSize) {
20
+ if (!lineHeight) return null;
21
+ const pixels = textLengthPixels(lineHeight, fontSize);
22
+ return lineHeight.unit === "PIXELS" ? pixels : Math.round(pixels);
23
+ }
15
24
  /** A length in pixels, as a bound number variable and most authored formats give one. */
16
25
  function pixelLength(value) {
17
26
  return {
@@ -35,6 +44,6 @@ function formatTextLength(length) {
35
44
  return length.unit === "PIXELS" ? `${length.value}px` : `${length.value}%`;
36
45
  }
37
46
  //#endregion
38
- export { NO_LETTER_SPACING, formatTextLength, lineHeightPixels, percentLength, pixelLength, scaledTextLength, textLengthPixels };
47
+ export { NO_LETTER_SPACING, formatTextLength, lineHeightPixels, lineStepPixels, percentLength, pixelLength, scaledTextLength, textLengthPixels };
39
48
 
40
49
  //# sourceMappingURL=lengths.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"lengths.js","names":[],"sources":["../../src/text/lengths.ts"],"sourcesContent":["import type { TextLength } from '../types'\n\n/** No letter spacing, as a new text has it and as Figma writes it. */\nexport const NO_LETTER_SPACING: TextLength = { value: 0, unit: 'PERCENT' }\n\n/** `length` in pixels at `fontSize`. */\nexport function textLengthPixels(length: TextLength, fontSize: number): number {\n return length.unit === 'PIXELS' ? length.value : (length.value / 100) * fontSize\n}\n\n/** A line height in pixels at `fontSize`, or null when it is automatic. */\nexport function lineHeightPixels(lineHeight: TextLength | null, fontSize: number): number | null {\n return lineHeight ? textLengthPixels(lineHeight, fontSize) : null\n}\n\n/** A length in pixels, as a bound number variable and most authored formats give one. */\nexport function pixelLength(value: number): TextLength {\n return { value, unit: 'PIXELS' }\n}\n\n/** A length as a percent of the font size. */\nexport function percentLength(value: number): TextLength {\n return { value, unit: 'PERCENT' }\n}\n\n/** `length` scaled by `factor`: pixels scale, a percent already follows the font size. */\nexport function scaledTextLength(length: TextLength, factor: number): TextLength {\n return length.unit === 'PIXELS' ? pixelLength(length.value * factor) : length\n}\n\n/** `length` as people read it: `24px` or `150%`. */\nexport function formatTextLength(length: TextLength): string {\n return length.unit === 'PIXELS' ? `${length.value}px` : `${length.value}%`\n}\n"],"mappings":";;AAGA,MAAa,oBAAgC;CAAE,OAAO;CAAG,MAAM;AAAU;;AAGzE,SAAgB,iBAAiB,QAAoB,UAA0B;CAC7E,OAAO,OAAO,SAAS,WAAW,OAAO,QAAS,OAAO,QAAQ,MAAO;AAC1E;;AAGA,SAAgB,iBAAiB,YAA+B,UAAiC;CAC/F,OAAO,aAAa,iBAAiB,YAAY,QAAQ,IAAI;AAC/D;;AAGA,SAAgB,YAAY,OAA2B;CACrD,OAAO;EAAE;EAAO,MAAM;CAAS;AACjC;;AAGA,SAAgB,cAAc,OAA2B;CACvD,OAAO;EAAE;EAAO,MAAM;CAAU;AAClC;;AAGA,SAAgB,iBAAiB,QAAoB,QAA4B;CAC/E,OAAO,OAAO,SAAS,WAAW,YAAY,OAAO,QAAQ,MAAM,IAAI;AACzE;;AAGA,SAAgB,iBAAiB,QAA4B;CAC3D,OAAO,OAAO,SAAS,WAAW,GAAG,OAAO,MAAM,MAAM,GAAG,OAAO,MAAM;AAC1E"}
1
+ {"version":3,"file":"lengths.js","names":[],"sources":["../../src/text/lengths.ts"],"sourcesContent":["import type { TextLength } from '../types'\n\n/** No letter spacing, as a new text has it and as Figma writes it. */\nexport const NO_LETTER_SPACING: TextLength = { value: 0, unit: 'PERCENT' }\n\n/** `length` in pixels at `fontSize`. */\nexport function textLengthPixels(length: TextLength, fontSize: number): number {\n return length.unit === 'PIXELS' ? length.value : (length.value / 100) * fontSize\n}\n\n/** A line height in pixels at `fontSize`, or null when it is automatic. */\nexport function lineHeightPixels(lineHeight: TextLength | null, fontSize: number): number | null {\n return lineHeight ? textLengthPixels(lineHeight, fontSize) : null\n}\n\n/**\n * How far apart a line height sets lines at `fontSize`, as Figma steps them: a height in pixels\n * as it is, a percent one to whole pixels (Figma desktop 126); null when it is automatic.\n */\nexport function lineStepPixels(lineHeight: TextLength | null, fontSize: number): number | null {\n if (!lineHeight) return null\n const pixels = textLengthPixels(lineHeight, fontSize)\n return lineHeight.unit === 'PIXELS' ? pixels : Math.round(pixels)\n}\n\n/** A length in pixels, as a bound number variable and most authored formats give one. */\nexport function pixelLength(value: number): TextLength {\n return { value, unit: 'PIXELS' }\n}\n\n/** A length as a percent of the font size. */\nexport function percentLength(value: number): TextLength {\n return { value, unit: 'PERCENT' }\n}\n\n/** `length` scaled by `factor`: pixels scale, a percent already follows the font size. */\nexport function scaledTextLength(length: TextLength, factor: number): TextLength {\n return length.unit === 'PIXELS' ? pixelLength(length.value * factor) : length\n}\n\n/** `length` as people read it: `24px` or `150%`. */\nexport function formatTextLength(length: TextLength): string {\n return length.unit === 'PIXELS' ? `${length.value}px` : `${length.value}%`\n}\n"],"mappings":";;AAGA,MAAa,oBAAgC;CAAE,OAAO;CAAG,MAAM;AAAU;;AAGzE,SAAgB,iBAAiB,QAAoB,UAA0B;CAC7E,OAAO,OAAO,SAAS,WAAW,OAAO,QAAS,OAAO,QAAQ,MAAO;AAC1E;;AAGA,SAAgB,iBAAiB,YAA+B,UAAiC;CAC/F,OAAO,aAAa,iBAAiB,YAAY,QAAQ,IAAI;AAC/D;;;;;AAMA,SAAgB,eAAe,YAA+B,UAAiC;CAC7F,IAAI,CAAC,YAAY,OAAO;CACxB,MAAM,SAAS,iBAAiB,YAAY,QAAQ;CACpD,OAAO,WAAW,SAAS,WAAW,SAAS,KAAK,MAAM,MAAM;AAClE;;AAGA,SAAgB,YAAY,OAA2B;CACrD,OAAO;EAAE;EAAO,MAAM;CAAS;AACjC;;AAGA,SAAgB,cAAc,OAA2B;CACvD,OAAO;EAAE;EAAO,MAAM;CAAU;AAClC;;AAGA,SAAgB,iBAAiB,QAAoB,QAA4B;CAC/E,OAAO,OAAO,SAAS,WAAW,YAAY,OAAO,QAAQ,MAAM,IAAI;AACzE;;AAGA,SAAgB,iBAAiB,QAA4B;CAC3D,OAAO,OAAO,SAAS,WAAW,GAAG,OAAO,MAAM,MAAM,GAAG,OAAO,MAAM;AAC1E"}
@@ -1,6 +1,6 @@
1
- import { VisualBoundsNode } from "../geometry.js";
1
+ import { SceneNode } from "../types.js";
2
2
  //#region src/text/overflow.d.ts
3
- type TextBoundsNode = Pick<VisualBoundsNode, 'type' | 'height' | 'derivedTextHeight'>;
3
+ type TextBoundsNode = Pick<SceneNode, 'type' | 'height' | 'derivedTextHeight'>;
4
4
  /**
5
5
  * How far a text's lines reach below its box: a fixed-size box does not clip them, as in Figma,
6
6
  * and the renderer starts them at its top.
@@ -1 +1 @@
1
- {"version":3,"file":"overflow.js","names":[],"sources":["../../src/text/overflow.ts"],"sourcesContent":["import type { VisualBoundsNode } from '../geometry'\n\ntype TextBoundsNode = Pick<VisualBoundsNode, 'type' | 'height' | 'derivedTextHeight'>\n\n/**\n * How far a text's lines reach below its box: a fixed-size box does not clip them, as in Figma,\n * and the renderer starts them at its top.\n */\nexport function textLinesOverflow(node: TextBoundsNode): number {\n if (node.type !== 'TEXT' || !node.derivedTextHeight) return 0\n return Math.max(0, node.derivedTextHeight - node.height)\n}\n"],"mappings":";;;;;AAQA,SAAgB,kBAAkB,MAA8B;CAC9D,IAAI,KAAK,SAAS,UAAU,CAAC,KAAK,mBAAmB,OAAO;CAC5D,OAAO,KAAK,IAAI,GAAG,KAAK,oBAAoB,KAAK,MAAM;AACzD"}
1
+ {"version":3,"file":"overflow.js","names":[],"sources":["../../src/text/overflow.ts"],"sourcesContent":["import type { SceneNode } from '../types'\n\ntype TextBoundsNode = Pick<SceneNode, 'type' | 'height' | 'derivedTextHeight'>\n\n/**\n * How far a text's lines reach below its box: a fixed-size box does not clip them, as in Figma,\n * and the renderer starts them at its top.\n */\nexport function textLinesOverflow(node: TextBoundsNode): number {\n if (node.type !== 'TEXT' || !node.derivedTextHeight) return 0\n return Math.max(0, node.derivedTextHeight - node.height)\n}\n"],"mappings":";;;;;AAQA,SAAgB,kBAAkB,MAA8B;CAC9D,IAAI,KAAK,SAAS,UAAU,CAAC,KAAK,mBAAmB,OAAO;CAC5D,OAAO,KAAK,IAAI,GAAG,KAAK,oBAAoB,KAAK,MAAM;AACzD"}
@@ -12,7 +12,6 @@ declare const GLYPH_AFFECTING_KEYS: ReadonlySet<string>;
12
12
  * replaces them in the same update (resize supplies scaled copies).
13
13
  */
14
14
  declare function textCacheInvalidationChanges(node: SceneNode, changes: Partial<SceneNode>): Partial<SceneNode>;
15
- declare function invalidateTextCaches(node: SceneNode, changes: Partial<SceneNode>): void;
16
15
  //#endregion
17
- export { GLYPH_AFFECTING_KEYS, TEXT_PICTURE_KEYS, invalidateTextCaches, textCacheInvalidationChanges };
16
+ export { GLYPH_AFFECTING_KEYS, TEXT_PICTURE_KEYS, textCacheInvalidationChanges };
18
17
  //# sourceMappingURL=picture.d.ts.map