@polotno/schema 0.13.0 → 0.14.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.
@@ -0,0 +1,220 @@
1
+ import { substituteText } from './variable-text.js';
2
+ import { removeTags } from './text.js';
3
+ export { VARIABLE_NAME } from './variable-text.js';
4
+ import { polotnoError } from './errors.js';
5
+ const MEDIA = ['src', 'visible'];
6
+ const PAINT = ['fill', 'visible'];
7
+ /** The properties each element type can bind. Any other element binds `visible`. */
8
+ export const BINDABLE_PROPS = {
9
+ image: MEDIA,
10
+ svg: MEDIA,
11
+ gif: MEDIA,
12
+ video: MEDIA,
13
+ text: PAINT,
14
+ figure: PAINT,
15
+ };
16
+ export const bindableProps = (type) => BINDABLE_PROPS[type] ?? [
17
+ 'visible',
18
+ ];
19
+ /** The type a binding gives its variable. */
20
+ export const bindingType = (elementType, prop) => prop === 'src'
21
+ ? elementType === 'video'
22
+ ? 'video'
23
+ : 'image'
24
+ : prop === 'fill'
25
+ ? 'color'
26
+ : 'boolean';
27
+ function visit(design, callback) {
28
+ function walk(nodes = []) {
29
+ for (const node of nodes) {
30
+ callback(node, node.type);
31
+ if (node.type === 'group')
32
+ walk(node.children);
33
+ if (node.type === 'table') {
34
+ // A cell may omit its discriminator in sparse design JSON.
35
+ for (const cell of node.cells ?? [])
36
+ callback(cell, 'tablecell');
37
+ }
38
+ }
39
+ }
40
+ for (const page of design.pages)
41
+ walk(page.children);
42
+ }
43
+ function uses(node, nodeType, apply, write) {
44
+ if ((nodeType === 'text' || nodeType === 'tablecell') && node.text) {
45
+ const text = substituteText(node.text, (name) => {
46
+ const value = apply(name, 'text', 'text');
47
+ return typeof value === 'string' ? value : undefined;
48
+ });
49
+ if (write && text !== node.text) {
50
+ node.text = text;
51
+ // Zero is the shared "measure on first render" sentinel. Only an
52
+ // explicit 'resize' box follows its content: a missing mode follows the
53
+ // renderer's global, which may fit the text to the authored box.
54
+ if (nodeType === 'text' && node.textOverflow === 'resize')
55
+ node.height = 0;
56
+ // A blank value stays blank: an empty text would draw its placeholder.
57
+ if (node.placeholder && !removeTags(text))
58
+ node.placeholder = '';
59
+ }
60
+ }
61
+ if (!node.bindings)
62
+ return;
63
+ for (const prop of bindableProps(nodeType ?? '')) {
64
+ const name = node.bindings[prop];
65
+ if (name === undefined)
66
+ continue;
67
+ const value = apply(name, prop, bindingType(nodeType, prop));
68
+ // The resolver returns a boolean for `visible` and a string otherwise.
69
+ if (write && value !== undefined)
70
+ Object.assign(node, { [prop]: value });
71
+ }
72
+ if (write)
73
+ delete node.bindings;
74
+ }
75
+ export function getVariables(design) {
76
+ const variables = new Map();
77
+ // Binding kinds only: any variable may also print in text.
78
+ const bound = new Map();
79
+ for (const definition of design.variables ?? []) {
80
+ variables.set(definition.name, {
81
+ ...definition,
82
+ type: 'text',
83
+ declared: true,
84
+ usages: [],
85
+ });
86
+ }
87
+ visit(design, (node, nodeType) => uses(node, nodeType, (name, property, type) => {
88
+ const item = variables.get(name) ?? {
89
+ name,
90
+ type,
91
+ declared: false,
92
+ usages: [],
93
+ };
94
+ if (type !== 'text') {
95
+ const kinds = bound.get(name) ?? new Set();
96
+ if (!kinds.size)
97
+ item.type = type;
98
+ bound.set(name, kinds.add(type));
99
+ }
100
+ item.usages.push({ elementId: node.id ?? '', property });
101
+ variables.set(name, item);
102
+ return undefined;
103
+ }, false));
104
+ const issues = [];
105
+ for (const item of variables.values()) {
106
+ if (!item.usages.length)
107
+ issues.push({
108
+ severity: 'warning',
109
+ reason: 'orphan',
110
+ variable: item.name,
111
+ });
112
+ if ((bound.get(item.name)?.size ?? 0) > 1)
113
+ issues.push({
114
+ severity: 'warning',
115
+ reason: 'mixed-types',
116
+ variable: item.name,
117
+ });
118
+ }
119
+ return { variables: [...variables.values()], issues };
120
+ }
121
+ /** The record value a dotted variable name reads, or undefined. */
122
+ export function readPath(record, name) {
123
+ let current = record;
124
+ for (const key of name.split('.')) {
125
+ if (!current ||
126
+ typeof current !== 'object' ||
127
+ !Object.prototype.hasOwnProperty.call(current, key))
128
+ return undefined;
129
+ current = current[key];
130
+ }
131
+ return current;
132
+ }
133
+ /** A value as the property it fills reads it, or undefined. */
134
+ function typed(value, property) {
135
+ if (property === 'text')
136
+ return ['string', 'number', 'boolean'].includes(typeof value)
137
+ ? String(value)
138
+ : undefined;
139
+ if (property === 'visible')
140
+ return typeof value === 'boolean' ? value : undefined;
141
+ return typeof value === 'string' ? value : undefined;
142
+ }
143
+ /** The registry by name, for `fillElement`: build it once per registry. */
144
+ export const variablesByName = (variables) => new Map(variables?.map((v) => [v.name, v]));
145
+ /** What a variable reads: a record replaces the stored values. */
146
+ function reader(definitions, record) {
147
+ return (name) => (record ? readPath(record, name) : definitions.get(name)?.value) ??
148
+ definitions.get(name)?.default;
149
+ }
150
+ /**
151
+ * Fill `design` in place, from `record` or else from its stored values, and
152
+ * strip the template. Returns the issues about the record.
153
+ */
154
+ export function fillVariables(design, record) {
155
+ const read = reader(variablesByName(design.variables), record);
156
+ const issues = [];
157
+ const keys = new Set();
158
+ function error(variable, reason) {
159
+ if (!issues.some((i) => i.reason === reason && i.variable === variable))
160
+ issues.push({ severity: 'error', reason, variable });
161
+ }
162
+ for (const definition of design.variables ?? []) {
163
+ keys.add(definition.name.split('.')[0]);
164
+ if (record && definition.required)
165
+ if (readPath(record, definition.name) == null)
166
+ error(definition.name, 'missing-required');
167
+ }
168
+ visit(design, (node, nodeType) => uses(node, nodeType, (name, property) => {
169
+ keys.add(name.split('.')[0]);
170
+ const value = read(name);
171
+ if (value == null)
172
+ return undefined;
173
+ const filled = typed(value, property);
174
+ if (filled === undefined)
175
+ error(name, 'type-mismatch');
176
+ return filled;
177
+ }, true));
178
+ delete design.variables;
179
+ for (const key of Object.keys(record ?? {})) {
180
+ if (!keys.has(key))
181
+ issues.push({ severity: 'warning', reason: 'unknown-key', key });
182
+ }
183
+ return issues;
184
+ }
185
+ /**
186
+ * A plain copy of `template` filled from `record`, or from the stored values
187
+ * when no record is passed.
188
+ */
189
+ export function resolveVariables(template, record, options = {}) {
190
+ const design = JSON.parse(JSON.stringify(template));
191
+ const issues = fillVariables(design, record);
192
+ const first = issues.find((i) => i.severity === 'error');
193
+ if (options.strict &&
194
+ first &&
195
+ (first.reason === 'missing-required' || first.reason === 'type-mismatch')) {
196
+ throw polotnoError('VARIABLES_INVALID', 'Invalid template record: ' + first.reason + ' (' + first.variable + ')', { reason: first.reason, issues });
197
+ }
198
+ return { design, issues };
199
+ }
200
+ const DRAWN = ['text', 'placeholder', 'src', 'fill', 'visible'];
201
+ // One shared result for an element nothing fills: an editor view returning it
202
+ // again notifies no observer, so a registry edit leaves those elements alone.
203
+ const UNFILLED = Object.freeze({});
204
+ /**
205
+ * The properties an element draws with the stored values in `variables`, for
206
+ * an editor that shows filled values while keeping the template. Only the
207
+ * properties that change are returned.
208
+ */
209
+ export function fillElement(node, variables) {
210
+ if (!node.bindings && !node.text?.includes('{{'))
211
+ return UNFILLED;
212
+ const read = reader(variables);
213
+ const filled = { ...node };
214
+ uses(filled, node.type, (name, property) => typed(read(name), property), true);
215
+ const changed = {};
216
+ for (const key of DRAWN)
217
+ if (filled[key] !== node[key])
218
+ Object.assign(changed, { [key]: filled[key] });
219
+ return changed;
220
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polotno/schema",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "Canonical Polotno design format: types, normalize, validate, JSON Schema. Authored in zod, DOM-free.",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "type": "module",
@@ -23,7 +23,15 @@
23
23
  "./json": {
24
24
  "import": "./lib/design.schema.json"
25
25
  },
26
- "./design.schema.json": "./lib/design.schema.json"
26
+ "./design.schema.json": "./lib/design.schema.json",
27
+ "./variables": {
28
+ "import": "./lib/variables.js",
29
+ "types": "./lib/variables.d.ts"
30
+ },
31
+ "./text": {
32
+ "import": "./lib/text.js",
33
+ "types": "./lib/text.d.ts"
34
+ }
27
35
  },
28
36
  "author": "Anton Lavrenov",
29
37
  "homepage": "https://polotno.com",
@@ -50,7 +58,7 @@
50
58
  },
51
59
  "devDependencies": {
52
60
  "typescript": "~7.0.2",
53
- "vitest": "^5.1.0"
61
+ "vitest": "^5.1.1"
54
62
  },
55
63
  "scripts": {
56
64
  "build": "rm -rf lib && tsc && node scripts/generate-schema.mjs && node ../../scripts/check-pack.mjs",