@pairdraw/core 0.16.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/canvas/rulers.js +1 -1
  2. package/dist/canvas/rulers.js.map +1 -1
  3. package/dist/clipboard/pairdraw.d.ts.map +1 -1
  4. package/dist/clipboard/pairdraw.js +53 -7
  5. package/dist/clipboard/pairdraw.js.map +1 -1
  6. package/dist/design-jsx/preview/picture.js +6 -1
  7. package/dist/design-jsx/preview/picture.js.map +1 -1
  8. package/dist/editor/alignment.d.ts.map +1 -1
  9. package/dist/editor/alignment.js +35 -27
  10. package/dist/editor/alignment.js.map +1 -1
  11. package/dist/editor/clipboard/detach.d.ts.map +1 -1
  12. package/dist/editor/clipboard/detach.js +3 -3
  13. package/dist/editor/clipboard/detach.js.map +1 -1
  14. package/dist/editor/clipboard/paste/properties.d.ts.map +1 -1
  15. package/dist/editor/clipboard/paste/properties.js +3 -1
  16. package/dist/editor/clipboard/paste/properties.js.map +1 -1
  17. package/dist/editor/structure.d.ts.map +1 -1
  18. package/dist/editor/structure.js +3 -1
  19. package/dist/editor/structure.js.map +1 -1
  20. package/dist/editor/viewport.js +2 -2
  21. package/dist/editor/viewport.js.map +1 -1
  22. package/dist/figma-api/text/bindings.d.ts.map +1 -1
  23. package/dist/figma-api/text/bindings.js +20 -8
  24. package/dist/figma-api/text/bindings.js.map +1 -1
  25. package/dist/figma-api/text/index.js +1 -1
  26. package/dist/io/formats/design-tokens/apply.d.ts +1 -1
  27. package/dist/io/formats.d.ts.map +1 -1
  28. package/dist/io/formats.js +3 -5
  29. package/dist/io/formats.js.map +1 -1
  30. package/dist/text/character-style.d.ts.map +1 -1
  31. package/dist/text/character-style.js +2 -1
  32. package/dist/text/character-style.js.map +1 -1
  33. package/dist/text/index.js +1 -1
  34. package/dist/tools/read/libraries.d.ts.map +1 -1
  35. package/dist/tools/read/libraries.js +5 -5
  36. package/dist/tools/read/libraries.js.map +1 -1
  37. package/package.json +9 -9
  38. package/src/canvas/rulers.ts +1 -1
  39. package/src/clipboard/pairdraw.ts +51 -7
  40. package/src/design-jsx/preview/picture.ts +8 -2
  41. package/src/editor/alignment.ts +33 -29
  42. package/src/editor/clipboard/detach.ts +9 -3
  43. package/src/editor/clipboard/paste/properties.ts +3 -1
  44. package/src/editor/structure.ts +3 -1
  45. package/src/editor/viewport.ts +2 -2
  46. package/src/figma-api/text/bindings.ts +26 -8
  47. package/src/io/formats.ts +5 -9
  48. package/src/text/character-style.ts +8 -4
  49. package/src/tools/read/libraries.ts +15 -8
