@open-pencil/scene-graph 0.15.0 → 0.16.0-beta.1

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 (232) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -1
  3. package/dist/chunks/behaviours/kinds.js +273 -0
  4. package/dist/chunks/behaviours/kinds.js.map +1 -0
  5. package/dist/chunks/behaviours/layers.js +596 -0
  6. package/dist/chunks/behaviours/layers.js.map +1 -0
  7. package/dist/chunks/behaviours/spec.js +181 -0
  8. package/dist/chunks/behaviours/spec.js.map +1 -0
  9. package/dist/chunks/buffered-events.js +57 -0
  10. package/dist/chunks/buffered-events.js.map +1 -0
  11. package/dist/chunks/color/contrast.js +57 -0
  12. package/dist/chunks/color/contrast.js.map +1 -0
  13. package/dist/chunks/{components/properties.js → color/index.js} +573 -521
  14. package/dist/chunks/color/index.js.map +1 -0
  15. package/dist/chunks/comments/document.js +32 -0
  16. package/dist/chunks/comments/document.js.map +1 -0
  17. package/dist/chunks/comments/list.js +182 -0
  18. package/dist/chunks/comments/list.js.map +1 -0
  19. package/dist/chunks/comments/merge.js +58 -0
  20. package/dist/chunks/comments/merge.js.map +1 -0
  21. package/dist/chunks/components/exposure.js +2021 -0
  22. package/dist/chunks/components/exposure.js.map +1 -0
  23. package/dist/chunks/components/variants.js +32 -0
  24. package/dist/chunks/components/variants.js.map +1 -0
  25. package/dist/chunks/coordinate.js +93 -55
  26. package/dist/chunks/coordinate.js.map +1 -1
  27. package/dist/chunks/css/grid.js +94 -0
  28. package/dist/chunks/css/grid.js.map +1 -0
  29. package/dist/chunks/css/index.js +160 -0
  30. package/dist/chunks/css/index.js.map +1 -0
  31. package/dist/chunks/fields/geometry.js +14 -0
  32. package/dist/chunks/fields/geometry.js.map +1 -0
  33. package/dist/chunks/fields/text.js +36 -0
  34. package/dist/chunks/fields/text.js.map +1 -0
  35. package/dist/chunks/group-bounds.js +104 -0
  36. package/dist/chunks/group-bounds.js.map +1 -0
  37. package/dist/chunks/icons/glyph.js +147 -0
  38. package/dist/chunks/icons/glyph.js.map +1 -0
  39. package/dist/chunks/index.js +1712 -662
  40. package/dist/chunks/index.js.map +1 -1
  41. package/dist/color.d.ts +72 -0
  42. package/dist/color.d.ts.map +1 -0
  43. package/dist/color.js +3 -0
  44. package/dist/constants.d.ts +2 -2
  45. package/dist/constants.js +2 -2
  46. package/dist/constants2.d.ts +3 -1
  47. package/dist/constants2.d.ts.map +1 -1
  48. package/dist/coordinate.d.ts +2 -448
  49. package/dist/coordinate.js +2 -2
  50. package/dist/copy.d.ts +1 -1
  51. package/dist/copy.js +1 -1
  52. package/dist/css.d.ts +39 -0
  53. package/dist/css.d.ts.map +1 -0
  54. package/dist/css.js +3 -0
  55. package/dist/geometry.d.ts +1 -1
  56. package/dist/geometry.js +1 -1
  57. package/dist/gradient.d.ts +51 -0
  58. package/dist/gradient.d.ts.map +1 -0
  59. package/dist/gradient.js +132 -0
  60. package/dist/gradient.js.map +1 -0
  61. package/dist/guides.d.ts +2 -2
  62. package/dist/guides.js +39 -0
  63. package/dist/guides.js.map +1 -0
  64. package/dist/hit-test.d.ts +2 -9
  65. package/dist/hit-test.js +154 -18
  66. package/dist/hit-test.js.map +1 -1
  67. package/dist/index.d.ts +4 -8
  68. package/dist/index.js +20 -5
  69. package/dist/instances.d.ts +2 -2
  70. package/dist/instances.js +2 -2
  71. package/dist/layout.d.ts +2 -0
  72. package/dist/layout.js +4 -0
  73. package/dist/node-defaults.d.ts +2 -8
  74. package/dist/node-defaults.js +2 -2
  75. package/dist/order-keys.d.ts +39 -0
  76. package/dist/order-keys.d.ts.map +1 -0
  77. package/dist/order-keys.js +136 -0
  78. package/dist/order-keys.js.map +1 -0
  79. package/dist/parse-path.d.ts +7 -1
  80. package/dist/parse-path.d.ts.map +1 -1
  81. package/dist/parse-path.js +6 -2
  82. package/dist/parse-path.js.map +1 -1
  83. package/dist/polygon.d.ts +53 -0
  84. package/dist/polygon.d.ts.map +1 -0
  85. package/dist/polygon.js +205 -0
  86. package/dist/polygon.js.map +1 -0
  87. package/dist/preview.d.ts +1 -1
  88. package/dist/random.d.ts +7 -0
  89. package/dist/random.d.ts.map +1 -0
  90. package/dist/random.js +2 -0
  91. package/dist/resize.d.ts +11 -2
  92. package/dist/resize.d.ts.map +1 -1
  93. package/dist/resize.js +2 -184
  94. package/dist/snap.d.ts +1 -1
  95. package/dist/text-direction.d.ts +13 -0
  96. package/dist/text-direction.d.ts.map +1 -0
  97. package/dist/text-direction.js +31 -0
  98. package/dist/text-direction.js.map +1 -0
  99. package/dist/text-picture.d.ts +1 -1
  100. package/dist/text-picture.d.ts.map +1 -1
  101. package/dist/text.d.ts +2 -0
  102. package/dist/text.js +3 -0
  103. package/dist/types.d.ts +2063 -13
  104. package/dist/types.d.ts.map +1 -1
  105. package/dist/types.js +2 -1
  106. package/dist/types2.d.ts +2 -2
  107. package/dist/undo.d.ts +2 -2
  108. package/dist/undo.js +2 -2
  109. package/dist/undo2.d.ts +29 -1
  110. package/dist/undo2.d.ts.map +1 -1
  111. package/dist/variables.d.ts +2 -29
  112. package/dist/variables.js +2 -2
  113. package/dist/variant-properties.d.ts +9 -1
  114. package/dist/variant-properties.d.ts.map +1 -1
  115. package/dist/variant-properties.js +36 -1
  116. package/dist/variant-properties.js.map +1 -1
  117. package/dist/vector-network.d.ts +1 -1
  118. package/dist/vector-network.js +1 -1
  119. package/package.json +60 -9
  120. package/src/behaviours/kinds.ts +185 -0
  121. package/src/behaviours/layers.ts +51 -0
  122. package/src/behaviours/model.ts +192 -0
  123. package/src/behaviours/schema.ts +58 -0
  124. package/src/behaviours/spec.ts +223 -0
  125. package/src/buffered-events.ts +64 -0
  126. package/src/color/contrast.ts +31 -0
  127. package/src/color/index.ts +88 -0
  128. package/src/color/management.ts +210 -0
  129. package/src/color/normalize.ts +7 -0
  130. package/src/color/okhcl.ts +201 -0
  131. package/src/comments/document.ts +51 -0
  132. package/src/comments/list.ts +52 -0
  133. package/src/comments/merge.ts +63 -0
  134. package/src/comments/threads.ts +156 -0
  135. package/src/components/exposure.ts +61 -0
  136. package/src/components/properties.ts +18 -15
  137. package/src/components/variants.ts +53 -0
  138. package/src/constants.ts +2 -0
  139. package/src/coordinate.ts +100 -43
  140. package/src/copy.ts +13 -5
  141. package/src/css/grid.ts +70 -0
  142. package/src/css/index.ts +9 -0
  143. package/src/css/layout.ts +53 -0
  144. package/src/css/shadows.ts +68 -0
  145. package/src/css/values.ts +42 -0
  146. package/src/export-format.ts +12 -0
  147. package/src/fields/geometry.ts +11 -0
  148. package/src/fields/text.ts +35 -0
  149. package/src/gradient.ts +166 -0
  150. package/src/group-bounds.ts +131 -0
  151. package/src/guides.ts +39 -0
  152. package/src/hit-test.ts +219 -25
  153. package/src/icons/glyph.ts +128 -0
  154. package/src/icons/model.ts +54 -0
  155. package/src/icons/schema.ts +18 -0
  156. package/src/index.ts +344 -56
  157. package/src/instance-overrides.ts +27 -0
  158. package/src/instances/copies.ts +239 -0
  159. package/src/instances/cycles.ts +73 -0
  160. package/src/instances/fields.ts +143 -0
  161. package/src/instances/main-component.ts +19 -0
  162. package/src/instances/placement.ts +29 -0
  163. package/src/instances/source-walk.ts +41 -0
  164. package/src/instances/sync.ts +599 -0
  165. package/src/instances.ts +122 -330
  166. package/src/layout/aspect-ratio.ts +51 -0
  167. package/src/{layout-guides.ts → layout/guides.ts} +1 -1
  168. package/src/layout/index.ts +4 -0
  169. package/src/layout/keywords.ts +73 -0
  170. package/src/layout/sizing.ts +196 -0
  171. package/src/mutation-impact.ts +25 -10
  172. package/src/node-defaults.ts +50 -2
  173. package/src/order-keys.ts +162 -0
  174. package/src/parse-path.ts +10 -2
  175. package/src/plugin-data/field.ts +131 -0
  176. package/src/plugin-data/fields.ts +246 -0
  177. package/src/polygon.ts +211 -0
  178. package/src/preview.ts +1 -1
  179. package/src/random.ts +28 -0
  180. package/src/resize.ts +99 -12
  181. package/src/scaling/index.ts +2 -0
  182. package/src/scaling/node.ts +164 -0
  183. package/src/scaling/tree.ts +50 -0
  184. package/src/shaders/model.ts +98 -0
  185. package/src/shaders/schema.ts +48 -0
  186. package/src/slots/authoring.ts +101 -0
  187. package/src/slots/content.ts +124 -0
  188. package/src/slots/frames.ts +160 -0
  189. package/src/slots/limits.ts +49 -0
  190. package/src/text/direction.ts +55 -0
  191. package/src/text/index.ts +2 -0
  192. package/src/text/lists.ts +138 -0
  193. package/src/text/paragraphs.ts +241 -0
  194. package/src/{text-picture.ts → text/picture.ts} +21 -29
  195. package/src/transfer/apply.ts +84 -0
  196. package/src/transfer/history.ts +49 -0
  197. package/src/transfer/identity.ts +16 -0
  198. package/src/transfer/index.ts +6 -0
  199. package/src/transfer/nodes.ts +108 -0
  200. package/src/transfer/plan.ts +107 -0
  201. package/src/transfer/references.ts +9 -0
  202. package/src/transfer/remove.ts +39 -0
  203. package/src/transfer/validation.ts +54 -0
  204. package/src/transfer/variables.ts +82 -0
  205. package/src/types.ts +221 -11
  206. package/src/undo.ts +54 -2
  207. package/src/variables/bindings.ts +186 -0
  208. package/src/variables/fields.ts +43 -0
  209. package/src/variables/token.ts +14 -0
  210. package/src/variables/units.ts +15 -0
  211. package/src/variables.ts +118 -69
  212. package/src/variant-properties.ts +50 -0
  213. package/dist/chunks/components/properties.js.map +0 -1
  214. package/dist/chunks/export-scale.js +0 -19
  215. package/dist/chunks/export-scale.js.map +0 -1
  216. package/dist/coordinate.d.ts.map +0 -1
  217. package/dist/coordinate2.d.ts +0 -2
  218. package/dist/guides2.d.ts +0 -11
  219. package/dist/guides2.d.ts.map +0 -1
  220. package/dist/hit-test.d.ts.map +0 -1
  221. package/dist/layout-guides.d.ts +0 -2
  222. package/dist/layout-guides.js +0 -2
  223. package/dist/layout-guides2.d.ts +0 -16
  224. package/dist/layout-guides2.d.ts.map +0 -1
  225. package/dist/node-defaults.d.ts.map +0 -1
  226. package/dist/preview2.d.ts +0 -12
  227. package/dist/preview2.d.ts.map +0 -1
  228. package/dist/resize.js.map +0 -1
  229. package/dist/variables.d.ts.map +0 -1
  230. package/dist/vector-network2.d.ts +0 -32
  231. package/dist/vector-network2.d.ts.map +0 -1
  232. package/src/instance-overrides.test.ts +0 -67
