@open-pencil/scene-graph 0.16.0-beta.1 → 0.16.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.
@@ -16,7 +16,8 @@ const STYLE_TYPES = {
16
16
  grid: 'GRID'
17
17
  } as const satisfies Record<SharedStyleKind, SharedStyleType>
18
18
 
19
- const TEXT_STYLE_KEYS = new Set<keyof SceneNode>([
19
+ /** The fields a text style gives what uses it; changing one leaves the style. */
20
+ export const SHARED_TEXT_STYLE_FIELDS = [
20
21
  'fontFamily',
21
22
  'fontWeight',
22
23
  'italic',
@@ -26,7 +27,9 @@ const TEXT_STYLE_KEYS = new Set<keyof SceneNode>([
26
27
  'textDecoration',
27
28
  'textCase',
28
29
  'fontFeatures'
29
- ])
30
+ ] as const satisfies readonly (keyof SceneNode)[]
31
+
32
+ const TEXT_STYLE_KEYS = new Set<keyof SceneNode>(SHARED_TEXT_STYLE_FIELDS)
30
33
 
31
34
  export function sharedStyleRefKey(kind: SharedStyleKind): (typeof STYLE_REF_KEYS)[SharedStyleKind] {
32
35
  return STYLE_REF_KEYS[kind]
package/src/text/index.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './lists'
2
2
  export * from './paragraphs'
3
+ export * from './references'
@@ -0,0 +1,50 @@
1
+ import { mapValues } from 'es-toolkit/object'
2
+
3
+ import type { StyleRun } from '../types'
4
+
5
+ /** What a text's runs refer to outside the text: the variables they bind and the styles they use. */
6
+ export interface StyleRunReferences {
7
+ variables: string[]
8
+ styles: string[]
9
+ }
10
+
11
+ /** The variables and styles a text's runs refer to, which copies and transfers carry with it. */
12
+ export function styleRunReferences(runs: readonly StyleRun[]): StyleRunReferences {
13
+ const variables = new Set<string>()
14
+ const styles = new Set<string>()
15
+ for (const { style } of runs) {
16
+ for (const id of Object.values(style.boundVariables ?? {})) if (id) variables.add(id)
17
+ if (style.textStyleId) styles.add(style.textStyleId)
18
+ if (style.fillStyleId) styles.add(style.fillStyleId)
19
+ }
20
+ return { variables: [...variables], styles: [...styles] }
21
+ }
22
+
23
+ /**
24
+ * Runs whose variables, styles, and linked layers are renamed, as a copy into another document
25
+ * renames them. Layers are renamed only when given, since a link may name a layer left behind.
26
+ */
27
+ export function remapStyleRunReferences(
28
+ runs: readonly StyleRun[],
29
+ rename: {
30
+ variable: (id: string) => string
31
+ style: (id: string) => string
32
+ node?: (id: string) => string
33
+ }
34
+ ): StyleRun[] {
35
+ return runs.map((run) => {
36
+ const { boundVariables, textStyleId, fillStyleId, hyperlink } = run.style
37
+ const linksLayer = hyperlink?.type === 'NODE' && rename.node !== undefined
38
+ if (!boundVariables && !textStyleId && !fillStyleId && !linksLayer) return run
39
+ const style = { ...run.style }
40
+ if (hyperlink?.type === 'NODE' && rename.node) {
41
+ style.hyperlink = { type: 'NODE', value: rename.node(hyperlink.value) }
42
+ }
43
+ if (boundVariables) {
44
+ style.boundVariables = mapValues(boundVariables, (id) => (id ? rename.variable(id) : id))
45
+ }
46
+ if (textStyleId) style.textStyleId = rename.style(textStyleId)
47
+ if (fillStyleId) style.fillStyleId = rename.style(fillStyleId)
48
+ return { ...run, style }
49
+ })
50
+ }
@@ -1,13 +1,17 @@
1
1
  import { cloneNodeProps } from '../copy'
2
2
  import { remapInstanceOverrideState } from '../instance-overrides'
3
+ import { remapStyleRunReferences, styleRunReferences } from '../text/references'
3
4
  import type { ComponentPropertyType, SceneNode } from '../types'
4
5
  import { requireTransferReference as required } from './references'
5
6
  import type { VariableTransferReferences } from './variables'
6
7
 
7
8
  export function semanticTransferReferences(node: SceneNode): string[] {
9
+ const runs = styleRunReferences(node.styleRuns)
8
10
  return [
9
11
  ...(node.componentId ? [node.componentId] : []),
10
12
  ...Object.values(node.boundVariables),
13
+ ...runs.variables,
14
+ ...runs.styles,
11
15
  ...[
12
16
  node.fillStyleId,
13
17
  node.strokeStyleId,
@@ -89,6 +93,14 @@ export function prepareNodeTransfer(
89
93
  ] as const) {
90
94
  result[field] = source[field] ? style(source[field]) : null
91
95
  }
96
+ if (result.styleRuns) {
97
+ // A link to a layer the transfer leaves behind keeps naming it.
98
+ result.styleRuns = remapStyleRunReferences(result.styleRuns, {
99
+ variable,
100
+ style,
101
+ node: (id) => refs.nodes.get(id) ?? id
102
+ })
103
+ }
92
104
  for (const paths of [result.fillGeometry, result.strokeGeometry]) {
93
105
  for (const path of paths ?? []) if (path.fillStyleId) path.fillStyleId = style(path.fillStyleId)
94
106
  }
@@ -12,6 +12,18 @@ export interface GraphTransferInput {
12
12
  parentId: string
13
13
  }
14
14
 
15
+ /** A transferred style's props under the ID the transfer gives it. */
16
+ function withStyleId(
17
+ node: SceneNode,
18
+ props: Partial<SceneNode>,
19
+ styles: ReadonlyMap<string, string>
20
+ ): Partial<SceneNode> {
21
+ const id =
22
+ node.sharedStyleType !== null && node.source.id ? styles.get(node.source.id) : undefined
23
+ if (!id || id === node.source.id) return props
24
+ return { ...props, source: { ...(props.source ?? node.source), id } }
25
+ }
26
+
15
27
  /** Preflight a self-contained fragment; allocation does not insert anything into the target. */
16
28
  export function prepareGraphTransfer(input: GraphTransferInput) {
17
29
  const { source, target, parentId } = input
@@ -59,6 +71,17 @@ export function prepareGraphTransfer(input: GraphTransferInput) {
59
71
  propertyTypes.set(definition.id, definition.type)
60
72
  if (!properties.has(definition.id)) properties.set(definition.id, allocate())
61
73
  }
74
+ // Layers name a style by the style's own ID, which a transferred style keeps unless the
75
+ // target already holds another style by it: IDs read from Figma are only unique in one file.
76
+ const targetStyleIds = new Set<string>()
77
+ for (const node of target.getAllNodes())
78
+ if (node.sharedStyleType !== null && node.source.id) targetStyleIds.add(node.source.id)
79
+ const styles = new Map<string, string>()
80
+ for (const node of ordered) {
81
+ const id = node.source.id
82
+ if (node.sharedStyleType === null || !id) continue
83
+ styles.set(id, targetStyleIds.has(id) ? allocate() : id)
84
+ }
62
85
  const references = {
63
86
  nodes,
64
87
  variables,
@@ -66,7 +89,7 @@ export function prepareGraphTransfer(input: GraphTransferInput) {
66
89
  modes,
67
90
  properties,
68
91
  propertyTypes,
69
- styles: nodes
92
+ styles
70
93
  }
71
94
  const resources = prepareVariableTransfer(
72
95
  [...source.variables.values()],
@@ -93,7 +116,7 @@ export function prepareGraphTransfer(input: GraphTransferInput) {
93
116
  id: mapped(node.id),
94
117
  type: node.type,
95
118
  parentId: destinationParent(node),
96
- props: prepareNodeTransfer(node, references)
119
+ props: withStyleId(node, prepareNodeTransfer(node, references), styles)
97
120
  })),
98
121
  ...resources,
99
122
  activeModes: new Map(
@@ -25,9 +25,14 @@ export function validateTransferReferences(target: SceneGraph, plan: GraphTransf
25
25
  propertyTypes.set(definition.id, definition.type)
26
26
  }
27
27
  const collections = new Map(plan.collections.map((collection) => [collection.id, collection]))
28
+ const styles = new Map(
29
+ [...nodes.values()].flatMap((node) =>
30
+ node.sharedStyleType !== null && node.source.id ? [[node.source.id, node.source.id]] : []
31
+ )
32
+ )
28
33
  const references = {
29
34
  nodes: identities,
30
- styles: identities,
35
+ styles,
31
36
  properties,
32
37
  propertyTypes,
33
38
  ...variableIdentityReferences(plan.variables, plan.collections)
package/src/types.ts CHANGED
@@ -196,12 +196,14 @@ export type MaskType = 'ALPHA' | 'VECTOR' | 'LUMINANCE'
196
196
  export interface LayoutGrid {
197
197
  visible?: boolean
198
198
  color?: Color
199
- pattern?: 'COLUMNS' | 'ROWS' | 'GRID'
199
+ /** `STRIPES` is the archive's name for columns or rows, along `axis`. */
200
+ pattern?: 'COLUMNS' | 'ROWS' | 'GRID' | 'STRIPES'
200
201
  axis?: 'X' | 'Y'
201
202
  type?: 'MIN' | 'CENTER' | 'MAX' | 'STRETCH'
202
203
  alignment?: 'MIN' | 'CENTER' | 'MAX' | 'STRETCH'
203
204
  numSections?: number
204
- count?: number
205
+ /** Figma's plugin API reports an Auto count as `null` and accepts `Infinity` for it. */
206
+ count?: number | null
205
207
  offset?: number
206
208
  sectionSize?: number
207
209
  gutterSize?: number
@@ -270,6 +272,29 @@ export interface FontFeature {
270
272
  enabled: boolean
271
273
  }
272
274
 
275
+ /** Where a stretch of text links to, as Figma's `HyperlinkTarget`: a URL, or a node by its ID. */
276
+ export interface HyperlinkTarget {
277
+ type: 'URL' | 'NODE'
278
+ value: string
279
+ }
280
+
281
+ /** The text fields a range of characters can bind to a variable, as Figma lists them. */
282
+ export const TEXT_BINDABLE_FIELDS = [
283
+ 'fontFamily',
284
+ 'fontSize',
285
+ 'fontStyle',
286
+ 'fontWeight',
287
+ 'letterSpacing',
288
+ 'lineHeight',
289
+ 'paragraphSpacing',
290
+ 'paragraphIndent'
291
+ ] as const
292
+
293
+ export type TextBindableField = (typeof TEXT_BINDABLE_FIELDS)[number]
294
+
295
+ /** Variable IDs bound to text fields, by field. */
296
+ export type TextBoundVariables = Partial<Record<TextBindableField, string>>
297
+
273
298
  export interface CharacterStyleOverride {
274
299
  fontWeight?: number
275
300
  italic?: boolean
@@ -287,6 +312,15 @@ export interface CharacterStyleOverride {
287
312
  fontVariations?: FontVariation[]
288
313
  fontFeatures?: FontFeature[]
289
314
  textLanguage?: string | null
315
+ textCase?: TextCase
316
+ /** A link over the characters; `null`, like leaving it out, links nowhere. */
317
+ hyperlink?: HyperlinkTarget | null
318
+ /** The text style the characters use in place of the text's own; `null` uses none. */
319
+ textStyleId?: string | null
320
+ /** The fill style the characters use in place of the text's own; `null` uses none. */
321
+ fillStyleId?: string | null
322
+ /** The characters' text field bindings, in place of the text's own. */
323
+ boundVariables?: TextBoundVariables
290
324
  }
291
325
 
292
326
  export interface StyleRun {
@@ -2,7 +2,7 @@ import { copyFills, copyStrokes } from '../copy'
2
2
  import type { SceneGraph } from '../index'
3
3
  import { hasInstanceOverride } from '../instances'
4
4
  import type { Color } from '../primitives'
5
- import type { Fill, SceneNode, Stroke } from '../types'
5
+ import type { Fill, SceneNode, Stroke, StyleRun } from '../types'
6
6
  import type { VariableModeFallback } from '../variables'
7
7
  import { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'
8
8
  export { isNumericVariableBindingField } from './fields'
@@ -82,6 +82,43 @@ export function resolvedValueBindings(
82
82
  return updates
83
83
  }
84
84
 
85
+ /** Fields of a range of characters a bound number gives its value; the rest need fonts loaded. */
86
+ const NUMERIC_RUN_FIELDS = ['fontSize', 'fontWeight', 'letterSpacing', 'lineHeight'] as const
87
+
88
+ /**
89
+ * The runs a text's character bindings resolve to in its mode, when a bound number differs from
90
+ * what its characters hold. Bound font families and styles are left as stored, as the text's own.
91
+ */
92
+ export function resolvedRunBindings(
93
+ graph: SceneGraph,
94
+ node: SceneNode,
95
+ fallback: VariableModeFallback = 'active'
96
+ ): Pick<Partial<SceneNode>, 'styleRuns'> {
97
+ const styleRuns = node.styleRuns.map((run): StyleRun => {
98
+ const bound = run.style.boundVariables
99
+ if (!bound) return run
100
+ let style = run.style
101
+ for (const field of NUMERIC_RUN_FIELDS) {
102
+ const variableId = bound[field]
103
+ if (!variableId) continue
104
+ const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)
105
+ if (value === undefined || !Number.isFinite(value) || style[field] === value) continue
106
+ style = { ...style, [field]: value }
107
+ }
108
+ return style === run.style ? run : { ...run, style }
109
+ })
110
+ const changed = styleRuns.some((run, index) => run !== node.styleRuns[index])
111
+ return changed ? { styleRuns } : {}
112
+ }
113
+
114
+ /** The variables a node binds, its own and its characters'. */
115
+ function boundVariableIds(node: SceneNode): string[] {
116
+ return [
117
+ ...Object.values(node.boundVariables),
118
+ ...node.styleRuns.flatMap((run) => Object.values(run.style.boundVariables ?? {}))
119
+ ].filter((id): id is string => typeof id === 'string')
120
+ }
121
+
85
122
  /**
86
123
  * A bound paint takes its whole color from the variable, alpha included, the way Figma stores
87
124
  * it: the variable's RGB at full alpha, and its alpha as the paint's opacity.
@@ -162,7 +199,7 @@ function scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterab
162
199
  if ('subtrees' in scope) return subtreeNodes(graph, scope.subtrees)
163
200
  const variables = variablesResolvingThrough(graph, scope.variables)
164
201
  return [...graph.getAllNodes()].filter((node) =>
165
- Object.values(node.boundVariables).some((id) => variables.has(id))
202
+ boundVariableIds(node).some((id) => variables.has(id))
166
203
  )
167
204
  }
168
205
 
@@ -176,7 +213,8 @@ export function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScop
176
213
  for (const node of scopedNodes(graph, scope)) {
177
214
  const updates = {
178
215
  ...resolvedNumericBindings(graph, node),
179
- ...resolvedValueBindings(graph, node)
216
+ ...resolvedValueBindings(graph, node),
217
+ ...resolvedRunBindings(graph, node)
180
218
  }
181
219
  if (Object.keys(updates).length === 0) continue
182
220
  graph.updateNode(node.id, updates)
@@ -1,36 +0,0 @@
1
- //#region src/fields/text.ts
2
- /** Fields shared by shaping, paragraph measurement, and auto-width invalidation. */
3
- const TEXT_METRIC_FIELDS = [
4
- "text",
5
- "fontSize",
6
- "fontFamily",
7
- "fontWeight",
8
- "italic",
9
- "letterSpacing",
10
- "styleRuns",
11
- "fontVariations",
12
- "fontFeatures",
13
- "textParagraphs",
14
- "listSpacing",
15
- "paragraphSpacing",
16
- "paragraphIndent",
17
- "hangingList"
18
- ];
19
- const TEXT_SHAPING_FIELDS = [
20
- ...TEXT_METRIC_FIELDS,
21
- "lineHeight",
22
- "textCase",
23
- "textDirection",
24
- "textAlignHorizontal",
25
- "textAlignVertical"
26
- ];
27
- const TEXT_LAYOUT_FIELDS = [
28
- "width",
29
- "height",
30
- "textAutoResize",
31
- "maxLines"
32
- ];
33
- //#endregion
34
- export { TEXT_LAYOUT_FIELDS, TEXT_METRIC_FIELDS, TEXT_SHAPING_FIELDS };
35
-
36
- //# sourceMappingURL=text.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"text.js","names":[],"sources":["../../../src/fields/text.ts"],"sourcesContent":["import type { SceneNode } from '../types'\n\n/** Fields shared by shaping, paragraph measurement, and auto-width invalidation. */\nexport const TEXT_METRIC_FIELDS = [\n 'text',\n 'fontSize',\n 'fontFamily',\n 'fontWeight',\n 'italic',\n 'letterSpacing',\n 'styleRuns',\n 'fontVariations',\n 'fontFeatures',\n 'textParagraphs',\n 'listSpacing',\n 'paragraphSpacing',\n 'paragraphIndent',\n 'hangingList'\n] as const satisfies readonly (keyof SceneNode)[]\n\nexport const TEXT_SHAPING_FIELDS = [\n ...TEXT_METRIC_FIELDS,\n 'lineHeight',\n 'textCase',\n 'textDirection',\n 'textAlignHorizontal',\n 'textAlignVertical'\n] as const satisfies readonly (keyof SceneNode)[]\n\nexport const TEXT_LAYOUT_FIELDS = [\n 'width',\n 'height',\n 'textAutoResize',\n 'maxLines'\n] as const satisfies readonly (keyof SceneNode)[]\n"],"mappings":";;AAGA,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,sBAAsB;CACjC,GAAG;CACH;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;AACF"}