@@ -1 +1 @@
1
- {"version":3,"file":"character-style.js","names":[],"sources":["../../src/text/character-style.ts"],"sourcesContent":["import { omit, pick } from 'es-toolkit/object'\nimport { isEqual } from 'es-toolkit/predicate'\n\nimport {\n TEXT_BINDABLE_FIELDS,\n type CharacterStyleOverride,\n type HyperlinkTarget,\n type SceneNode,\n type StyleRun,\n type TextBoundVariables,\n type TextLength\n} from '@pairdraw/scene-graph'\nimport {\n FACE_KEYS,\n rangeFontStyle,\n SHARED_TEXT_STYLE_FIELDS,\n styleDetachmentChanges\n} from '@pairdraw/scene-graph/shared-styles'\n\n/** A character's style: the text's own, with its run's overrides over it. */\nexport type CharacterStyle = Required<\n Pick<\n CharacterStyleOverride,\n | 'fontFamily'\n | 'fontWeight'\n | 'italic'\n | 'fontSize'\n | 'letterSpacing'\n | 'fills'\n | 'textDecoration'\n | 'textDecorationStyle'\n | 'textDecorationFills'\n | 'textDecorationSkipInk'\n | 'fontFeatures'\n | 'fontVariations'\n | 'opticalSizeFromFontSize'\n | 'textCase'\n >\n> & {\n fontStyle: string | null\n lineHeight: TextLength | null\n textDecorationThickness: number | null\n textUnderlineOffset: number | null\n hyperlink: HyperlinkTarget | null\n textStyleId: string | null\n fillStyleId: string | null\n boundVariables: TextBoundVariables\n}\n\nexport type TextStyleKey = (typeof TEXT_STYLE_KEYS)[number]\n\nexport const TEXT_STYLE_KEYS = [\n 'fontFamily',\n 'fontWeight',\n 'italic',\n 'fontStyle',\n 'fontSize',\n 'letterSpacing',\n 'lineHeight',\n 'fills',\n 'textDecoration',\n 'textDecorationStyle',\n 'textDecorationThickness',\n 'textDecorationFills',\n 'textDecorationSkipInk',\n 'textUnderlineOffset',\n 'fontFeatures',\n 'fontVariations',\n 'opticalSizeFromFontSize',\n 'textCase'\n] as const satisfies readonly (keyof CharacterStyle)[]\n\n/**\n * What a range of characters can hold that is not a style of the text's own: a link, the\n * styles it uses, and its bindings. The text's styles and bindings are what ranges start from.\n */\nconst RANGE_STYLE_KEYS = ['hyperlink', 'textStyleId', 'fillStyleId', 'boundVariables'] as const\n\n/** Every field a character's style has, as runs override it. */\nexport const CHARACTER_STYLE_KEYS = [\n ...TEXT_STYLE_KEYS,\n ...RANGE_STYLE_KEYS\n] as const satisfies readonly (keyof CharacterStyle)[]\n\nexport function nodeStyle(node: SceneNode): CharacterStyle {\n return {\n fontFamily: node.fontFamily,\n fontWeight: node.fontWeight,\n italic: node.italic,\n fontStyle: node.fontStyle,\n fontSize: node.fontSize,\n letterSpacing: node.letterSpacing,\n lineHeight: node.lineHeight,\n fills: node.fills,\n textDecoration: node.textDecoration,\n textDecorationStyle: node.textDecorationStyle,\n textDecorationThickness: node.textDecorationThickness,\n textDecorationFills: node.textDecorationFills,\n textDecorationSkipInk: node.textDecorationSkipInk,\n textUnderlineOffset: node.textUnderlineOffset,\n fontFeatures: node.fontFeatures,\n fontVariations: node.fontVariations,\n opticalSizeFromFontSize: node.opticalSizeFromFontSize,\n textCase: node.textCase,\n hyperlink: null,\n textStyleId: node.textStyleId,\n fillStyleId: node.fillStyleId,\n boundVariables: pick(node.boundVariables, TEXT_BINDABLE_FIELDS)\n }\n}\n\n/** Every character's style, from the text's own and the runs over it. */\nexport function characterStyles(node: SceneNode, start: number, end: number): CharacterStyle[] {\n const base = nodeStyle(node)\n const styles = Array.from({ length: end - start }, () => base)\n for (const run of node.styleRuns) {\n const from = Math.max(start, run.start)\n const to = Math.min(end, run.start + run.length)\n for (let index = from; index < to; index++) {\n styles[index - start] = {\n ...styles[index - start],\n ...definedOverrides(run.style),\n fontStyle: rangeFontStyle(node, run.style)\n }\n }\n }\n return styles\n}\n\nfunction definedOverrides(style: CharacterStyleOverride): Partial<CharacterStyle> {\n const defined: Partial<Record<keyof CharacterStyle, unknown>> = {}\n for (const key of CHARACTER_STYLE_KEYS) {\n if (style[key] !== undefined) defined[key] = style[key]\n }\n return defined as Partial<CharacterStyle>\n}\n\n/** Style runs with no override that only repeats the text's own value. */\nfunction withoutRedundantOverrides(node: SceneNode, runs: StyleRun[]): StyleRun[] {\n const base = nodeStyle(node)\n const result: StyleRun[] = []\n for (const run of runs) {\n const style = omit(\n run.style,\n CHARACTER_STYLE_KEYS.filter(\n (key) => run.style[key] !== undefined && isEqual(run.style[key], base[key])\n )\n )\n if (Object.keys(style).length === 0) continue\n const previous = result.at(-1)\n if (\n previous &&\n previous.start + previous.length === run.start &&\n isEqual(previous.style, style)\n ) {\n previous.length += run.length\n } else {\n result.push({ start: run.start, length: run.length, style })\n }\n }\n return result\n}\n\n/**\n * A style for a range, or one per font size for a length given in percent of the font size,\n * which characters of each size resolve to their own length.\n */\nexport type TextStylePatch = CharacterStyleOverride | ((fontSize: number) => CharacterStyleOverride)\n\n/**\n * The styles characters leave when `style` changes what a style gave them, as a text leaves its\n * own: a font size leaves the text style, and fills leave the fill style.\n */\nfunction detachedStyles(\n node: SceneNode,\n current: CharacterStyleOverride,\n style: CharacterStyleOverride | undefined\n): CharacterStyleOverride {\n if (!style) return {}\n const styled = { ...node, ...current }\n const changes = pick(style, [...TEXT_STYLE_KEYS, 'fills', 'textStyleId', 'fillStyleId'])\n const detached = styleDetachmentChanges(styled, changes)\n return pick(\n detached,\n (['textStyleId', 'fillStyleId', 'fontStyle'] as const).filter(\n (key) => !Object.hasOwn(changes, key) && Object.hasOwn(detached, key)\n )\n )\n}\n\n/** Style runs with `patch` over `text[start, end)`, as Figma restyles a range. */\nexport function styleRunsWithPatch(\n node: SceneNode,\n start: number,\n end: number,\n patch: TextStylePatch\n): StyleRun[] {\n const length = node.text.length\n const chars: CharacterStyleOverride[] = Array.from({ length }, () => ({}))\n for (const run of node.styleRuns) {\n for (let index = run.start; index < run.start + run.length && index < length; index++) {\n chars[index] = { ...chars[index], ...run.style }\n }\n }\n const sized = typeof patch === 'function' ? patch : null\n const patches = new Map<number, CharacterStyleOverride>()\n for (let index = start; index < end; index++) {\n let style = sized ? undefined : (patch as CharacterStyleOverride)\n if (sized) {\n const fontSize = chars[index].fontSize ?? node.fontSize\n style = patches.get(fontSize) ?? sized(fontSize)\n patches.set(fontSize, style)\n }\n chars[index] = { ...chars[index], ...style, ...detachedStyles(node, chars[index], style) }\n }\n // A newline takes the style of the character before it, as in Figma: a range that ends a\n // paragraph styles its newline too, and a newline cannot be styled on its own.\n for (let index = 1; index < length; index++) {\n if (node.text[index] === '\\n') chars[index] = chars[index - 1]\n }\n const runs: StyleRun[] = []\n for (const [index, style] of chars.entries()) {\n const previous = runs.at(-1)\n if (previous && isEqual(previous.style, style)) previous.length++\n else runs.push({ start: index, length: 1, style })\n }\n return withoutRedundantOverrides(\n node,\n runs.filter((run) => Object.keys(run.style).length > 0)\n )\n}\n\n/**\n * The change that sets a style for the whole text, as Figma's node setters do: the text takes\n * the value and no range keeps one of its own.\n */\nexport function textStyleChanges(\n node: SceneNode,\n changes: Partial<Pick<SceneNode, TextStyleKey | 'textStyleId' | 'fillStyleId'>>,\n sized?: (fontSize: number) => CharacterStyleOverride\n): Partial<SceneNode> {\n const changed = Object.keys(changes) as (keyof CharacterStyleOverride)[]\n // A style a range keeps no longer gives it what the whole text now sets.\n const keys = [\n ...changed,\n ...(changed.some((key) => (SHARED_TEXT_STYLE_FIELDS as readonly string[]).includes(key))\n ? (['textStyleId'] as const)\n : []),\n ...(changed.includes('fills') ? (['fillStyleId'] as const) : []),\n // A range's face name names none once the text's face changes under it.\n ...(changed.some((key) => (FACE_KEYS as readonly string[]).includes(key))\n ? (['fontStyle'] as const)\n : [])\n ]\n const runs = node.styleRuns.map((run) => ({ ...run, style: omit(run.style, keys) }))\n const updated = { ...node, ...changes }\n const styleRuns = withoutRedundantOverrides(updated, runs)\n // A percent gives characters of another size their own length.\n if (!sized) return { ...changes, styleRuns }\n return {\n ...changes,\n styleRuns: styleRunsWithPatch({ ...updated, styleRuns }, 0, node.text.length, sized)\n }\n}\n"],"mappings":";;;;;AAmDA,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAMA,MAAM,mBAAmB;CAAC;CAAa;CAAe;CAAe;AAAgB;;AAGrF,MAAa,uBAAuB,CAClC,GAAG,iBACH,GAAG,gBACL;AAEA,SAAgB,UAAU,MAAiC;CACzD,OAAO;EACL,YAAY,KAAK;EACjB,YAAY,KAAK;EACjB,QAAQ,KAAK;EACb,WAAW,KAAK;EAChB,UAAU,KAAK;EACf,eAAe,KAAK;EACpB,YAAY,KAAK;EACjB,OAAO,KAAK;EACZ,gBAAgB,KAAK;EACrB,qBAAqB,KAAK;EAC1B,yBAAyB,KAAK;EAC9B,qBAAqB,KAAK;EAC1B,uBAAuB,KAAK;EAC5B,qBAAqB,KAAK;EAC1B,cAAc,KAAK;EACnB,gBAAgB,KAAK;EACrB,yBAAyB,KAAK;EAC9B,UAAU,KAAK;EACf,WAAW;EACX,aAAa,KAAK;EAClB,aAAa,KAAK;EAClB,gBAAgB,KAAK,KAAK,gBAAgB,oBAAoB;CAChE;AACF;;AAGA,SAAgB,gBAAgB,MAAiB,OAAe,KAA+B;CAC7F,MAAM,OAAO,UAAU,IAAI;CAC3B,MAAM,SAAS,MAAM,KAAK,EAAE,QAAQ,MAAM,MAAM,SAAS,IAAI;CAC7D,KAAK,MAAM,OAAO,KAAK,WAAW;EAChC,MAAM,OAAO,KAAK,IAAI,OAAO,IAAI,KAAK;EACtC,MAA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AQ,OAAO,KAAK,IAAI,KAAK,CAAC,CAAC,SAAS,CAAC,CACxD;AACF;;;;;AAMA,SAAgB,iBACd,MACA,SACA,OACoB;CACpB,MAAM,UAAU,OAAO,KAAK,OAAO;CAEnC,MAAM,OAAO;EACX,GAAG;EACH,GAAI,QAAQ,MAAM,QAAS,yBAA+C,SAAS,GAAG,CAAC,IAClF,CAAC,aAAa,IACf,CAAC;EACL,GAAI,QAAQ,SAAS,OAAO,IAAK,CAAC,aAAa,IAAc,CAAC;EAE9D,GAAI,QAAQ,MAAM,QAAS,UAAgC,SAAS,GAAG,CAAC,IACnE,CAAC,WAAW,IACb,CAAC;CACP;CACA,MAAM,OAAO,KAAK,UAAU,KAAK,SAAS;EAAE,GAAG;EAAK,OAAO,KAAK,IAAI,OAAO,IAAI;CAAE,EAAE;CACnF,MAAM,UAAU;EAAE,GAAG;EAAM,GAAG;CAAQ;CACtC,MAAM,YAAY,0BAA0B,SAAS,IAAI;CAEzD,IAAI,CAAC,OAAO,OAAO;EAAE,GAAG;EAAS;CAAU;CAC3C,OAAO;EACL,GAAG;EACH,WAAW,mBAAmB;GAAE,GAAG;GAAS;EAAU,GAAG,GAAG,KAAK,KAAK,QAAQ,KAAK;CACrF;AACF"}
1
+ {"version":3,"file":"character-style.js","names":[],"sources":["../../src/text/character-style.ts"],"sourcesContent":["import { omit, pick } from 'es-toolkit/object'\nimport { isEqual } from 'es-toolkit/predicate'\n\nimport {\n TEXT_BINDABLE_FIELDS,\n type CharacterStyleOverride,\n type HyperlinkTarget,\n type SceneNode,\n type StyleRun,\n type TextBoundVariables,\n type TextLength\n} from '@pairdraw/scene-graph'\nimport {\n FACE_KEYS,\n rangeFontStyle,\n SHARED_TEXT_STYLE_FIELDS,\n styleDetachmentChanges\n} from '@pairdraw/scene-graph/shared-styles'\nimport { withBoundBindingScales } from '@pairdraw/scene-graph/variables'\n\n/** A character's style: the text's own, with its run's overrides over it. */\nexport type CharacterStyle = Required<\n Pick<\n CharacterStyleOverride,\n | 'fontFamily'\n | 'fontWeight'\n | 'italic'\n | 'fontSize'\n | 'letterSpacing'\n | 'fills'\n | 'textDecoration'\n | 'textDecorationStyle'\n | 'textDecorationFills'\n | 'textDecorationSkipInk'\n | 'fontFeatures'\n | 'fontVariations'\n | 'opticalSizeFromFontSize'\n | 'textCase'\n >\n> & {\n fontStyle: string | null\n lineHeight: TextLength | null\n textDecorationThickness: number | null\n textUnderlineOffset: number | null\n hyperlink: HyperlinkTarget | null\n textStyleId: string | null\n fillStyleId: string | null\n boundVariables: TextBoundVariables\n}\n\nexport type TextStyleKey = (typeof TEXT_STYLE_KEYS)[number]\n\nexport const TEXT_STYLE_KEYS = [\n 'fontFamily',\n 'fontWeight',\n 'italic',\n 'fontStyle',\n 'fontSize',\n 'letterSpacing',\n 'lineHeight',\n 'fills',\n 'textDecoration',\n 'textDecorationStyle',\n 'textDecorationThickness',\n 'textDecorationFills',\n 'textDecorationSkipInk',\n 'textUnderlineOffset',\n 'fontFeatures',\n 'fontVariations',\n 'opticalSizeFromFontSize',\n 'textCase'\n] as const satisfies readonly (keyof CharacterStyle)[]\n\n/**\n * What a range of characters can hold that is not a style of the text's own: a link, the\n * styles it uses, and its bindings. The text's styles and bindings are what ranges start from.\n */\nconst RANGE_STYLE_KEYS = ['hyperlink', 'textStyleId', 'fillStyleId', 'boundVariables'] as const\n\n/** Every field a character's style has, as runs override it. */\nexport const CHARACTER_STYLE_KEYS = [\n ...TEXT_STYLE_KEYS,\n ...RANGE_STYLE_KEYS\n] as const satisfies readonly (keyof CharacterStyle)[]\n\nexport function nodeStyle(node: SceneNode): CharacterStyle {\n return {\n fontFamily: node.fontFamily,\n fontWeight: node.fontWeight,\n italic: node.italic,\n fontStyle: node.fontStyle,\n fontSize: node.fontSize,\n letterSpacing: node.letterSpacing,\n lineHeight: node.lineHeight,\n fills: node.fills,\n textDecoration: node.textDecoration,\n textDecorationStyle: node.textDecorationStyle,\n textDecorationThickness: node.textDecorationThickness,\n textDecorationFills: node.textDecorationFills,\n textDecorationSkipInk: node.textDecorationSkipInk,\n textUnderlineOffset: node.textUnderlineOffset,\n fontFeatures: node.fontFeatures,\n fontVariations: node.fontVariations,\n opticalSizeFromFontSize: node.opticalSizeFromFontSize,\n textCase: node.textCase,\n hyperlink: null,\n textStyleId: node.textStyleId,\n fillStyleId: node.fillStyleId,\n boundVariables: pick(node.boundVariables, TEXT_BINDABLE_FIELDS)\n }\n}\n\n/** Every character's style, from the text's own and the runs over it. */\nexport function characterStyles(node: SceneNode, start: number, end: number): CharacterStyle[] {\n const base = nodeStyle(node)\n const styles = Array.from({ length: end - start }, () => base)\n for (const run of node.styleRuns) {\n const from = Math.max(start, run.start)\n const to = Math.min(end, run.start + run.length)\n for (let index = from; index < to; index++) {\n styles[index - start] = {\n ...styles[index - start],\n ...definedOverrides(run.style),\n fontStyle: rangeFontStyle(node, run.style)\n }\n }\n }\n return styles\n}\n\nfunction definedOverrides(style: CharacterStyleOverride): Partial<CharacterStyle> {\n const defined: Partial<Record<keyof CharacterStyle, unknown>> = {}\n for (const key of CHARACTER_STYLE_KEYS) {\n if (style[key] !== undefined) defined[key] = style[key]\n }\n return defined as Partial<CharacterStyle>\n}\n\n/** Style runs with no override that only repeats the text's own value. */\nfunction withoutRedundantOverrides(node: SceneNode, runs: StyleRun[]): StyleRun[] {\n const base = nodeStyle(node)\n const result: StyleRun[] = []\n for (const run of runs) {\n // A range keeps a binding's scale only while it binds the number itself.\n const style = withBoundBindingScales(\n omit(\n run.style,\n CHARACTER_STYLE_KEYS.filter(\n (key) => run.style[key] !== undefined && isEqual(run.style[key], base[key])\n )\n )\n )\n if (Object.keys(style).length === 0) continue\n const previous = result.at(-1)\n if (\n previous &&\n previous.start + previous.length === run.start &&\n isEqual(previous.style, style)\n ) {\n previous.length += run.length\n } else {\n result.push({ start: run.start, length: run.length, style })\n }\n }\n return result\n}\n\n/**\n * A style for a range, or one per font size for a length given in percent of the font size,\n * which characters of each size resolve to their own length.\n */\nexport type TextStylePatch = CharacterStyleOverride | ((fontSize: number) => CharacterStyleOverride)\n\n/**\n * The styles characters leave when `style` changes what a style gave them, as a text leaves its\n * own: a font size leaves the text style, and fills leave the fill style.\n */\nfunction detachedStyles(\n node: SceneNode,\n current: CharacterStyleOverride,\n style: CharacterStyleOverride | undefined\n): CharacterStyleOverride {\n if (!style) return {}\n const styled = { ...node, ...current }\n const changes = pick(style, [...TEXT_STYLE_KEYS, 'fills', 'textStyleId', 'fillStyleId'])\n const detached = styleDetachmentChanges(styled, changes)\n return pick(\n detached,\n (['textStyleId', 'fillStyleId', 'fontStyle'] as const).filter(\n (key) => !Object.hasOwn(changes, key) && Object.hasOwn(detached, key)\n )\n )\n}\n\n/** Style runs with `patch` over `text[start, end)`, as Figma restyles a range. */\nexport function styleRunsWithPatch(\n node: SceneNode,\n start: number,\n end: number,\n patch: TextStylePatch\n): StyleRun[] {\n const length = node.text.length\n const chars: CharacterStyleOverride[] = Array.from({ length }, () => ({}))\n for (const run of node.styleRuns) {\n for (let index = run.start; index < run.start + run.length && index < length; index++) {\n chars[index] = { ...chars[index], ...run.style }\n }\n }\n const sized = typeof patch === 'function' ? patch : null\n const patches = new Map<number, CharacterStyleOverride>()\n for (let index = start; index < end; index++) {\n let style = sized ? undefined : (patch as CharacterStyleOverride)\n if (sized) {\n const fontSize = chars[index].fontSize ?? node.fontSize\n style = patches.get(fontSize) ?? sized(fontSize)\n patches.set(fontSize, style)\n }\n chars[index] = { ...chars[index], ...style, ...detachedStyles(node, chars[index], style) }\n }\n // A newline takes the style of the character before it, as in Figma: a range that ends a\n // paragraph styles its newline too, and a newline cannot be styled on its own.\n for (let index = 1; index < length; index++) {\n if (node.text[index] === '\\n') chars[index] = chars[index - 1]\n }\n const runs: StyleRun[] = []\n for (const [index, style] of chars.entries()) {\n const previous = runs.at(-1)\n if (previous && isEqual(previous.style, style)) previous.length++\n else runs.push({ start: index, length: 1, style })\n }\n return withoutRedundantOverrides(\n node,\n runs.filter((run) => Object.keys(run.style).length > 0)\n )\n}\n\n/**\n * The change that sets a style for the whole text, as Figma's node setters do: the text takes\n * the value and no range keeps one of its own.\n */\nexport function textStyleChanges(\n node: SceneNode,\n changes: Partial<Pick<SceneNode, TextStyleKey | 'textStyleId' | 'fillStyleId'>>,\n sized?: (fontSize: number) => CharacterStyleOverride\n): Partial<SceneNode> {\n const changed = Object.keys(changes) as (keyof CharacterStyleOverride)[]\n // A style a range keeps no longer gives it what the whole text now sets.\n const keys = [\n ...changed,\n ...(changed.some((key) => (SHARED_TEXT_STYLE_FIELDS as readonly string[]).includes(key))\n ? (['textStyleId'] as const)\n : []),\n ...(changed.includes('fills') ? (['fillStyleId'] as const) : []),\n // A range's face name names none once the text's face changes under it.\n ...(changed.some((key) => (FACE_KEYS as readonly string[]).includes(key))\n ? (['fontStyle'] as const)\n : [])\n ]\n const runs = node.styleRuns.map((run) => ({ ...run, style: omit(run.style, keys) }))\n const updated = { ...node, ...changes }\n const styleRuns = withoutRedundantOverrides(updated, runs)\n // A percent gives characters of another size their own length.\n if (!sized) return { ...changes, styleRuns }\n return {\n ...changes,\n styleRuns: styleRunsWithPatch({ ...updated, styleRuns }, 0, node.text.length, sized)\n }\n}\n"],"mappings":";;;;;;AAoDA,MAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAMA,MAAM,mBAAmB;CAAC;CAAa;CAAe;CAAe;AAAgB;;AAGrF,MAAa,uBAAuB,CAClC,GAAG,iBACH,GAAG,gBACL;AAEA,SAAgB,UAAU,MAAiC;CACzD,OAAO;EACL,YAAY,KAAK;EACjB,YAAY,KAAK;EACjB,QAAQ,KAAK;EACb,WAAW,KAAK;EAChB,UAAU,KAAK;EACf,eAAe,KAAK;EACpB,YAAY,KAAK;EACjB,OAAO,KAAK;EACZ,gBAAgB,KAAK;EACrB,qBAAqB,KAAK;EAC1B,yBAAyB,KAAK;EAC9B,qBAAqB,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K;CACrF;AACF"}
@@ -25,6 +25,6 @@ import { documentFontStatus } from "./font/status.js";
25
25
  import { prepareGraphFonts } from "./prepare.js";