@@ -0,0 +1,160 @@
1
+ import type { SceneGraph } from '../index'
2
+ import { instanceMainComponent } from '../instances/main-component'
3
+ import type { SceneNode } from '../types'
4
+
5
+ /** The slot property a frame holds the content of, if it is a slot. */
6
+ export function slotPropertyId(node: SceneNode): string | undefined {
7
+ return node.componentPropertyReferences.find((reference) => reference.field === 'SLOT_CONTENT')
8
+ ?.propertyId
9
+ }
10
+
11
+ /**
12
+ * Whether this slot frame's children belong to its instance rather than its component: the
13
+ * nearest enclosing instance assigns the slot. Such content is never synced from the component.
14
+ */
15
+ export function ownsSlotContent(
16
+ graph: SceneGraph,
17
+ node: SceneNode,
18
+ propertyId = slotPropertyId(node)
19
+ ): boolean {
20
+ if (!propertyId) return false
21
+ let owner = node.parentId ? graph.nodes.get(node.parentId) : undefined
22
+ while (owner && owner.type !== 'INSTANCE')
23
+ owner = owner.parentId ? graph.nodes.get(owner.parentId) : undefined
24
+ return !!owner && Object.hasOwn(owner.componentPropertyAssignments, propertyId)
25
+ }
26
+
27
+ /** The name of a slot property as the instance's component (or the component's set) defines it. */
28
+ function slotName(graph: SceneGraph, instance: SceneNode, propertyId: string) {
29
+ const component = instanceMainComponent(graph, instance)
30
+ const set = component?.parentId ? graph.nodes.get(component.parentId) : undefined
31
+ return [component, set]
32
+ .flatMap((node) => node?.componentPropertyDefinitions ?? [])
33
+ .find((definition) => definition.id === propertyId && definition.type === 'SLOT')?.name
34
+ }
35
+
36
+ /** An instance's slot frames, without entering nested instances, whose slots are their own. */
37
+ export function instanceSlotFrames(graph: SceneGraph, instance: SceneNode): SceneNode[] {
38
+ const frames: SceneNode[] = []
39
+ const visit = (node: SceneNode): void => {
40
+ for (const childId of node.childIds) {
41
+ const child = graph.nodes.get(childId)
42
+ if (!child) continue
43
+ if (slotPropertyId(child)) frames.push(child)
44
+ else if (child.type !== 'INSTANCE') visit(child)
45
+ }
46
+ }
47
+ visit(instance)
48
+ return frames
49
+ }
50
+
51
+ /** One slot's owned content, parked while the instance it belongs to is rebuilt. */
52
+ interface ParkedSlot {
53
+ /** Names of the nested instances leading to the slot's owner; empty for the instance itself. */
54
+ path: string[]
55
+ /** The slot property's name, which the replacement must share. */
56
+ name: string
57
+ /** Content layer ids, in layer order. */
58
+ content: string[]
59
+ }
60
+
61
+ /** Owned slot content parked under an instance while its component changes. */
62
+ export interface ParkedSlotContent {
63
+ slots: ParkedSlot[]
64
+ /** The instance's own slot assignments the content was parked from. */
65
+ propertyIds: string[]
66
+ }
67
+
68
+ /** Instances directly inside this one: not inside another nested instance or a slot. */
69
+ function nestedInstances(graph: SceneGraph, owner: SceneNode): SceneNode[] {
70
+ const found: SceneNode[] = []
71
+ const visit = (node: SceneNode): void => {
72
+ for (const childId of node.childIds) {
73
+ const child = graph.nodes.get(childId)
74
+ if (!child || slotPropertyId(child)) continue
75
+ if (child.type === 'INSTANCE') found.push(child)
76
+ else visit(child)
77
+ }
78
+ }
79
+ visit(owner)
80
+ return found
81
+ }
82
+
83
+ /** The nested instance a name path leads to from `root`, matched by layer name as Figma does. */
84
+ function instanceAtPath(
85
+ graph: SceneGraph,
86
+ root: SceneNode,
87
+ path: readonly string[]
88
+ ): SceneNode | undefined {
89
+ let current: SceneNode | undefined = root
90
+ for (const name of path) {
91
+ current = current && nestedInstances(graph, current).find((node) => node.name === name)
92
+ }
93
+ return current
94
+ }
95
+
96
+ /**
97
+ * Park the slot content an instance and the instances nested in it own, by slot name and the
98
+ * nested instance's name path, directly under the instance, so its component can be replaced.
99
+ * Figma keeps that content when a variant switch or swap leads to slots of the same names.
100
+ */
101
+ export function detachOwnedSlotContent(graph: SceneGraph, instance: SceneNode): ParkedSlotContent {
102
+ const parked: ParkedSlotContent = { slots: [], propertyIds: [] }
103
+ const visit = (owner: SceneNode, path: string[]): void => {
104
+ for (const nested of nestedInstances(graph, owner)) visit(nested, [...path, nested.name])
105
+ for (const frame of instanceSlotFrames(graph, owner)) {
106
+ const propertyId = slotPropertyId(frame)
107
+ if (!propertyId || !Object.hasOwn(owner.componentPropertyAssignments, propertyId)) continue
108
+ if (owner.id === instance.id) parked.propertyIds.push(propertyId)
109
+ const name = slotName(graph, owner, propertyId)
110
+ const key = [...path, name].join('\u0000')
111
+ if (!name || parked.slots.some((slot) => [...slot.path, slot.name].join('\u0000') === key))
112
+ continue
113
+ const content = [...frame.childIds]
114
+ for (const id of content) graph.reorderChild(id, instance.id, instance.childIds.length)
115
+ parked.slots.push({ path, name, content })
116
+ }
117
+ }
118
+ visit(instance, [])
119
+ return parked
120
+ }
121
+
122
+ /** Move parked content into the slots of the same names and paths, and reassign them. */
123
+ export function restoreOwnedSlotContent(
124
+ graph: SceneGraph,
125
+ instance: SceneNode,
126
+ parked: ParkedSlotContent
127
+ ): void {
128
+ if (parked.slots.length === 0 && parked.propertyIds.length === 0) return
129
+ graph.updateNode(instance.id, {
130
+ componentPropertyAssignments: Object.fromEntries(
131
+ Object.entries(instance.componentPropertyAssignments).filter(
132
+ ([id]) => !parked.propertyIds.includes(id)
133
+ )
134
+ )
135
+ })
136
+ for (const slot of parked.slots) {
137
+ const owner = instanceAtPath(graph, instance, slot.path)
138
+ const frame =
139
+ owner &&
140
+ instanceSlotFrames(graph, owner).find((candidate) => {
141
+ const propertyId = slotPropertyId(candidate)
142
+ return !!propertyId && slotName(graph, owner, propertyId) === slot.name
143
+ })
144
+ const propertyId = frame && slotPropertyId(frame)
145
+ if (
146
+ !owner ||
147
+ !frame ||
148
+ !propertyId ||
149
+ Object.hasOwn(owner.componentPropertyAssignments, propertyId)
150
+ ) {
151
+ for (const id of slot.content) graph.deleteNode(id)
152
+ continue
153
+ }
154
+ for (const id of Array.from(frame.childIds)) graph.deleteNode(id)
155
+ for (const [index, id] of slot.content.entries()) graph.reorderChild(id, frame.id, index)
156
+ graph.updateNode(owner.id, {
157
+ componentPropertyAssignments: { ...owner.componentPropertyAssignments, [propertyId]: '' }
158
+ })
159
+ }
160
+ }
@@ -0,0 +1,49 @@
1
+ import type { SceneGraph } from '../index'
2
+ import type { ComponentPropertyDefinition, SceneNode } from '../types'
3
+
4
+ /** A limit a slot's content breaks, named as Figma's `SlotNode.limitViolations` names them. */
5
+ export type SlotLimitViolation = 'BELOW_MIN' | 'ABOVE_MAX' | 'HAS_NON_PREFERRED'
6
+
7
+ /** Whether a component is among a slot's preferred values, by id, key, or library key. */
8
+ export function isPreferredComponent(
9
+ component: SceneNode | undefined,
10
+ preferredValues: readonly string[] = []
11
+ ): boolean {
12
+ if (!component) return false
13
+ return [component.id, component.componentKey, component.sourceLibraryKey].some(
14
+ (value) => !!value && preferredValues.includes(value)
15
+ )
16
+ }
17
+
18
+ /** Content layers a preferred-only slot does not allow: anything but preferred instances. */
19
+ export function nonPreferredLayers(
20
+ graph: SceneGraph,
21
+ definition: ComponentPropertyDefinition,
22
+ content: readonly SceneNode[]
23
+ ): SceneNode[] {
24
+ if (!definition.slotSettings?.allowPreferredValuesOnly) return []
25
+ return content.filter(
26
+ (node) =>
27
+ node.type !== 'INSTANCE' ||
28
+ !isPreferredComponent(
29
+ node.componentId ? graph.getNode(node.componentId) : undefined,
30
+ definition.preferredValues
31
+ )
32
+ )
33
+ }
34
+
35
+ /** The limits a slot's content breaks; below-minimum and above-maximum exclude each other. */
36
+ export function slotLimitViolations(
37
+ graph: SceneGraph,
38
+ definition: ComponentPropertyDefinition,
39
+ content: readonly SceneNode[]
40
+ ): SlotLimitViolation[] {
41
+ const settings = definition.slotSettings
42
+ const violations: SlotLimitViolation[] = []
43
+ if (settings?.minChildren !== undefined && content.length < settings.minChildren)
44
+ violations.push('BELOW_MIN')
45
+ else if (settings?.maxChildren !== undefined && content.length > settings.maxChildren)
46
+ violations.push('ABOVE_MAX')
47
+ if (nonPreferredLayers(graph, definition, content).length) violations.push('HAS_NON_PREFERRED')
48
+ return violations
49
+ }
@@ -0,0 +1,55 @@
1
+ import type { LayoutDirection, SceneNode, TextDirection } from '../types'
2
+
3
+ const RTL_CHAR_RE =
4
+ /\p{Script=Arabic}|\p{Script=Hebrew}|\p{Script=Syriac}|\p{Script=Thaana}|\p{Script=Nko}|\p{Script=Adlam}/u
5
+ const LTR_CHAR_RE = /\p{Script=Latin}|\p{Script=Cyrillic}|\p{Script=Greek}/u
6
+
7
+ export function detectTextDirection(text: string): Exclude<TextDirection, 'AUTO'> {
8
+ for (const char of text) {
9
+ if (RTL_CHAR_RE.test(char)) return 'RTL'
10
+ if (LTR_CHAR_RE.test(char)) return 'LTR'
11
+ }
12
+ return 'LTR'
13
+ }
14
+
15
+ export function resolveTextDirection(
16
+ direction: TextDirection,
17
+ text: string
18
+ ): Exclude<TextDirection, 'AUTO'> {
19
+ return direction === 'AUTO' ? detectTextDirection(text) : direction
20
+ }
21
+
22
+ export function resolveNodeTextDirection(
23
+ node: Pick<SceneNode, 'textDirection' | 'text'>
24
+ ): 'LTR' | 'RTL' {
25
+ return resolveTextDirection(node.textDirection, node.text)
26
+ }
27
+
28
+ export function resolveNodeLayoutDirection(
29
+ node: { layoutDirection?: LayoutDirection },
30
+ inheritedDirection: Exclude<LayoutDirection, 'AUTO'> = 'LTR'
31
+ ): Exclude<LayoutDirection, 'AUTO'> {
32
+ return !node.layoutDirection || node.layoutDirection === 'AUTO'
33
+ ? inheritedDirection
34
+ : node.layoutDirection
35
+ }
36
+
37
+ export function isLogicalTextAlignStart(
38
+ node: Pick<SceneNode, 'textAlignHorizontal' | 'textDirection' | 'text'>
39
+ ): boolean {
40
+ const direction = resolveNodeTextDirection(node)
41
+ return (
42
+ (direction === 'LTR' && node.textAlignHorizontal === 'LEFT') ||
43
+ (direction === 'RTL' && node.textAlignHorizontal === 'RIGHT')
44
+ )
45
+ }
46
+
47
+ export function isLogicalTextAlignEnd(
48
+ node: Pick<SceneNode, 'textAlignHorizontal' | 'textDirection' | 'text'>
49
+ ): boolean {
50
+ const direction = resolveNodeTextDirection(node)
51
+ return (
52
+ (direction === 'LTR' && node.textAlignHorizontal === 'RIGHT') ||
53
+ (direction === 'RTL' && node.textAlignHorizontal === 'LEFT')
54
+ )
55
+ }
@@ -0,0 +1,2 @@
1
+ export * from './lists'
2
+ export * from './paragraphs'
@@ -0,0 +1,138 @@
1
+ import type { TextParagraphStyle } from '../types'
2
+ import { paragraphStyleAt, textParagraphRanges, type TextParagraphRange } from './paragraphs'
3
+
4
+ /** How an ordered item's number is written at its nesting level. */
5
+ export type ListNumberFormat = 'DECIMAL' | 'LOWER_ALPHA' | 'LOWER_ROMAN'
6
+
7
+ /** A list item paragraph and what marks it. */
8
+ export interface TextListItem extends TextParagraphRange {
9
+ paragraph: number
10
+ listType: 'ORDERED' | 'UNORDERED'
11
+ /** Nesting level, from 1. */
12
+ level: number
13
+ /** The item's number among the items of its list at its level, from 1. */
14
+ ordinal: number
15
+ /** The marker drawn before the item: a bullet, or its number and a period. */
16
+ marker: string
17
+ /** Whether the item starts a new count at its level. */
18
+ startsList: boolean
19
+ /**
20
+ * The paragraph that starts the group of list items this item belongs to. A list group runs
21
+ * from a list item that follows a plain paragraph, or that starts a top-level list, and its
22
+ * first character styles every marker and indent in it.
23
+ */
24
+ groupStart: number
25
+ }
26
+
27
+ /** The marker of an unordered item, at every level. */
28
+ export const LIST_BULLET = '•'
29
+
30
+ const NUMBER_FORMATS: readonly ListNumberFormat[] = ['DECIMAL', 'LOWER_ALPHA', 'LOWER_ROMAN']
31
+
32
+ /** Ordered items count in decimal, then letters, then roman numerals, repeating as they nest. */
33
+ export function listNumberFormat(level: number): ListNumberFormat {
34
+ return NUMBER_FORMATS[(Math.max(1, level) - 1) % NUMBER_FORMATS.length]
35
+ }
36
+
37
+ function alphabetic(value: number): string {
38
+ let letters = ''
39
+ for (let rest = value; rest > 0; rest = Math.floor((rest - 1) / 26)) {
40
+ letters = String.fromCharCode(97 + ((rest - 1) % 26)) + letters
41
+ }
42
+ return letters
43
+ }
44
+
45
+ const ROMAN_DIGITS: ReadonlyArray<readonly [number, string]> = [
46
+ [1000, 'm'],
47
+ [900, 'cm'],
48
+ [500, 'd'],
49
+ [400, 'cd'],
50
+ [100, 'c'],
51
+ [90, 'xc'],
52
+ [50, 'l'],
53
+ [40, 'xl'],
54
+ [10, 'x'],
55
+ [9, 'ix'],
56
+ [5, 'v'],
57
+ [4, 'iv'],
58
+ [1, 'i']
59
+ ]
60
+
61
+ function roman(value: number): string {
62
+ let rest = value
63
+ let numeral = ''
64
+ for (const [amount, digits] of ROMAN_DIGITS) {
65
+ for (; rest >= amount; rest -= amount) numeral += digits
66
+ }
67
+ return numeral
68
+ }
69
+
70
+ /** An ordered item's number as its level writes it, without the period. */
71
+ export function formatListNumber(ordinal: number, format: ListNumberFormat): string {
72
+ if (format === 'LOWER_ALPHA') return alphabetic(ordinal)
73
+ if (format === 'LOWER_ROMAN') return roman(ordinal)
74
+ return String(ordinal)
75
+ }
76
+
77
+ interface LevelCount {
78
+ listType: TextListItem['listType']
79
+ count: number
80
+ }
81
+
82
+ /**
83
+ * The list items of a text, numbered as Figma numbers them: each level counts its own items,
84
+ * a deeper item leaves the count above it running, a shallower one restarts the counts below
85
+ * it, and a plain paragraph or an item of the other list type restarts the count.
86
+ */
87
+ export function textListItems(
88
+ text: string,
89
+ paragraphs: readonly TextParagraphStyle[]
90
+ ): TextListItem[] {
91
+ if (!paragraphs.some((paragraph) => paragraph.listType !== 'NONE')) return []
92
+ const items: TextListItem[] = []
93
+ const counts: Array<LevelCount | undefined> = []
94
+ let groupStart = -1
95
+ for (const [paragraph, range] of textParagraphRanges(text).entries()) {
96
+ const style = paragraphStyleAt(paragraphs, paragraph)
97
+ if (style.listType === 'NONE') {
98
+ counts.length = 0
99
+ groupStart = -1
100
+ continue
101
+ }
102
+ const level = Math.max(1, style.indentation)
103
+ counts.length = Math.min(counts.length, level)
104
+ const current = counts[level - 1]
105
+ const continues = current?.listType === style.listType
106
+ const count = continues ? current.count + 1 : 1
107
+ counts[level - 1] = { listType: style.listType, count }
108
+ const shallower = counts.slice(0, level - 1).some((entry) => entry !== undefined)
109
+ if (groupStart === -1 || (!continues && !shallower)) groupStart = paragraph
110
+ const marker =
111
+ style.listType === 'UNORDERED'
112
+ ? LIST_BULLET
113
+ : `${formatListNumber(count, listNumberFormat(level))}.`
114
+ items.push({
115
+ ...range,
116
+ paragraph,
117
+ listType: style.listType,
118
+ level,
119
+ ordinal: count,
120
+ marker,
121
+ startsList: !continues,
122
+ groupStart
123
+ })
124
+ }
125
+ return items
126
+ }
127
+
128
+ /**
129
+ * Digits in the largest number of a top-level ordered item. Figma widens the indent of every
130
+ * ordered item by the extra digits, so a list's numbers line up past nine.
131
+ */
132
+ export function topLevelNumberDigits(items: readonly TextListItem[]): number {
133
+ let largest = 0
134
+ for (const item of items) {
135
+ if (item.listType === 'ORDERED' && item.level === 1) largest = Math.max(largest, item.ordinal)
136
+ }
137
+ return largest === 0 ? 0 : String(largest).length
138
+ }
@@ -0,0 +1,241 @@
1
+ import type {
2
+ SceneNode,
3
+ TextListType,
4
+ TextParagraphSpacingField,
5
+ TextParagraphStyle
6
+ } from '../types'
7
+
8
+ /** The style of a paragraph with no entry: not in a list. */
9
+ export const PLAIN_PARAGRAPH: Readonly<TextParagraphStyle> = Object.freeze({
10
+ listType: 'NONE',
11
+ indentation: 0
12
+ })
13
+
14
+ /** Figma nests list items at most this deep. */
15
+ export const MAX_LIST_INDENTATION = 5
16
+
17
+ /** A paragraph's characters: `start` to `end`, not counting the newline that ends it. */
18
+ export interface TextParagraphRange {
19
+ start: number
20
+ end: number
21
+ }
22
+
23
+ /** The paragraphs of `text`: one per line ending at a newline, and one after the last. */
24
+ export function textParagraphRanges(text: string): TextParagraphRange[] {
25
+ const ranges: TextParagraphRange[] = []
26
+ let start = 0
27
+ for (let index = text.indexOf('\n'); index !== -1; index = text.indexOf('\n', start)) {
28
+ ranges.push({ start, end: index })
29
+ start = index + 1
30
+ }
31
+ ranges.push({ start, end: text.length })
32
+ return ranges
33
+ }
34
+
35
+ /** The paragraph holding character `index`; a newline belongs to the paragraph it ends. */
36
+ export function paragraphIndexAt(text: string, index: number): number {
37
+ let paragraph = 0
38
+ const end = Math.min(index, text.length)
39
+ for (let at = text.indexOf('\n'); at !== -1 && at < end; at = text.indexOf('\n', at + 1)) {
40
+ paragraph++
41
+ }
42
+ return paragraph
43
+ }
44
+
45
+ export function paragraphStyleAt(
46
+ paragraphs: readonly TextParagraphStyle[],
47
+ paragraph: number
48
+ ): TextParagraphStyle {
49
+ return paragraphs[paragraph] ?? PLAIN_PARAGRAPH
50
+ }
51
+
52
+ export const TEXT_PARAGRAPH_SPACING_FIELDS: readonly TextParagraphSpacingField[] = [
53
+ 'listSpacing',
54
+ 'paragraphSpacing',
55
+ 'paragraphIndent'
56
+ ]
57
+
58
+ /** A paragraph's spacing: its own value, or the text's when it sets none. */
59
+ export function paragraphSpacingAt(
60
+ node: Pick<SceneNode, 'textParagraphs' | TextParagraphSpacingField>,
61
+ paragraph: number,
62
+ field: TextParagraphSpacingField
63
+ ): number {
64
+ return paragraphStyleAt(node.textParagraphs, paragraph)[field] ?? node[field]
65
+ }
66
+
67
+ /** Whether a paragraph sets any spacing of its own. */
68
+ export function hasParagraphSpacing(style: TextParagraphStyle): boolean {
69
+ return TEXT_PARAGRAPH_SPACING_FIELDS.some((field) => style[field] !== undefined)
70
+ }
71
+
72
+ /** A paragraph style with its own `field` set, or following the text again for `undefined`. */
73
+ export function withParagraphSpacing(
74
+ style: TextParagraphStyle,
75
+ field: TextParagraphSpacingField,
76
+ value: number | undefined
77
+ ): TextParagraphStyle {
78
+ const { [field]: _previous, ...rest } = style
79
+ return value === undefined ? rest : { ...rest, [field]: value }
80
+ }
81
+
82
+ /** Every paragraph's `field`, or `null` when they differ. */
83
+ export function sharedParagraphSpacing(
84
+ node: Pick<SceneNode, 'text' | 'textParagraphs' | TextParagraphSpacingField>,
85
+ field: TextParagraphSpacingField,
86
+ first = 0,
87
+ last = paragraphCount(node.text) - 1
88
+ ): number | null {
89
+ const value = paragraphSpacingAt(node, first, field)
90
+ for (let index = first + 1; index <= last; index++) {
91
+ if (paragraphSpacingAt(node, index, field) !== value) return null
92
+ }
93
+ return value
94
+ }
95
+
96
+ /** Paragraph styles with no paragraph setting its own `field`, as setting the text's does. */
97
+ export function paragraphStylesWithoutSpacing(
98
+ paragraphs: readonly TextParagraphStyle[],
99
+ field: TextParagraphSpacingField
100
+ ): TextParagraphStyle[] {
101
+ return trimParagraphStyles(
102
+ paragraphs.map((style) => withParagraphSpacing(style, field, undefined)),
103
+ paragraphs.length
104
+ )
105
+ }
106
+
107
+ /** Whether any paragraph of the node is a list item. */
108
+ export function hasTextList(node: Pick<SceneNode, 'textParagraphs'>): boolean {
109
+ return node.textParagraphs.some((paragraph) => paragraph.listType !== 'NONE')
110
+ }
111
+
112
+ /**
113
+ * Paragraph styles for `count` paragraphs, without the plain paragraphs at the end, so text
114
+ * without lists, indentation, or paragraph spacing of its own keeps none.
115
+ */
116
+ export function trimParagraphStyles(
117
+ paragraphs: readonly TextParagraphStyle[],
118
+ count: number
119
+ ): TextParagraphStyle[] {
120
+ const styles = paragraphs.slice(0, count).map((paragraph) => ({ ...paragraph }))
121
+ while (styles.length > 0) {
122
+ const last = styles[styles.length - 1]
123
+ if (last.listType !== 'NONE' || last.indentation !== 0 || hasParagraphSpacing(last)) break
124
+ styles.pop()
125
+ }
126
+ return styles
127
+ }
128
+
129
+ /** How many paragraphs `text` has: one more than its newlines. */
130
+ export function paragraphCount(text: string): number {
131
+ let count = 1
132
+ for (let at = text.indexOf('\n'); at !== -1; at = text.indexOf('\n', at + 1)) count++
133
+ return count
134
+ }
135
+
136
+ /**
137
+ * Paragraph styles after replacing `text[start, end)` with `inserted`, as Figma keeps them: the
138
+ * paragraph the edit starts in keeps its style, paragraphs a deleted newline joins to it are
139
+ * dropped, and paragraphs an inserted newline starts take its style.
140
+ */
141
+ export function paragraphStylesAfterEdit(
142
+ paragraphs: readonly TextParagraphStyle[],
143
+ text: string,
144
+ start: number,
145
+ end: number,
146
+ inserted: string
147
+ ): TextParagraphStyle[] {
148
+ if (paragraphs.length === 0) return []
149
+ const first = paragraphIndexAt(text, start)
150
+ const last = paragraphIndexAt(text, end)
151
+ const style = paragraphStyleAt(paragraphs, first)
152
+ const added = paragraphCount(inserted) - 1
153
+ const next = [
154
+ ...Array.from({ length: first }, (_, index) => paragraphStyleAt(paragraphs, index)),
155
+ ...Array.from({ length: added + 1 }, () => style),
156
+ ...paragraphs.slice(last + 1)
157
+ ]
158
+ return trimParagraphStyles(next, paragraphCount(text) - (last - first) + added)
159
+ }
160
+
161
+ /**
162
+ * Paragraph styles with every paragraph that `text[start, end)` touches changed by `change`,
163
+ * as a range setter changes whole paragraphs.
164
+ */
165
+ export function paragraphStylesInRange(
166
+ paragraphs: readonly TextParagraphStyle[],
167
+ text: string,
168
+ start: number,
169
+ end: number,
170
+ change: (style: TextParagraphStyle) => TextParagraphStyle
171
+ ): TextParagraphStyle[] {
172
+ const count = paragraphCount(text)
173
+ const first = paragraphIndexAt(text, start)
174
+ // An empty range still names the paragraph it sits in; a range ending right after a
175
+ // newline does not reach into the next paragraph.
176
+ const last = end > start ? paragraphIndexAt(text, end - 1) : first
177
+ const next = Array.from({ length: count }, (_, index) => {
178
+ const style = paragraphStyleAt(paragraphs, index)
179
+ return index >= first && index <= last ? change(style) : style
180
+ })
181
+ return trimParagraphStyles(next, count)
182
+ }
183
+
184
+ /**
185
+ * A paragraph style with its list type set. A list item is nested at least one level, and a
186
+ * paragraph leaving a list keeps no indentation.
187
+ */
188
+ export function withListType(
189
+ style: TextParagraphStyle,
190
+ listType: TextListType
191
+ ): TextParagraphStyle {
192
+ if (listType === 'NONE') return { ...style, listType, indentation: 0 }
193
+ return { ...style, listType, indentation: clampListIndentation(style.indentation) }
194
+ }
195
+
196
+ /** A paragraph style with its nesting set, kept in the range a list item allows. */
197
+ export function withIndentation(
198
+ style: TextParagraphStyle,
199
+ indentation: number
200
+ ): TextParagraphStyle {
201
+ if (style.listType === 'NONE') {
202
+ return {
203
+ ...style,
204
+ indentation: Math.max(0, Math.min(MAX_LIST_INDENTATION, Math.round(indentation)))
205
+ }
206
+ }
207
+ return { ...style, indentation: clampListIndentation(indentation) }
208
+ }
209
+
210
+ function clampListIndentation(indentation: number): number {
211
+ return Math.max(1, Math.min(MAX_LIST_INDENTATION, Math.round(indentation)))
212
+ }
213
+
214
+ /**
215
+ * Paragraph styles after `before` became `after` through one edit, found as the text between
216
+ * their common start and end, for editors that replace the text rather than report the edit.
217
+ */
218
+ export function paragraphStylesAfterTextChange(
219
+ paragraphs: readonly TextParagraphStyle[],
220
+ before: string,
221
+ after: string
222
+ ): TextParagraphStyle[] {
223
+ if (paragraphs.length === 0 || before === after) return paragraphs.map((style) => ({ ...style }))
224
+ let prefix = 0
225
+ const shorter = Math.min(before.length, after.length)
226
+ while (prefix < shorter && before[prefix] === after[prefix]) prefix++
227
+ let suffix = 0
228
+ while (
229
+ suffix < shorter - prefix &&
230
+ before[before.length - 1 - suffix] === after[after.length - 1 - suffix]
231
+ ) {
232
+ suffix++
233
+ }
234
+ return paragraphStylesAfterEdit(
235
+ paragraphs,
236
+ before,
237
+ prefix,
238
+ before.length - suffix,
239
+ after.slice(prefix, after.length - suffix)
240
+ )
241
+ }