@pairdraw/pen 0.0.0-stage → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +10 -2
- package/dist/chunks/annotations.js +510 -0
- package/dist/chunks/annotations.js.map +1 -0
- package/dist/chunks/assets.js +158 -0
- package/dist/chunks/assets.js.map +1 -0
- package/dist/chunks/effects.js +775 -0
- package/dist/chunks/effects.js.map +1 -0
- package/dist/chunks/geometry.js +95 -0
- package/dist/chunks/geometry.js.map +1 -0
- package/dist/chunks/icons.js +156 -0
- package/dist/chunks/icons.js.map +1 -0
- package/dist/chunks/imports.js +120 -0
- package/dist/chunks/imports.js.map +1 -0
- package/dist/chunks/index.js +1478 -0
- package/dist/chunks/index.js.map +1 -0
- package/dist/index.d.ts +492 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/package.json +31 -4
- package/src/annotations.ts +128 -0
- package/src/assets.ts +224 -0
- package/src/effects.ts +62 -0
- package/src/geometry.ts +71 -0
- package/src/icons.ts +173 -0
- package/src/images.ts +109 -0
- package/src/imports.ts +169 -0
- package/src/index.ts +23 -0
- package/src/instances.ts +272 -0
- package/src/jsonc.ts +77 -0
- package/src/layout.ts +135 -0
- package/src/library.ts +153 -0
- package/src/nodes.ts +410 -0
- package/src/paints.ts +417 -0
- package/src/placeholders.ts +86 -0
- package/src/placement.ts +84 -0
- package/src/plugin-data.ts +86 -0
- package/src/read.ts +150 -0
- package/src/schema.ts +299 -0
- package/src/slots.ts +41 -0
- package/src/text.ts +92 -0
- package/src/variables.ts +284 -0
- package/src/write.ts +594 -0
package/src/images.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import type { Fill, ImageScaleMode, SceneGraph } from '@pairdraw/scene-graph'
|
|
2
|
+
import { BLACK } from '@pairdraw/scene-graph/constants'
|
|
3
|
+
import { coverImageTransform, computeImageHash, imageSize } from '@pairdraw/scene-graph/images'
|
|
4
|
+
import type { Matrix, Size } from '@pairdraw/scene-graph/primitives'
|
|
5
|
+
|
|
6
|
+
import type { PenImagePaint } from './schema'
|
|
7
|
+
|
|
8
|
+
/** An image a paint draws: its bytes' name in the graph and its size in pixels. */
|
|
9
|
+
export interface PenImage {
|
|
10
|
+
hash: string
|
|
11
|
+
size: Size | null
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** The images a document's paints name, by URL. */
|
|
15
|
+
export interface PenImages {
|
|
16
|
+
get(url: string): PenImage | undefined
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Stores the images a host loaded, by the URLs paints name them with; others stay unpainted. */
|
|
20
|
+
export function createImageStore(
|
|
21
|
+
graph: SceneGraph,
|
|
22
|
+
files: ReadonlyMap<string, Uint8Array> = new Map()
|
|
23
|
+
): PenImages {
|
|
24
|
+
const byURL = new Map<string, PenImage | undefined>()
|
|
25
|
+
const store = (bytes: Uint8Array): PenImage => {
|
|
26
|
+
const hash = computeImageHash(bytes)
|
|
27
|
+
graph.images.set(hash, bytes)
|
|
28
|
+
// A header declaring no pixels gives no size to fit a crop to.
|
|
29
|
+
const size = imageSize(bytes)
|
|
30
|
+
return { hash, size: size && size.width > 0 && size.height > 0 ? size : null }
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
get(url) {
|
|
34
|
+
if (byURL.has(url)) return byURL.get(url)
|
|
35
|
+
const file = files.get(url)
|
|
36
|
+
const image = file ? store(file) : undefined
|
|
37
|
+
byURL.set(url, image)
|
|
38
|
+
return image
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** pen.dev's affine `[a, b, c, d, tx, ty]`, inverted, as the scene graph's matrix. */
|
|
44
|
+
function invertAffine([a, b, c, d, tx, ty]: readonly number[]): Matrix | null {
|
|
45
|
+
const det = a * d - b * c
|
|
46
|
+
if (Math.abs(det) < 1e-12) return null
|
|
47
|
+
return {
|
|
48
|
+
m00: d / det,
|
|
49
|
+
m01: -c / det,
|
|
50
|
+
m02: (c * ty - d * tx) / det,
|
|
51
|
+
m10: -b / det,
|
|
52
|
+
m11: a / det,
|
|
53
|
+
m12: (b * tx - a * ty) / det
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function compose(outer: Matrix, inner: Matrix): Matrix {
|
|
58
|
+
return {
|
|
59
|
+
m00: outer.m00 * inner.m00 + outer.m01 * inner.m10,
|
|
60
|
+
m01: outer.m00 * inner.m01 + outer.m01 * inner.m11,
|
|
61
|
+
m02: outer.m00 * inner.m02 + outer.m01 * inner.m12 + outer.m02,
|
|
62
|
+
m10: outer.m10 * inner.m00 + outer.m11 * inner.m10,
|
|
63
|
+
m11: outer.m10 * inner.m01 + outer.m11 * inner.m11,
|
|
64
|
+
m12: outer.m10 * inner.m02 + outer.m11 * inner.m12 + outer.m12
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const IDENTITY: Matrix = { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Where an image paint draws. `cover` and `contain` are Fill and Fit, and `stretch` a crop of the
|
|
72
|
+
* whole image. pen.dev's `transform` crops the image first and fits the crop as it would a whole
|
|
73
|
+
* image; the scene graph has that as a crop of the image's window, which needs the image's size
|
|
74
|
+
* when the crop is covered. A crop fitted with `contain` is drawn covered, since a crop cannot
|
|
75
|
+
* leave the bars `contain` shows beside it.
|
|
76
|
+
*/
|
|
77
|
+
function placement(
|
|
78
|
+
paint: PenImagePaint,
|
|
79
|
+
image: PenImage,
|
|
80
|
+
box: Size
|
|
81
|
+
): { imageScaleMode: ImageScaleMode; imageTransform?: Matrix } {
|
|
82
|
+
const mode = paint.mode ?? 'cover'
|
|
83
|
+
const crop = paint.transform ? invertAffine(paint.transform) : null
|
|
84
|
+
if (!crop) {
|
|
85
|
+
if (mode === 'stretch') return { imageScaleMode: 'CROP', imageTransform: IDENTITY }
|
|
86
|
+
return { imageScaleMode: mode === 'contain' ? 'FIT' : 'FILL' }
|
|
87
|
+
}
|
|
88
|
+
if (mode === 'stretch' || !image.size) return { imageScaleMode: 'CROP', imageTransform: crop }
|
|
89
|
+
const cropWidth = image.size.width * Math.hypot(crop.m00, crop.m10)
|
|
90
|
+
const cropHeight = image.size.height * Math.hypot(crop.m01, crop.m11)
|
|
91
|
+
const covered = coverImageTransform(box.width, box.height, cropWidth, cropHeight)
|
|
92
|
+
return { imageScaleMode: 'CROP', imageTransform: compose(crop, covered) }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function imagePaint(
|
|
96
|
+
paint: PenImagePaint,
|
|
97
|
+
image: PenImage,
|
|
98
|
+
box: Size,
|
|
99
|
+
opacity: number
|
|
100
|
+
): Fill {
|
|
101
|
+
return {
|
|
102
|
+
type: 'IMAGE',
|
|
103
|
+
color: { ...BLACK },
|
|
104
|
+
opacity,
|
|
105
|
+
visible: true,
|
|
106
|
+
imageHash: image.hash,
|
|
107
|
+
...placement(paint, image, box)
|
|
108
|
+
}
|
|
109
|
+
}
|
package/src/imports.ts
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { uniq } from 'es-toolkit/array'
|
|
2
|
+
import { mapValues } from 'es-toolkit/object'
|
|
3
|
+
import { isEmptyObject } from 'es-toolkit/predicate'
|
|
4
|
+
|
|
5
|
+
import { IMPORTED_IMAGE_PREFIX, isDataURL, isDocumentAssetPath } from './assets'
|
|
6
|
+
import type { PenDocument, PenNode, PenOverride, PenVariable } from './schema'
|
|
7
|
+
import { isVarRef } from './variables'
|
|
8
|
+
|
|
9
|
+
/** A `.pen` document another one imports, as the importing document names its contents. */
|
|
10
|
+
export interface PenImport {
|
|
11
|
+
/** The path the importing document names it with, relative to that document. */
|
|
12
|
+
path: string
|
|
13
|
+
/** Its layers, components, and variables under the alias, from `importedDocument`. */
|
|
14
|
+
doc: PenDocument
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The documents a document imports, by the alias it names each one with. */
|
|
18
|
+
export type PenImports = ReadonlyMap<string, PenImport>
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The name an image an imported document draws goes by in the document importing it as `alias`:
|
|
22
|
+
* a file beside the imported document, or one a document it imports draws, gets the alias, so it
|
|
23
|
+
* never meets a file of the same name beside the importer. A data URL carries the image itself
|
|
24
|
+
* and keeps its name; a URL of any other kind names nothing a host loads.
|
|
25
|
+
*/
|
|
26
|
+
function importedImageURL(alias: string, url: string): string {
|
|
27
|
+
if (isDataURL(url)) return url
|
|
28
|
+
if (isDocumentAssetPath(url) || url.startsWith(IMPORTED_IMAGE_PREFIX)) {
|
|
29
|
+
return `${IMPORTED_IMAGE_PREFIX}${alias}/${url}`
|
|
30
|
+
}
|
|
31
|
+
return url
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Fields that hold layers or layer IDs, which `renameOverride` renames itself. */
|
|
35
|
+
const STRUCTURAL_FIELDS: ReadonlySet<string> = new Set([
|
|
36
|
+
'id',
|
|
37
|
+
'ref',
|
|
38
|
+
'slot',
|
|
39
|
+
'children',
|
|
40
|
+
'descendants'
|
|
41
|
+
])
|
|
42
|
+
|
|
43
|
+
/** How an imported document's names read in the document importing it. */
|
|
44
|
+
interface Renaming {
|
|
45
|
+
id: (id: string) => string
|
|
46
|
+
/** A value of the imported document's own, with its variables and image files renamed. */
|
|
47
|
+
value: (value: unknown) => unknown
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
51
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function renaming(alias: string, variables: ReadonlySet<string>): Renaming {
|
|
55
|
+
const id = (raw: string) => `${alias}:${raw}`
|
|
56
|
+
const value = (raw: unknown): unknown => {
|
|
57
|
+
// Only the document's own variables: text such as `$12.00` names no variable to rename.
|
|
58
|
+
if (isVarRef(raw)) return variables.has(raw.slice(1)) ? `$${id(raw.slice(1))}` : raw
|
|
59
|
+
if (Array.isArray(raw)) return raw.map(value)
|
|
60
|
+
if (!isRecord(raw)) return raw
|
|
61
|
+
const renamed = mapValues(raw, (field) => value(field))
|
|
62
|
+
if (raw.type === 'image' && typeof raw.url === 'string') {
|
|
63
|
+
renamed.url = importedImageURL(alias, raw.url)
|
|
64
|
+
}
|
|
65
|
+
return renamed
|
|
66
|
+
}
|
|
67
|
+
return { id, value }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function renameOverride(override: PenOverride, names: Renaming): PenOverride {
|
|
71
|
+
const renamed: PenOverride = {}
|
|
72
|
+
for (const [key, field] of Object.entries(override)) {
|
|
73
|
+
if (!STRUCTURAL_FIELDS.has(key)) renamed[key] = names.value(field)
|
|
74
|
+
}
|
|
75
|
+
if (override.id !== undefined) renamed.id = names.id(override.id)
|
|
76
|
+
if (override.ref !== undefined) renamed.ref = names.id(override.ref)
|
|
77
|
+
if (Array.isArray(override.slot)) renamed.slot = override.slot.map(names.id)
|
|
78
|
+
else if (override.slot !== undefined) renamed.slot = override.slot
|
|
79
|
+
if (override.children) {
|
|
80
|
+
renamed.children = override.children.map((child) => renameNode(child, names))
|
|
81
|
+
}
|
|
82
|
+
if (override.descendants) {
|
|
83
|
+
// A key is a path of layer IDs, each inside the copy the one before it names.
|
|
84
|
+
renamed.descendants = Object.fromEntries(
|
|
85
|
+
Object.entries(override.descendants).map(([path, inner]) => [
|
|
86
|
+
path.split('/').map(names.id).join('/'),
|
|
87
|
+
renameOverride(inner, names)
|
|
88
|
+
])
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
return renamed
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function renameNode(node: PenNode, names: Renaming): PenNode {
|
|
95
|
+
return { ...renameOverride(node, names), type: node.type, id: names.id(node.id) }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Each theme axis with the values any of the documents gives it, the importer's first. */
|
|
99
|
+
function mergeThemes(themes: readonly PenDocument['themes'][]): PenDocument['themes'] {
|
|
100
|
+
const merged: Record<string, string[]> = {}
|
|
101
|
+
for (const axes of themes) {
|
|
102
|
+
for (const [axis, values] of Object.entries(axes ?? {})) {
|
|
103
|
+
merged[axis] = uniq([...(merged[axis] ?? []), ...values])
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return isEmptyObject(merged) ? undefined : merged
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* A document with the documents it imports read into it: their variables, theme axes, and layers,
|
|
111
|
+
* which it names as `<alias>:<id>` and `$<alias>:<variable>`, after its own. The document's own
|
|
112
|
+
* variables win a name both have.
|
|
113
|
+
*/
|
|
114
|
+
export function withImports(doc: PenDocument, imports: PenImports): PenDocument {
|
|
115
|
+
if (imports.size === 0) return doc
|
|
116
|
+
const docs = [...imports.values()].map((entry) => entry.doc)
|
|
117
|
+
const variables: Record<string, PenVariable> = {}
|
|
118
|
+
for (const imported of docs) Object.assign(variables, imported.variables)
|
|
119
|
+
Object.assign(variables, doc.variables)
|
|
120
|
+
return {
|
|
121
|
+
...doc,
|
|
122
|
+
imports: undefined,
|
|
123
|
+
themes: mergeThemes([doc.themes, ...docs.map((imported) => imported.themes)]),
|
|
124
|
+
variables,
|
|
125
|
+
children: [...doc.children, ...docs.flatMap((imported) => imported.children)]
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* A document as the document importing it as `alias` from `path` names it: the documents it
|
|
131
|
+
* imports read into it by `withImports`, then every layer ID, component reference, override path,
|
|
132
|
+
* variable, and image file it names prefixed with the alias, as pen.dev names an imported
|
|
133
|
+
* document's components `alias:id` and its variables `$alias:name`.
|
|
134
|
+
*/
|
|
135
|
+
export function importedDocument(
|
|
136
|
+
alias: string,
|
|
137
|
+
path: string,
|
|
138
|
+
doc: PenDocument,
|
|
139
|
+
imports: PenImports
|
|
140
|
+
): PenImport {
|
|
141
|
+
const flat = withImports(doc, imports)
|
|
142
|
+
const names = renaming(alias, new Set(Object.keys(flat.variables ?? {})))
|
|
143
|
+
const variables: Record<string, PenVariable> = {}
|
|
144
|
+
for (const [name, variable] of Object.entries(flat.variables ?? {})) {
|
|
145
|
+
const value = names.value(variable.value)
|
|
146
|
+
variables[names.id(name)] = {
|
|
147
|
+
...variable,
|
|
148
|
+
value: isVariableValue(value) ? value : variable.value
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return {
|
|
152
|
+
path,
|
|
153
|
+
doc: {
|
|
154
|
+
...flat,
|
|
155
|
+
variables,
|
|
156
|
+
children: flat.children.map((node) => renameNode(node, names))
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Renaming keeps a variable's value in its shape; this tells the type checker so. */
|
|
162
|
+
function isVariableValue(value: unknown): value is PenVariable['value'] {
|
|
163
|
+
return (
|
|
164
|
+
typeof value === 'string' ||
|
|
165
|
+
typeof value === 'number' ||
|
|
166
|
+
typeof value === 'boolean' ||
|
|
167
|
+
(Array.isArray(value) && value.every(isRecord))
|
|
168
|
+
)
|
|
169
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export {
|
|
2
|
+
iconName,
|
|
3
|
+
iconOptions,
|
|
4
|
+
isDataURL,
|
|
5
|
+
isDocumentAssetPath,
|
|
6
|
+
parseImportedImageURL,
|
|
7
|
+
penAssets,
|
|
8
|
+
type PenAssets,
|
|
9
|
+
type PenIconRequest
|
|
10
|
+
} from './assets'
|
|
11
|
+
export { importedDocument, type PenImport, type PenImports } from './imports'
|
|
12
|
+
export { withUsedImports } from './library'
|
|
13
|
+
export type { PenIconSource } from './nodes'
|
|
14
|
+
export { PEN_PLUGIN_DATA_NAMESPACE } from './plugin-data'
|
|
15
|
+
export {
|
|
16
|
+
buildPenGraph,
|
|
17
|
+
parsePenDocument,
|
|
18
|
+
parsePenFile,
|
|
19
|
+
readPenFile,
|
|
20
|
+
type PenReadOptions
|
|
21
|
+
} from './read'
|
|
22
|
+
export type { PenDocument, PenNode, PenOverride } from './schema'
|
|
23
|
+
export { penDocumentFromGraph, stringifyPenDocument, writePenDocument } from './write'
|
package/src/instances.ts
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { pick } from 'es-toolkit/object'
|
|
2
|
+
import { isEqual } from 'es-toolkit/predicate'
|
|
3
|
+
|
|
4
|
+
import { generateId, type SceneGraph, type SceneNode } from '@pairdraw/scene-graph'
|
|
5
|
+
import {
|
|
6
|
+
detachInstance,
|
|
7
|
+
INSTANCE_OVERRIDE_FIELDS,
|
|
8
|
+
populateInstanceChildren,
|
|
9
|
+
recordInstanceOverride,
|
|
10
|
+
swapInstanceComponent
|
|
11
|
+
} from '@pairdraw/scene-graph/instances'
|
|
12
|
+
|
|
13
|
+
import { applyPenProperties, createSceneNode, fieldsSetBy, type Build } from './nodes'
|
|
14
|
+
import type { PenNode, PenOverride } from './schema'
|
|
15
|
+
import { claimSlot } from './slots'
|
|
16
|
+
|
|
17
|
+
/** Fills an instance read from `.pen`, after the instances inside its component. */
|
|
18
|
+
type Populate = (id: string) => void
|
|
19
|
+
|
|
20
|
+
/** The layers a copy was made from, nearest first, through copies of copies. */
|
|
21
|
+
function sources(graph: SceneGraph, node: SceneNode): Set<string> {
|
|
22
|
+
const found = new Set<string>()
|
|
23
|
+
for (
|
|
24
|
+
let id = node.componentId;
|
|
25
|
+
id && !found.has(id);
|
|
26
|
+
id = graph.getNode(id)?.componentId ?? null
|
|
27
|
+
) {
|
|
28
|
+
found.add(id)
|
|
29
|
+
}
|
|
30
|
+
return found
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The copy in `root`'s layers made from the pen.dev layer `sourceId`, at any depth. */
|
|
34
|
+
function findCopy(graph: SceneGraph, root: SceneNode, sourceId: string): SceneNode | undefined {
|
|
35
|
+
const queue = graph.getChildren(root.id)
|
|
36
|
+
for (const node of queue) {
|
|
37
|
+
if (sources(graph, node).has(sourceId)) return node
|
|
38
|
+
queue.push(...graph.getChildren(node.id))
|
|
39
|
+
}
|
|
40
|
+
return undefined
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The layer an override's key names: pen.dev IDs separated by `/`, each one inside the copy of the
|
|
45
|
+
* instance the one before it names.
|
|
46
|
+
*/
|
|
47
|
+
function resolvePath(graph: SceneGraph, instance: SceneNode, path: string): SceneNode | undefined {
|
|
48
|
+
let current: SceneNode | undefined = instance
|
|
49
|
+
for (const id of path.split('/')) {
|
|
50
|
+
current = current ? findCopy(graph, current, id) : undefined
|
|
51
|
+
}
|
|
52
|
+
return current
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Runs `apply` in the merged theme of a layer's ancestors, as the layer was read in. */
|
|
56
|
+
export function inAncestorThemes<T>(build: Build, node: SceneNode, apply: () => T): T {
|
|
57
|
+
const chain: Record<string, string>[] = []
|
|
58
|
+
for (let id = node.parentId; id; id = build.graph.getNode(id)?.parentId ?? null) {
|
|
59
|
+
const theme = build.effective.get(id)?.theme
|
|
60
|
+
if (theme) chain.unshift(theme)
|
|
61
|
+
}
|
|
62
|
+
const leave = chain.map((theme) => build.ctx.enterTheme(theme))
|
|
63
|
+
try {
|
|
64
|
+
return apply()
|
|
65
|
+
} finally {
|
|
66
|
+
for (const exit of leave.toReversed()) exit()
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function replaceLayer(
|
|
71
|
+
build: Build,
|
|
72
|
+
target: SceneNode,
|
|
73
|
+
replacement: PenOverride,
|
|
74
|
+
populate: Populate
|
|
75
|
+
): void {
|
|
76
|
+
const { graph } = build
|
|
77
|
+
const parentId = target.parentId
|
|
78
|
+
if (!parentId) return
|
|
79
|
+
if (swapLayer(build, target, replacement, populate)) return
|
|
80
|
+
const index = graph.getNode(parentId)?.childIds.indexOf(target.id) ?? -1
|
|
81
|
+
const pen: PenNode = {
|
|
82
|
+
...replacement,
|
|
83
|
+
type: replacement.type ?? 'frame',
|
|
84
|
+
id: replacement.id ?? generateId()
|
|
85
|
+
}
|
|
86
|
+
inAncestorThemes(build, target, () => {
|
|
87
|
+
graph.deleteNode(target.id)
|
|
88
|
+
const id = createSceneNode(pen, parentId, build)
|
|
89
|
+
if (id && index >= 0) graph.insertChildAt(id, parentId, index)
|
|
90
|
+
// The parent's layers changed; a replacement that is itself an instance stays one.
|
|
91
|
+
if (id) build.replaced.add(parentId)
|
|
92
|
+
})
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Swaps a nested instance an override replaces with an instance of another component for that
|
|
97
|
+
* component, as Figma's instance swap does, so the instances holding it stay instances. The
|
|
98
|
+
* replacement's own fields and overrides then apply to the swapped layer. Returns whether it
|
|
99
|
+
* swapped; any other replacement changes the layers of the instance holding it.
|
|
100
|
+
*/
|
|
101
|
+
function swapLayer(
|
|
102
|
+
build: Build,
|
|
103
|
+
target: SceneNode,
|
|
104
|
+
replacement: PenOverride,
|
|
105
|
+
populate: Populate
|
|
106
|
+
): boolean {
|
|
107
|
+
const { graph, effective, instances } = build
|
|
108
|
+
const component =
|
|
109
|
+
typeof replacement.ref === 'string' ? build.components.get(replacement.ref) : undefined
|
|
110
|
+
if (target.type !== 'INSTANCE' || replacement.type !== 'ref' || component?.type !== 'frame')
|
|
111
|
+
return false
|
|
112
|
+
for (const nested of instances.keys()) {
|
|
113
|
+
if (graph.isDescendant(nested, component.id)) populate(nested)
|
|
114
|
+
}
|
|
115
|
+
swapInstanceComponent(graph, target.id, component.id)
|
|
116
|
+
if (graph.getNode(target.id)?.componentId !== component.id) return false
|
|
117
|
+
const {
|
|
118
|
+
children: _children,
|
|
119
|
+
reusable: _reusable,
|
|
120
|
+
descendants: _descendants,
|
|
121
|
+
...fields
|
|
122
|
+
} = component
|
|
123
|
+
effective.set(target.id, { ...fields, id: target.id })
|
|
124
|
+
inheritCopyFields(build, target)
|
|
125
|
+
const { ref: _ref, type: _type, id: _id, descendants, ...own } = replacement
|
|
126
|
+
overrideLayer(build, target, own)
|
|
127
|
+
applyDescendants(build, target, descendants, populate)
|
|
128
|
+
return true
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Records as the instance's overrides the fields an override set or changed on a copy, so they
|
|
133
|
+
* survive the instance's next sync and a save, as an edit made in the editor would.
|
|
134
|
+
*/
|
|
135
|
+
function recordChangedFields(
|
|
136
|
+
graph: SceneGraph,
|
|
137
|
+
target: SceneNode,
|
|
138
|
+
before: Partial<SceneNode>,
|
|
139
|
+
override: PenOverride
|
|
140
|
+
): void {
|
|
141
|
+
const changed = INSTANCE_OVERRIDE_FIELDS.filter((field) => !isEqual(before[field], target[field]))
|
|
142
|
+
recordInstanceOverride(graph, target.id, [...changed, ...fieldsSetBy(override)])
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Records as the instance's own overrides the fields its `ref` sets or makes differ from its
|
|
147
|
+
* component's. A size counts only when the `ref` sets it: otherwise it is the layout's, which
|
|
148
|
+
* follows the component's.
|
|
149
|
+
*/
|
|
150
|
+
function recordOwnFields(graph: SceneGraph, instance: SceneNode, ref: PenNode): void {
|
|
151
|
+
const component = instance.componentId ? graph.getNode(instance.componentId) : undefined
|
|
152
|
+
if (!component) return
|
|
153
|
+
const changed = INSTANCE_OVERRIDE_FIELDS.filter(
|
|
154
|
+
(field) =>
|
|
155
|
+
(field !== 'width' || 'width' in ref) &&
|
|
156
|
+
(field !== 'height' || 'height' in ref) &&
|
|
157
|
+
!isEqual(instance[field], component[field])
|
|
158
|
+
)
|
|
159
|
+
recordInstanceOverride(graph, instance.id, [...changed, ...fieldsSetBy(ref)])
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Gives a copy an override's fields. Children the override gives a slot of `instance` become the
|
|
164
|
+
* instance's content for that slot; any other layer's children are replaced, which detaches the
|
|
165
|
+
* instances holding it.
|
|
166
|
+
*/
|
|
167
|
+
function overrideLayer(
|
|
168
|
+
build: Build,
|
|
169
|
+
target: SceneNode,
|
|
170
|
+
override: PenOverride,
|
|
171
|
+
instance?: SceneNode
|
|
172
|
+
): void {
|
|
173
|
+
const { graph, ctx, effective } = build
|
|
174
|
+
const base = effective.get(target.id) ?? { type: 'frame', id: target.id }
|
|
175
|
+
const { descendants: _descendants, children, ...fields } = override
|
|
176
|
+
const merged: PenNode = { ...base, ...fields, type: base.type, id: base.id }
|
|
177
|
+
const before = structuredClone(pick(target, INSTANCE_OVERRIDE_FIELDS))
|
|
178
|
+
inAncestorThemes(build, target, () => {
|
|
179
|
+
const leave = merged.theme ? ctx.enterTheme(merged.theme) : undefined
|
|
180
|
+
try {
|
|
181
|
+
applyPenProperties(target, merged, build)
|
|
182
|
+
recordChangedFields(graph, target, before, fields)
|
|
183
|
+
if (children) {
|
|
184
|
+
const fillsSlot = instance !== undefined && claimSlot(build, instance, target)
|
|
185
|
+
const replaced = target.childIds
|
|
186
|
+
for (const childId of replaced) graph.deleteNode(childId)
|
|
187
|
+
for (const child of children) createSceneNode(child, target.id, build)
|
|
188
|
+
if (!fillsSlot) build.replaced.add(target.id)
|
|
189
|
+
}
|
|
190
|
+
} finally {
|
|
191
|
+
leave?.()
|
|
192
|
+
}
|
|
193
|
+
})
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Detaches the instances holding a layer whose children an override replaced. An instance keeps
|
|
198
|
+
* its component's layers, overriding their fields but never replacing them, so such an instance
|
|
199
|
+
* becomes a frame that keeps what it shows, as detaching it in Figma does.
|
|
200
|
+
*/
|
|
201
|
+
function detachReplacingInstances(build: Build): void {
|
|
202
|
+
const { graph } = build
|
|
203
|
+
for (const id of build.replaced) {
|
|
204
|
+
for (let node = graph.getNode(id); node;) {
|
|
205
|
+
if (node.type === 'INSTANCE') detachInstance(graph, node.id)
|
|
206
|
+
node = node.parentId ? graph.getNode(node.parentId) : undefined
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
build.replaced.clear()
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Gives an instance's copies their overrides; a key with a `type` replaces the layer. */
|
|
213
|
+
function applyDescendants(
|
|
214
|
+
build: Build,
|
|
215
|
+
instance: SceneNode,
|
|
216
|
+
descendants: PenNode['descendants'],
|
|
217
|
+
populate: Populate
|
|
218
|
+
): void {
|
|
219
|
+
for (const [path, override] of Object.entries(descendants ?? {})) {
|
|
220
|
+
const target = resolvePath(build.graph, instance, path)
|
|
221
|
+
if (!target) continue
|
|
222
|
+
if (override.type) replaceLayer(build, target, override, populate)
|
|
223
|
+
else overrideLayer(build, target, override, instance)
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Gives each copy inside `root` the pen.dev fields and placement of the layer it copies. */
|
|
228
|
+
function inheritCopyFields(build: Build, root: SceneNode): void {
|
|
229
|
+
const { graph, effective, placements } = build
|
|
230
|
+
const copies = graph.getChildren(root.id)
|
|
231
|
+
for (const copy of copies) {
|
|
232
|
+
const source = copy.componentId
|
|
233
|
+
const fields = source ? effective.get(source) : undefined
|
|
234
|
+
if (fields) effective.set(copy.id, fields)
|
|
235
|
+
const placement = source ? placements.get(source) : undefined
|
|
236
|
+
if (placement) placements.set(copy.id, placement)
|
|
237
|
+
if (source && build.groupIds.has(source)) build.groupIds.add(copy.id)
|
|
238
|
+
copies.push(...graph.getChildren(copy.id))
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Fills each instance with copies of its component's layers, then applies its overrides. An
|
|
244
|
+
* instance inside a component is filled first, so the copies made of it carry its layers and
|
|
245
|
+
* overrides; a copy keeps its source's pen.dev fields and placement.
|
|
246
|
+
*/
|
|
247
|
+
export function populateInstances(build: Build): void {
|
|
248
|
+
const { graph, instances } = build
|
|
249
|
+
const done = new Set<string>()
|
|
250
|
+
|
|
251
|
+
function populate(id: string): void {
|
|
252
|
+
if (done.has(id)) return
|
|
253
|
+
done.add(id)
|
|
254
|
+
const instance = graph.getNode(id)
|
|
255
|
+
const ref = instances.get(id)
|
|
256
|
+
if (!instance?.componentId || !ref) return
|
|
257
|
+
const component = graph.getNode(instance.componentId)
|
|
258
|
+
if (!component) return
|
|
259
|
+
for (const nested of instances.keys()) {
|
|
260
|
+
if (graph.isDescendant(nested, component.id)) populate(nested)
|
|
261
|
+
}
|
|
262
|
+
populateInstanceChildren(graph, instance.id, component.id)
|
|
263
|
+
recordOwnFields(graph, instance, ref)
|
|
264
|
+
inheritCopyFields(build, instance)
|
|
265
|
+
applyDescendants(build, instance, ref.descendants, populate)
|
|
266
|
+
// Before anything copies this instance, so the copies are of what it became.
|
|
267
|
+
detachReplacingInstances(build)
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// A replacement may hold instances of its own, which join the map as they are read.
|
|
271
|
+
for (const id of instances.keys()) populate(id)
|
|
272
|
+
}
|
package/src/jsonc.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pen.dev accepts JSON with comments in `.pen` files. This turns such text into plain JSON: `//`
|
|
3
|
+
* and block comments outside strings become spaces, keeping line breaks so a parse error still
|
|
4
|
+
* points where it did, and a comma before a closing bracket or brace becomes a space, as readers
|
|
5
|
+
* of JSON with comments allow. Text without comments or such commas comes back unchanged.
|
|
6
|
+
*/
|
|
7
|
+
export function stripJSONComments(text: string): string {
|
|
8
|
+
if (!text.includes('/') && !text.includes(',')) return text
|
|
9
|
+
const parts: string[] = []
|
|
10
|
+
let copied = 0
|
|
11
|
+
let index = 0
|
|
12
|
+
const skipTo = (end: number, replacement: string) => {
|
|
13
|
+
parts.push(text.slice(copied, index), replacement)
|
|
14
|
+
copied = end
|
|
15
|
+
index = end
|
|
16
|
+
}
|
|
17
|
+
while (index < text.length) {
|
|
18
|
+
const char = text[index]
|
|
19
|
+
const next = text[index + 1]
|
|
20
|
+
if (char === '"') {
|
|
21
|
+
index = stringEnd(text, index)
|
|
22
|
+
} else if (char === '/' && next === '/') {
|
|
23
|
+
const newline = text.indexOf('\n', index)
|
|
24
|
+
const end = newline === -1 ? text.length : newline
|
|
25
|
+
skipTo(end, blank(text.slice(index, end)))
|
|
26
|
+
} else if (char === '/' && next === '*') {
|
|
27
|
+
const close = text.indexOf('*/', index + 2)
|
|
28
|
+
const end = close === -1 ? text.length : close + 2
|
|
29
|
+
skipTo(end, blank(text.slice(index, end)))
|
|
30
|
+
} else if (char === ',' && closesNext(text, index + 1)) {
|
|
31
|
+
skipTo(index + 1, ' ')
|
|
32
|
+
} else {
|
|
33
|
+
index++
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
parts.push(text.slice(copied))
|
|
37
|
+
return parts.join('')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The end of the string literal opening at `start`, past its closing quote. */
|
|
41
|
+
function stringEnd(text: string, start: number): number {
|
|
42
|
+
let index = start + 1
|
|
43
|
+
while (index < text.length) {
|
|
44
|
+
const char = text[index]
|
|
45
|
+
if (char === '\\') index += 2
|
|
46
|
+
else if (char === '"') return index + 1
|
|
47
|
+
else index++
|
|
48
|
+
}
|
|
49
|
+
return text.length
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Spaces in place of every character of `comment` but its line breaks. */
|
|
53
|
+
function blank(comment: string): string {
|
|
54
|
+
return comment.replace(/[^\r\n]/g, ' ')
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Whether a closing bracket or brace comes next, past whitespace and comments. */
|
|
58
|
+
function closesNext(text: string, from: number): boolean {
|
|
59
|
+
let index = from
|
|
60
|
+
while (index < text.length) {
|
|
61
|
+
const char = text[index] ?? ''
|
|
62
|
+
if (/\s/.test(char)) {
|
|
63
|
+
index++
|
|
64
|
+
} else if (char === '/' && text[index + 1] === '/') {
|
|
65
|
+
const newline = text.indexOf('\n', index)
|
|
66
|
+
if (newline === -1) return false
|
|
67
|
+
index = newline
|
|
68
|
+
} else if (char === '/' && text[index + 1] === '*') {
|
|
69
|
+
const close = text.indexOf('*/', index + 2)
|
|
70
|
+
if (close === -1) return false
|
|
71
|
+
index = close + 2
|
|
72
|
+
} else {
|
|
73
|
+
return char === '}' || char === ']'
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return false
|
|
77
|
+
}
|