26
26
  import { documentFontData, documentFontsOf, isDocumentFontFileName, mergeArchiveFonts, prepareDocumentFonts, registerDocumentFonts } from "./font/document.js";
27
27
  import { TextEditor } from "./editor.js";
28
- import { hyperlinkInRange, hyperlinkSpanAt, hyperlinkSpans, isOpenableLinkURL, normalizeLinkURL, styleRunsWithHyperlink } from "./hyperlink.js";
29
28
  import { adjustRunsForDelete, adjustRunsForInsert, applyStyleToRange, getStyleAt, insertRunsWithStyle, removeStyleFromRange, selectionHasStyle, toggleBoldInRange, toggleDecorationInRange, toggleItalicInRange } from "./style-runs.js";
29
+ import { hyperlinkInRange, hyperlinkSpanAt, hyperlinkSpans, isOpenableLinkURL, normalizeLinkURL, styleRunsWithHyperlink } from "./hyperlink.js";
30
30
  export { ARABIC_CHARACTER, ARABIC_LOCAL_FALLBACK_FAMILIES, ARABIC_REMOTE_FALLBACK_FAMILIES, DEFAULT_WEB_FONT_PROVIDER_SETTINGS, FontManager, FontResolver, HANGUL_CHARACTER, HAN_CHARACTER, KANA_CHARACTER, TRADITIONAL_HAN_CHARACTER, TextEditor, UnsupportedFontFormatError, WEB_FONT_PROVIDER_IDS, WEB_FONT_PROVIDER_LABELS, WebFontResolver, adjustRunsForDelete, adjustRunsForInsert, applyStyleToRange, calibratePathTextLayout, chooseLocalFontMatch, cjkFallbackScriptForLanguage, cjkLocalFallbackFamilies, collectGraphFontKeys, collectGraphFontRequirements, collectNamedNodeFontFaces, collectNodeFontFaces, documentFontData, documentFontStatus, documentFontsOf, faceForStyle, faceStyleName, facesFromStyles, fitTextPathBoxToGlyphs, fontAxes, fontCoverageDemand, fontFaceDemand, fontFaceFromFigmaFontName, fontFaceRenderFamily, fontFallbackEntry, fontFallbackManifest, fontFallbackScriptForCharacter, fontManager, fontRemoteCoverageDemand, fontResolver, fontTableView, fontWeightMatchOrder, getStyleAt, getTextPathData, hasFamilyFace, hasNamedInstance, hasTrueTypeOutlines, hyperlinkInRange, hyperlinkSpanAt, hyperlinkSpans, insertRunsWithStyle, isDocumentFontFileName, isOpenableLinkURL, isVariableFont, isWOFF2, layoutPathTextFromAdvances, mergeArchiveFonts, missingGlyphCharacters, missingGlyphOccurrences, missingGlyphScripts, missingGlyphsByScript, missingGraphFontScripts, namedInstanceVariations, namedInstances, nearestArcPoint, nearestFamilyFace, normalizeLinkURL, normalizedCoverageText, pathTextCaret, pathTextIndexAt, pathTextSelectionQuads, pointAtArc, prepareDocumentFonts, prepareGraphFonts, probeGlyphOutlineCommands, reflowPathTextGlyphs, registerDocumentFonts, removeStyleFromRange, sampleTextPath, selectionHasStyle, setHarfBuzzSubsetLocator, sfntFamilyNames, sfntFont, sfntFontName, shownCharacters, shownText, shownTextSlice, standardFace, standardFaces, styleRunsWithHyperlink, textCaseSegments, textFaceName, textFallbackScriptsWithoutCoverage, textFontFace, textHasFallbackScript, textNeededFallbackScripts, textNeedsFallbackScript, textPathStartArc, textPathStartDistance, textStyleName, toggleBoldInRange, toggleDecorationInRange, toggleItalicInRange, transformTextCase, webFontSubsetsForText };
@@ -1 +1 @@
1
- {"version":3,"file":"libraries.d.ts","names":[],"sources":["../../../src/tools/read/libraries.ts"],"mappings":";;cAKa,eAAA;cAaA,wBAAA"}
1
+ {"version":3,"file":"libraries.d.ts","names":[],"sources":["../../../src/tools/read/libraries.ts"],"mappings":";;cAca,eAAA;cAaA,wBAAA"}
@@ -1,7 +1,9 @@
1
1
  import { defineTool, toolNumber } from "../schema.js";
2
2
  import { getComponentCatalog } from "../component-catalog.js";
3
+ import { isPlainObject } from "es-toolkit";
3
4
  import * as v from "valibot";
4
5
  //#region src/tools/read/libraries.ts
6
+ const variantValuesSchema = v.pipe(v.string(), v.parseJson(), v.check(isPlainObject, "Expected a JSON object"), v.record(v.string(), v.string()));
5
7
  const listLibraries = defineTool({
6
8
  name: "list_libraries",
7
9
  description: "List available published component libraries.",
@@ -41,11 +43,9 @@ const insertLibraryComponent = defineTool({
41
43
  if (!catalog) throw new Error("No component library catalog is configured");
42
44
  let variantValues;
43
45
  if (args.variant_values) {
44
- const parsed = JSON.parse(args.variant_values);
45
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError("variant_values must be a JSON object");
46
- const entries = Object.entries(parsed);
47
- if (entries.some(([, value]) => typeof value !== "string")) throw new TypeError("variant_values values must be strings");
48
- variantValues = Object.fromEntries(entries);
46
+ const parsed = v.safeParse(variantValuesSchema, args.variant_values);
47
+ if (!parsed.success) throw new TypeError(`variant_values must be a JSON object of strings: ${v.summarize(parsed.issues)}`);
48
+ variantValues = parsed.output;
49
49
  }
50
50
  return catalog.insertComponent({
51
51
  libraryId: args.library_id,
@@ -1 +1 @@
1
- {"version":3,"file":"libraries.js","names":[],"sources":["../../../src/tools/read/libraries.ts"],"sourcesContent":["import * as v from 'valibot'\n\nimport { getComponentCatalog } from '#core/tools/component-catalog'\nimport { toolNumber, defineTool } from '#core/tools/schema'\n\nexport const listLibraries = defineTool({\n name: 'list_libraries',\n description: 'List available published component libraries.',\n execution: { kind: 'async', mutation: 'none' },\n exposure: { webmcp: false },\n input: v.strictObject({}),\n execute: async (figma) => {\n const catalog = getComponentCatalog(figma.graph)\n const libraries = catalog ? await catalog.listLibraries() : []\n return { count: libraries.length, libraries }\n }\n})\n\nexport const insertLibraryComponent = defineTool({\n name: 'insert_library_component',\n description:\n 'Insert a reusable component from an enabled library by stable library and asset identity.',\n\n execution: { kind: 'async', mutation: 'document' },\n input: v.strictObject({\n library_id: v.pipe(v.string(), v.description('Library ID')),\n revision_id: v.optional(v.pipe(v.string(), v.description('Pinned revision ID'))),\n asset_key: v.pipe(v.string(), v.description('Stable asset key')),\n parent_id: v.optional(v.pipe(v.string(), v.description('Optional parent node ID'))),\n x: v.optional(toolNumber(v.pipe(v.number(), v.description('X position')))),\n y: v.optional(toolNumber(v.pipe(v.number(), v.description('Y position')))),\n variant_values: v.optional(\n v.pipe(v.string(), v.description('Optional JSON object of variant property values'))\n )\n }),\n execute: async (figma, args) => {\n const catalog = getComponentCatalog(figma.graph)\n if (!catalog) throw new Error('No component library catalog is configured')\n let variantValues: Record<string, string> | undefined\n if (args.variant_values) {\n const parsed: unknown = JSON.parse(args.variant_values)\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new TypeError('variant_values must be a JSON object')\n }\n const entries = Object.entries(parsed)\n if (entries.some(([, value]) => typeof value !== 'string')) {\n throw new TypeError('variant_values values must be strings')\n }\n variantValues = Object.fromEntries(entries)\n }\n return catalog.insertComponent({\n libraryId: args.library_id,\n revisionId: args.revision_id,\n assetKey: args.asset_key,\n parentId: args.parent_id,\n x: args.x,\n y: args.y,\n variantValues\n })\n }\n})\n"],"mappings":";;;;AAKA,MAAa,gBAAgB,WAAW;CACtC,MAAM;CACN,aAAa;CACb,WAAW;EAAE,MAAM;EAAS,UAAU;CAAO;CAC7C,UAAU,EAAE,QAAQ,MAAM;CAC1B,OAAO,EAAE,aAAa,CAAC,CAAC;CACxB,SAAS,OAAO,UAAU;EACxB,MAAM,UAAU,oBAAoB,MAAM,KAAK;EAC/C,MAAM,YAAY,UAAU,MAAM,QAAQ,cAAc,IAAI,CAAC;EAC7D,OAAO;GAAE,OAAO,UAAU;GAAQ;EAAU;CAC9C;AACF,CAAC;AAED,MAAa,yBAAyB,WAAW;CAC/C,MAAM;CACN,aACE;CAEF,WAAW;EAAE,MAAM;EAAS,UAAU;CAAW;CACjD,OAAO,EAAE,aAAa;EACpB,YAAY,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,YAAY,CAAC;EAC1D,aAAa,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,oBAAoB,CAAC,CAAC;EAC/E,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,kBAAkB,CAAC;EAC/D,WAAW,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,yBAAyB,CAAC,CAAC;EAClF,GAAG,EAAE,SAAS,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,YAAY,CAAC,CAAC,CAAC;EACzE,GAAG,EAAE,SAAS,WAAW,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,YAAY,CAAC,CAAC,CAAC;EACzE,gBAAgB,EAAE,SAChB,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,YAAY,iDAAiD,CAAC,CACrF;CACF,CAAC;CACD,SAAS,OAAO,OAAO,SAAS;EAC9B,MAAM,UAAU,oBAAoB,MAAM,KAAK;EAC/C,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,4CAA4C;EAC1E,IAAI;EACJ,IAAI,KAAK,gBAAgB;GACvB,MAAM,SAAkB,KAAK,MAAM,KAAK,cAAc;GACtD,IAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GAC/D,MAAM,IAAI,UAAU,sCAAsC;GAE5D,MAAM,UAAU,OAAO,QAAQ,MAAM;GACrC,IAAI,QAAQ,MAAM,GAAG,WAAW,OAAO,UAAU,QAAQ,GACvD,MAAM,IAAI,UAAU,uCAAuC;GAE7D,gBAAgB,OAAO,YAAY,OAAO;EAC5C;EACA,OAAO,QAAQ,gBAAgB;GAC7B,WAAW,KAAK;GAChB,YAAY,KAAK;GACjB,UAAU,KAAK;GACf,UAAU,KAAK;GACf,GAAG,KAAK;GACR,GAAG,KAAK;GACR;EACF,CAAC;CACH;AACF,CAAC"}
1
+ {"version":3,"file":"libraries.js","names":[],"sources":["../../../src/tools/read/libraries.ts"],"sourcesContent":["import { isPlainObject } from 'es-toolkit'\nimport * as v from 'valibot'\n\nimport { getComponentCatalog } from '#core/tools/component-catalog'\nimport { toolNumber, defineTool } from '#core/tools/schema'\n\nconst variantValuesSchema = v.pipe(\n v.string(),\n v.parseJson(),\n // A record also takes an array, as its indices.\n v.check(isPlainObject, 'Expected a JSON object'),\n v.record(v.string(), v.string())\n)\n\nexport const listLibraries = defineTool({\n name: 'list_libraries',\n description: 'List available published component libraries.',\n execution: { kind: 'async', mutation: 'none' },\n exposure: { webmcp: false },\n input: v.strictObject({}),\n execute: async (figma) => {\n const catalog = getComponentCatalog(figma.graph)\n const libraries = catalog ? await catalog.listLibraries() : []\n return { count: libraries.length, libraries }\n }\n})\n\nexport const insertLibraryComponent = defineTool({\n name: 'insert_library_component',\n description:\n 'Insert a reusable component from an enabled library by stable library and asset identity.',\n\n execution: { kind: 'async', mutation: 'document' },\n input: v.strictObject({\n library_id: v.pipe(v.string(), v.description('Library ID')),\n revision_id: v.optional(v.pipe(v.string(), v.description('Pinned revision ID'))),\n asset_key: v.pipe(v.string(), v.description('Stable asset key')),\n parent_id: v.optional(v.pipe(v.string(), v.description('Optional parent node ID'))),\n x: v.optional(toolNumber(v.pipe(v.number(), v.description('X position')))),\n y: v.optional(toolNumber(v.pipe(v.number(), v.description('Y position')))),\n variant_values: v.optional(\n v.pipe(v.string(), v.description('Optional JSON object of variant property values'))\n )\n }),\n execute: async (figma, args) => {\n const catalog = getComponentCatalog(figma.graph)\n if (!catalog) throw new Error('No component library catalog is configured')\n let variantValues: Record<string, string> | undefined\n if (args.variant_values) {\n const parsed = v.safeParse(variantValuesSchema, args.variant_values)\n if (!parsed.success) {\n throw new TypeError(\n `variant_values must be a JSON object of strings: ${v.summarize(parsed.issues)}`\n )\n }\n variantValues = parsed.output\n }\n return catalog.insertComponent({\n libraryId: args.library_id,\n revisionId: args.revision_id,\n assetKey: args.asset_key,\n parentId: args.parent_id,\n x: args.x,\n y: args.y,\n variantValues\n })\n }\n})\n"],"mappings":";;;;;AAMA,MAAM,sBAAsB,EAAE,KAC5B,EAAE,OAAO,GACT,EAAE,UAAU,GAEZ,EAAE,MAAM,eAAe,wBAAwB,GAC/C,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,CACjC;AAEA,MAAa,gBAAgB,WAAW;CACtC,MAAM;CACN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E,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,UACR,oDAAoD,EAAE,UAAU,OAAO,MAAM,GAC/E;GAEF,gBAAgB,OAAO;EACzB;EACA,OAAO,QAAQ,gBAAgB;GAC7B,WAAW,KAAK;GAChB,YAAY,KAAK;GACjB,UAAU,KAAK;GACf,UAAU,KAAK;GACf,GAAG,KAAK;GACR,GAAG,KAAK;GACR;EACF,CAAC;CACH;AACF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pairdraw/core",
3
- "version": "0.16.1",
3
+ "version": "0.17.0",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
@@ -12,14 +12,14 @@
12
12
  "dependencies": {
13
13
  "@chenglou/pretext": "^0.0.7",
14
14
  "@iconify/utils": "^3.1.4",
15
- "@pairdraw/design-jsx": "^0.16.1",
16
- "@pairdraw/dom-css": "^0.16.1",
17
- "@pairdraw/drawio": "^0.16.1",
18
- "@pairdraw/fig": "^0.16.1",
19
- "@pairdraw/kiwi": "^0.16.1",
20
- "@pairdraw/mermaid": "^0.16.1",
21
- "@pairdraw/pen": "^0.16.1",
22
- "@pairdraw/scene-graph": "^0.16.1",
15
+ "@pairdraw/design-jsx": "^0.17.0",
16
+ "@pairdraw/dom-css": "^0.17.0",
17
+ "@pairdraw/drawio": "^0.17.0",
18
+ "@pairdraw/fig": "^0.17.0",
19
+ "@pairdraw/kiwi": "^0.17.0",
20
+ "@pairdraw/mermaid": "^0.17.0",
21
+ "@pairdraw/pen": "^0.17.0",
22
+ "@pairdraw/scene-graph": "^0.17.0",
23
23
  "@tauri-apps/api": "^2.12.1",
24
24
  "@valibot/to-json-schema": "^1.8.0",
25
25
  "@xmldom/xmldom": "^0.9.12",
@@ -34,7 +34,7 @@ function getSelectionScreenBounds(
34
34
  graph: SceneGraph,
35
35
  selNodes: SceneNode[]
36
36
  ): SelectionScreenBounds {
37
- const b = computeAbsoluteBounds(selNodes, (id) => graph.getAbsolutePosition(id))
37
+ const b = computeAbsoluteBounds(selNodes, graph)
38
38
  return {
39
39
  sx1: b.x * r.zoom + r.panX,
40
40
  sx2: (b.x + b.width) * r.zoom + r.panX,
@@ -1,3 +1,4 @@
1
+ import { isPlainObject, omit } from 'es-toolkit'
1
2
  import { deflateSync, inflateSync } from 'fflate'
2
3
  import { fromUint8Array, isValid, toUint8Array } from 'js-base64'
3
4
  import * as v from 'valibot'
@@ -16,6 +17,7 @@ import {
16
17
  setInstanceOverride,
17
18
  type InstanceOverrideState
18
19
  } from '@pairdraw/scene-graph/instances/overrides'
20
+ import { fillSchema } from '@pairdraw/scene-graph/paints'
19
21
  import type { JSONObject } from '@pairdraw/scene-graph/primitives'
20
22
 
21
23
  import type { ClipboardSnapshot } from '#core/editor/clipboard/copy'
@@ -93,6 +95,42 @@ const serializedClipboardNodeSchema: v.GenericSchema<unknown, SerializedClipboar
93
95
  children: v.optional(v.array(v.lazy(() => serializedClipboardNodeSchema)))
94
96
  })
95
97
 
98
+ const paintsSchema = v.array(fillSchema)
99
+ const effectsSchema = v.array(v.unknown())
100
+ const sourceMetadataSchema = v.looseObject({
101
+ format: v.nullable(v.literal('fig')),
102
+ id: v.nullable(v.string()),
103
+ orderKey: v.nullable(v.string()),
104
+ editedFields: v.array(v.string()),
105
+ fig: v.looseObject({})
106
+ })
107
+
108
+ /**
109
+ * Fields the graph reads without checking. `v.is` checks them without parsing, which would reorder
110
+ * paint keys; a malformed field is dropped and the rest of the layer kept.
111
+ */
112
+ const CHECKED_FIELDS: [string, v.GenericSchema][] = [
113
+ ['fills', paintsSchema],
114
+ ['strokes', paintsSchema],
115
+ ['effects', effectsSchema],
116
+ ['source', sourceMetadataSchema]
117
+ ]
118
+
119
+ function malformedFields(fields: Record<string, unknown>, checked = CHECKED_FIELDS): string[] {
120
+ return checked
121
+ .filter(([key, schema]) => key in fields && !v.is(schema, fields[key]))
122
+ .map(([key]) => key)
123
+ }
124
+
125
+ /** Payloads from v0.15.1 and earlier wrote strokes without a paint type; they are solid. */
126
+ function withStrokeTypes(fields: Record<string, unknown>): Record<string, unknown> {
127
+ if (!Array.isArray(fields.strokes)) return fields
128
+ const strokes = fields.strokes.map((stroke: unknown) =>
129
+ isPlainObject(stroke) && !Object.hasOwn(stroke, 'type') ? { ...stroke, type: 'SOLID' } : stroke
130
+ )
131
+ return { ...fields, strokes }
132
+ }
133
+
96
134
  /** Clipboard HTML is writable by any application, so the payload is validated before paste. */
97
135
  const pairdrawClipboardSchema = v.pipe(
98
136
  v.string(),
@@ -154,10 +192,14 @@ function legacyInstanceOverrides(
154
192
  }
155
193
 
156
194
  function restoreGeometry(paths: SerializedGeometryPath[] | undefined): GeometryPath[] {
157
- return (paths ?? []).map((path) => ({
158
- ...path,
159
- commandsBlob: Uint8Array.from(Object.values(path.commandsBlob))
160
- }))
195
+ return (paths ?? []).map((path) => {
196
+ const { fills, ...rest } = path
197
+ return {
198
+ ...rest,
199
+ ...(v.is(paintsSchema, fills) ? { fills } : {}),
200
+ commandsBlob: Uint8Array.from(Object.values(path.commandsBlob))
201
+ }
202
+ })
161
203
  }
162
204
 
163
205
  /** Clipboard HTML comes from other applications, so its Base64 is checked before decoding. */
@@ -168,14 +210,16 @@ function clipboardBytes(value: string): Uint8Array {
168
210
 
169
211
  function restoreNodeData(nodes: SerializedClipboardNode[]): ClipboardNode[] {
170
212
  return nodes.map((node) => {
171
- const { children, instanceOverrides, overrides, textPicture, ...rest } = node
213
+ const { children, instanceOverrides, overrides, textPicture, ...fields } = node
214
+ const typed = withStrokeTypes(fields)
215
+ const rest = { ...omit(typed, malformedFields(typed)), id: node.id, type: node.type }
172
216
  const overrideState = instanceOverrides
173
217
  ? deserializeInstanceOverrideState(instanceOverrides)
174
218
  : legacyInstanceOverrides(rest.id, overrides)
175
219
  return {
176
220
  ...rest,
177
- fillGeometry: restoreGeometry(rest.fillGeometry),
178
- strokeGeometry: restoreGeometry(rest.strokeGeometry),
221
+ fillGeometry: restoreGeometry(node.fillGeometry),
222
+ strokeGeometry: restoreGeometry(node.strokeGeometry),
179
223
  instanceOverrides: overrideState,
180
224
  textPicture: typeof textPicture === 'string' ? clipboardBytes(textPicture) : textPicture,
181
225
  ...(children ? { children: restoreNodeData(children) } : {})
@@ -64,9 +64,15 @@ export function createJSXPreviewRecorder(ck: CanvasKit): JSXPreviewRecorder {
64
64
  const surface = ck.MakeSurface(1, 1)
65
65
  if (!surface) return null
66
66
  const created = new SkiaRenderer(ck, surface)
67
+ // Loading fonts drops every cache, so it happens once rather than before each record; a
68
+ // renderer whose fonts failed to load is not kept, so the next record tries again.
69
+ try {
70
+ await created.loadFonts()
71
+ } catch (error) {
72
+ created.destroy()
73
+ throw error
74
+ }
67
75
  renderer = created
68
- // Loading fonts drops every cache, so it happens once rather than before each record.
69
- await created.loadFonts()
70
76
  return created
71
77
  }
72
78
 
@@ -1,7 +1,11 @@
1
1
  import { sumBy } from 'es-toolkit'
2
2
 
3
3
  import type { SceneNode } from '@pairdraw/scene-graph'
4
- import { getAbsolutePositionFull, getWorldMatrix } from '@pairdraw/scene-graph/coordinate'
4
+ import {
5
+ getAbsolutePositionFull,
6
+ getAxisAlignedWorldBounds,
7
+ getWorldMatrix
8
+ } from '@pairdraw/scene-graph/coordinate'
5
9
  import { computeAbsoluteBounds } from '@pairdraw/scene-graph/geometry'
6
10
  import Matrix from '@pairdraw/scene-graph/matrix'
7
11
  import type { Vector } from '@pairdraw/scene-graph/primitives'
@@ -30,15 +34,23 @@ function alignSingleNode(
30
34
  axis: 'horizontal' | 'vertical',
31
35
  align: 'min' | 'center' | 'max'
32
36
  ) {
37
+ // The layer's drawn box against the parent's, so a rotated layer's visible edge lands on the
38
+ // target as it does when several layers align together.
33
39
  const parent = node.parentId ? ctx.graph.getNode(node.parentId) : undefined
34
- const pw = parent?.width ?? 0
35
- const ph = parent?.height ?? 0
36
-
37
- if (axis === 'horizontal') {
38
- ctx.graph.updateNode(node.id, { x: computeAlignTarget(0, pw, node.width, align) })
39
- } else {
40
- ctx.graph.updateNode(node.id, { y: computeAlignTarget(0, ph, node.height, align) })
41
- }
40
+ const target = parent
41
+ ? getAxisAlignedWorldBounds(parent, ctx.graph)
42
+ : { x: 0, y: 0, width: 0, height: 0 }
43
+ const box = getAxisAlignedWorldBounds(node, ctx.graph)
44
+ const worldDelta =
45
+ axis === 'horizontal'
46
+ ? { x: computeAlignTarget(target.x, target.x + target.width, box.width, align) - box.x, y: 0 }
47
+ : {
48
+ x: 0,
49
+ y: computeAlignTarget(target.y, target.y + target.height, box.height, align) - box.y
50
+ }
51
+ const localDelta = parentLocalDelta(ctx, node, worldDelta)
52
+ if (!localDelta) return
53
+ ctx.graph.updateNode(node.id, { x: node.x + localDelta.x, y: node.y + localDelta.y })
42
54
  }
43
55
 
44
56
  function alignMultipleNodes(
@@ -47,28 +59,20 @@ function alignMultipleNodes(
47
59
  axis: 'horizontal' | 'vertical',
48
60
  align: 'min' | 'center' | 'max'
49
61
  ) {
50
- const absPositions = new Map<string, Vector>()
51
- for (const n of nodes) absPositions.set(n.id, ctx.graph.getAbsolutePosition(n.id))
52
-
53
- const getPos = (id: string) => absPositions.get(id) ?? { x: 0, y: 0 }
54
- const b = computeAbsoluteBounds(nodes, getPos)
55
- const minX = b.x
56
- const minY = b.y
57
- const maxX = b.x + b.width
58
- const maxY = b.y + b.height
62
+ // Each layer's drawn box, so a rotated layer's visible edge lands on the target.
63
+ const boxes = new Map(nodes.map((n) => [n.id, getAxisAlignedWorldBounds(n, ctx.graph)]))
64
+ const b = computeAbsoluteBounds(nodes, ctx.graph)
59
65
 
60
66
  for (const n of nodes) {
61
- const abs = absPositions.get(n.id)
62
- if (!abs) continue
63
- const parentAbs = n.parentId ? ctx.graph.getAbsolutePosition(n.parentId) : { x: 0, y: 0 }
64
-
65
- if (axis === 'horizontal') {
66
- const target = computeAlignTarget(minX, maxX, n.width, align)
67
- ctx.graph.updateNode(n.id, { x: target - parentAbs.x })
68
- } else {
69
- const target = computeAlignTarget(minY, maxY, n.height, align)
70
- ctx.graph.updateNode(n.id, { y: target - parentAbs.y })
71
- }
67
+ const box = boxes.get(n.id)
68
+ if (!box) continue
69
+ const worldDelta =
70
+ axis === 'horizontal'
71
+ ? { x: computeAlignTarget(b.x, b.x + b.width, box.width, align) - box.x, y: 0 }
72
+ : { x: 0, y: computeAlignTarget(b.y, b.y + b.height, box.height, align) - box.y }
73
+ const localDelta = parentLocalDelta(ctx, n, worldDelta)
74
+ if (!localDelta) continue
75
+ ctx.graph.updateNode(n.id, { x: n.x + localDelta.x, y: n.y + localDelta.y })
72
76
  }
73
77
  }
74
78
 
@@ -27,9 +27,15 @@ export function resolvedClipboardBindings(
27
27
  }
28
28
 
29
29
  function unlinkedRun(run: StyleRun): StyleRun {
30
- const { boundVariables, textStyleId, fillStyleId } = run.style
31
- if (!boundVariables && !textStyleId && !fillStyleId) return run
32
- const { boundVariables: _variables, textStyleId: _text, fillStyleId: _fill, ...style } = run.style
30
+ const { boundVariables, variableBindingScales, textStyleId, fillStyleId } = run.style
31
+ if (!boundVariables && !variableBindingScales && !textStyleId && !fillStyleId) return run
32
+ const {
33
+ boundVariables: _variables,
34
+ variableBindingScales: _scales,
35
+ textStyleId: _text,
36
+ fillStyleId: _fill,
37
+ ...style
38
+ } = run.style
33
39
  return { ...run, style }
34
40
  }
35
41
 
@@ -12,6 +12,7 @@ import {
12
12
  TEXT_STYLE_FIELDS
13
13
  } from '@pairdraw/scene-graph/fields'
14
14
  import { STYLE_LINK_FIELDS, sharedStyleRefKey } from '@pairdraw/scene-graph/shared-styles'
15
+ import { withBoundBindingScales } from '@pairdraw/scene-graph/variables'
15
16
 
16
17
  import { parsePairdrawClipboard } from '#core/clipboard'
17
18
  import { importClipboardDependenciesWithUndo } from '#core/editor/clipboard/dependencies'
@@ -89,12 +90,13 @@ function pastedFields(source: SceneNode, target: SceneNode): PastedField[] {
89
90
  function runsWithout(runs: StyleRun[], fields: ReadonlySet<string>): StyleRun[] {
90
91
  const overrides = new Set([...fields].flatMap((field) => RUN_OVERRIDES[field] ?? [field]))
91
92
  return runs.flatMap((run) => {
92
- const style = omitBy(run.style, (_, key) => overrides.has(key))
93
+ let style = omitBy(run.style, (_, key) => overrides.has(key))
93
94
  if (style.boundVariables) {
94
95
  const bound = omitBy(style.boundVariables, (_, key) => fields.has(key))
95
96
  if (Object.keys(bound).length > 0) style.boundVariables = bound
96
97
  else delete style.boundVariables
97
98
  }
99
+ style = withBoundBindingScales(style)
98
100
  return Object.keys(style).length > 0 ? [{ ...run, style }] : []
99
101
  })
100
102
  }
@@ -121,12 +121,13 @@ export function createStructureActions(ctx: EditorContext) {
121
121
  .sort((a, b) => a.index - b.index)
122
122
  if (origins.length === 0) return
123
123
  const parentIds = new Set(origins.map((origin) => origin.parentId))
124
+ const prevSelection = new Set(ctx.state.selectedIds)
124
125
  const move = () => {
125
126
  for (const { id } of origins) ctx.graph.reparentNode(id, pageId)
126
127
  for (const parentId of parentIds) ctx.runLayoutForNode(parentId)
128
+ ctx.setSelectedIds(new Set())
127
129
  }
128
130
  move()
129
- ctx.setSelectedIds(new Set())
130
131
  ctx.undo.push({
131
132
  label: 'Move to page',
132
133
  forward: move,
@@ -136,6 +137,7 @@ export function createStructureActions(ctx: EditorContext) {
136
137
  ctx.graph.updateNode(id, place)
137
138
  }
138
139
  for (const parentId of parentIds) ctx.runLayoutForNode(parentId)
140
+ ctx.setSelectedIds(new Set(prevSelection))
139
141
  }
140
142
  })
141
143
  }
@@ -69,7 +69,7 @@ export function createViewportActions(ctx: EditorContext) {
69
69
  const h = maxY - minY + padding * 2
70
70
 
71
71
  const { width: viewW, height: viewH } = ctx.getViewportSize()
72
- const zoom = Math.min(viewW / w, viewH / h, 1)
72
+ const zoom = Math.max(0.02, Math.min(viewW / w, viewH / h, 1))
73
73
 
74
74
  ctx.state.zoom = zoom
75
75
  ctx.state.panX = (viewW - w * zoom) / 2 - minX * zoom + padding * zoom
@@ -147,7 +147,7 @@ export function createViewportActions(ctx: EditorContext) {
147
147
  .filter((n): n is NonNullable<typeof n> => n != null)
148
148
  if (nodes.length === 0) return
149
149
 
150
- const b = computeAbsoluteBounds(nodes, (id) => ctx.graph.getAbsolutePosition(id))
150
+ const b = computeAbsoluteBounds(nodes, ctx.graph)
151
151
  zoomToBounds(b.x, b.y, b.x + b.width, b.y + b.height)
152
152
  }
153
153
 
@@ -11,10 +11,16 @@ import {
11
11
  } from '@pairdraw/scene-graph'
12
12
  import { copyFills } from '@pairdraw/scene-graph/copy'
13
13
  import { getSharedStyles, SHARED_TEXT_STYLE_FIELDS } from '@pairdraw/scene-graph/shared-styles'
14
+ import {
15
+ boundNumberValue,
16
+ SCALED_RUN_BINDING_FIELDS,
17
+ variableBindingOwner
18
+ } from '@pairdraw/scene-graph/variables'
14
19
 
15
20
  import { variableAlias, type FigmaVariableAlias } from '#core/figma-api/variables/values'
16
21
  import { styleRunsWithPatch } from '#core/text/character-style'
17
22
  import { faceForStyle } from '#core/text/font/names'
23
+ import { getStyleAt } from '#core/text/style-runs'
18
24
 
19
25
  import { getStyledTextSegments } from './style'
20
26
 
@@ -77,12 +83,16 @@ function boundVariable(
77
83
  return found
78
84
  }
79
85
 
80
- /** What the characters show for a bound field: the variable's value in their mode. */
86
+ /**
87
+ * What the characters show for a bound field: the variable's value in their mode, a number in
88
+ * the scale the characters' binding keeps.
89
+ */
81
90
  function boundValue(
82
91
  graph: SceneGraph,
83
92
  node: SceneNode,
84
93
  field: TextBindableField,
85
- variable: Variable
94
+ variable: Variable,
95
+ scale: number
86
96
  ): CharacterStyleOverride {
87
97
  if (STRING_FIELDS.has(field)) {
88
98
  const value = graph.resolveVariableForNode(node.id, variable.id)
@@ -94,7 +104,7 @@ function boundValue(
94
104
  }
95
105
  const value = graph.resolveNumberVariableForNode(node.id, variable.id)
96
106
  if (value === undefined || !Number.isFinite(value) || isParagraphField(field)) return {}
97
- return { [field]: value }
107
+ return { [field]: boundNumberValue(field, value * scale) }
98
108
  }
99
109
 
100
110
  /**
@@ -112,17 +122,25 @@ export function rangeBindingChanges(
112
122
  ): { styleRuns: StyleRun[]; paragraphValue: number | null } {
113
123
  const bound =
114
124
  variable === null ? null : boundVariable(graph, 'setRangeBoundVariable', field, variable)
115
- const value = bound ? boundValue(graph, node, field, bound) : {}
125
+ // A new binding starts at the variable's number in the scope that declares it, as a layer's does
126
+ // (`assignVariableBindingUnits`), not at a scale a rescale left on the characters' old binding.
127
+ const scaled = SCALED_RUN_BINDING_FIELDS.has(field)
128
+ const scale = scaled
129
+ ? (variableBindingOwner(graph, node).variableAssignmentScales[field] ?? 1)
130
+ : 1
116
131
  let styleRuns = node.styleRuns
117
132
  // Characters bound apart keep their other bindings.
118
133
  for (const segment of getStyledTextSegments(node, ['boundVariables'], start, end)) {
119
134
  const aliases = (segment.boundVariables ?? {}) as Record<string, FigmaVariableAlias>
120
135
  const ids = mapValues(aliases, (alias) => alias.id)
121
136
  const boundVariables = bound ? { ...ids, [field]: bound.id } : omit(ids, [field])
122
- styleRuns = styleRunsWithPatch({ ...node, styleRuns }, segment.start, segment.end, {
123
- ...value,
124
- boundVariables
125
- })
137
+ const scales = getStyleAt(node.styleRuns, segment.start).variableBindingScales ?? {}
138
+ const patch: CharacterStyleOverride = bound
139
+ ? { ...boundValue(graph, node, field, bound, scale), boundVariables }
140
+ : { boundVariables }
141
+ // An unbound range's scale goes with its binding (`withBoundBindingScales`).
142
+ if (bound && scaled) patch.variableBindingScales = { ...scales, [field]: scale }
143
+ styleRuns = styleRunsWithPatch({ ...node, styleRuns }, segment.start, segment.end, patch)
126
144
  }
127
145
  const resolved = bound ? graph.resolveNumberVariableForNode(node.id, bound.id) : undefined
128
146
  const paragraphValue =
package/src/io/formats.ts CHANGED
@@ -458,19 +458,15 @@ export const jsxFormat: IOFormatAdapter<'jsx'> = {
458
458
  category: 'code',
459
459
  extensions: ['jsx'],
460
460
  mimeTypes: ['text/plain', 'text/jsx'],
461
- support: {
462
- exportSelection: true,
463
- exportNode: true
464
- },
461
+ support: EXPORT_EVERY_TARGET,
465
462
  exportOptions: FIXED_SIZE_EXPORT,
466
463
  async exportContent(request): Promise<ExportResult> {
467
464
  const nodeId = ensureSingleNode(request.target)
465
+ // A page or a document exports its top-level layers, as Tailwind JSX does.
466
+ const target = nodeId ? null : resolveExportNodes(request)
468
467
  let data = ''
469
- if (nodeId) {
470
- data = sceneNodeToJSX(nodeId, request.graph)
471
- } else if (request.target.scope === 'selection') {
472
- data = selectionToJSX(request.target.nodeIds, request.graph)
473
- }
468
+ if (nodeId) data = sceneNodeToJSX(nodeId, request.graph)
469
+ else if (target) data = selectionToJSX(target.nodeIds, request.graph)
474
470
  if (!data) throw new Error('Nothing to export')
475
471
  return {
476
472
  format: 'jsx',
@@ -16,6 +16,7 @@ import {
16
16
  SHARED_TEXT_STYLE_FIELDS,
17
17
  styleDetachmentChanges
18
18
  } from '@pairdraw/scene-graph/shared-styles'
19
+ import { withBoundBindingScales } from '@pairdraw/scene-graph/variables'
19
20
 
20
21
  /** A character's style: the text's own, with its run's overrides over it. */
21
22
  export type CharacterStyle = Required<
@@ -140,10 +141,13 @@ function withoutRedundantOverrides(node: SceneNode, runs: StyleRun[]): StyleRun[
140
141
  const base = nodeStyle(node)
141
142
  const result: StyleRun[] = []
142
143
  for (const run of runs) {
143
- const style = omit(
144
- run.style,
145
- CHARACTER_STYLE_KEYS.filter(
146
- (key) => run.style[key] !== undefined && isEqual(run.style[key], base[key])
144
+ // A range keeps a binding's scale only while it binds the number itself.
145
+ const style = withBoundBindingScales(
146
+ omit(
147
+ run.style,
148
+ CHARACTER_STYLE_KEYS.filter(
149
+ (key) => run.style[key] !== undefined && isEqual(run.style[key], base[key])
150
+ )
147
151
  )
148
152
  )
149
153
  if (Object.keys(style).length === 0) continue
@@ -1,8 +1,17 @@
1
+ import { isPlainObject } from 'es-toolkit'
1
2
  import * as v from 'valibot'
2
3
 
3
4
  import { getComponentCatalog } from '#core/tools/component-catalog'
4
5
  import { toolNumber, defineTool } from '#core/tools/schema'
5
6
 
7
+ const variantValuesSchema = v.pipe(
8
+ v.string(),
9
+ v.parseJson(),
10
+ // A record also takes an array, as its indices.
11
+ v.check(isPlainObject, 'Expected a JSON object'),
12
+ v.record(v.string(), v.string())
13
+ )
14
+
6
15
  export const listLibraries = defineTool({
7
16
  name: 'list_libraries',
8
17
  description: 'List available published component libraries.',
@@ -38,15 +47,13 @@ export const insertLibraryComponent = defineTool({
38
47
  if (!catalog) throw new Error('No component library catalog is configured')
39
48
  let variantValues: Record<string, string> | undefined
40
49
  if (args.variant_values) {
41
- const parsed: unknown = JSON.parse(args.variant_values)
42
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
43
- throw new TypeError('variant_values must be a JSON object')
44
- }
45
- const entries = Object.entries(parsed)
46
- if (entries.some(([, value]) => typeof value !== 'string')) {
47
- throw new TypeError('variant_values values must be strings')
50
+ const parsed = v.safeParse(variantValuesSchema, args.variant_values)
51
+ if (!parsed.success) {
52
+ throw new TypeError(
53
+ `variant_values must be a JSON object of strings: ${v.summarize(parsed.issues)}`
54
+ )
48
55
  }
49
- variantValues = Object.fromEntries(entries)
56
+ variantValues = parsed.output
50
57
  }
51
58
  return catalog.insertComponent({
52
59
  libraryId: args.library_id,