@enhance-eng/enhance 0.1.37 → 0.1.38
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/dist/{cli-output-identity.lib-i4KnVAYs.mjs → cli-output-identity.lib-C3i0q8cd.mjs} +1004 -398
- package/dist/main.mjs +335 -388
- package/dist/{mcp-invocation.adapter-CBnzmPZl.mjs → mcp-invocation.adapter-taWD_Gn7.mjs} +18 -13
- package/dist/mcp-main.mjs +7 -7
- package/dist/{mcp-server.adapter-DC9gAePw.mjs → mcp-server.adapter-bUMHR5ct.mjs} +1 -1
- package/dist/mcp.mjs +2 -2
- package/dist/{mutation-key.adapter-Ck8nOqke.mjs → mutation-key.adapter-BVKXAugo.mjs} +4057 -134
- package/dist/remote-mcp-main.mjs +5 -5
- package/package.json +5 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { $ as canvasRenderPendingSchema, At as PartialBatchError, B as canvasCaptureCapabilityInputSchema, Bn as
|
|
2
|
+
import { $ as canvasRenderPendingSchema, $n as canvasNodeStylePatchSchema, An as canvasReferencePageOf, Ar as canvasBlendModeSchema, At as PartialBatchError, B as canvasCaptureCapabilityInputSchema, Bn as IMAGE_KIND, Bt as PROTOTYPE_ARTIFACT_MANIFEST_PATH, C as canvasSnapshotToken, Cn as canvasTextPropsWithContent, Cr as canvasImageAssetIdentityFromPath, Dn as canvasPrototypePropsSchema, Dr as CANVAS_RICH_TEXT_STYLE_PROPERTIES, E as resolveCanvasSnapshot, En as canvasConversionMetadataSchema, Er as hasCanvasRichTextPaints, G as canvasRenderCapabilityInputSchema, Gn as applyCanvasOperationsOutputSchema, Gt as getPrototypePublishStatusOutputSchema, Hn as RECTANGLE_KIND, Ht as createPrototypeArtifactOutputSchema, I as canvasDuplicateCapabilityInputSchema, In as createCanvasPreparationOutputSchema, J as prototypePublishCapabilityInputSchema, Jn as textOf, Jt as submitPrototypeArtifactOutputSchema, K as canvasWriteHtmlCapabilityInputSchema, Kn as getCanvasMutationOutputSchema, Kt as prototypeArtifactManifestSchema, Ln as getCanvasPreparationOutputSchema, Mn as beginCanvasActivityOutputSchema, Mt as transcriptOutputSchema, N as canvasAssetImportOutputSchema, On as canvasRecordingPropsSchema, Or as canvasAdditionalStyleSchema, Ot as hasCanvasReferenceScope, P as canvasArrangeCapabilityInputSchema, Pn as AGENT_CLIENT_HEADER, Pr as listCanvasesOutputSchema, Qt as createAgentTokenOutputSchema, Rn as FRAME_KIND, Rt as getRecordingOutputSchema, S as canvasExchangeDigest, Sn as canvasTextChangeBetween, Sr as canvasFontAssetIdentityFromPath, St as canvasEditCapabilityInputSchema, T as encodeCanvasExchangeToken, Tn as canvasCaptureSchema, Tr as canvasRichTextValueOf, Tt as canvasReferenceNodeIds, U as canvasApplyCapabilityInputSchema, Un as TEXT_KIND, Ut as foldPrototypeArtifactPath, Vn as PAGE_KIND, Vt as attachPrototypeArtifactOutputSchema, W as canvasReadCapabilityInputSchema, Wn as applyCanvasOperationsInputSchema, Wt as getPrototypeArtifactCapabilitiesOutputSchema, X as transcriptReadCapabilityInputSchema, Xn as getCanvasDocumentOutputSchema, Y as recordingSnapshotCapabilityInputSchema, Yn as mapCanvasFontSources, Yt as getMeOutputSchema, Z as canvasRenderBatchRequestSchema, Zt as cliAuthConfigurationSchema, _r as canvasCssTokens, bn as applyCanvasTypographyPatch, br as reserveCanvasAssetInputSchema, bt as canvasMakeEditableCapabilityInputSchema, cr as downloadCanvasRenderOutputSchema, dr as canvasSceneDocumentSchema, dt as canvasTranscriptCursorSchema, en as listOrganisationsOutputSchema, er as createCanvasConversionOutputSchema, ft as canvasResourcesCursorSchema, gt as canvasFindInputSchema, ht as canvasFindCursorSchema, it as canvasRemoveCapabilityInputSchema, j as canvasAssetImportCapabilityInputSchema, jn as resolveCanvasReference, jr as canvasPaintSchema, jt as CliError, k as operationStatusInputSchema, kn as DEFAULT_CANVAS_REFERENCE_PAGE_ID, kr as CANVAS_BLEND_MODES, kt as parseCanvasReference, lr as getCanvasRenderOutputSchema, lt as canvasUpdateHtmlCapabilityInputSchema, mr as canvasAxisStyleProperties, nt as canvasRenderRequestSchema, or as createCanvasRenderOutputSchema, ot as canvasOutlineCursorSchema, pr as canvasAuthoredStyleDeclarations, q as commentAttentionCapabilityInputSchema, qn as canvasLayoutWithoutCssProperties, qt as prototypeArtifactPathSchema, rr as canvasRenderStateSchema, rt as canvasRenderFileSchema, s as toRemoteError, sr as createRecordingSnapshotOutputSchema, st as canvasReadInputSchema, tr as getCanvasConversionOutputSchema, ur as canvasReadableSceneDocumentSchema, ut as canvasUpdateHtmlInputSchema, v as canvasPrototypeCapabilityInputSchema, vr as canvasCssValue, vt as canvasInsertHtmlCapabilityInputSchema, w as decodeCanvasExchangeToken, wr as canvasRichTextOf, wt as assertCanvasReferenceNodes, xn as canvasCssTypographyOwners, xr as reserveCanvasAssetOutputSchema, yr as canvasAssetUploadOutputSchema, zn as GROUP_KIND } from "./cli-output-identity.lib-C3i0q8cd.mjs";
|
|
3
3
|
import process from "node:process";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
import { homedir, tmpdir } from "node:os";
|
|
@@ -20,6 +20,14 @@ import { createTRPCUntypedClient, httpLink } from "@trpc/client";
|
|
|
20
20
|
import { spawn } from "node:child_process";
|
|
21
21
|
import { createServer } from "node:http";
|
|
22
22
|
|
|
23
|
+
//#region ../../packages/canvas-format/src/canvas-sort-key.lib.ts
|
|
24
|
+
/**
|
|
25
|
+
* Sibling order by sort key. Fractional keys compare by code unit, so "Zz" comes before "a0";
|
|
26
|
+
* locale collation would put them the other way round.
|
|
27
|
+
*/
|
|
28
|
+
const compareCanvasSortKeys = (left, right) => left < right ? -1 : left > right ? 1 : 0;
|
|
29
|
+
|
|
30
|
+
//#endregion
|
|
23
31
|
//#region ../../packages/contract/src/canvas/canvas-additional-style-patch.lib.ts
|
|
24
32
|
const reorderedDeclarations = (declarations, order) => {
|
|
25
33
|
const ordered = new Set(order);
|
|
@@ -69,6 +77,778 @@ const canvasAdditionalStylePatchBetween = (before, after) => {
|
|
|
69
77
|
};
|
|
70
78
|
};
|
|
71
79
|
|
|
80
|
+
//#endregion
|
|
81
|
+
//#region ../../packages/contract/src/canvas/canvas-color-css.lib.ts
|
|
82
|
+
const BYTE_MAX$1 = 255;
|
|
83
|
+
const CHANNEL_PRECISION = 1e6;
|
|
84
|
+
const roundedChannel = (value) => Math.round(value * BYTE_MAX$1 * CHANNEL_PRECISION) / CHANNEL_PRECISION;
|
|
85
|
+
const canvasColorCss = (color, opacity = 1) => {
|
|
86
|
+
const alpha = color.alpha * opacity;
|
|
87
|
+
if (color.space === "srgb") {
|
|
88
|
+
const channels = [
|
|
89
|
+
color.red,
|
|
90
|
+
color.green,
|
|
91
|
+
color.blue
|
|
92
|
+
].map((channel) => String(roundedChannel(channel))).join(" ");
|
|
93
|
+
return alpha === 1 ? `rgb(${channels})` : `rgb(${channels} / ${String(alpha)})`;
|
|
94
|
+
}
|
|
95
|
+
const channels = `${String(color.red)} ${String(color.green)} ${String(color.blue)}`;
|
|
96
|
+
return `color(${color.space} ${channels} / ${String(alpha)})`;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
//#endregion
|
|
100
|
+
//#region ../../packages/contract/src/canvas/canvas-gradient-field.lib.ts
|
|
101
|
+
const UNIT_BOUNDS = {
|
|
102
|
+
x: 0,
|
|
103
|
+
y: 0,
|
|
104
|
+
width: 1,
|
|
105
|
+
height: 1
|
|
106
|
+
};
|
|
107
|
+
const fieldPoint = (paint, point) => {
|
|
108
|
+
const [a, b, c, d, e, f] = paint.transform;
|
|
109
|
+
const determinant = a * d - b * c;
|
|
110
|
+
const x = point.x - e, y = point.y - f;
|
|
111
|
+
return {
|
|
112
|
+
x: (d * x - c * y) / determinant,
|
|
113
|
+
y: (a * y - b * x) / determinant
|
|
114
|
+
};
|
|
115
|
+
};
|
|
116
|
+
const canvasGradientFieldCoordinates = (paint, bounds = UNIT_BOUNDS) => [
|
|
117
|
+
{
|
|
118
|
+
x: bounds.x,
|
|
119
|
+
y: bounds.y
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
x: bounds.x + bounds.width,
|
|
123
|
+
y: bounds.y
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
x: bounds.x,
|
|
127
|
+
y: bounds.y + bounds.height
|
|
128
|
+
},
|
|
129
|
+
{
|
|
130
|
+
x: bounds.x + bounds.width,
|
|
131
|
+
y: bounds.y + bounds.height
|
|
132
|
+
}
|
|
133
|
+
].flatMap((point) => {
|
|
134
|
+
const local = fieldPoint(paint, point);
|
|
135
|
+
return [local.x, local.y];
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
//#endregion
|
|
139
|
+
//#region ../../packages/contract/src/canvas/canvas-angular-gradient.lib.ts
|
|
140
|
+
const HALF$1 = .5;
|
|
141
|
+
const FULL_TURN$1 = 360;
|
|
142
|
+
const PERCENT$4 = 100;
|
|
143
|
+
const FIELD_UNIT = 1024;
|
|
144
|
+
const LINEAR_COEFFICIENTS = 4;
|
|
145
|
+
const gradient = (paint, center, isAlpha) => {
|
|
146
|
+
const stops = paint.stops.map((stop) => {
|
|
147
|
+
return `${isAlpha ? `rgb(255 255 255 / ${String(stop.color.alpha * paint.opacity)})` : canvasColorCss({
|
|
148
|
+
...stop.color,
|
|
149
|
+
alpha: 1
|
|
150
|
+
})} ${String(stop.position * FULL_TURN$1)}deg`;
|
|
151
|
+
});
|
|
152
|
+
return `conic-gradient(from 90deg at ${String(center)}% ${String(center)}% in srgb, ${stops.join(", ")})`;
|
|
153
|
+
};
|
|
154
|
+
/** Separate alpha from color so translucent stops interpolate straight sRGB, as copied by Figma. */
|
|
155
|
+
const canvasAngularGradientField = (paint, bounds) => {
|
|
156
|
+
const coordinates = canvasGradientFieldCoordinates(paint, bounds);
|
|
157
|
+
const low = Math.min(0, ...coordinates);
|
|
158
|
+
const span = Math.max(1, ...coordinates) - low;
|
|
159
|
+
const center = (HALF$1 - low) / span * PERCENT$4;
|
|
160
|
+
const matrix = paint.transform.map((value, index) => index < LINEAR_COEFFICIENTS ? value / FIELD_UNIT : value);
|
|
161
|
+
const style = `width:100%;height:100%;background-image:${gradient(paint, center, false)};mask-image:${gradient(paint, center, true)};`;
|
|
162
|
+
return `<g transform="matrix(${matrix.map(String).join(" ")})"><foreignObject x="${String(low * FIELD_UNIT)}" y="${String(low * FIELD_UNIT)}" width="${String(span * FIELD_UNIT)}" height="${String(span * FIELD_UNIT)}" overflow="visible"><div xmlns="http://www.w3.org/1999/xhtml" style="${style}"></div></foreignObject></g>`;
|
|
163
|
+
};
|
|
164
|
+
const canvasAngularGradientSvg = (paint) => `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${canvasAngularGradientField(paint)}</svg>`;
|
|
165
|
+
|
|
166
|
+
//#endregion
|
|
167
|
+
//#region ../../packages/contract/src/canvas/canvas-path-serialization.lib.ts
|
|
168
|
+
const areSamePoints = (left, right) => {
|
|
169
|
+
if (left === void 0 || right === void 0) return false;
|
|
170
|
+
return left.x === right.x && left.y === right.y;
|
|
171
|
+
};
|
|
172
|
+
const withoutClosingDuplicates = (points) => {
|
|
173
|
+
const result = [...points];
|
|
174
|
+
while (result.length > 1 && areSamePoints(result[0], result.at(-1))) result.pop();
|
|
175
|
+
while (result.length > 1 && areSamePoints(result[0], result[1])) result.splice(1, 1);
|
|
176
|
+
return result;
|
|
177
|
+
};
|
|
178
|
+
const straightPathTokens = (path) => {
|
|
179
|
+
const tokens = path.match(/[MLHVZ]|[+-]?\d*\.?\d+(?:e[+-]?\d+)?/giu) ?? [];
|
|
180
|
+
if (tokens.join("") !== path.replaceAll(/[\s,]/gu, "") || !/^M/iu.test(tokens[0] ?? "") || !/^Z$/iu.test(tokens.at(-1) ?? "")) return null;
|
|
181
|
+
return tokens;
|
|
182
|
+
};
|
|
183
|
+
const straightPoint = (command, tokens, index, current) => {
|
|
184
|
+
const kind = command.toUpperCase();
|
|
185
|
+
const first = Number(tokens[index]);
|
|
186
|
+
const second = ["M", "L"].includes(kind) ? Number(tokens[index + 1]) : first;
|
|
187
|
+
if (!Number.isFinite(first) || !Number.isFinite(second)) return null;
|
|
188
|
+
const origin = command === command.toLowerCase() ? current : {
|
|
189
|
+
x: 0,
|
|
190
|
+
y: 0
|
|
191
|
+
};
|
|
192
|
+
const point = {
|
|
193
|
+
x: kind === "V" ? current.x : origin.x + first,
|
|
194
|
+
y: kind === "H" ? current.y : origin.y + second
|
|
195
|
+
};
|
|
196
|
+
return Number.isFinite(point.x) && Number.isFinite(point.y) ? point : null;
|
|
197
|
+
};
|
|
198
|
+
/** Reads only a single straight contour; curves remain owned by the geometry engine. */
|
|
199
|
+
const canvasStraightPathVertices = (path) => {
|
|
200
|
+
const tokens = straightPathTokens(path);
|
|
201
|
+
if (tokens === null) return null;
|
|
202
|
+
const points = [];
|
|
203
|
+
let command = "M";
|
|
204
|
+
let index = 0;
|
|
205
|
+
let current = {
|
|
206
|
+
x: 0,
|
|
207
|
+
y: 0
|
|
208
|
+
};
|
|
209
|
+
while (index < tokens.length - 1) {
|
|
210
|
+
const token = tokens[index] ?? "";
|
|
211
|
+
if (/^[MLHV]$/iu.test(token)) {
|
|
212
|
+
command = token;
|
|
213
|
+
index += 1;
|
|
214
|
+
}
|
|
215
|
+
const kind = command.toUpperCase();
|
|
216
|
+
if (kind === "M" && points.length > 0) return null;
|
|
217
|
+
const point = straightPoint(command, tokens, index, current);
|
|
218
|
+
if (point === null) return null;
|
|
219
|
+
current = point;
|
|
220
|
+
points.push(current);
|
|
221
|
+
index += ["M", "L"].includes(kind) ? 2 : 1;
|
|
222
|
+
command = command.replace("M", "L").replace("m", "l");
|
|
223
|
+
}
|
|
224
|
+
return index === tokens.length - 1 ? withoutClosingDuplicates(points) : null;
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
//#endregion
|
|
228
|
+
//#region ../../packages/ui/src/geometry/corner-contour.lib.ts
|
|
229
|
+
const QUARTER_TURN$1 = Math.PI / 2;
|
|
230
|
+
const CUBIC_CONTROL_PARTS = 3;
|
|
231
|
+
const CONTOUR_PRECISION = 1e6;
|
|
232
|
+
const number = (value) => String(Math.round(value * CONTOUR_PRECISION) / CONTOUR_PRECISION);
|
|
233
|
+
const point = ([x, y]) => `${number(x)} ${number(y)}`;
|
|
234
|
+
const corner = (radius, [horizontalNeighbour, verticalNeighbour], { width, height }, smoothing) => {
|
|
235
|
+
if (radius <= 0) return {
|
|
236
|
+
radius: 0,
|
|
237
|
+
reach: 0,
|
|
238
|
+
smoothing: 0
|
|
239
|
+
};
|
|
240
|
+
const edgeBudget = (length, neighbour) => {
|
|
241
|
+
const product = length * radius;
|
|
242
|
+
const total = radius + neighbour;
|
|
243
|
+
if (Number.isFinite(product) && Number.isFinite(total)) return product / total;
|
|
244
|
+
const ratio = Math.min(radius, neighbour) / Math.max(radius, neighbour);
|
|
245
|
+
return (radius >= neighbour ? length : length * ratio) / (1 + ratio);
|
|
246
|
+
};
|
|
247
|
+
const budget = Math.min(edgeBudget(width, horizontalNeighbour), edgeBudget(height, verticalNeighbour));
|
|
248
|
+
const effectiveRadius = Math.min(radius, budget);
|
|
249
|
+
if (effectiveRadius === 0) return {
|
|
250
|
+
radius: 0,
|
|
251
|
+
reach: 0,
|
|
252
|
+
smoothing: 0
|
|
253
|
+
};
|
|
254
|
+
const effectiveSmoothing = Math.max(0, Math.min(smoothing, budget / effectiveRadius - 1));
|
|
255
|
+
return {
|
|
256
|
+
radius: effectiveRadius,
|
|
257
|
+
reach: effectiveRadius * (1 + effectiveSmoothing),
|
|
258
|
+
smoothing: effectiveSmoothing
|
|
259
|
+
};
|
|
260
|
+
};
|
|
261
|
+
const cornerCommands = (value, transform) => {
|
|
262
|
+
const { radius, reach, smoothing } = value;
|
|
263
|
+
const start = point(transform([reach, 0]));
|
|
264
|
+
if (radius === 0) return `L${start}`;
|
|
265
|
+
const angle = smoothing * QUARTER_TURN$1 / 2;
|
|
266
|
+
const x = radius * (1 - Math.sin(angle));
|
|
267
|
+
const y = radius * (1 - Math.cos(angle));
|
|
268
|
+
const tangent = angle === 0 ? 0 : y / Math.tan(angle);
|
|
269
|
+
const straightControl = (reach - x - tangent) / CUBIC_CONTROL_PARTS;
|
|
270
|
+
const firstControl = point(transform([reach - 2 * straightControl, 0]));
|
|
271
|
+
const secondControl = point(transform([x + tangent, 0]));
|
|
272
|
+
const arcStart = point(transform([x, y]));
|
|
273
|
+
const arcEnd = point(transform([y, x]));
|
|
274
|
+
const thirdControl = point(transform([0, x + tangent]));
|
|
275
|
+
const fourthControl = point(transform([0, reach - 2 * straightControl]));
|
|
276
|
+
const end = point(transform([0, reach]));
|
|
277
|
+
return `L${start}C${firstControl} ${secondControl} ${arcStart}${smoothing === 1 ? "" : `A${number(radius)} ${number(radius)} 0 0 1 ${arcEnd}`}C${thirdControl} ${fourthControl} ${end}`;
|
|
278
|
+
};
|
|
279
|
+
const cornersFrom = (radius, size) => {
|
|
280
|
+
const { topLeft, topRight, bottomRight, bottomLeft, smoothing = 0 } = radius;
|
|
281
|
+
return [
|
|
282
|
+
corner(topLeft, [topRight, bottomLeft], size, smoothing),
|
|
283
|
+
corner(topRight, [topLeft, bottomRight], size, smoothing),
|
|
284
|
+
corner(bottomRight, [bottomLeft, topRight], size, smoothing),
|
|
285
|
+
corner(bottomLeft, [bottomRight, topLeft], size, smoothing)
|
|
286
|
+
];
|
|
287
|
+
};
|
|
288
|
+
const constrainedCornerRadii = (radius, size) => {
|
|
289
|
+
const [topLeft, topRight, bottomRight, bottomLeft] = cornersFrom(radius, {
|
|
290
|
+
width: Math.max(0, size.width),
|
|
291
|
+
height: Math.max(0, size.height)
|
|
292
|
+
});
|
|
293
|
+
return {
|
|
294
|
+
topLeft: topLeft.radius,
|
|
295
|
+
topRight: topRight.radius,
|
|
296
|
+
bottomRight: bottomRight.radius,
|
|
297
|
+
bottomLeft: bottomLeft.radius
|
|
298
|
+
};
|
|
299
|
+
};
|
|
300
|
+
/**
|
|
301
|
+
* @justified intent
|
|
302
|
+
* Figma's curve keeps its circle center while replacing the tangent ends with cubics.
|
|
303
|
+
* Edge budgets reduce smoothing before radius; independent corners share each edge
|
|
304
|
+
* in proportion to their radii. Native flattened Figma paths are the browser-test oracle.
|
|
305
|
+
*/
|
|
306
|
+
const cornerContour = (radius, size, offset = [0, 0]) => {
|
|
307
|
+
const width = Math.max(0, size.width);
|
|
308
|
+
const height = Math.max(0, size.height);
|
|
309
|
+
if (width === 0 || height === 0) return "M0 0Z";
|
|
310
|
+
const [topLeft, topRight, bottomRight, bottomLeft] = cornersFrom(radius, {
|
|
311
|
+
width,
|
|
312
|
+
height
|
|
313
|
+
});
|
|
314
|
+
return [
|
|
315
|
+
`M${point([offset[0], topLeft.reach + offset[1]])}`,
|
|
316
|
+
cornerCommands(topLeft, ([x, y]) => [y + offset[0], x + offset[1]]),
|
|
317
|
+
cornerCommands(topRight, ([x, y]) => [width - x + offset[0], y + offset[1]]),
|
|
318
|
+
cornerCommands(bottomRight, ([x, y]) => [width - y + offset[0], height - x + offset[1]]),
|
|
319
|
+
cornerCommands(bottomLeft, ([x, y]) => [x + offset[0], height - y + offset[1]]),
|
|
320
|
+
"Z"
|
|
321
|
+
].join("");
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
//#endregion
|
|
325
|
+
//#region ../../packages/ui/src/geometry/corner-contour-offset.lib.ts
|
|
326
|
+
const MAX_SUBDIVISIONS = 16;
|
|
327
|
+
const FLATNESS_DIVISOR = 8;
|
|
328
|
+
const ARC_ARGUMENTS_AFTER_RADIUS = 4;
|
|
329
|
+
const MIN_POLYGON_POINTS = 3;
|
|
330
|
+
const PRECISION = 1e5;
|
|
331
|
+
const FLATNESS = .01;
|
|
332
|
+
const EPSILON = 1e-9;
|
|
333
|
+
const midpoint = (a, b) => [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
|
|
334
|
+
const distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1]);
|
|
335
|
+
const cross = (a, b) => a[0] * b[1] - a[1] * b[0];
|
|
336
|
+
const difference = (a, b) => [a[0] - b[0], a[1] - b[1]];
|
|
337
|
+
const stable = (value) => String(Math.round(value * PRECISION) / PRECISION);
|
|
338
|
+
const flattenCubic = (points, result, depth = 0) => {
|
|
339
|
+
const [a, b, c, d] = points;
|
|
340
|
+
const chord = distance(a, d);
|
|
341
|
+
if (depth >= MAX_SUBDIVISIONS || distance(a, b) + distance(b, c) + distance(c, d) - chord <= FLATNESS / FLATNESS_DIVISOR) {
|
|
342
|
+
result.push(d);
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
const ab = midpoint(a, b);
|
|
346
|
+
const bc = midpoint(b, c);
|
|
347
|
+
const cd = midpoint(c, d);
|
|
348
|
+
const abc = midpoint(ab, bc);
|
|
349
|
+
const bcd = midpoint(bc, cd);
|
|
350
|
+
const middle = midpoint(abc, bcd);
|
|
351
|
+
flattenCubic([
|
|
352
|
+
a,
|
|
353
|
+
ab,
|
|
354
|
+
abc,
|
|
355
|
+
middle
|
|
356
|
+
], result, depth + 1);
|
|
357
|
+
flattenCubic([
|
|
358
|
+
middle,
|
|
359
|
+
bcd,
|
|
360
|
+
cd,
|
|
361
|
+
d
|
|
362
|
+
], result, depth + 1);
|
|
363
|
+
};
|
|
364
|
+
const flattenArc = (start, end, radius, result) => {
|
|
365
|
+
const delta = difference(end, start);
|
|
366
|
+
const length = distance(start, end);
|
|
367
|
+
if (length < EPSILON) return;
|
|
368
|
+
const centreDistance = Math.sqrt(Math.max(0, radius * radius - length * length / 4));
|
|
369
|
+
const centre = [(start[0] + end[0]) / 2 - delta[1] * centreDistance / length, (start[1] + end[1]) / 2 + delta[0] * centreDistance / length];
|
|
370
|
+
const first = Math.atan2(start[1] - centre[1], start[0] - centre[0]);
|
|
371
|
+
let sweep = Math.atan2(end[1] - centre[1], end[0] - centre[0]) - first;
|
|
372
|
+
if (sweep < 0) sweep += 2 * Math.PI;
|
|
373
|
+
const steps = Math.max(1, Math.ceil(sweep / (2 * Math.acos(Math.max(-1, 1 - FLATNESS / radius)))));
|
|
374
|
+
for (let index = 1; index <= steps; index += 1) {
|
|
375
|
+
const angle = first + sweep * index / steps;
|
|
376
|
+
result.push([centre[0] + radius * Math.cos(angle), centre[1] + radius * Math.sin(angle)]);
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
const flattenedContour = (path) => {
|
|
380
|
+
const tokens = path.match(/[MLCAZ]|-?(?:\d*\.)?\d+(?:e[-+]?\d+)?/giu) ?? [];
|
|
381
|
+
const points = [];
|
|
382
|
+
let cursor = 0;
|
|
383
|
+
const number = () => Number(tokens[cursor++]);
|
|
384
|
+
const readPoint = () => [number(), number()];
|
|
385
|
+
const readCommand = (command) => {
|
|
386
|
+
const start = points.at(-1) ?? [0, 0];
|
|
387
|
+
if (command === "M" || command === "L") {
|
|
388
|
+
points.push(readPoint());
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
if (command === "C") {
|
|
392
|
+
flattenCubic([
|
|
393
|
+
start,
|
|
394
|
+
readPoint(),
|
|
395
|
+
readPoint(),
|
|
396
|
+
readPoint()
|
|
397
|
+
], points);
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
if (command === "A") {
|
|
401
|
+
const radius = number();
|
|
402
|
+
cursor += ARC_ARGUMENTS_AFTER_RADIUS;
|
|
403
|
+
flattenArc(start, readPoint(), radius, points);
|
|
404
|
+
}
|
|
405
|
+
};
|
|
406
|
+
while (cursor < tokens.length) readCommand(tokens[cursor++] ?? "Z");
|
|
407
|
+
return points.filter((point, index) => distance(point, points[(index + 1) % points.length] ?? point) > EPSILON);
|
|
408
|
+
};
|
|
409
|
+
const offsetEdge = (a, b, outset) => {
|
|
410
|
+
const [x, y] = difference(b, a);
|
|
411
|
+
const length = Math.hypot(x, y);
|
|
412
|
+
const shift = [y * outset / length, -x * outset / length];
|
|
413
|
+
return [[a[0] + shift[0], a[1] + shift[1]], [b[0] + shift[0], b[1] + shift[1]]];
|
|
414
|
+
};
|
|
415
|
+
const intersection = (a, b, c, d) => {
|
|
416
|
+
const ab = difference(b, a);
|
|
417
|
+
const cd = difference(d, c);
|
|
418
|
+
const divisor = cross(ab, cd);
|
|
419
|
+
if (Math.abs(divisor) < EPSILON) return midpoint(b, c);
|
|
420
|
+
const amount = cross(difference(c, a), cd) / divisor;
|
|
421
|
+
return [a[0] + amount * ab[0], a[1] + amount * ab[1]];
|
|
422
|
+
};
|
|
423
|
+
const insetPolygon = (points, outset) => {
|
|
424
|
+
let polygon = [...points];
|
|
425
|
+
for (const [index, point] of points.entries()) {
|
|
426
|
+
const next = points[(index + 1) % points.length];
|
|
427
|
+
if (next === void 0) continue;
|
|
428
|
+
const [a, b] = offsetEdge(point, next, outset);
|
|
429
|
+
const edge = difference(b, a);
|
|
430
|
+
const clipped = [];
|
|
431
|
+
for (const [candidateIndex, candidate] of polygon.entries()) {
|
|
432
|
+
const following = polygon[(candidateIndex + 1) % polygon.length] ?? candidate;
|
|
433
|
+
const isInside = cross(edge, difference(candidate, a)) >= -1e-9;
|
|
434
|
+
const isFollowingInside = cross(edge, difference(following, a)) >= -1e-9;
|
|
435
|
+
if (isInside) clipped.push(candidate);
|
|
436
|
+
if (isInside !== isFollowingInside) clipped.push(intersection(candidate, following, a, b));
|
|
437
|
+
}
|
|
438
|
+
polygon = clipped;
|
|
439
|
+
if (polygon.length === 0) break;
|
|
440
|
+
}
|
|
441
|
+
return polygon;
|
|
442
|
+
};
|
|
443
|
+
/** A parallel convex contour in CSS pixels; collapsed insets return an empty path. */
|
|
444
|
+
const offsetConvexContour = (contour, outset) => {
|
|
445
|
+
if (outset === 0) return contour;
|
|
446
|
+
const points = flattenedContour(contour);
|
|
447
|
+
const offset = outset < 0 ? insetPolygon(points, outset) : points.map((point, index) => {
|
|
448
|
+
const before = points[(index + points.length - 1) % points.length] ?? point;
|
|
449
|
+
const after = points[(index + 1) % points.length] ?? point;
|
|
450
|
+
const incoming = offsetEdge(before, point, outset);
|
|
451
|
+
const outgoing = offsetEdge(point, after, outset);
|
|
452
|
+
return intersection(...incoming, ...outgoing);
|
|
453
|
+
});
|
|
454
|
+
return offset.length < MIN_POLYGON_POINTS ? "" : offset.map((point, index) => `${index === 0 ? "M" : "L"}${stable(point[0])} ${stable(point[1])}`).join("") + "Z";
|
|
455
|
+
};
|
|
456
|
+
const offsetCornerContour = (radius, size, outset) => size.width <= 0 || size.height <= 0 ? "" : offsetConvexContour(cornerContour(radius, size), outset);
|
|
457
|
+
|
|
458
|
+
//#endregion
|
|
459
|
+
//#region ../../packages/contract/src/canvas/canvas-geometry-affine.lib.ts
|
|
460
|
+
const HALF_TURN = 180;
|
|
461
|
+
/** The same center-based affine transform is used by scene geometry and browser paint. */
|
|
462
|
+
const canvasGeometryLocalMatrixFor = (box, transform, residual) => {
|
|
463
|
+
const radians = (transform.rotation ?? 0) * Math.PI / HALF_TURN;
|
|
464
|
+
const cosine = Math.cos(radians);
|
|
465
|
+
const sine = Math.sin(radians);
|
|
466
|
+
const scaleX = transform.flipHorizontal === true ? -1 : 1;
|
|
467
|
+
const scaleY = transform.flipVertical === true ? -1 : 1;
|
|
468
|
+
const baseA = cosine * scaleX;
|
|
469
|
+
const baseB = sine * scaleX;
|
|
470
|
+
const baseC = -sine * scaleY;
|
|
471
|
+
const baseD = cosine * scaleY;
|
|
472
|
+
const a = residual === void 0 ? baseA : baseA * residual.a + baseC * residual.b;
|
|
473
|
+
const b = residual === void 0 ? baseB : baseB * residual.a + baseD * residual.b;
|
|
474
|
+
const c = residual === void 0 ? baseC : baseA * residual.c + baseC * residual.d;
|
|
475
|
+
const d = residual === void 0 ? baseD : baseB * residual.c + baseD * residual.d;
|
|
476
|
+
const centerX = box.width / 2;
|
|
477
|
+
const centerY = box.height / 2;
|
|
478
|
+
return {
|
|
479
|
+
a,
|
|
480
|
+
b,
|
|
481
|
+
c,
|
|
482
|
+
d,
|
|
483
|
+
e: box.x + centerX - a * centerX - c * centerY,
|
|
484
|
+
f: box.y + centerY - b * centerX - d * centerY
|
|
485
|
+
};
|
|
486
|
+
};
|
|
487
|
+
const MATRIX_COMPONENTS = 6;
|
|
488
|
+
const residualOf = (node) => {
|
|
489
|
+
const value = node.additionalStyles?.declarations.find((declaration) => declaration.enabled && declaration.property === "--enhance-group-affine-residual")?.value;
|
|
490
|
+
if (value === void 0) return;
|
|
491
|
+
const parts = /^matrix\(([^)]*)\)$/iu.exec(value)?.[1]?.split(",").map((part) => Number(part.trim()));
|
|
492
|
+
if (parts?.length !== MATRIX_COMPONENTS || parts.some((part) => !Number.isFinite(part))) return null;
|
|
493
|
+
const [a, b, c, d] = parts;
|
|
494
|
+
return a === void 0 || b === void 0 || c === void 0 || d === void 0 ? null : {
|
|
495
|
+
a,
|
|
496
|
+
b,
|
|
497
|
+
c,
|
|
498
|
+
d
|
|
499
|
+
};
|
|
500
|
+
};
|
|
501
|
+
/** A layer's placement in its parent: its box, rotation, flips and any group residual. */
|
|
502
|
+
const canvasNodeLocalMatrixOf = (node) => {
|
|
503
|
+
const residual = residualOf(node);
|
|
504
|
+
return residual === null || node.box === void 0 ? null : canvasGeometryLocalMatrixFor(node.box, node.layout ?? {}, residual);
|
|
505
|
+
};
|
|
506
|
+
|
|
507
|
+
//#endregion
|
|
508
|
+
//#region ../../packages/contract/src/canvas/canvas-polygon-geometry.lib.ts
|
|
509
|
+
const CUBIC_DEGREE = 3;
|
|
510
|
+
const ANGLE_DIVISOR = 4;
|
|
511
|
+
const shifted = (point, direction, distance) => ({
|
|
512
|
+
x: point.x + direction.x * distance,
|
|
513
|
+
y: point.y + direction.y * distance
|
|
514
|
+
});
|
|
515
|
+
const coordinates = (point) => `${String(point.x)} ${String(point.y)}`;
|
|
516
|
+
const unitTowards = (point, target, distance) => ({
|
|
517
|
+
x: (target.x - point.x) / distance,
|
|
518
|
+
y: (target.y - point.y) / distance
|
|
519
|
+
});
|
|
520
|
+
const polygonVertices = (node, width, height) => {
|
|
521
|
+
const isStar = node.innerRatio !== void 0;
|
|
522
|
+
const count = node.count;
|
|
523
|
+
const inner = node.innerRatio ?? 1;
|
|
524
|
+
const length = isStar ? count * 2 : count;
|
|
525
|
+
return Array.from({ length }, (_, index) => {
|
|
526
|
+
const radius = index % 2 === 0 ? 1 : inner;
|
|
527
|
+
const angle = -Math.PI / 2 + index * Math.PI * 2 / length;
|
|
528
|
+
return {
|
|
529
|
+
x: width / 2 + Math.cos(angle) * width * radius / 2,
|
|
530
|
+
y: height / 2 + Math.sin(angle) * height * radius / 2
|
|
531
|
+
};
|
|
532
|
+
});
|
|
533
|
+
};
|
|
534
|
+
const polygonCorner = (vertices, index) => {
|
|
535
|
+
const vertex = vertices[index];
|
|
536
|
+
const previous = vertices[(index + vertices.length - 1) % vertices.length];
|
|
537
|
+
const next = vertices[(index + 1) % vertices.length];
|
|
538
|
+
if (vertex === void 0 || previous === void 0 || next === void 0) return void 0;
|
|
539
|
+
const previousLength = Math.hypot(previous.x - vertex.x, previous.y - vertex.y);
|
|
540
|
+
const nextLength = Math.hypot(next.x - vertex.x, next.y - vertex.y);
|
|
541
|
+
if (previousLength === 0 || nextLength === 0) return void 0;
|
|
542
|
+
const before = unitTowards(vertex, previous, previousLength);
|
|
543
|
+
const after = unitTowards(vertex, next, nextLength);
|
|
544
|
+
const angle = Math.acos(Math.min(1, Math.max(-1, before.x * after.x + before.y * after.y)));
|
|
545
|
+
if (angle === 0 || angle === Math.PI) return void 0;
|
|
546
|
+
return {
|
|
547
|
+
vertex,
|
|
548
|
+
before,
|
|
549
|
+
after,
|
|
550
|
+
previousLength,
|
|
551
|
+
nextLength,
|
|
552
|
+
angle,
|
|
553
|
+
cotangent: 1 / Math.tan(angle / 2)
|
|
554
|
+
};
|
|
555
|
+
};
|
|
556
|
+
const cornerSide = (corner, direction, radius, smoothing) => {
|
|
557
|
+
const offset = radius * corner.cotangent;
|
|
558
|
+
const start = shifted(corner.vertex, direction, offset * (1 + smoothing));
|
|
559
|
+
const tangent = shifted(corner.vertex, direction, offset);
|
|
560
|
+
const center = shifted(corner.vertex, {
|
|
561
|
+
x: corner.before.x + corner.after.x,
|
|
562
|
+
y: corner.before.y + corner.after.y
|
|
563
|
+
}, radius / Math.sin(corner.angle));
|
|
564
|
+
const normal = unitTowards(tangent, center, radius);
|
|
565
|
+
const angle = (Math.PI - corner.angle) * smoothing / 2;
|
|
566
|
+
const end = shifted(shifted(tangent, direction, -radius * Math.sin(angle)), normal, radius * (1 - Math.cos(angle)));
|
|
567
|
+
const travel = {
|
|
568
|
+
x: -direction.x * Math.cos(angle) + normal.x * Math.sin(angle),
|
|
569
|
+
y: -direction.y * Math.cos(angle) + normal.y * Math.sin(angle)
|
|
570
|
+
};
|
|
571
|
+
const second = shifted(end, travel, -radius * Math.tan(angle / 2));
|
|
572
|
+
return {
|
|
573
|
+
start,
|
|
574
|
+
first: {
|
|
575
|
+
x: start.x + (second.x - start.x) * 2 / CUBIC_DEGREE,
|
|
576
|
+
y: start.y + (second.y - start.y) * 2 / CUBIC_DEGREE
|
|
577
|
+
},
|
|
578
|
+
second,
|
|
579
|
+
end,
|
|
580
|
+
travel
|
|
581
|
+
};
|
|
582
|
+
};
|
|
583
|
+
const cornerPath = (corner, radius, smoothing) => {
|
|
584
|
+
const before = cornerSide(corner, corner.before, radius, smoothing);
|
|
585
|
+
const after = cornerSide(corner, corner.after, radius, smoothing);
|
|
586
|
+
const handle = ANGLE_DIVISOR / CUBIC_DEGREE * radius * Math.tan((Math.PI - corner.angle) * (1 - smoothing) / ANGLE_DIVISOR);
|
|
587
|
+
const first = shifted(before.end, before.travel, handle);
|
|
588
|
+
const second = shifted(after.end, after.travel, handle);
|
|
589
|
+
const curve = (a, b, end) => `C${coordinates(a)} ${coordinates(b)} ${coordinates(end)}`;
|
|
590
|
+
return coordinates(before.start) + (smoothing > 0 ? curve(before.first, before.second, before.end) : "") + curve(first, second, after.end) + (smoothing > 0 ? curve(after.second, after.first, after.start) : "");
|
|
591
|
+
};
|
|
592
|
+
const canvasPolygonContour = (vertices, radii, smoothing) => {
|
|
593
|
+
const corners = vertices.map((_, index) => polygonCorner(vertices, index));
|
|
594
|
+
const radiusAt = (index) => typeof radii === "number" ? radii : radii[index] ?? 0;
|
|
595
|
+
return `${vertices.map((vertex, index) => {
|
|
596
|
+
const corner = corners[index];
|
|
597
|
+
const previousIndex = (index + vertices.length - 1) % vertices.length;
|
|
598
|
+
const nextIndex = (index + 1) % vertices.length;
|
|
599
|
+
const previous = corners[previousIndex];
|
|
600
|
+
const next = corners[nextIndex];
|
|
601
|
+
const radius = radiusAt(index);
|
|
602
|
+
const prefix = index === 0 ? "M" : "L";
|
|
603
|
+
if (radius === 0 || corner === void 0) return prefix + coordinates(vertex);
|
|
604
|
+
const maximum = Math.min(corner.previousLength / (corner.cotangent + (previous?.cotangent ?? 0) * (radiusAt(previousIndex) / radius)), corner.nextLength / (corner.cotangent + (next?.cotangent ?? 0) * (radiusAt(nextIndex) / radius)));
|
|
605
|
+
const limitedRadius = Math.min(radius, maximum);
|
|
606
|
+
const limitedSmoothing = Math.min(smoothing, Math.max(0, maximum / limitedRadius - 1));
|
|
607
|
+
return prefix + cornerPath(corner, limitedRadius, limitedSmoothing);
|
|
608
|
+
}).join("")}Z`;
|
|
609
|
+
};
|
|
610
|
+
const canvasPolygonPath = (node, width, height) => canvasPolygonContour(polygonVertices(node, width, height), node.cornerRadius, node.cornerSmoothing);
|
|
611
|
+
|
|
612
|
+
//#endregion
|
|
613
|
+
//#region ../../packages/contract/src/canvas/canvas-path-rounding.lib.ts
|
|
614
|
+
const RECTANGLE_CORNERS = 4;
|
|
615
|
+
const MINIMUM_POLYGON_CORNERS = 3;
|
|
616
|
+
const vertices = /* @__PURE__ */ new WeakMap();
|
|
617
|
+
const booleanVertices = /* @__PURE__ */ new WeakMap();
|
|
618
|
+
const booleanContours = (geometry) => {
|
|
619
|
+
if (booleanVertices.has(geometry)) return booleanVertices.get(geometry) ?? null;
|
|
620
|
+
const parts = geometry.result.path.match(/M[^M]*/gu) ?? [];
|
|
621
|
+
const contours = parts.map((path) => {
|
|
622
|
+
const points = canvasStraightPathVertices(path);
|
|
623
|
+
return {
|
|
624
|
+
path,
|
|
625
|
+
vertices: points !== null && points.length >= MINIMUM_POLYGON_CORNERS ? points : null
|
|
626
|
+
};
|
|
627
|
+
});
|
|
628
|
+
const result = parts.length > 0 && parts.join("") === geometry.result.path ? contours : null;
|
|
629
|
+
booleanVertices.set(geometry, result);
|
|
630
|
+
return result;
|
|
631
|
+
};
|
|
632
|
+
const canvasRoundedBooleanPath = (geometry, box, radius) => {
|
|
633
|
+
const original = {
|
|
634
|
+
kind: "path",
|
|
635
|
+
path: geometry.result.path,
|
|
636
|
+
fillRule: geometry.result.fillRule,
|
|
637
|
+
viewBox: {
|
|
638
|
+
x: 0,
|
|
639
|
+
y: 0,
|
|
640
|
+
width: box.width,
|
|
641
|
+
height: box.height
|
|
642
|
+
}
|
|
643
|
+
};
|
|
644
|
+
if (radius === void 0 || radius.topLeft === 0 || [
|
|
645
|
+
radius.topRight,
|
|
646
|
+
radius.bottomLeft,
|
|
647
|
+
radius.bottomRight
|
|
648
|
+
].some((value) => value !== radius.topLeft)) return original;
|
|
649
|
+
const contours = booleanContours(geometry);
|
|
650
|
+
return contours === null ? original : {
|
|
651
|
+
...original,
|
|
652
|
+
path: contours.map((contour) => contour.vertices === null ? contour.path : canvasPolygonContour(contour.vertices, radius.topLeft, radius.smoothing ?? 0)).join("")
|
|
653
|
+
};
|
|
654
|
+
};
|
|
655
|
+
const rectangleVertices = (geometry) => {
|
|
656
|
+
if (vertices.has(geometry)) return vertices.get(geometry) ?? null;
|
|
657
|
+
const points = canvasStraightPathVertices(geometry.path);
|
|
658
|
+
const result = points?.length === RECTANGLE_CORNERS && points.every((point, index) => {
|
|
659
|
+
const next = points[(index + 1) % RECTANGLE_CORNERS];
|
|
660
|
+
const after = points[(index + 2) % RECTANGLE_CORNERS];
|
|
661
|
+
return next !== void 0 && after !== void 0 && (next.x - point.x) * (after.y - next.y) > (next.y - point.y) * (after.x - next.x);
|
|
662
|
+
}) ? points : null;
|
|
663
|
+
vertices.set(geometry, result);
|
|
664
|
+
return result;
|
|
665
|
+
};
|
|
666
|
+
const canvasRoundedRectanglePath = (geometry, radius, box) => {
|
|
667
|
+
if (box.width <= 0 || box.height <= 0) return geometry;
|
|
668
|
+
const radii = [
|
|
669
|
+
radius.topLeft,
|
|
670
|
+
radius.topRight,
|
|
671
|
+
radius.bottomRight,
|
|
672
|
+
radius.bottomLeft
|
|
673
|
+
];
|
|
674
|
+
if (radii.every((value) => value === 0) && geometry.viewBox.x === 0 && geometry.viewBox.y === 0 && box.width === geometry.viewBox.width && box.height === geometry.viewBox.height) return geometry;
|
|
675
|
+
const points = rectangleVertices(geometry);
|
|
676
|
+
if (points === null) return geometry;
|
|
677
|
+
const local = points.map((point) => ({
|
|
678
|
+
x: (point.x - geometry.viewBox.x) * box.width / geometry.viewBox.width,
|
|
679
|
+
y: (point.y - geometry.viewBox.y) * box.height / geometry.viewBox.height
|
|
680
|
+
}));
|
|
681
|
+
return {
|
|
682
|
+
...geometry,
|
|
683
|
+
path: canvasPolygonContour(local, radii, radius.smoothing ?? 0),
|
|
684
|
+
viewBox: {
|
|
685
|
+
x: 0,
|
|
686
|
+
y: 0,
|
|
687
|
+
width: box.width,
|
|
688
|
+
height: box.height
|
|
689
|
+
}
|
|
690
|
+
};
|
|
691
|
+
};
|
|
692
|
+
|
|
693
|
+
//#endregion
|
|
694
|
+
//#region ../../packages/contract/src/canvas/canvas-composition-geometry.lib.ts
|
|
695
|
+
const PERCENT_BASE = 100;
|
|
696
|
+
const EMPTY_RADIUS = {
|
|
697
|
+
topLeft: 0,
|
|
698
|
+
topRight: 0,
|
|
699
|
+
bottomRight: 0,
|
|
700
|
+
bottomLeft: 0
|
|
701
|
+
};
|
|
702
|
+
const RADIUS_PROPERTIES = [
|
|
703
|
+
"border-top-left-radius",
|
|
704
|
+
"border-top-right-radius",
|
|
705
|
+
"border-bottom-right-radius",
|
|
706
|
+
"border-bottom-left-radius"
|
|
707
|
+
];
|
|
708
|
+
const radiusValue = (value, size) => {
|
|
709
|
+
if (value === void 0) return 0;
|
|
710
|
+
if (typeof value === "number") return Number.isFinite(value) && value >= 0 ? value : null;
|
|
711
|
+
const match = /^\s*(\d+(?:\.\d+)?)(px|%)?\s*$/u.exec(value);
|
|
712
|
+
if (match === null) return null;
|
|
713
|
+
const amount = Number(match[1]);
|
|
714
|
+
return match[2] === "%" ? size * amount / PERCENT_BASE : amount;
|
|
715
|
+
};
|
|
716
|
+
const rectangleRadius = (node) => {
|
|
717
|
+
if (node.appearance?.radius !== void 0) return node.appearance.radius;
|
|
718
|
+
if (node.box === void 0) return null;
|
|
719
|
+
const base = node.styles["border-radius"];
|
|
720
|
+
const [topLeft, topRight, bottomRight, bottomLeft] = RADIUS_PROPERTIES.map((property) => radiusValue(node.styles[property] ?? base, Math.min(node.box?.width ?? 0, node.box?.height ?? 0)));
|
|
721
|
+
return topLeft === null || topRight === null || bottomRight === null || bottomLeft === null ? null : {
|
|
722
|
+
topLeft: topLeft ?? 0,
|
|
723
|
+
topRight: topRight ?? 0,
|
|
724
|
+
bottomRight: bottomRight ?? 0,
|
|
725
|
+
bottomLeft: bottomLeft ?? 0
|
|
726
|
+
};
|
|
727
|
+
};
|
|
728
|
+
const ellipsePath = (width, height) => {
|
|
729
|
+
const x = width / 2;
|
|
730
|
+
const y = height / 2;
|
|
731
|
+
return `M0 ${String(y)}A${String(x)} ${String(y)} 0 1 0 ${String(width)} ${String(y)}A${String(x)} ${String(y)} 0 1 0 0 ${String(y)}Z`;
|
|
732
|
+
};
|
|
733
|
+
const shapePathOf = (node, editable) => {
|
|
734
|
+
if (node.geometry?.kind === "path") return node.geometry;
|
|
735
|
+
const box = node.box;
|
|
736
|
+
if (box !== void 0 && node.geometry?.kind === "polygon" && box.width > 0 && box.height > 0) return {
|
|
737
|
+
kind: "path",
|
|
738
|
+
path: canvasPolygonPath(node.geometry, box.width, box.height),
|
|
739
|
+
fillRule: "nonzero",
|
|
740
|
+
viewBox: {
|
|
741
|
+
x: 0,
|
|
742
|
+
y: 0,
|
|
743
|
+
width: box.width,
|
|
744
|
+
height: box.height
|
|
745
|
+
}
|
|
746
|
+
};
|
|
747
|
+
if (box === void 0 || !["rectangle", "frame"].includes(node.component) || box.width <= 0 || box.height <= 0) return "Choose a closed shape or an editable vector path.";
|
|
748
|
+
const radius = rectangleRadius(node);
|
|
749
|
+
if (radius === null) return "This shape uses a corner expression that cannot be edited as a path.";
|
|
750
|
+
return {
|
|
751
|
+
kind: "path",
|
|
752
|
+
fillRule: "nonzero",
|
|
753
|
+
path: node.styles["border-radius"] === "50%" && node.appearance?.radius === void 0 && RADIUS_PROPERTIES.every((property) => node.styles[property] === void 0) ? ellipsePath(box.width, box.height) : cornerContour(editable && node.component === "rectangle" && node.appearance?.radius !== void 0 ? EMPTY_RADIUS : {
|
|
754
|
+
...EMPTY_RADIUS,
|
|
755
|
+
...radius
|
|
756
|
+
}, box),
|
|
757
|
+
viewBox: {
|
|
758
|
+
x: 0,
|
|
759
|
+
y: 0,
|
|
760
|
+
width: box.width,
|
|
761
|
+
height: box.height
|
|
762
|
+
}
|
|
763
|
+
};
|
|
764
|
+
};
|
|
765
|
+
const canvasShapePathOf = (node) => {
|
|
766
|
+
if (node.geometry?.kind === "boolean" && node.box !== void 0) return node.geometry.result.isEmpty ? "This shape has no closed geometry." : canvasRoundedBooleanPath(node.geometry, node.box, node.appearance?.radius);
|
|
767
|
+
const geometry = shapePathOf(node, false);
|
|
768
|
+
return typeof geometry !== "string" && node.geometry?.kind === "path" && node.component === "rectangle" && node.appearance?.radius !== void 0 && node.box !== void 0 ? canvasRoundedRectanglePath(geometry, node.appearance.radius, node.box) : geometry;
|
|
769
|
+
};
|
|
770
|
+
const canvasShapeOperandOf = (node) => {
|
|
771
|
+
const geometry = canvasShapePathOf(node);
|
|
772
|
+
if (typeof geometry === "string") return geometry;
|
|
773
|
+
if (node.box === void 0) return "The shape has no settled local box.";
|
|
774
|
+
const matrix = canvasNodeLocalMatrixOf(node);
|
|
775
|
+
if (matrix === null) return "The shape has an invalid affine transform.";
|
|
776
|
+
const scaleX = node.box.width / geometry.viewBox.width;
|
|
777
|
+
const scaleY = node.box.height / geometry.viewBox.height;
|
|
778
|
+
return {
|
|
779
|
+
path: geometry.path,
|
|
780
|
+
fillRule: geometry.fillRule,
|
|
781
|
+
matrix: [
|
|
782
|
+
matrix.a * scaleX,
|
|
783
|
+
matrix.b * scaleX,
|
|
784
|
+
matrix.c * scaleY,
|
|
785
|
+
matrix.d * scaleY,
|
|
786
|
+
matrix.e - matrix.a * scaleX * geometry.viewBox.x - matrix.c * scaleY * geometry.viewBox.y,
|
|
787
|
+
matrix.f - matrix.b * scaleX * geometry.viewBox.x - matrix.d * scaleY * geometry.viewBox.y
|
|
788
|
+
]
|
|
789
|
+
};
|
|
790
|
+
};
|
|
791
|
+
|
|
792
|
+
//#endregion
|
|
793
|
+
//#region ../../packages/contract/src/canvas/canvas-diamond-gradient.lib.ts
|
|
794
|
+
const HALF = .5;
|
|
795
|
+
const QUARTER = .25;
|
|
796
|
+
/** Each quadrant is a linear field with slope 2*(abs(x-.5)+abs(y-.5)). */
|
|
797
|
+
const canvasDiamondGradientField = (paint, id = "field", bounds) => {
|
|
798
|
+
const coordinates = canvasGradientFieldCoordinates(paint, bounds);
|
|
799
|
+
const extent = Math.max(HALF, ...coordinates.map((value) => Math.abs(value - HALF))) + 1;
|
|
800
|
+
const low = HALF - extent, high = HALF + extent;
|
|
801
|
+
const quadrants = [
|
|
802
|
+
{
|
|
803
|
+
x: .75,
|
|
804
|
+
y: .75,
|
|
805
|
+
points: `.5,.5 ${String(high)},.5 ${String(high)},${String(high)} .5,${String(high)}`
|
|
806
|
+
},
|
|
807
|
+
{
|
|
808
|
+
x: QUARTER,
|
|
809
|
+
y: .75,
|
|
810
|
+
points: `.5,.5 .5,${String(high)} ${String(low)},${String(high)} ${String(low)},.5`
|
|
811
|
+
},
|
|
812
|
+
{
|
|
813
|
+
x: QUARTER,
|
|
814
|
+
y: QUARTER,
|
|
815
|
+
points: `.5,.5 ${String(low)},.5 ${String(low)},${String(low)} .5,${String(low)}`
|
|
816
|
+
},
|
|
817
|
+
{
|
|
818
|
+
x: .75,
|
|
819
|
+
y: QUARTER,
|
|
820
|
+
points: `.5,.5 .5,${String(low)} ${String(high)},${String(low)} ${String(high)},.5`
|
|
821
|
+
}
|
|
822
|
+
];
|
|
823
|
+
const stops = paint.stops.map((stop) => `<stop offset="${String(stop.position)}" stop-color="${canvasColorCss({
|
|
824
|
+
...stop.color,
|
|
825
|
+
alpha: 1
|
|
826
|
+
})}" stop-opacity="${String(stop.color.alpha * paint.opacity)}" />`).join("");
|
|
827
|
+
const definitions = quadrants.map((quadrant, index) => `<linearGradient id="${id}-${String(index)}" gradientUnits="userSpaceOnUse" x1=".5" y1=".5" x2="${String(quadrant.x)}" y2="${String(quadrant.y)}" color-interpolation="sRGB">${stops}</linearGradient>`).join("");
|
|
828
|
+
const fields = quadrants.map((quadrant, index) => `<polygon points="${quadrant.points}" fill="url(#${id}-${String(index)})" shape-rendering="crispEdges" />`).join("");
|
|
829
|
+
return `<defs>${definitions}</defs><g transform="matrix(${paint.transform.map(String).join(" ")})">${fields}</g>`;
|
|
830
|
+
};
|
|
831
|
+
const canvasDiamondGradientSvg = (paint) => `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">${canvasDiamondGradientField(paint)}</svg>`;
|
|
832
|
+
|
|
833
|
+
//#endregion
|
|
834
|
+
//#region ../../packages/contract/src/canvas/canvas-filter.lib.ts
|
|
835
|
+
const PERCENT$3 = 100;
|
|
836
|
+
/** Radius/2 preserves the existing Gaussian approximation, not native sampling parity. */
|
|
837
|
+
const canvasBlurStandardDeviation = (filter) => filter.parameter === "radius" ? filter.value / 2 : filter.value;
|
|
838
|
+
const filterCss = (filter) => {
|
|
839
|
+
switch (filter.kind) {
|
|
840
|
+
case "blur": return `blur(${String(canvasBlurStandardDeviation(filter))}px)`;
|
|
841
|
+
case "brightness":
|
|
842
|
+
case "contrast":
|
|
843
|
+
case "saturate": return `${filter.kind}(${String(filter.value)})`;
|
|
844
|
+
case "grayscale":
|
|
845
|
+
case "invert":
|
|
846
|
+
case "sepia": return `${filter.kind}(${String(filter.value * PERCENT$3)}%)`;
|
|
847
|
+
case "hue-rotate": return `hue-rotate(${String(filter.value)}deg)`;
|
|
848
|
+
}
|
|
849
|
+
};
|
|
850
|
+
const canvasFilterListCss = (filters) => filters.filter((filter) => filter.visible).map((filter) => filterCss(filter)).join(" ");
|
|
851
|
+
|
|
72
852
|
//#endregion
|
|
73
853
|
//#region ../../packages/contract/src/canvas/canvas-html-source.lib.ts
|
|
74
854
|
const OMITTED_ELEMENTS = /* @__PURE__ */ new Set([
|
|
@@ -145,11 +925,11 @@ const mapCanvasNodeImageSources = (node, map) => {
|
|
|
145
925
|
...appearance.fills !== void 0 && { fills: appearance.fills.map((paint) => mapPaint(paint, map)) },
|
|
146
926
|
...appearance.border !== void 0 && { border: {
|
|
147
927
|
...appearance.border,
|
|
148
|
-
|
|
928
|
+
paints: appearance.border.paints.map((paint) => mapPaint(paint, map))
|
|
149
929
|
} },
|
|
150
930
|
...appearance.outline !== void 0 && { outline: {
|
|
151
931
|
...appearance.outline,
|
|
152
|
-
|
|
932
|
+
paints: appearance.outline.paints.map((paint) => mapPaint(paint, map))
|
|
153
933
|
} }
|
|
154
934
|
} },
|
|
155
935
|
...node.typography?.stroke !== void 0 && { typography: {
|
|
@@ -167,6 +947,89 @@ const mapCanvasNodeImageSources = (node, map) => {
|
|
|
167
947
|
};
|
|
168
948
|
};
|
|
169
949
|
|
|
950
|
+
//#endregion
|
|
951
|
+
//#region ../../packages/contract/src/canvas/canvas-linear-gradient.lib.ts
|
|
952
|
+
const canvasLinearGradientDefinition = (paint, id, units = "userSpaceOnUse") => {
|
|
953
|
+
const stops = paint.stops.map((stop) => `<stop offset="${String(stop.position)}" stop-color="${canvasColorCss({
|
|
954
|
+
...stop.color,
|
|
955
|
+
alpha: 1
|
|
956
|
+
})}" stop-opacity="${String(stop.color.alpha * paint.opacity)}" />`).join("");
|
|
957
|
+
return `<linearGradient id="${id}" gradientUnits="${units}" x1="0" y1=".5" x2="1" y2=".5" gradientTransform="matrix(${paint.transform.map(String).join(" ")})" color-interpolation="sRGB">${stops}</linearGradient>`;
|
|
958
|
+
};
|
|
959
|
+
const canvasLinearGradientSvg = (paint) => {
|
|
960
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${canvasLinearGradientDefinition(paint, "field")}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`;
|
|
961
|
+
};
|
|
962
|
+
|
|
963
|
+
//#endregion
|
|
964
|
+
//#region ../../packages/contract/src/canvas/canvas-presentation-defaults.lib.ts
|
|
965
|
+
const emptySolidPaint = (id) => ({
|
|
966
|
+
id,
|
|
967
|
+
visible: false,
|
|
968
|
+
opacity: 1,
|
|
969
|
+
kind: "solid",
|
|
970
|
+
color: {
|
|
971
|
+
space: "srgb",
|
|
972
|
+
red: 0,
|
|
973
|
+
green: 0,
|
|
974
|
+
blue: 0,
|
|
975
|
+
alpha: 0
|
|
976
|
+
}
|
|
977
|
+
});
|
|
978
|
+
const emptyCanvasAppearance = () => ({
|
|
979
|
+
opacity: 1,
|
|
980
|
+
blendMode: "normal",
|
|
981
|
+
fills: [],
|
|
982
|
+
border: {
|
|
983
|
+
visible: false,
|
|
984
|
+
width: {
|
|
985
|
+
top: 0,
|
|
986
|
+
right: 0,
|
|
987
|
+
bottom: 0,
|
|
988
|
+
left: 0
|
|
989
|
+
},
|
|
990
|
+
style: "solid",
|
|
991
|
+
paints: [emptySolidPaint("empty-border")]
|
|
992
|
+
},
|
|
993
|
+
outline: {
|
|
994
|
+
visible: false,
|
|
995
|
+
width: 0,
|
|
996
|
+
offset: 0,
|
|
997
|
+
style: "solid",
|
|
998
|
+
paints: [emptySolidPaint("empty-outline")]
|
|
999
|
+
},
|
|
1000
|
+
radius: {
|
|
1001
|
+
topLeft: 0,
|
|
1002
|
+
topRight: 0,
|
|
1003
|
+
bottomRight: 0,
|
|
1004
|
+
bottomLeft: 0
|
|
1005
|
+
},
|
|
1006
|
+
shadows: [],
|
|
1007
|
+
filters: [],
|
|
1008
|
+
backdropFilters: []
|
|
1009
|
+
});
|
|
1010
|
+
|
|
1011
|
+
//#endregion
|
|
1012
|
+
//#region ../../packages/contract/src/canvas/canvas-radial-gradient.lib.ts
|
|
1013
|
+
const DIAMETER = 2;
|
|
1014
|
+
const transformFor = (paint) => paint.transform ?? [
|
|
1015
|
+
paint.radius.x * DIAMETER,
|
|
1016
|
+
0,
|
|
1017
|
+
0,
|
|
1018
|
+
paint.radius.y * DIAMETER,
|
|
1019
|
+
paint.center.x - paint.radius.x,
|
|
1020
|
+
paint.center.y - paint.radius.y
|
|
1021
|
+
];
|
|
1022
|
+
const canvasRadialGradientDefinition = (paint, id, units = "userSpaceOnUse") => {
|
|
1023
|
+
const stops = paint.stops.map((stop) => `<stop offset="${String(stop.position)}" stop-color="${canvasColorCss({
|
|
1024
|
+
...stop.color,
|
|
1025
|
+
alpha: 1
|
|
1026
|
+
})}" stop-opacity="${String(stop.color.alpha * paint.opacity)}" />`).join("");
|
|
1027
|
+
return `<radialGradient id="${id}" gradientUnits="${units}" cx=".5" cy=".5" r=".5" gradientTransform="matrix(${transformFor(paint).map(String).join(" ")})" color-interpolation="sRGB">${stops}</radialGradient>`;
|
|
1028
|
+
};
|
|
1029
|
+
const canvasRadialGradientSvg = (paint) => {
|
|
1030
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><defs>${canvasRadialGradientDefinition(paint, "field")}</defs><path d="M0 0H1V1H0Z" fill="url(#field)" /></svg>`;
|
|
1031
|
+
};
|
|
1032
|
+
|
|
170
1033
|
//#endregion
|
|
171
1034
|
//#region src/application/auth.use-case.ts
|
|
172
1035
|
const TOKEN = /^enh_[\w-]{43}$/;
|
|
@@ -545,7 +1408,7 @@ const union = (boxes) => {
|
|
|
545
1408
|
const apply = async (remote, input) => {
|
|
546
1409
|
const response = await remote.mutate(APPLY_PROCEDURE, {
|
|
547
1410
|
...input,
|
|
548
|
-
documentFormatVersion:
|
|
1411
|
+
documentFormatVersion: 13
|
|
549
1412
|
});
|
|
550
1413
|
const parsed = applyCanvasOperationsOutputSchema.safeParse(response);
|
|
551
1414
|
if (!parsed.success) throw new CliError("INTERNAL", "The API returned an invalid canvas apply response.", "Run `enhance doctor`; report the API and CLI versions if they differ.");
|
|
@@ -583,7 +1446,7 @@ const sceneAtVersion = async (input, canvasId, expectedVersion) => {
|
|
|
583
1446
|
//#endregion
|
|
584
1447
|
//#region src/application/canvas-structure-document.use-case.ts
|
|
585
1448
|
const ROOT_CANVAS_NODE_ID = "root";
|
|
586
|
-
const canvasChildIds = (document, parentId) => Object.entries(document.relationships).filter(([, relationship]) => relationship.parentId === parentId).toSorted(([leftId, left], [rightId, right]) => left.sortKey === right.sortKey ? leftId.localeCompare(rightId) : left.sortKey
|
|
1449
|
+
const canvasChildIds = (document, parentId) => Object.entries(document.relationships).filter(([, relationship]) => relationship.parentId === parentId).toSorted(([leftId, left], [rightId, right]) => left.sortKey === right.sortKey ? leftId.localeCompare(rightId) : compareCanvasSortKeys(left.sortKey, right.sortKey)).map(([nodeId]) => nodeId);
|
|
587
1450
|
const canvasChildrenByParent = (document) => {
|
|
588
1451
|
const children = /* @__PURE__ */ new Map();
|
|
589
1452
|
for (const [id, relationship] of Object.entries(document.relationships)) {
|
|
@@ -803,46 +1666,2302 @@ const applyMove = (input, destination, state) => {
|
|
|
803
1666
|
parentId: destination.parentId,
|
|
804
1667
|
sortKey
|
|
805
1668
|
};
|
|
806
|
-
relationships[input.nodeId] = parentage;
|
|
807
|
-
operations.push({
|
|
808
|
-
op: "setParentage",
|
|
809
|
-
nodeId: input.nodeId,
|
|
810
|
-
parentage
|
|
811
|
-
});
|
|
1669
|
+
relationships[input.nodeId] = parentage;
|
|
1670
|
+
operations.push({
|
|
1671
|
+
op: "setParentage",
|
|
1672
|
+
nodeId: input.nodeId,
|
|
1673
|
+
parentage
|
|
1674
|
+
});
|
|
1675
|
+
}
|
|
1676
|
+
children.splice(destination.index, 0, input.nodeId);
|
|
1677
|
+
state.children.set(destination.parentId, children);
|
|
1678
|
+
state.parentOf.set(input.nodeId, destination.parentId);
|
|
1679
|
+
state.affected.add(destination.parentId);
|
|
1680
|
+
return {
|
|
1681
|
+
operations,
|
|
1682
|
+
document: {
|
|
1683
|
+
...state.document,
|
|
1684
|
+
relationships
|
|
1685
|
+
}
|
|
1686
|
+
};
|
|
1687
|
+
};
|
|
1688
|
+
const moveCanvasNodeOperations = (document, inputs) => {
|
|
1689
|
+
if (inputs.length === 0) throw new CliError("BAD_REQUEST", "No moves were provided.", "Pass at least one move operation.");
|
|
1690
|
+
const state = moveState(document);
|
|
1691
|
+
const moves = [];
|
|
1692
|
+
return {
|
|
1693
|
+
operations: inputs.flatMap((input) => {
|
|
1694
|
+
const destination = destinationFor(input, state);
|
|
1695
|
+
validateMove(input, destination, state);
|
|
1696
|
+
moves.push({
|
|
1697
|
+
nodeId: input.nodeId,
|
|
1698
|
+
...destination
|
|
1699
|
+
});
|
|
1700
|
+
const applied = applyMove(input, destination, state);
|
|
1701
|
+
state.document = applied.document;
|
|
1702
|
+
return applied.operations;
|
|
1703
|
+
}),
|
|
1704
|
+
moves,
|
|
1705
|
+
affectedParents: Array.from(state.affected, (parentId) => ({
|
|
1706
|
+
parentId,
|
|
1707
|
+
children: [...state.children.get(parentId) ?? []]
|
|
1708
|
+
}))
|
|
1709
|
+
};
|
|
1710
|
+
};
|
|
1711
|
+
|
|
1712
|
+
//#endregion
|
|
1713
|
+
//#region ../../packages/canvas-document/src/canvas-color.lib.ts
|
|
1714
|
+
const HEX_RADIX = 16;
|
|
1715
|
+
const BYTE_MAX = 255;
|
|
1716
|
+
const PERCENT$2 = 100;
|
|
1717
|
+
const SHORT_HEX_LENGTH = 3;
|
|
1718
|
+
const SHORT_HEX_ALPHA_LENGTH = 4;
|
|
1719
|
+
const LONG_HEX_LENGTH = 6;
|
|
1720
|
+
const LONG_HEX_ALPHA_LENGTH = 8;
|
|
1721
|
+
const HEX_BYTE_LENGTH = 2;
|
|
1722
|
+
const BLUE_HEX_OFFSET = 4;
|
|
1723
|
+
const ratio = (value) => Math.min(1, Math.max(0, value));
|
|
1724
|
+
const byteRatio = (value) => ratio(Number(value) / BYTE_MAX);
|
|
1725
|
+
const hexColor = (value) => {
|
|
1726
|
+
const hex = value.slice(1);
|
|
1727
|
+
if (![
|
|
1728
|
+
SHORT_HEX_LENGTH,
|
|
1729
|
+
SHORT_HEX_ALPHA_LENGTH,
|
|
1730
|
+
LONG_HEX_LENGTH,
|
|
1731
|
+
LONG_HEX_ALPHA_LENGTH
|
|
1732
|
+
].includes(hex.length) || !/^[\da-f]+$/iu.test(hex)) return null;
|
|
1733
|
+
const expanded = hex.length <= SHORT_HEX_ALPHA_LENGTH ? hex.replaceAll(/([\da-f])/giu, "$1$1") : hex;
|
|
1734
|
+
const channel = (offset) => Number.parseInt(expanded.slice(offset, offset + HEX_BYTE_LENGTH), HEX_RADIX) / BYTE_MAX;
|
|
1735
|
+
return {
|
|
1736
|
+
space: "srgb",
|
|
1737
|
+
red: channel(0),
|
|
1738
|
+
green: channel(2),
|
|
1739
|
+
blue: channel(BLUE_HEX_OFFSET),
|
|
1740
|
+
alpha: expanded.length === LONG_HEX_ALPHA_LENGTH ? channel(LONG_HEX_LENGTH) : 1
|
|
1741
|
+
};
|
|
1742
|
+
};
|
|
1743
|
+
const functionalColor = (value) => {
|
|
1744
|
+
const match = /^rgba?\(\s*([\d.]+)(%?)(?:\s*,\s*|\s+)([\d.]+)(%?)(?:\s*,\s*|\s+)([\d.]+)(%?)(?:\s*[,/]\s*([\d.]+)(%?))?\s*\)$/iu.exec(value);
|
|
1745
|
+
if (match === null) return null;
|
|
1746
|
+
const channel = (held, unit) => unit === "%" ? ratio(Number(held) / PERCENT$2) : byteRatio(held ?? "0");
|
|
1747
|
+
const alpha = match[7] === void 0 ? 1 : ratio(Number(match[7]) / (match[8] === "%" ? PERCENT$2 : 1));
|
|
1748
|
+
return {
|
|
1749
|
+
space: "srgb",
|
|
1750
|
+
red: channel(match[1], match[2]),
|
|
1751
|
+
green: channel(match[3], match[4]),
|
|
1752
|
+
blue: channel(match[5], match[6]),
|
|
1753
|
+
alpha
|
|
1754
|
+
};
|
|
1755
|
+
};
|
|
1756
|
+
const colorFunction = (value) => {
|
|
1757
|
+
const match = /^color\(\s*(srgb|display-p3)\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s*\/\s*([\d.]+))?\s*\)$/iu.exec(value);
|
|
1758
|
+
if (match === null) return null;
|
|
1759
|
+
return {
|
|
1760
|
+
space: match[1] === "display-p3" ? "display-p3" : "srgb",
|
|
1761
|
+
red: ratio(Number(match[2])),
|
|
1762
|
+
green: ratio(Number(match[3])),
|
|
1763
|
+
blue: ratio(Number(match[4])),
|
|
1764
|
+
alpha: ratio(match[5] === void 0 ? 1 : Number(match[5]))
|
|
1765
|
+
};
|
|
1766
|
+
};
|
|
1767
|
+
const canvasColorFromCss = (value) => {
|
|
1768
|
+
const normalized = value.trim().toLowerCase();
|
|
1769
|
+
if (normalized === "transparent") return {
|
|
1770
|
+
space: "srgb",
|
|
1771
|
+
red: 0,
|
|
1772
|
+
green: 0,
|
|
1773
|
+
blue: 0,
|
|
1774
|
+
alpha: 0
|
|
1775
|
+
};
|
|
1776
|
+
if (normalized.startsWith("#")) return hexColor(normalized);
|
|
1777
|
+
if (normalized.startsWith("rgb")) return functionalColor(normalized);
|
|
1778
|
+
if (normalized.startsWith("color(")) return colorFunction(normalized);
|
|
1779
|
+
return null;
|
|
1780
|
+
};
|
|
1781
|
+
const solidCanvasPaint = (id, color) => ({
|
|
1782
|
+
id,
|
|
1783
|
+
visible: true,
|
|
1784
|
+
opacity: 1,
|
|
1785
|
+
kind: "solid",
|
|
1786
|
+
color
|
|
1787
|
+
});
|
|
1788
|
+
const solidCanvasPaintFromCss = (id, value) => {
|
|
1789
|
+
const color = canvasColorFromCss(value);
|
|
1790
|
+
return color === null ? null : solidCanvasPaint(id, color);
|
|
1791
|
+
};
|
|
1792
|
+
|
|
1793
|
+
//#endregion
|
|
1794
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/_u64.js
|
|
1795
|
+
const fromNumH = (n) => n / 2 ** 32 | 0;
|
|
1796
|
+
const fromNumL = (n) => n >>> 0;
|
|
1797
|
+
function setU64FromNum(view, byteOffset, n, isLE) {
|
|
1798
|
+
const h = fromNumH(n);
|
|
1799
|
+
const l = fromNumL(n);
|
|
1800
|
+
view.setUint32(byteOffset, isLE ? l : h, isLE);
|
|
1801
|
+
view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
//#endregion
|
|
1805
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/utils.js
|
|
1806
|
+
/**
|
|
1807
|
+
* Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
|
|
1808
|
+
* @param a - value to test
|
|
1809
|
+
* @returns `true` when the value is a Uint8Array-compatible view.
|
|
1810
|
+
* @example
|
|
1811
|
+
* Check whether a value is a Uint8Array-compatible view.
|
|
1812
|
+
* ```ts
|
|
1813
|
+
* isBytes(new Uint8Array([1, 2, 3]));
|
|
1814
|
+
* ```
|
|
1815
|
+
*/
|
|
1816
|
+
function isBytes(a) {
|
|
1817
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
|
|
1818
|
+
}
|
|
1819
|
+
const atitle = (title) => title ? `"${title}" ` : "";
|
|
1820
|
+
/**
|
|
1821
|
+
* Asserts something is a non-negative integer.
|
|
1822
|
+
* @param n - number to validate
|
|
1823
|
+
* @param title - label included in thrown errors
|
|
1824
|
+
* @returns The validated number.
|
|
1825
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1826
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
1827
|
+
* @example
|
|
1828
|
+
* Validate a non-negative integer option.
|
|
1829
|
+
* ```ts
|
|
1830
|
+
* anumber(32, 'length');
|
|
1831
|
+
* ```
|
|
1832
|
+
*/
|
|
1833
|
+
function anumber(n, title = "") {
|
|
1834
|
+
if (typeof n !== "number") throw new TypeError(atitle(title) + "expected number, got " + typeof n);
|
|
1835
|
+
if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
|
|
1836
|
+
return n;
|
|
1837
|
+
}
|
|
1838
|
+
/**
|
|
1839
|
+
* Asserts something is Uint8Array.
|
|
1840
|
+
* @param value - value to validate
|
|
1841
|
+
* @param length - optional exact length constraint
|
|
1842
|
+
* @param title - label included in thrown errors
|
|
1843
|
+
* @returns The validated byte array.
|
|
1844
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1845
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
1846
|
+
* @example
|
|
1847
|
+
* Validate that a value is a byte array.
|
|
1848
|
+
* ```ts
|
|
1849
|
+
* abytes(new Uint8Array([1, 2, 3]));
|
|
1850
|
+
* ```
|
|
1851
|
+
*/
|
|
1852
|
+
function abytes(value, length, title = "") {
|
|
1853
|
+
if (isBytes(value) && (length === void 0 || value.length === length)) return value;
|
|
1854
|
+
if (length !== void 0) anumber(length, "length");
|
|
1855
|
+
const bytes = isBytes(value);
|
|
1856
|
+
const ofLen = length !== void 0 ? ` of length ${length}` : "";
|
|
1857
|
+
const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
|
|
1858
|
+
const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
|
|
1859
|
+
if (!bytes) throw new TypeError(message);
|
|
1860
|
+
throw new RangeError(message);
|
|
1861
|
+
}
|
|
1862
|
+
const aobject = (value, label) => {
|
|
1863
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
|
|
1864
|
+
};
|
|
1865
|
+
/**
|
|
1866
|
+
* Asserts a hash instance has not been destroyed or finished.
|
|
1867
|
+
* @param instance - hash instance to validate
|
|
1868
|
+
* @param checkFinished - whether to reject finalized instances
|
|
1869
|
+
* @throws If the hash instance has already been destroyed or finalized. {@link Error}
|
|
1870
|
+
* @example
|
|
1871
|
+
* Validate that a hash instance is still usable.
|
|
1872
|
+
* ```ts
|
|
1873
|
+
* import { aexists } from '@noble/hashes/utils.js';
|
|
1874
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
1875
|
+
* const hash = sha256.create();
|
|
1876
|
+
* aexists(hash);
|
|
1877
|
+
* ```
|
|
1878
|
+
*/
|
|
1879
|
+
function aexists(instance, checkFinished = true) {
|
|
1880
|
+
if (instance.destroyed) throw new Error("hash was destroyed");
|
|
1881
|
+
if (checkFinished && instance.finished) throw new Error("digest() was already called");
|
|
1882
|
+
}
|
|
1883
|
+
/**
|
|
1884
|
+
* Asserts output is a sufficiently-sized byte array.
|
|
1885
|
+
* @param out - destination buffer
|
|
1886
|
+
* @param instance - hash instance providing output length
|
|
1887
|
+
* Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
|
|
1888
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1889
|
+
* @throws On wrong argument ranges or values. {@link RangeError}
|
|
1890
|
+
* @example
|
|
1891
|
+
* Validate a caller-provided digest buffer.
|
|
1892
|
+
* ```ts
|
|
1893
|
+
* import { aoutput } from '@noble/hashes/utils.js';
|
|
1894
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
1895
|
+
* const hash = sha256.create();
|
|
1896
|
+
* aoutput(new Uint8Array(hash.outputLen), hash);
|
|
1897
|
+
* ```
|
|
1898
|
+
*/
|
|
1899
|
+
function aoutput(out, instance) {
|
|
1900
|
+
abytes(out, void 0, "output");
|
|
1901
|
+
const min = instance.outputLen;
|
|
1902
|
+
if (!(out.length >= min)) throw new RangeError("\"output\" expected length >= " + min);
|
|
1903
|
+
}
|
|
1904
|
+
/**
|
|
1905
|
+
* Zeroizes typed arrays in place. Warning: JS provides no guarantees.
|
|
1906
|
+
* @param arrays - arrays to overwrite with zeros
|
|
1907
|
+
* @example
|
|
1908
|
+
* Zeroize sensitive buffers in place.
|
|
1909
|
+
* ```ts
|
|
1910
|
+
* clean(new Uint8Array([1, 2, 3]));
|
|
1911
|
+
* ```
|
|
1912
|
+
*/
|
|
1913
|
+
function clean(...arrays) {
|
|
1914
|
+
for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
|
|
1915
|
+
}
|
|
1916
|
+
/**
|
|
1917
|
+
* Creates a DataView for byte-level manipulation.
|
|
1918
|
+
* @param arr - source typed array
|
|
1919
|
+
* @returns DataView over the same buffer region.
|
|
1920
|
+
* @example
|
|
1921
|
+
* Create a DataView over an existing buffer.
|
|
1922
|
+
* ```ts
|
|
1923
|
+
* createView(new Uint8Array(4));
|
|
1924
|
+
* ```
|
|
1925
|
+
*/
|
|
1926
|
+
function createView(arr) {
|
|
1927
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
1928
|
+
}
|
|
1929
|
+
/**
|
|
1930
|
+
* Rotate-right operation for uint32 values.
|
|
1931
|
+
* @param word - source word
|
|
1932
|
+
* @param shift - shift amount in bits
|
|
1933
|
+
* @returns Rotated word.
|
|
1934
|
+
* @example
|
|
1935
|
+
* Rotate a 32-bit word to the right.
|
|
1936
|
+
* ```ts
|
|
1937
|
+
* rotr(0x12345678, 8);
|
|
1938
|
+
* ```
|
|
1939
|
+
*/
|
|
1940
|
+
function rotr(word, shift) {
|
|
1941
|
+
return word << 32 - shift | word >>> shift;
|
|
1942
|
+
}
|
|
1943
|
+
const hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
|
|
1944
|
+
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
1945
|
+
/**
|
|
1946
|
+
* Convert byte array to hex string.
|
|
1947
|
+
* Uses the built-in function when available and assumes it matches the tested
|
|
1948
|
+
* fallback semantics.
|
|
1949
|
+
* @param bytes - bytes to encode
|
|
1950
|
+
* @returns Lowercase hexadecimal string.
|
|
1951
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1952
|
+
* @example
|
|
1953
|
+
* Convert bytes to lowercase hexadecimal.
|
|
1954
|
+
* ```ts
|
|
1955
|
+
* bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
|
|
1956
|
+
* ```
|
|
1957
|
+
*/
|
|
1958
|
+
function bytesToHex(bytes) {
|
|
1959
|
+
abytes(bytes);
|
|
1960
|
+
if (hasHexBuiltin) return bytes.toHex();
|
|
1961
|
+
let hex = "";
|
|
1962
|
+
for (let i = 0; i < bytes.length; i++) hex += hexes[bytes[i]];
|
|
1963
|
+
return hex;
|
|
1964
|
+
}
|
|
1965
|
+
/**
|
|
1966
|
+
* Converts string to bytes using UTF8 encoding.
|
|
1967
|
+
* Built-in doesn't validate input to be string: we do the check.
|
|
1968
|
+
* Non-ASCII details are delegated to the platform `TextEncoder`.
|
|
1969
|
+
* @param str - string to encode
|
|
1970
|
+
* @returns UTF-8 encoded bytes.
|
|
1971
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1972
|
+
* @example
|
|
1973
|
+
* Encode a string as UTF-8 bytes.
|
|
1974
|
+
* ```ts
|
|
1975
|
+
* utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])
|
|
1976
|
+
* ```
|
|
1977
|
+
*/
|
|
1978
|
+
function utf8ToBytes(str) {
|
|
1979
|
+
if (typeof str !== "string") throw new TypeError("string expected");
|
|
1980
|
+
return new Uint8Array(new TextEncoder().encode(str));
|
|
1981
|
+
}
|
|
1982
|
+
/**
|
|
1983
|
+
* Merges default options and passed options.
|
|
1984
|
+
* @param defaults - base option object
|
|
1985
|
+
* @param opts - user overrides
|
|
1986
|
+
* @param title - label included in thrown override errors
|
|
1987
|
+
* @returns Merged option object. The merge mutates `defaults` in place.
|
|
1988
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
1989
|
+
* @example
|
|
1990
|
+
* Merge user overrides onto default options.
|
|
1991
|
+
* ```ts
|
|
1992
|
+
* checkOpts({ dkLen: 32 }, { asyncTick: 10 });
|
|
1993
|
+
* ```
|
|
1994
|
+
*/
|
|
1995
|
+
function checkOpts(defaults, opts, title = "opts") {
|
|
1996
|
+
aobject(defaults, "defaults");
|
|
1997
|
+
if (opts !== void 0) aobject(opts, title);
|
|
1998
|
+
return Object.assign(defaults, opts);
|
|
1999
|
+
}
|
|
2000
|
+
/**
|
|
2001
|
+
* Creates a callable hash function from a stateful class constructor.
|
|
2002
|
+
* @param hashCons - hash constructor or factory
|
|
2003
|
+
* @param info - optional metadata such as DER OID
|
|
2004
|
+
* @returns Frozen callable hash wrapper with `.create()`.
|
|
2005
|
+
* Wrapper construction eagerly calls `hashCons(undefined)` once to read
|
|
2006
|
+
* `outputLen` / `blockLen`, so constructor side effects happen at module
|
|
2007
|
+
* init time.
|
|
2008
|
+
* @throws On wrong argument types. {@link TypeError}
|
|
2009
|
+
* @example
|
|
2010
|
+
* Wrap a stateful hash constructor into a callable helper.
|
|
2011
|
+
* ```ts
|
|
2012
|
+
* import { createHasher } from '@noble/hashes/utils.js';
|
|
2013
|
+
* import { sha256 } from '@noble/hashes/sha2.js';
|
|
2014
|
+
* const wrapped = createHasher(sha256.create, { oid: sha256.oid });
|
|
2015
|
+
* wrapped(new Uint8Array([1]));
|
|
2016
|
+
* ```
|
|
2017
|
+
*/
|
|
2018
|
+
function createHasher(hashCons, info = {}) {
|
|
2019
|
+
if (typeof hashCons !== "function") throw new TypeError("\"hashCons\" expected function, got type=" + typeof hashCons);
|
|
2020
|
+
info = checkOpts({}, info, "info");
|
|
2021
|
+
const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
|
|
2022
|
+
const tmp = hashCons(void 0);
|
|
2023
|
+
hashC.outputLen = tmp.outputLen;
|
|
2024
|
+
hashC.blockLen = tmp.blockLen;
|
|
2025
|
+
hashC.canXOF = tmp.canXOF;
|
|
2026
|
+
hashC.create = (opts) => hashCons(opts);
|
|
2027
|
+
Object.assign(hashC, info);
|
|
2028
|
+
return Object.freeze(hashC);
|
|
2029
|
+
}
|
|
2030
|
+
/**
|
|
2031
|
+
* Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
|
|
2032
|
+
* @param suffix - final OID byte for the selected hash.
|
|
2033
|
+
* The helper accepts any byte even though only the documented NIST hash
|
|
2034
|
+
* suffixes are meaningful downstream.
|
|
2035
|
+
* @returns Object containing the DER-encoded OID.
|
|
2036
|
+
* @example
|
|
2037
|
+
* Build OID metadata for a NIST hash.
|
|
2038
|
+
* ```ts
|
|
2039
|
+
* oidNist(0x01);
|
|
2040
|
+
* ```
|
|
2041
|
+
*/
|
|
2042
|
+
const oidNist = (suffix) => ({ oid: Uint8Array.from([
|
|
2043
|
+
6,
|
|
2044
|
+
9,
|
|
2045
|
+
96,
|
|
2046
|
+
134,
|
|
2047
|
+
72,
|
|
2048
|
+
1,
|
|
2049
|
+
101,
|
|
2050
|
+
3,
|
|
2051
|
+
4,
|
|
2052
|
+
2,
|
|
2053
|
+
suffix
|
|
2054
|
+
]) });
|
|
2055
|
+
|
|
2056
|
+
//#endregion
|
|
2057
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/_md.js
|
|
2058
|
+
/**
|
|
2059
|
+
* Internal Merkle-Damgard hash utils.
|
|
2060
|
+
* @module
|
|
2061
|
+
*/
|
|
2062
|
+
/**
|
|
2063
|
+
* Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
|
|
2064
|
+
* Returns bits from `b` when `a` is set, otherwise from `c`.
|
|
2065
|
+
* The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
|
|
2066
|
+
* set the same bit.
|
|
2067
|
+
* @param a - selector word
|
|
2068
|
+
* @param b - word chosen when selector bit is set
|
|
2069
|
+
* @param c - word chosen when selector bit is clear
|
|
2070
|
+
* @returns Mixed 32-bit word.
|
|
2071
|
+
* @example
|
|
2072
|
+
* Combine three words with the shared 32-bit choice primitive.
|
|
2073
|
+
* ```ts
|
|
2074
|
+
* Chi(0xffffffff, 0x12345678, 0x87654321);
|
|
2075
|
+
* ```
|
|
2076
|
+
*/
|
|
2077
|
+
function Chi(a, b, c) {
|
|
2078
|
+
return a & b ^ ~a & c;
|
|
2079
|
+
}
|
|
2080
|
+
/**
|
|
2081
|
+
* Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
|
|
2082
|
+
* Returns bits shared by at least two inputs.
|
|
2083
|
+
* @param a - first input word
|
|
2084
|
+
* @param b - second input word
|
|
2085
|
+
* @param c - third input word
|
|
2086
|
+
* @returns Mixed 32-bit word.
|
|
2087
|
+
* @example
|
|
2088
|
+
* Combine three words with the shared 32-bit majority primitive.
|
|
2089
|
+
* ```ts
|
|
2090
|
+
* Maj(0xffffffff, 0x12345678, 0x87654321);
|
|
2091
|
+
* ```
|
|
2092
|
+
*/
|
|
2093
|
+
function Maj(a, b, c) {
|
|
2094
|
+
return a & b ^ a & c ^ b & c;
|
|
2095
|
+
}
|
|
2096
|
+
/**
|
|
2097
|
+
* Merkle-Damgard hash construction base class.
|
|
2098
|
+
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
|
|
2099
|
+
* Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
|
|
2100
|
+
* strings with partial-byte tails.
|
|
2101
|
+
* @param blockLen - internal block size in bytes
|
|
2102
|
+
* @param outputLen - digest size in bytes
|
|
2103
|
+
* @param padOffset - trailing length field size in bytes
|
|
2104
|
+
* @param isLE - whether length and state words are encoded in little-endian
|
|
2105
|
+
* @example
|
|
2106
|
+
* Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
|
|
2107
|
+
* ```ts
|
|
2108
|
+
* import { _SHA1 } from '@noble/hashes/legacy.js';
|
|
2109
|
+
* const hash = new _SHA1();
|
|
2110
|
+
* hash.update(new Uint8Array([97, 98, 99]));
|
|
2111
|
+
* hash.digest();
|
|
2112
|
+
* ```
|
|
2113
|
+
*/
|
|
2114
|
+
var HashMD = class {
|
|
2115
|
+
blockLen;
|
|
2116
|
+
outputLen;
|
|
2117
|
+
canXOF = false;
|
|
2118
|
+
padOffset;
|
|
2119
|
+
isLE;
|
|
2120
|
+
buffer;
|
|
2121
|
+
view;
|
|
2122
|
+
finished = false;
|
|
2123
|
+
length = 0;
|
|
2124
|
+
pos = 0;
|
|
2125
|
+
destroyed = false;
|
|
2126
|
+
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
2127
|
+
this.blockLen = blockLen;
|
|
2128
|
+
this.outputLen = outputLen;
|
|
2129
|
+
this.padOffset = padOffset;
|
|
2130
|
+
this.isLE = isLE;
|
|
2131
|
+
this.buffer = new Uint8Array(blockLen);
|
|
2132
|
+
this.view = createView(this.buffer);
|
|
2133
|
+
}
|
|
2134
|
+
update(data) {
|
|
2135
|
+
aexists(this);
|
|
2136
|
+
abytes(data);
|
|
2137
|
+
const { view, buffer, blockLen } = this;
|
|
2138
|
+
const len = data.length;
|
|
2139
|
+
let processed = false;
|
|
2140
|
+
for (let pos = 0; pos < len;) {
|
|
2141
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
2142
|
+
if (take === blockLen) {
|
|
2143
|
+
const dataView = createView(data);
|
|
2144
|
+
for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
|
|
2145
|
+
processed = true;
|
|
2146
|
+
continue;
|
|
2147
|
+
}
|
|
2148
|
+
buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
|
|
2149
|
+
this.pos += take;
|
|
2150
|
+
pos += take;
|
|
2151
|
+
if (this.pos === blockLen) {
|
|
2152
|
+
this.process(view, 0);
|
|
2153
|
+
this.pos = 0;
|
|
2154
|
+
processed = true;
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
this.length += data.length;
|
|
2158
|
+
if (processed) this.roundClean();
|
|
2159
|
+
return this;
|
|
2160
|
+
}
|
|
2161
|
+
digestInto(out) {
|
|
2162
|
+
aexists(this);
|
|
2163
|
+
aoutput(out, this);
|
|
2164
|
+
this.finished = true;
|
|
2165
|
+
const { buffer, view, blockLen, isLE } = this;
|
|
2166
|
+
let { pos } = this;
|
|
2167
|
+
buffer[pos++] = 128;
|
|
2168
|
+
buffer.fill(0, pos);
|
|
2169
|
+
if (this.padOffset > blockLen - pos) {
|
|
2170
|
+
this.process(view, 0);
|
|
2171
|
+
buffer.fill(0);
|
|
2172
|
+
}
|
|
2173
|
+
setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
|
|
2174
|
+
this.process(view, 0);
|
|
2175
|
+
this.roundClean();
|
|
2176
|
+
const oview = out === buffer ? view : createView(out);
|
|
2177
|
+
const len = this.outputLen;
|
|
2178
|
+
const outLen = len / 4;
|
|
2179
|
+
const state = this.get();
|
|
2180
|
+
if (len % 4 || outLen > state.length) throw new Error("invalid outputLen");
|
|
2181
|
+
for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
|
|
2182
|
+
}
|
|
2183
|
+
digest() {
|
|
2184
|
+
const { buffer, outputLen } = this;
|
|
2185
|
+
this.digestInto(buffer);
|
|
2186
|
+
const res = buffer.slice(0, outputLen);
|
|
2187
|
+
this.destroy();
|
|
2188
|
+
return res;
|
|
2189
|
+
}
|
|
2190
|
+
_cloneIntoMeta(to) {
|
|
2191
|
+
const { buffer, length, finished, destroyed, pos } = this;
|
|
2192
|
+
to.destroyed = destroyed;
|
|
2193
|
+
to.finished = finished;
|
|
2194
|
+
to.length = length;
|
|
2195
|
+
to.pos = pos;
|
|
2196
|
+
if (pos) to.buffer.set(buffer);
|
|
2197
|
+
return to;
|
|
2198
|
+
}
|
|
2199
|
+
clone() {
|
|
2200
|
+
return this._cloneInto();
|
|
2201
|
+
}
|
|
2202
|
+
};
|
|
2203
|
+
/**
|
|
2204
|
+
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
|
|
2205
|
+
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
|
|
2206
|
+
*/
|
|
2207
|
+
/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
|
|
2208
|
+
* square roots of the first eight prime numbers. Exported as a shared table; callers must treat
|
|
2209
|
+
* it as read-only because constructors copy words from it by index. */
|
|
2210
|
+
const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
2211
|
+
1779033703,
|
|
2212
|
+
3144134277,
|
|
2213
|
+
1013904242,
|
|
2214
|
+
2773480762,
|
|
2215
|
+
1359893119,
|
|
2216
|
+
2600822924,
|
|
2217
|
+
528734635,
|
|
2218
|
+
1541459225
|
|
2219
|
+
]);
|
|
2220
|
+
|
|
2221
|
+
//#endregion
|
|
2222
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.3.0/node_modules/@noble/hashes/sha2.js
|
|
2223
|
+
/**
|
|
2224
|
+
* SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
|
|
2225
|
+
* SHA256 is the fastest hash implementable in JS, even faster than Blake3.
|
|
2226
|
+
* Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
|
|
2227
|
+
* {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
|
|
2228
|
+
* @module
|
|
2229
|
+
*/
|
|
2230
|
+
/**
|
|
2231
|
+
* SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
|
|
2232
|
+
* of the cube roots of the first 64 primes (2..311).
|
|
2233
|
+
*/
|
|
2234
|
+
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
2235
|
+
1116352408,
|
|
2236
|
+
1899447441,
|
|
2237
|
+
3049323471,
|
|
2238
|
+
3921009573,
|
|
2239
|
+
961987163,
|
|
2240
|
+
1508970993,
|
|
2241
|
+
2453635748,
|
|
2242
|
+
2870763221,
|
|
2243
|
+
3624381080,
|
|
2244
|
+
310598401,
|
|
2245
|
+
607225278,
|
|
2246
|
+
1426881987,
|
|
2247
|
+
1925078388,
|
|
2248
|
+
2162078206,
|
|
2249
|
+
2614888103,
|
|
2250
|
+
3248222580,
|
|
2251
|
+
3835390401,
|
|
2252
|
+
4022224774,
|
|
2253
|
+
264347078,
|
|
2254
|
+
604807628,
|
|
2255
|
+
770255983,
|
|
2256
|
+
1249150122,
|
|
2257
|
+
1555081692,
|
|
2258
|
+
1996064986,
|
|
2259
|
+
2554220882,
|
|
2260
|
+
2821834349,
|
|
2261
|
+
2952996808,
|
|
2262
|
+
3210313671,
|
|
2263
|
+
3336571891,
|
|
2264
|
+
3584528711,
|
|
2265
|
+
113926993,
|
|
2266
|
+
338241895,
|
|
2267
|
+
666307205,
|
|
2268
|
+
773529912,
|
|
2269
|
+
1294757372,
|
|
2270
|
+
1396182291,
|
|
2271
|
+
1695183700,
|
|
2272
|
+
1986661051,
|
|
2273
|
+
2177026350,
|
|
2274
|
+
2456956037,
|
|
2275
|
+
2730485921,
|
|
2276
|
+
2820302411,
|
|
2277
|
+
3259730800,
|
|
2278
|
+
3345764771,
|
|
2279
|
+
3516065817,
|
|
2280
|
+
3600352804,
|
|
2281
|
+
4094571909,
|
|
2282
|
+
275423344,
|
|
2283
|
+
430227734,
|
|
2284
|
+
506948616,
|
|
2285
|
+
659060556,
|
|
2286
|
+
883997877,
|
|
2287
|
+
958139571,
|
|
2288
|
+
1322822218,
|
|
2289
|
+
1537002063,
|
|
2290
|
+
1747873779,
|
|
2291
|
+
1955562222,
|
|
2292
|
+
2024104815,
|
|
2293
|
+
2227730452,
|
|
2294
|
+
2361852424,
|
|
2295
|
+
2428436474,
|
|
2296
|
+
2756734187,
|
|
2297
|
+
3204031479,
|
|
2298
|
+
3329325298
|
|
2299
|
+
]);
|
|
2300
|
+
/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
|
|
2301
|
+
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
2302
|
+
/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
|
|
2303
|
+
var SHA2_32B = class extends HashMD {
|
|
2304
|
+
A = 0;
|
|
2305
|
+
B = 0;
|
|
2306
|
+
C = 0;
|
|
2307
|
+
D = 0;
|
|
2308
|
+
E = 0;
|
|
2309
|
+
F = 0;
|
|
2310
|
+
G = 0;
|
|
2311
|
+
H = 0;
|
|
2312
|
+
constructor(outputLen, IV) {
|
|
2313
|
+
super(64, outputLen, 8, false);
|
|
2314
|
+
this.A = IV[0] | 0;
|
|
2315
|
+
this.B = IV[1] | 0;
|
|
2316
|
+
this.C = IV[2] | 0;
|
|
2317
|
+
this.D = IV[3] | 0;
|
|
2318
|
+
this.E = IV[4] | 0;
|
|
2319
|
+
this.F = IV[5] | 0;
|
|
2320
|
+
this.G = IV[6] | 0;
|
|
2321
|
+
this.H = IV[7] | 0;
|
|
2322
|
+
}
|
|
2323
|
+
get() {
|
|
2324
|
+
const { A, B, C, D, E, F, G, H } = this;
|
|
2325
|
+
return [
|
|
2326
|
+
A,
|
|
2327
|
+
B,
|
|
2328
|
+
C,
|
|
2329
|
+
D,
|
|
2330
|
+
E,
|
|
2331
|
+
F,
|
|
2332
|
+
G,
|
|
2333
|
+
H
|
|
2334
|
+
];
|
|
2335
|
+
}
|
|
2336
|
+
set(A, B, C, D, E, F, G, H) {
|
|
2337
|
+
this.A = A | 0;
|
|
2338
|
+
this.B = B | 0;
|
|
2339
|
+
this.C = C | 0;
|
|
2340
|
+
this.D = D | 0;
|
|
2341
|
+
this.E = E | 0;
|
|
2342
|
+
this.F = F | 0;
|
|
2343
|
+
this.G = G | 0;
|
|
2344
|
+
this.H = H | 0;
|
|
2345
|
+
}
|
|
2346
|
+
_cloneInto(to) {
|
|
2347
|
+
(to ||= new this.constructor()).set(...this.get());
|
|
2348
|
+
return this._cloneIntoMeta(to);
|
|
2349
|
+
}
|
|
2350
|
+
process(view, offset) {
|
|
2351
|
+
for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
|
|
2352
|
+
for (let i = 16; i < 64; i++) {
|
|
2353
|
+
const W15 = SHA256_W[i - 15];
|
|
2354
|
+
const W2 = SHA256_W[i - 2];
|
|
2355
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
|
2356
|
+
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
|
|
2357
|
+
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
|
2358
|
+
}
|
|
2359
|
+
let { A, B, C, D, E, F, G, H } = this;
|
|
2360
|
+
for (let i = 0; i < 64; i++) {
|
|
2361
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
2362
|
+
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
|
|
2363
|
+
const T2 = (rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22)) + Maj(A, B, C) | 0;
|
|
2364
|
+
H = G;
|
|
2365
|
+
G = F;
|
|
2366
|
+
F = E;
|
|
2367
|
+
E = D + T1 | 0;
|
|
2368
|
+
D = C;
|
|
2369
|
+
C = B;
|
|
2370
|
+
B = A;
|
|
2371
|
+
A = T1 + T2 | 0;
|
|
2372
|
+
}
|
|
2373
|
+
A = A + this.A | 0;
|
|
2374
|
+
B = B + this.B | 0;
|
|
2375
|
+
C = C + this.C | 0;
|
|
2376
|
+
D = D + this.D | 0;
|
|
2377
|
+
E = E + this.E | 0;
|
|
2378
|
+
F = F + this.F | 0;
|
|
2379
|
+
G = G + this.G | 0;
|
|
2380
|
+
H = H + this.H | 0;
|
|
2381
|
+
this.set(A, B, C, D, E, F, G, H);
|
|
2382
|
+
}
|
|
2383
|
+
roundClean() {
|
|
2384
|
+
clean(SHA256_W);
|
|
2385
|
+
}
|
|
2386
|
+
destroy() {
|
|
2387
|
+
this.destroyed = true;
|
|
2388
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
2389
|
+
clean(this.buffer);
|
|
2390
|
+
}
|
|
2391
|
+
};
|
|
2392
|
+
/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
|
|
2393
|
+
var _SHA256 = class extends SHA2_32B {
|
|
2394
|
+
constructor() {
|
|
2395
|
+
super(32, SHA256_IV);
|
|
2396
|
+
}
|
|
2397
|
+
};
|
|
2398
|
+
/**
|
|
2399
|
+
* SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
|
|
2400
|
+
*
|
|
2401
|
+
* - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
|
|
2402
|
+
* - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
|
|
2403
|
+
* - Each sha256 hash is executing 2^18 bit operations.
|
|
2404
|
+
* - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
|
|
2405
|
+
* @param msg - message bytes to hash
|
|
2406
|
+
* @param opts - Reserved hash options.
|
|
2407
|
+
* @returns Digest bytes.
|
|
2408
|
+
* @example
|
|
2409
|
+
* Hash a message with SHA2-256.
|
|
2410
|
+
* ```ts
|
|
2411
|
+
* sha256(new Uint8Array([97, 98, 99]));
|
|
2412
|
+
* ```
|
|
2413
|
+
*/
|
|
2414
|
+
const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), /* @__PURE__ */ oidNist(1));
|
|
2415
|
+
|
|
2416
|
+
//#endregion
|
|
2417
|
+
//#region ../../packages/canvas-document/src/node-relationships.lib.ts
|
|
2418
|
+
const inSortOrder = (left, right) => left.sortKey === right.sortKey ? left.childId.localeCompare(right.childId) : left.sortKey < right.sortKey ? -1 : 1;
|
|
2419
|
+
const indexChildren = (relationships) => {
|
|
2420
|
+
const seats = /* @__PURE__ */ new Map();
|
|
2421
|
+
for (const [childId, parentage] of Object.entries(relationships)) {
|
|
2422
|
+
const seated = {
|
|
2423
|
+
childId,
|
|
2424
|
+
sortKey: parentage.sortKey
|
|
2425
|
+
};
|
|
2426
|
+
const held = seats.get(parentage.parentId);
|
|
2427
|
+
if (held === void 0) seats.set(parentage.parentId, [seated]);
|
|
2428
|
+
else held.push(seated);
|
|
2429
|
+
}
|
|
2430
|
+
const byParent = /* @__PURE__ */ new Map();
|
|
2431
|
+
for (const [parentId, children] of seats) byParent.set(parentId, children.toSorted(inSortOrder).map((seated) => seated.childId));
|
|
2432
|
+
return byParent;
|
|
2433
|
+
};
|
|
2434
|
+
const heldIndexes = /* @__PURE__ */ new WeakMap();
|
|
2435
|
+
/**
|
|
2436
|
+
* @justified warning
|
|
2437
|
+
* Every parent's children, built once for a whole document.
|
|
2438
|
+
*
|
|
2439
|
+
* `childIdsOf` used to be a scan over every relationship to find one node's children, and
|
|
2440
|
+
* `CanvasNode` calls it while recursing from the root — so one render of a board of N did N
|
|
2441
|
+
* scans of N, a million entry tuples per frame of a pan at a thousand nodes. This is the same
|
|
2442
|
+
* answer in one pass, built per document and handed down.
|
|
2443
|
+
*/
|
|
2444
|
+
const childIndexOf = (relationships) => {
|
|
2445
|
+
const held = heldIndexes.get(relationships);
|
|
2446
|
+
if (held !== void 0) return held;
|
|
2447
|
+
const index = indexChildren(relationships);
|
|
2448
|
+
if (Object.isFrozen(relationships)) heldIndexes.set(relationships, index);
|
|
2449
|
+
return index;
|
|
2450
|
+
};
|
|
2451
|
+
/** No children, shared: a leaf is the common case and each one would otherwise allocate. */
|
|
2452
|
+
const NO_CHILDREN = [];
|
|
2453
|
+
const childIdsIn = (index, parentId) => index.get(parentId) ?? NO_CHILDREN;
|
|
2454
|
+
/**
|
|
2455
|
+
* A parent's children when there is no index to hand. A held (frozen) document shares one index;
|
|
2456
|
+
* a document still being built gets a fresh one per call, so loops over one should build it once.
|
|
2457
|
+
*/
|
|
2458
|
+
const childIdsOf = (relationships, parentId) => childIdsIn(childIndexOf(relationships), parentId);
|
|
2459
|
+
|
|
2460
|
+
//#endregion
|
|
2461
|
+
//#region ../../packages/canvas-document/src/canvas-image-resource.lib.ts
|
|
2462
|
+
const RESOURCE_PREFIX = "enhance-pending-image:";
|
|
2463
|
+
const isEmptyCanvasImageSource = (source) => source.trim() === "" || source.trim() === "about:blank";
|
|
2464
|
+
const isPendingCanvasImageSource = (source) => typeof source === "string" && source.startsWith(RESOURCE_PREFIX);
|
|
2465
|
+
|
|
2466
|
+
//#endregion
|
|
2467
|
+
//#region ../../packages/canvas-document/src/canvas-paint-projection.lib.ts
|
|
2468
|
+
const requiresCanvasImagePaintResource = (paint) => isPendingCanvasImageSource(paint.assetId) || paint.opacity !== 1 || paint.fit === "crop" && paint.transform !== void 0 || (paint.rotation ?? 0) !== 0 || paint.fit === "tile" && (paint.tileScale ?? 1) !== 1;
|
|
2469
|
+
const canvasImagePaintProperty = (paint) => `--canvas-image-paint-${bytesToHex(sha256(utf8ToBytes(JSON.stringify([
|
|
2470
|
+
paint.assetId,
|
|
2471
|
+
paint.opacity,
|
|
2472
|
+
paint.rotation ?? 0,
|
|
2473
|
+
paint.fit === "tile" ? paint.tileScale ?? 1 : 1,
|
|
2474
|
+
paint.fit === "crop" ? paint.transform : void 0
|
|
2475
|
+
]))))}`;
|
|
2476
|
+
const canvasTextPaintStackProperty = (paints) => `--canvas-text-paints-${bytesToHex(sha256(utf8ToBytes(JSON.stringify(paints.filter((paint) => paint.visible), (key, value) => key === "id" ? void 0 : value))))}`;
|
|
2477
|
+
const PERCENT$1 = 100;
|
|
2478
|
+
const stopCss = (stop, opacity = 1) => `${canvasColorCss(stop.color, opacity)} ${String(stop.position * PERCENT$1)}%`;
|
|
2479
|
+
const canvasPaintImageUrl = (source) => `url("${encodeURI(source).replaceAll("\"", "%22")}")`;
|
|
2480
|
+
const canvasPaintLayerCss = (paint) => {
|
|
2481
|
+
switch (paint.kind) {
|
|
2482
|
+
case "solid": {
|
|
2483
|
+
const color = canvasColorCss(paint.color, paint.opacity);
|
|
2484
|
+
return `linear-gradient(${color}, ${color})`;
|
|
2485
|
+
}
|
|
2486
|
+
case "linear-gradient":
|
|
2487
|
+
if (paint.transform !== void 0) return `url("data:image/svg+xml,${encodeURIComponent(canvasLinearGradientSvg({
|
|
2488
|
+
...paint,
|
|
2489
|
+
transform: paint.transform
|
|
2490
|
+
}))}")`;
|
|
2491
|
+
return `linear-gradient(${String(paint.angle)}deg, ${paint.stops.map((stop) => stopCss(stop, paint.opacity)).join(", ")})`;
|
|
2492
|
+
case "radial-gradient": {
|
|
2493
|
+
if (paint.transform !== void 0) return `url("data:image/svg+xml,${encodeURIComponent(canvasRadialGradientSvg(paint))}")`;
|
|
2494
|
+
const at = `${String(paint.center.x * PERCENT$1)}% ${String(paint.center.y * PERCENT$1)}%`;
|
|
2495
|
+
return `radial-gradient(ellipse ${String(paint.radius.x * PERCENT$1)}% ${String(paint.radius.y * PERCENT$1)}% at ${at}, ${paint.stops.map((stop) => stopCss(stop, paint.opacity)).join(", ")})`;
|
|
2496
|
+
}
|
|
2497
|
+
case "angular-gradient": return `url("data:image/svg+xml,${encodeURIComponent(canvasAngularGradientSvg(paint))}")`;
|
|
2498
|
+
case "diamond-gradient": return `url("data:image/svg+xml,${encodeURIComponent(canvasDiamondGradientSvg(paint))}")`;
|
|
2499
|
+
case "image":
|
|
2500
|
+
if (isEmptyCanvasImageSource(paint.assetId)) return "none";
|
|
2501
|
+
return requiresCanvasImagePaintResource(paint) ? `var(${canvasImagePaintProperty(paint)}, none)` : canvasPaintImageUrl(paint.assetId);
|
|
2502
|
+
}
|
|
2503
|
+
};
|
|
2504
|
+
const cropAxisPosition = (start, size) => size >= 1 ? 0 : start / (1 - size) * PERCENT$1;
|
|
2505
|
+
const cropDeclarations = (crop) => {
|
|
2506
|
+
if (crop === void 0) return {
|
|
2507
|
+
"background-position": "center",
|
|
2508
|
+
"background-size": "cover"
|
|
2509
|
+
};
|
|
2510
|
+
const width = Math.max(crop.width, Number.EPSILON);
|
|
2511
|
+
const height = Math.max(crop.height, Number.EPSILON);
|
|
2512
|
+
return {
|
|
2513
|
+
"background-position": `${String(cropAxisPosition(crop.x, width))}% ${String(cropAxisPosition(crop.y, height))}%`,
|
|
2514
|
+
"background-size": `${String(PERCENT$1 / width)}% ${String(PERCENT$1 / height)}%`
|
|
2515
|
+
};
|
|
2516
|
+
};
|
|
2517
|
+
const paintGeometry = (paint) => {
|
|
2518
|
+
if (paint.kind !== "image") return {
|
|
2519
|
+
"background-size": paint.kind === "angular-gradient" || paint.kind === "diamond-gradient" || (paint.kind === "linear-gradient" || paint.kind === "radial-gradient") && paint.transform !== void 0 ? "100% 100%" : "auto",
|
|
2520
|
+
"background-position": "center",
|
|
2521
|
+
"background-repeat": "no-repeat",
|
|
2522
|
+
"background-origin": "border-box"
|
|
2523
|
+
};
|
|
2524
|
+
const size = {
|
|
2525
|
+
fill: "100% 100%",
|
|
2526
|
+
cover: "cover",
|
|
2527
|
+
fit: "contain",
|
|
2528
|
+
crop: "cover",
|
|
2529
|
+
tile: "auto"
|
|
2530
|
+
}[paint.fit];
|
|
2531
|
+
return {
|
|
2532
|
+
...paint.fit === "crop" && paint.transform !== void 0 ? {
|
|
2533
|
+
"background-position": "0% 0%",
|
|
2534
|
+
"background-size": "100% 100%"
|
|
2535
|
+
} : paint.fit === "crop" ? cropDeclarations(paint.crop) : {
|
|
2536
|
+
"background-position": paint.fit === "tile" && paint.tileOrigin === "top-left" ? "0% 0%" : "center",
|
|
2537
|
+
"background-size": size
|
|
2538
|
+
},
|
|
2539
|
+
"background-repeat": paint.fit === "tile" ? "repeat" : "no-repeat",
|
|
2540
|
+
"background-origin": "padding-box"
|
|
2541
|
+
};
|
|
2542
|
+
};
|
|
2543
|
+
const paintGeometryDeclarations = (paints) => {
|
|
2544
|
+
if (paints.length === 0) return {};
|
|
2545
|
+
const layers = paints.toReversed().map((paint) => paintGeometry(paint));
|
|
2546
|
+
return Object.fromEntries([
|
|
2547
|
+
"background-size",
|
|
2548
|
+
"background-position",
|
|
2549
|
+
"background-repeat",
|
|
2550
|
+
"background-origin"
|
|
2551
|
+
].map((property) => [property, layers.map((layer) => layer[property]).join(", ")]));
|
|
2552
|
+
};
|
|
2553
|
+
/** The colour of a solid paint, for owners that have no blend: a stored mode is ignored. */
|
|
2554
|
+
const canvasSolidPaintColor = (paint) => paint.kind === "solid" && paint.visible ? canvasColorCss(paint.color, paint.opacity) : void 0;
|
|
2555
|
+
const isBlended = (paint) => paint.visible && (paint.blendMode ?? "normal") !== "normal";
|
|
2556
|
+
/**
|
|
2557
|
+
* The colour of a solid paint for a drawing shortcut of an owner that has a blend. A blended paint
|
|
2558
|
+
* has none, so it falls through to its paint element, ring or SVG paint group.
|
|
2559
|
+
*/
|
|
2560
|
+
const canvasUnblendedSolidColor = (paint) => isBlended(paint) ? void 0 : canvasSolidPaintColor(paint);
|
|
2561
|
+
/** A CSS border or outline colour draws one visible solid paint; the paint element draws any other list. */
|
|
2562
|
+
const canvasStrokeCssColor = (paints) => {
|
|
2563
|
+
const visible = paints.filter((paint) => paint.visible);
|
|
2564
|
+
const [only] = visible;
|
|
2565
|
+
if (only === void 0 || visible.length !== 1) return "transparent";
|
|
2566
|
+
return canvasUnblendedSolidColor(only) ?? "transparent";
|
|
2567
|
+
};
|
|
2568
|
+
/** Paints as backgrounds of one element: they blend with nothing, so a blend never comes here. */
|
|
2569
|
+
const canvasPaintLayerDeclarations = (paints) => ({
|
|
2570
|
+
"background-image": paints.toReversed().map((paint) => canvasPaintLayerCss(paint)).join(", "),
|
|
2571
|
+
...paintGeometryDeclarations(paints)
|
|
2572
|
+
});
|
|
2573
|
+
/** The layer's own fills; when one blends, its fill paint elements draw them all instead. */
|
|
2574
|
+
const canvasPaintDeclarations = (paints) => {
|
|
2575
|
+
const visible = paints.filter((paint) => paint.visible);
|
|
2576
|
+
if (visible.length === 0 || visible.some((paint) => isBlended(paint))) return { background: "none" };
|
|
2577
|
+
const [only] = visible;
|
|
2578
|
+
const color = only === void 0 ? void 0 : canvasUnblendedSolidColor(only);
|
|
2579
|
+
if (color !== void 0 && visible.length === 1) return {
|
|
2580
|
+
background: color,
|
|
2581
|
+
"background-image": "none"
|
|
2582
|
+
};
|
|
2583
|
+
return {
|
|
2584
|
+
"background-color": "transparent",
|
|
2585
|
+
...canvasPaintLayerDeclarations(visible)
|
|
2586
|
+
};
|
|
2587
|
+
};
|
|
2588
|
+
const canvasTextPaintDeclarations = (paints) => {
|
|
2589
|
+
const visible = paints.filter((paint) => paint.visible);
|
|
2590
|
+
const [only] = visible;
|
|
2591
|
+
if (visible.length === 1 && only?.kind === "solid") return { color: canvasColorCss(only.color, only.opacity) };
|
|
2592
|
+
if (visible.length === 0) return { color: "transparent" };
|
|
2593
|
+
return {
|
|
2594
|
+
color: "transparent",
|
|
2595
|
+
...visible.length > 1 ? {
|
|
2596
|
+
"background-image": `var(${canvasTextPaintStackProperty(visible)}, none)`,
|
|
2597
|
+
"background-size": "100% 100%",
|
|
2598
|
+
"background-position": "center",
|
|
2599
|
+
"background-repeat": "no-repeat"
|
|
2600
|
+
} : canvasPaintLayerDeclarations(visible),
|
|
2601
|
+
...visible.some((paint) => paint.kind === "image" && paint.fit === "crop" && paint.transform !== void 0) && {
|
|
2602
|
+
"background-size": "100% var(--canvas-text-paint-height, 100%)",
|
|
2603
|
+
"background-position": "0% var(--canvas-text-paint-y, 0%)"
|
|
2604
|
+
},
|
|
2605
|
+
"background-clip": "text",
|
|
2606
|
+
"-webkit-background-clip": "text"
|
|
2607
|
+
};
|
|
2608
|
+
};
|
|
2609
|
+
|
|
2610
|
+
//#endregion
|
|
2611
|
+
//#region ../../packages/canvas-document/src/canvas-box-decoration.lib.ts
|
|
2612
|
+
const DECORATION_PROPERTIES = new Set(canvasNodeStylePatchSchema.keyof().options.filter((property) => /^(?:border|outline)(?:-|$)/u.test(property) && !property.includes("radius")));
|
|
2613
|
+
const isCanvasDecorationProperty = (control, property) => {
|
|
2614
|
+
const key = property.toLowerCase();
|
|
2615
|
+
return DECORATION_PROPERTIES.has(key) && (key === control || key.startsWith(`${control}-`));
|
|
2616
|
+
};
|
|
2617
|
+
const BORDER_SIDES = [
|
|
2618
|
+
"top",
|
|
2619
|
+
"right",
|
|
2620
|
+
"bottom",
|
|
2621
|
+
"left"
|
|
2622
|
+
];
|
|
2623
|
+
const DECORATION_STYLES = [
|
|
2624
|
+
"solid",
|
|
2625
|
+
"dashed",
|
|
2626
|
+
"dotted"
|
|
2627
|
+
];
|
|
2628
|
+
const DECORATION_PARTS = [
|
|
2629
|
+
"width",
|
|
2630
|
+
"style",
|
|
2631
|
+
"color"
|
|
2632
|
+
];
|
|
2633
|
+
const decorationLength = (value, minimum = 0) => {
|
|
2634
|
+
if (value === void 0 || !/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?(?:px)?$/iu.test(value)) return void 0;
|
|
2635
|
+
const parsed = Number(value.replace(/px$/iu, ""));
|
|
2636
|
+
if (parsed !== 0 && !/px$/iu.test(value)) return void 0;
|
|
2637
|
+
return Number.isFinite(parsed) && parsed >= minimum ? parsed : void 0;
|
|
2638
|
+
};
|
|
2639
|
+
const expandedDecoration = (property, value) => {
|
|
2640
|
+
const parts = canvasCssTokens(value);
|
|
2641
|
+
if (/^(?:border(?:-(?:top|right|bottom|left))?|outline)$/u.test(property)) {
|
|
2642
|
+
const width = parts.find((part) => decorationLength(part) !== void 0);
|
|
2643
|
+
const style = parts.find((part) => /^(?:none|hidden|solid|dashed|dotted|double|groove|ridge|inset|outset)$/u.test(part));
|
|
2644
|
+
const color = parts.find((part) => solidCanvasPaintFromCss("probe", part) !== null);
|
|
2645
|
+
if (width === void 0 || style === void 0 || color === void 0 || parts.length !== DECORATION_PARTS.length) return null;
|
|
2646
|
+
const owners = property === "border" ? BORDER_SIDES.map((side) => `border-${side}`) : [property];
|
|
2647
|
+
return Object.fromEntries(owners.flatMap((owner) => DECORATION_PARTS.map((key) => [`${owner}-${key}`, {
|
|
2648
|
+
width,
|
|
2649
|
+
style,
|
|
2650
|
+
color
|
|
2651
|
+
}[key]])));
|
|
2652
|
+
}
|
|
2653
|
+
if (/^border-(?:width|style|color)$/u.test(property)) {
|
|
2654
|
+
if (parts.length === 0 || parts.length > BORDER_SIDES.length) return null;
|
|
2655
|
+
const [top = "", right = top, bottom = top, left = right] = parts;
|
|
2656
|
+
return Object.fromEntries(BORDER_SIDES.map((side, index) => [`border-${side}-${property.slice(7)}`, [
|
|
2657
|
+
top,
|
|
2658
|
+
right,
|
|
2659
|
+
bottom,
|
|
2660
|
+
left
|
|
2661
|
+
][index] ?? ""]));
|
|
2662
|
+
}
|
|
2663
|
+
return /^(?:border-(?:top|right|bottom|left)-(?:width|style|color)|outline-(?:width|style|color|offset))$/u.test(property) ? { [property]: value } : null;
|
|
2664
|
+
};
|
|
2665
|
+
const decorationDeclarationsOf = (node, control) => node.additionalStyles?.declarations.filter(({ property, value, enabled }) => isCanvasDecorationProperty(control, property) && (!enabled || value.trim() !== "" || node.appearance?.[control] === void 0)) ?? [];
|
|
2666
|
+
const decorationCssOf = (node, control) => {
|
|
2667
|
+
const additional = decorationDeclarationsOf(node, control);
|
|
2668
|
+
if (additional.some(({ enabled }) => !enabled)) return null;
|
|
2669
|
+
const controlled = new Set(additional.map(({ property }) => property.toLowerCase()));
|
|
2670
|
+
const entries = [...Object.entries(node.styles).filter(([property]) => !controlled.has(property.toLowerCase())), ...additional.map(({ property, value }) => [property, value])];
|
|
2671
|
+
const result = {};
|
|
2672
|
+
for (const [property, value] of entries) {
|
|
2673
|
+
if (!isCanvasDecorationProperty(control, property)) continue;
|
|
2674
|
+
const expanded = expandedDecoration(property.toLowerCase(), canvasCssValue(property, value).trim());
|
|
2675
|
+
if (expanded === null || String(value).includes("!")) return null;
|
|
2676
|
+
Object.assign(result, expanded);
|
|
2677
|
+
}
|
|
2678
|
+
return result;
|
|
2679
|
+
};
|
|
2680
|
+
const canvasBorderOf = (node) => {
|
|
2681
|
+
const css = decorationCssOf(node, "border");
|
|
2682
|
+
if (css === null) return { kind: "custom" };
|
|
2683
|
+
if (node.appearance?.border !== void 0 && decorationDeclarationsOf(node, "border").length === 0) return {
|
|
2684
|
+
kind: "native",
|
|
2685
|
+
value: node.appearance.border
|
|
2686
|
+
};
|
|
2687
|
+
if (node.appearance?.border !== void 0) return { kind: "custom" };
|
|
2688
|
+
if (Object.keys(css).length === 0) return { kind: "absent" };
|
|
2689
|
+
const sides = BORDER_SIDES.map((side) => ({
|
|
2690
|
+
width: decorationLength(css[`border-${side}-width`] ?? "0"),
|
|
2691
|
+
authoredStyle: css[`border-${side}-style`],
|
|
2692
|
+
authoredColor: css[`border-${side}-color`],
|
|
2693
|
+
style: DECORATION_STYLES.find((style) => style === css[`border-${side}-style`]),
|
|
2694
|
+
paint: solidCanvasPaintFromCss(`${node.id}-border`, css[`border-${side}-color`] ?? "")
|
|
2695
|
+
}));
|
|
2696
|
+
const first = sides.find((side) => side.width !== 0) ?? sides[0];
|
|
2697
|
+
if (first?.style === void 0 || first.paint === null || sides.some((side) => side.width === void 0 || side.authoredStyle !== void 0 && side.style === void 0 || side.authoredColor !== void 0 && side.paint === null || side.width !== 0 && (side.style !== first.style || JSON.stringify(side.paint) !== JSON.stringify(first.paint)) || side.width === 0 && (side.style !== void 0 && side.style !== first.style || side.paint !== null && JSON.stringify(side.paint) !== JSON.stringify(first.paint)))) return { kind: "custom" };
|
|
2698
|
+
const [top = 0, right = 0, bottom = 0, left = 0] = sides.map((side) => side.width);
|
|
2699
|
+
return {
|
|
2700
|
+
kind: "native",
|
|
2701
|
+
value: {
|
|
2702
|
+
visible: true,
|
|
2703
|
+
width: {
|
|
2704
|
+
top,
|
|
2705
|
+
right,
|
|
2706
|
+
bottom,
|
|
2707
|
+
left
|
|
2708
|
+
},
|
|
2709
|
+
style: first.style,
|
|
2710
|
+
paints: [first.paint]
|
|
2711
|
+
}
|
|
2712
|
+
};
|
|
2713
|
+
};
|
|
2714
|
+
const canvasOutlineOf = (node) => {
|
|
2715
|
+
const css = decorationCssOf(node, "outline");
|
|
2716
|
+
if (css === null) return { kind: "custom" };
|
|
2717
|
+
if (node.appearance?.outline !== void 0 && decorationDeclarationsOf(node, "outline").length === 0) return {
|
|
2718
|
+
kind: "native",
|
|
2719
|
+
value: node.appearance.outline
|
|
2720
|
+
};
|
|
2721
|
+
if (node.appearance?.outline !== void 0) return { kind: "custom" };
|
|
2722
|
+
if (Object.keys(css).length === 0) return { kind: "absent" };
|
|
2723
|
+
const width = decorationLength(css["outline-width"]);
|
|
2724
|
+
const offset = decorationLength(css["outline-offset"] ?? "0", -Infinity);
|
|
2725
|
+
const style = DECORATION_STYLES.find((held) => held === css["outline-style"]);
|
|
2726
|
+
const paint = solidCanvasPaintFromCss(`${node.id}-outline`, css["outline-color"] ?? "");
|
|
2727
|
+
return width === void 0 || offset === void 0 || style === void 0 || paint === null ? { kind: "custom" } : {
|
|
2728
|
+
kind: "native",
|
|
2729
|
+
value: {
|
|
2730
|
+
visible: true,
|
|
2731
|
+
width,
|
|
2732
|
+
offset,
|
|
2733
|
+
style,
|
|
2734
|
+
paints: [paint]
|
|
2735
|
+
}
|
|
2736
|
+
};
|
|
2737
|
+
};
|
|
2738
|
+
const ZERO_BORDER_WIDTHS = Object.freeze({
|
|
2739
|
+
top: 0,
|
|
2740
|
+
right: 0,
|
|
2741
|
+
bottom: 0,
|
|
2742
|
+
left: 0
|
|
2743
|
+
});
|
|
2744
|
+
/** Only an inside border takes layout space; a centre or outside border paints outside the box. */
|
|
2745
|
+
const canvasBorderLayoutWidths = (border) => border.alignment !== void 0 && border.alignment !== "inside" || border.layoutInclusion === "none" || border.layoutInclusion === "visible" && (!border.visible || border.paints.every((paint) => !paint.visible)) ? ZERO_BORDER_WIDTHS : border.width;
|
|
2746
|
+
const borderDeclarations = (border) => {
|
|
2747
|
+
const color = border.visible ? canvasStrokeCssColor(border.paints) : "transparent";
|
|
2748
|
+
const width = canvasBorderLayoutWidths(border);
|
|
2749
|
+
return {
|
|
2750
|
+
"border-style": border.style,
|
|
2751
|
+
"border-top-width": width.top,
|
|
2752
|
+
"border-right-width": width.right,
|
|
2753
|
+
"border-bottom-width": width.bottom,
|
|
2754
|
+
"border-left-width": width.left,
|
|
2755
|
+
"border-color": color
|
|
2756
|
+
};
|
|
2757
|
+
};
|
|
2758
|
+
const outlineDeclarations = (outline) => {
|
|
2759
|
+
if (!outline.visible) return { "outline-style": "none" };
|
|
2760
|
+
const color = canvasStrokeCssColor(outline.paints);
|
|
2761
|
+
return {
|
|
2762
|
+
"outline-style": outline.style,
|
|
2763
|
+
"outline-width": outline.width,
|
|
2764
|
+
"outline-offset": outline.offset,
|
|
2765
|
+
"outline-color": color
|
|
2766
|
+
};
|
|
2767
|
+
};
|
|
2768
|
+
const canvasBoxDecorationDeclarations = (appearance) => ({
|
|
2769
|
+
...appearance.border !== void 0 && borderDeclarations(appearance.border),
|
|
2770
|
+
...appearance.outline !== void 0 && outlineDeclarations(appearance.outline)
|
|
2771
|
+
});
|
|
2772
|
+
|
|
2773
|
+
//#endregion
|
|
2774
|
+
//#region ../../packages/canvas-document/src/canvas-corner-contour.lib.ts
|
|
2775
|
+
const hasCanvasRoundedBorderFallback = (node) => {
|
|
2776
|
+
if (node.geometry?.kind === "boolean") return false;
|
|
2777
|
+
if ((node.appearance?.radius?.smoothing ?? 0) <= 0) return false;
|
|
2778
|
+
const border = canvasBorderOf(node);
|
|
2779
|
+
return border.kind === "custom" || border.kind === "native" && border.value.style !== "solid";
|
|
2780
|
+
};
|
|
2781
|
+
const canvasCornerShapeDeclarations = (node, size = node.box) => {
|
|
2782
|
+
const radius = node.appearance?.radius;
|
|
2783
|
+
if (radius === void 0 || size === void 0 || node.geometry?.kind === "path" || node.geometry?.kind === "boolean") return {};
|
|
2784
|
+
const effective = constrainedCornerRadii(radius, size);
|
|
2785
|
+
const declarations = canvasCornerRadiusDeclarations(effective);
|
|
2786
|
+
if ((radius.smoothing ?? 0) <= 0) return declarations;
|
|
2787
|
+
if (hasCanvasRoundedBorderFallback(node)) return {};
|
|
2788
|
+
const outer = `path("${cornerContour(radius, size)}") border-box`;
|
|
2789
|
+
const border = canvasBorderOf(node);
|
|
2790
|
+
if (border.kind !== "native" || Object.values(canvasBorderLayoutWidths(border.value)).every((width) => width === 0)) return {
|
|
2791
|
+
...declarations,
|
|
2792
|
+
"border-shape": outer
|
|
2793
|
+
};
|
|
2794
|
+
const { top, right, bottom, left } = canvasBorderLayoutWidths(border.value);
|
|
2795
|
+
const radii = [
|
|
2796
|
+
effective.topLeft,
|
|
2797
|
+
effective.topRight,
|
|
2798
|
+
effective.bottomRight,
|
|
2799
|
+
effective.bottomLeft
|
|
2800
|
+
];
|
|
2801
|
+
const innerRadii = (sides) => radii.map((value, index) => `max(0px, ${String(value)}px - ${String(sides[index] ?? 0)}px)`).join(" ");
|
|
2802
|
+
const horizontal = innerRadii([
|
|
2803
|
+
left,
|
|
2804
|
+
right,
|
|
2805
|
+
right,
|
|
2806
|
+
left
|
|
2807
|
+
]);
|
|
2808
|
+
const vertical = innerRadii([
|
|
2809
|
+
top,
|
|
2810
|
+
top,
|
|
2811
|
+
bottom,
|
|
2812
|
+
bottom
|
|
2813
|
+
]);
|
|
2814
|
+
return {
|
|
2815
|
+
...declarations,
|
|
2816
|
+
"border-shape": `${outer} inset(0 round ${horizontal} / ${vertical}) padding-box`
|
|
2817
|
+
};
|
|
2818
|
+
};
|
|
2819
|
+
const canvasCornerRadiusDeclarations = (radius) => ({
|
|
2820
|
+
"border-top-left-radius": radius.topLeft,
|
|
2821
|
+
"border-top-right-radius": radius.topRight,
|
|
2822
|
+
"border-bottom-right-radius": radius.bottomRight,
|
|
2823
|
+
"border-bottom-left-radius": radius.bottomLeft
|
|
2824
|
+
});
|
|
2825
|
+
|
|
2826
|
+
//#endregion
|
|
2827
|
+
//#region ../../packages/canvas-document/src/canvas-progressive-blur.lib.ts
|
|
2828
|
+
const OWNERS = /* @__PURE__ */ new Set([FRAME_KIND, RECTANGLE_KIND]);
|
|
2829
|
+
const isProgressive = (filter) => filter.visible && filter.kind === "blur" && filter.progression !== void 0;
|
|
2830
|
+
/** The layer's visible progressive background blur, drawn as stacked layers, if it has one. */
|
|
2831
|
+
const canvasProgressiveBlurOf = (node) => node.geometry === void 0 && OWNERS.has(node.component) ? (node.appearance?.backdropFilters ?? []).find((filter) => isProgressive(filter)) ?? null : null;
|
|
2832
|
+
/** The background filters the layer's own backdrop-filter draws: all but the progressive blur. */
|
|
2833
|
+
const canvasUniformBackdropFilters = (node, filters) => {
|
|
2834
|
+
const progressive = canvasProgressiveBlurOf(node);
|
|
2835
|
+
return progressive === null ? filters : filters.filter((filter) => filter !== progressive);
|
|
2836
|
+
};
|
|
2837
|
+
|
|
2838
|
+
//#endregion
|
|
2839
|
+
//#region ../../packages/canvas-document/src/canvas-paint-element-plan.lib.ts
|
|
2840
|
+
const BOX_LAYERS = /* @__PURE__ */ new Set([
|
|
2841
|
+
FRAME_KIND,
|
|
2842
|
+
GROUP_KIND,
|
|
2843
|
+
RECTANGLE_KIND,
|
|
2844
|
+
IMAGE_KIND
|
|
2845
|
+
]);
|
|
2846
|
+
const STROKE_OWNERS = /* @__PURE__ */ new Set([
|
|
2847
|
+
FRAME_KIND,
|
|
2848
|
+
GROUP_KIND,
|
|
2849
|
+
RECTANGLE_KIND
|
|
2850
|
+
]);
|
|
2851
|
+
const isCanvasBlendedPaint = (paint) => paint.visible && (paint.blendMode ?? "normal") !== "normal";
|
|
2852
|
+
const isPainted = (paint) => {
|
|
2853
|
+
if (!paint.visible || paint.opacity <= 0) return false;
|
|
2854
|
+
if (paint.kind === "solid") return paint.color.alpha > 0;
|
|
2855
|
+
if (paint.kind === "image") return true;
|
|
2856
|
+
return paint.stops.some((stop) => stop.color.alpha > 0);
|
|
2857
|
+
};
|
|
2858
|
+
const hasCapturedBox = (node) => {
|
|
2859
|
+
const source = node.props?.["source"];
|
|
2860
|
+
if (typeof source !== "object" || source === null) return false;
|
|
2861
|
+
const layout = Reflect.get(source, "layout");
|
|
2862
|
+
return typeof Reflect.get(source, "path") === "string" && typeof layout === "object" && layout !== null && typeof Reflect.get(layout, "tag") === "string";
|
|
2863
|
+
};
|
|
2864
|
+
/**
|
|
2865
|
+
* As in Figma, a rectangle casts its shadows from what it paints, so one with no fill, border or
|
|
2866
|
+
* outline that shows casts none. A frame, and a box captured from HTML, keep the box's shadow.
|
|
2867
|
+
*/
|
|
2868
|
+
const canvasCastsNoShadow = (node) => {
|
|
2869
|
+
if (node.component !== "rectangle" || node.geometry !== void 0 || hasCapturedBox(node)) return false;
|
|
2870
|
+
const { fills = [], border, outline } = node.appearance ?? {};
|
|
2871
|
+
const strokes = [border, outline].filter((stroke) => stroke?.visible === true);
|
|
2872
|
+
return [...fills, ...strokes.flatMap((stroke) => stroke?.paints ?? [])].every((paint) => !isPainted(paint));
|
|
2873
|
+
};
|
|
2874
|
+
/** A native image is an `img`, which holds no element; an image drawn from its fills is a box. */
|
|
2875
|
+
const isBoxLayer = (node) => node.geometry === void 0 && BOX_LAYERS.has(node.component) && (node.component !== "image" || (typeof node.props?.["src"] !== "string" || node.props["src"] === "") && node.appearance?.fills !== void 0);
|
|
2876
|
+
const visibleStrokePaints = (stroke) => stroke?.visible === true ? stroke.paints.filter((paint) => paint.visible) : [];
|
|
2877
|
+
/** Plus darker and an image filter have no CSS background form; a blend reaches only so. */
|
|
2878
|
+
const fillNeedsElement = (paint) => isCanvasBlendedPaint(paint) || paint.kind === "image" && (paint.filters?.some((filter) => filter.visible) ?? false);
|
|
2879
|
+
/** The visible fills, when any of them needs its own element: then every fill is one, in order. */
|
|
2880
|
+
const fillElementsOf = (node) => {
|
|
2881
|
+
if (!isBoxLayer(node)) return [];
|
|
2882
|
+
const fills = (node.appearance?.fills ?? []).filter((paint) => paint.visible);
|
|
2883
|
+
return fills.some((paint) => fillNeedsElement(paint)) || fills.length > 0 && canvasProgressiveBlurOf(node) !== null ? fills : [];
|
|
2884
|
+
};
|
|
2885
|
+
/**
|
|
2886
|
+
* One solid paint on an undashed inside border stays CSS border-color on the layer. Anything else
|
|
2887
|
+
* is #469's border element: its paints stacked as backgrounds clipped to the border area.
|
|
2888
|
+
*/
|
|
2889
|
+
const borderNeedsElement = (border) => {
|
|
2890
|
+
const paints = visibleStrokePaints(border);
|
|
2891
|
+
return paints.length > 0 && ((border.alignment ?? "inside") !== "inside" || border.style !== "solid" || paints.length > 1 || paints.some((paint) => paint.kind !== "solid"));
|
|
2892
|
+
};
|
|
2893
|
+
/** The border's ring elements: one per paint when a paint blends, so each blends on its own. */
|
|
2894
|
+
const borderElementsOf = (node, hasFillElements) => {
|
|
2895
|
+
const border = node.appearance?.border;
|
|
2896
|
+
if (border === void 0 || node.geometry !== void 0 || !STROKE_OWNERS.has(node.component)) return [];
|
|
2897
|
+
const paints = visibleStrokePaints(border);
|
|
2898
|
+
if (paints.some((paint) => isCanvasBlendedPaint(paint))) return paints.map((paint) => ({
|
|
2899
|
+
kind: "border",
|
|
2900
|
+
paints: [paint]
|
|
2901
|
+
}));
|
|
2902
|
+
return border.layoutInclusion === "none" || border.layoutInclusion === "visible" || borderNeedsElement(border) || hasFillElements && paints.length > 0 ? [{
|
|
2903
|
+
kind: "border",
|
|
2904
|
+
paints
|
|
2905
|
+
}] : [];
|
|
2906
|
+
};
|
|
2907
|
+
/**
|
|
2908
|
+
* One solid unblended paint around smoothed corners is the editor's contour outline, which follows
|
|
2909
|
+
* the smoothed shape and dashes it.
|
|
2910
|
+
*/
|
|
2911
|
+
const isCanvasContourOutlinePaint = (node) => {
|
|
2912
|
+
const [only, ...others] = visibleStrokePaints(node.appearance?.outline);
|
|
2913
|
+
return (node.appearance?.radius?.smoothing ?? 0) > 0 && others.length === 0 && only?.kind === "solid" && !isCanvasBlendedPaint(only);
|
|
2914
|
+
};
|
|
2915
|
+
/** One solid paint on an undashed outline stays CSS outline-color; anything else is a ring. */
|
|
2916
|
+
const outlineElementsOf = (node) => {
|
|
2917
|
+
const outline = node.appearance?.outline;
|
|
2918
|
+
if (outline === void 0 || node.geometry !== void 0 || !STROKE_OWNERS.has(node.component) || outline.width <= 0 || isCanvasContourOutlinePaint(node)) return [];
|
|
2919
|
+
const paints = visibleStrokePaints(outline);
|
|
2920
|
+
if (paints.some((paint) => isCanvasBlendedPaint(paint))) return paints.map((paint) => ({
|
|
2921
|
+
kind: "outline",
|
|
2922
|
+
paints: [paint]
|
|
2923
|
+
}));
|
|
2924
|
+
return paints.length > 1 || outline.style !== "solid" || paints.some((paint) => paint.kind !== "solid") ? [{
|
|
2925
|
+
kind: "outline",
|
|
2926
|
+
paints
|
|
2927
|
+
}] : [];
|
|
2928
|
+
};
|
|
2929
|
+
/** The paint elements of a layer, in the order CSS paints a box, and whether it has any. */
|
|
2930
|
+
const canvasPaintElementPlanOf = (node) => {
|
|
2931
|
+
const fills = fillElementsOf(node);
|
|
2932
|
+
const shadows = isBoxLayer(node) && !canvasCastsNoShadow(node) ? (node.appearance?.shadows ?? []).filter((shadow) => shadow.visible) : [];
|
|
2933
|
+
const outer = shadows.filter((shadow) => shadow.kind === "outer" && isCanvasBlendedPaint(shadow));
|
|
2934
|
+
const inner = shadows.filter((shadow) => shadow.kind === "inner" && (fills.length > 0 || isCanvasBlendedPaint(shadow)));
|
|
2935
|
+
const underChildren = [
|
|
2936
|
+
...outer.map((shadow) => ({
|
|
2937
|
+
kind: "outer-shadow",
|
|
2938
|
+
shadow
|
|
2939
|
+
})),
|
|
2940
|
+
...fills.map((paint) => ({
|
|
2941
|
+
kind: "fill",
|
|
2942
|
+
paint
|
|
2943
|
+
})),
|
|
2944
|
+
...inner.map((shadow) => ({
|
|
2945
|
+
kind: "inner-shadow",
|
|
2946
|
+
shadow
|
|
2947
|
+
}))
|
|
2948
|
+
];
|
|
2949
|
+
return {
|
|
2950
|
+
elements: [
|
|
2951
|
+
...underChildren,
|
|
2952
|
+
...borderElementsOf(node, fills.length > 0),
|
|
2953
|
+
...outlineElementsOf(node)
|
|
2954
|
+
],
|
|
2955
|
+
hasPaintElements: underChildren.length > 0
|
|
2956
|
+
};
|
|
2957
|
+
};
|
|
2958
|
+
const canvasFillElementsOf = (plan) => plan.elements.flatMap((element) => element.kind === "fill" ? [element.paint] : []);
|
|
2959
|
+
const canvasShadowElementsOf = (plan, kind) => plan.elements.flatMap((element) => element.kind === kind ? [element.shadow] : []);
|
|
2960
|
+
const canvasStrokeElementsOf = (plan, kind) => plan.elements.flatMap((element) => element.kind === kind ? [element.paints] : []);
|
|
2961
|
+
|
|
2962
|
+
//#endregion
|
|
2963
|
+
//#region ../../packages/canvas-document/src/canvas-stroke-pattern.lib.ts
|
|
2964
|
+
const DASH_LENGTH_FACTOR = 3;
|
|
2965
|
+
/** A stroke's dash, from its stored pattern and cap or, without one, three widths on and two off. */
|
|
2966
|
+
const canvasGeometryStrokePatternOf = (style, width, stored = {}) => {
|
|
2967
|
+
if (style === "solid") return {
|
|
2968
|
+
dash: void 0,
|
|
2969
|
+
linecap: "butt"
|
|
2970
|
+
};
|
|
2971
|
+
if (stored.dashPattern !== void 0) return {
|
|
2972
|
+
dash: stored.dashPattern.map(String).join(" "),
|
|
2973
|
+
linecap: stored.dashCap === "round" ? "round" : stored.dashCap === "square" ? "square" : "butt"
|
|
2974
|
+
};
|
|
2975
|
+
return style === "dotted" ? {
|
|
2976
|
+
dash: `0 ${String(width * 2)}`,
|
|
2977
|
+
linecap: "round"
|
|
2978
|
+
} : {
|
|
2979
|
+
dash: `${String(width * DASH_LENGTH_FACTOR)} ${String(width * 2)}`,
|
|
2980
|
+
linecap: "butt"
|
|
2981
|
+
};
|
|
2982
|
+
};
|
|
2983
|
+
|
|
2984
|
+
//#endregion
|
|
2985
|
+
//#region ../../packages/canvas-document/src/canvas-box-stroke.lib.ts
|
|
2986
|
+
const NO_OUTSET = {
|
|
2987
|
+
top: 0,
|
|
2988
|
+
right: 0,
|
|
2989
|
+
bottom: 0,
|
|
2990
|
+
left: 0
|
|
2991
|
+
};
|
|
2992
|
+
/** How far past the layer's edge each alignment paints, as a share of the side's width. */
|
|
2993
|
+
const BORDER_OUTSET = {
|
|
2994
|
+
inside: 0,
|
|
2995
|
+
center: .5,
|
|
2996
|
+
outside: 1
|
|
2997
|
+
};
|
|
2998
|
+
const CORNERS$1 = [
|
|
2999
|
+
[
|
|
3000
|
+
"topLeft",
|
|
3001
|
+
"top-left",
|
|
3002
|
+
"left",
|
|
3003
|
+
"top"
|
|
3004
|
+
],
|
|
3005
|
+
[
|
|
3006
|
+
"topRight",
|
|
3007
|
+
"top-right",
|
|
3008
|
+
"right",
|
|
3009
|
+
"top"
|
|
3010
|
+
],
|
|
3011
|
+
[
|
|
3012
|
+
"bottomRight",
|
|
3013
|
+
"bottom-right",
|
|
3014
|
+
"right",
|
|
3015
|
+
"bottom"
|
|
3016
|
+
],
|
|
3017
|
+
[
|
|
3018
|
+
"bottomLeft",
|
|
3019
|
+
"bottom-left",
|
|
3020
|
+
"left",
|
|
3021
|
+
"bottom"
|
|
3022
|
+
]
|
|
3023
|
+
];
|
|
3024
|
+
/** Whether the layer's border is drawn by paint elements, which the layer then leaves transparent. */
|
|
3025
|
+
const hasCanvasBoxStroke = (node) => canvasStrokeElementsOf(canvasPaintElementPlanOf(node), "border").length > 0;
|
|
3026
|
+
const canvasBoxStrokeRootDeclarations = (node, size = node.box) => {
|
|
3027
|
+
if (!hasCanvasBoxStroke(node)) return {};
|
|
3028
|
+
const declarations = { "border-color": "transparent" };
|
|
3029
|
+
const border = node.appearance?.border;
|
|
3030
|
+
const radius = node.appearance?.radius;
|
|
3031
|
+
if (radius === void 0 || size === void 0 || border?.style !== "solid" || node.geometry?.kind === "path") return declarations;
|
|
3032
|
+
const widths = canvasBorderLayoutWidths(border);
|
|
3033
|
+
if ((radius.smoothing ?? 0) <= 0 || Object.values(widths).every((width) => width === 0)) return declarations;
|
|
3034
|
+
const outer = cornerContour(radius, size);
|
|
3035
|
+
const inner = cornerContour(radius, size, [-widths.left, -widths.top]);
|
|
3036
|
+
return {
|
|
3037
|
+
...declarations,
|
|
3038
|
+
"border-shape": `path("${outer}") border-box path("${inner}") padding-box`
|
|
3039
|
+
};
|
|
3040
|
+
};
|
|
3041
|
+
/** A rounded corner grows by the outset of its two sides; a square corner stays square. */
|
|
3042
|
+
const outsetRadiusDeclarations = (node, outset) => {
|
|
3043
|
+
const radius = node.appearance?.radius;
|
|
3044
|
+
if (radius === void 0) return { "border-radius": "inherit" };
|
|
3045
|
+
return Object.fromEntries(CORNERS$1.map(([corner, property, horizontal, vertical]) => {
|
|
3046
|
+
const value = radius[corner];
|
|
3047
|
+
return [`border-${property}-radius`, value <= 0 ? 0 : `${String(value + outset[horizontal])}px ${String(value + outset[vertical])}px`];
|
|
3048
|
+
}));
|
|
3049
|
+
};
|
|
3050
|
+
const SVG_PRECISION = 1e3;
|
|
3051
|
+
const svgNumber = (value) => String(Math.round(value * SVG_PRECISION) / SVG_PRECISION);
|
|
3052
|
+
/** A rounded rectangle, clockwise from the end of the top left corner, as SVG draws a rectangle. */
|
|
3053
|
+
const roundedRectanglePath = (width, height, corners) => {
|
|
3054
|
+
const fit = ([x, y]) => [Math.min(x, width / 2), Math.min(y, height / 2)];
|
|
3055
|
+
const [tl, tr, br, bl] = [
|
|
3056
|
+
fit(corners.topLeft),
|
|
3057
|
+
fit(corners.topRight),
|
|
3058
|
+
fit(corners.bottomRight),
|
|
3059
|
+
fit(corners.bottomLeft)
|
|
3060
|
+
];
|
|
3061
|
+
const arc = ([x, y], toX, toY) => x === 0 || y === 0 ? `L${svgNumber(toX)} ${svgNumber(toY)}` : `A${svgNumber(x)} ${svgNumber(y)} 0 0 1 ${svgNumber(toX)} ${svgNumber(toY)}`;
|
|
3062
|
+
return [
|
|
3063
|
+
`M${svgNumber(tl[0])} 0`,
|
|
3064
|
+
`H${svgNumber(width - tr[0])}`,
|
|
3065
|
+
arc(tr, width, tr[1]),
|
|
3066
|
+
`V${svgNumber(height - br[1])}`,
|
|
3067
|
+
arc(br, width - br[0], height),
|
|
3068
|
+
`H${svgNumber(bl[0])}`,
|
|
3069
|
+
arc(bl, 0, height - bl[1]),
|
|
3070
|
+
`V${svgNumber(tl[1])}`,
|
|
3071
|
+
arc(tl, tl[0], 0),
|
|
3072
|
+
"Z"
|
|
3073
|
+
].join("");
|
|
3074
|
+
};
|
|
3075
|
+
/**
|
|
3076
|
+
* A dashed ring is the solid ring cut by a mask that strokes its outer edge with the dash pattern
|
|
3077
|
+
* and cap, twice as wide as the ring's widest side so the stroke covers all of it.
|
|
3078
|
+
*/
|
|
3079
|
+
const canvasDashMaskDeclarations = (ring) => {
|
|
3080
|
+
if (ring.stroke.style === "solid") return {};
|
|
3081
|
+
const pattern = canvasGeometryStrokePatternOf(ring.stroke.style, ring.widest, ring.stroke);
|
|
3082
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${svgNumber(ring.width)}" height="${svgNumber(ring.height)}"><path d="${roundedRectanglePath(ring.width, ring.height, ring.corners)}" fill="none" stroke="#000" stroke-width="${svgNumber(ring.widest * 2)}" stroke-dasharray="${pattern.dash ?? "none"}" stroke-linecap="${pattern.linecap}"/></svg>`;
|
|
3083
|
+
return {
|
|
3084
|
+
"border-style": "solid",
|
|
3085
|
+
"mask-image": `url("data:image/svg+xml,${encodeURIComponent(svg)}")`,
|
|
3086
|
+
"mask-size": "100% 100%",
|
|
3087
|
+
"mask-repeat": "no-repeat",
|
|
3088
|
+
"mask-origin": "border-box"
|
|
3089
|
+
};
|
|
3090
|
+
};
|
|
3091
|
+
/** The border's dash mask, over its paint element: the layer grown by the alignment's outset. */
|
|
3092
|
+
const borderDashMaskDeclarations = (node, border, size, outset) => {
|
|
3093
|
+
if (size === void 0) return {};
|
|
3094
|
+
const radius = node.appearance?.radius;
|
|
3095
|
+
const grown = ([corner, , horizontal, vertical]) => {
|
|
3096
|
+
const value = radius?.[corner] ?? 0;
|
|
3097
|
+
return value <= 0 ? [0, 0] : [value + outset[horizontal], value + outset[vertical]];
|
|
3098
|
+
};
|
|
3099
|
+
return canvasDashMaskDeclarations({
|
|
3100
|
+
width: size.width + outset.left + outset.right,
|
|
3101
|
+
height: size.height + outset.top + outset.bottom,
|
|
3102
|
+
corners: {
|
|
3103
|
+
topLeft: grown(CORNERS$1[0]),
|
|
3104
|
+
topRight: grown(CORNERS$1[1]),
|
|
3105
|
+
bottomRight: grown(CORNERS$1[2]),
|
|
3106
|
+
bottomLeft: grown(CORNERS$1[3])
|
|
3107
|
+
},
|
|
3108
|
+
widest: Math.max(...Object.values(border.width)),
|
|
3109
|
+
stroke: border
|
|
3110
|
+
});
|
|
3111
|
+
};
|
|
3112
|
+
/**
|
|
3113
|
+
* One of the border's paint elements: a ring with the given paints, the border's whole paint list
|
|
3114
|
+
* unless a paint blends, when each paint has its own ring. It has no scene identity and never
|
|
3115
|
+
* takes part in child layout.
|
|
3116
|
+
*/
|
|
3117
|
+
const canvasBoxStrokeDeclarations = (node, size = node.box, ringPaints) => {
|
|
3118
|
+
const border = node.appearance?.border;
|
|
3119
|
+
const [firstRing] = canvasStrokeElementsOf(canvasPaintElementPlanOf(node), "border");
|
|
3120
|
+
if (border === void 0 || firstRing === void 0) return null;
|
|
3121
|
+
const paints = ringPaints ?? firstRing;
|
|
3122
|
+
const widths = canvasBorderLayoutWidths(border);
|
|
3123
|
+
const share = BORDER_OUTSET[border.alignment ?? "inside"];
|
|
3124
|
+
const outset = {
|
|
3125
|
+
top: border.width.top * share,
|
|
3126
|
+
right: border.width.right * share,
|
|
3127
|
+
bottom: border.width.bottom * share,
|
|
3128
|
+
left: border.width.left * share
|
|
3129
|
+
};
|
|
3130
|
+
const appearance = {
|
|
3131
|
+
border: {
|
|
3132
|
+
...border,
|
|
3133
|
+
alignment: "inside",
|
|
3134
|
+
layoutInclusion: "always"
|
|
3135
|
+
},
|
|
3136
|
+
radius: node.appearance?.radius
|
|
3137
|
+
};
|
|
3138
|
+
const [only] = paints;
|
|
3139
|
+
const isBorderColor = paints.length === 1 && only?.kind === "solid" && (only.blendMode ?? "normal") === "normal" && border.style === "solid" && share === 0;
|
|
3140
|
+
return {
|
|
3141
|
+
position: "absolute",
|
|
3142
|
+
inset: 0,
|
|
3143
|
+
top: -(widths.top + outset.top),
|
|
3144
|
+
right: -(widths.right + outset.right),
|
|
3145
|
+
bottom: -(widths.bottom + outset.bottom),
|
|
3146
|
+
left: -(widths.left + outset.left),
|
|
3147
|
+
"box-sizing": "border-box",
|
|
3148
|
+
"pointer-events": "none",
|
|
3149
|
+
...share === 0 ? { "border-radius": "inherit" } : outsetRadiusDeclarations(node, outset),
|
|
3150
|
+
...canvasBoxDecorationDeclarations({
|
|
3151
|
+
...appearance,
|
|
3152
|
+
border: {
|
|
3153
|
+
...appearance.border,
|
|
3154
|
+
paints: [...paints]
|
|
3155
|
+
}
|
|
3156
|
+
}),
|
|
3157
|
+
...!isBorderColor && {
|
|
3158
|
+
"border-color": "transparent",
|
|
3159
|
+
...canvasPaintLayerDeclarations(paints),
|
|
3160
|
+
"background-origin": "border-box",
|
|
3161
|
+
"background-clip": "border-area"
|
|
3162
|
+
},
|
|
3163
|
+
...paints.length === 1 && only?.blendMode !== void 0 && only.blendMode !== "normal" && { "mix-blend-mode": only.blendMode },
|
|
3164
|
+
...share === 0 && canvasCornerShapeDeclarations({
|
|
3165
|
+
...node,
|
|
3166
|
+
styles: {},
|
|
3167
|
+
additionalStyles: void 0,
|
|
3168
|
+
appearance
|
|
3169
|
+
}, size),
|
|
3170
|
+
...borderDashMaskDeclarations(node, border, size, share === 0 ? NO_OUTSET : outset)
|
|
3171
|
+
};
|
|
3172
|
+
};
|
|
3173
|
+
|
|
3174
|
+
//#endregion
|
|
3175
|
+
//#region ../../packages/canvas-document/src/canvas-effect-projection.lib.ts
|
|
3176
|
+
/** The shadows the layer element draws itself: those the plan does not give their own element. */
|
|
3177
|
+
const layerShadowsOf = (node, shadows) => {
|
|
3178
|
+
if (canvasCastsNoShadow(node)) return [];
|
|
3179
|
+
const plan = canvasPaintElementPlanOf(node);
|
|
3180
|
+
const elements = [...canvasShadowElementsOf(plan, "outer-shadow"), ...canvasShadowElementsOf(plan, "inner-shadow")];
|
|
3181
|
+
return elements.length === 0 ? shadows : shadows.filter((shadow) => !elements.includes(shadow));
|
|
3182
|
+
};
|
|
3183
|
+
const shadowCss = (shadow) => {
|
|
3184
|
+
return `${shadow.kind === "inner" ? "inset " : ""}${String(shadow.offsetX)}px ${String(shadow.offsetY)}px ${String(shadow.blur)}px ${String(shadow.spread)}px ${canvasColorCss(shadow.color)}`;
|
|
3185
|
+
};
|
|
3186
|
+
const textShadowCss = (shadow) => `${String(shadow.offsetX)}px ${String(shadow.offsetY)}px ${String(shadow.blur)}px ${canvasColorCss(shadow.color)}`;
|
|
3187
|
+
const canvasShadowDeclarations = (node, shadows) => {
|
|
3188
|
+
const visible = layerShadowsOf(node, shadows).filter((shadow) => shadow.visible);
|
|
3189
|
+
if (node.component === "text") {
|
|
3190
|
+
const textShadow = visible.filter((shadow) => shadow.kind === "outer" && shadow.spread === 0).map((shadow) => textShadowCss(shadow)).join(", ");
|
|
3191
|
+
return {
|
|
3192
|
+
"box-shadow": "none",
|
|
3193
|
+
"text-shadow": textShadow === "" ? "none" : textShadow
|
|
3194
|
+
};
|
|
3195
|
+
}
|
|
3196
|
+
const boxShadow = visible.map((shadow) => shadowCss(shadow)).join(", ");
|
|
3197
|
+
return { "box-shadow": boxShadow === "" ? "none" : boxShadow };
|
|
3198
|
+
};
|
|
3199
|
+
/** One shadow's paint element: the layer's border box casting only that shadow, with its blend. */
|
|
3200
|
+
const canvasShadowPaintDeclarations = (node, shadow) => {
|
|
3201
|
+
const border = node.appearance?.border;
|
|
3202
|
+
const widths = border === void 0 ? {
|
|
3203
|
+
top: 0,
|
|
3204
|
+
right: 0,
|
|
3205
|
+
bottom: 0,
|
|
3206
|
+
left: 0
|
|
3207
|
+
} : canvasBorderLayoutWidths(border);
|
|
3208
|
+
return {
|
|
3209
|
+
position: "absolute",
|
|
3210
|
+
top: -widths.top,
|
|
3211
|
+
right: -widths.right,
|
|
3212
|
+
bottom: -widths.bottom,
|
|
3213
|
+
left: -widths.left,
|
|
3214
|
+
"border-radius": "inherit",
|
|
3215
|
+
"pointer-events": "none",
|
|
3216
|
+
"box-shadow": shadowCss(shadow),
|
|
3217
|
+
"mix-blend-mode": shadow.blendMode ?? "normal"
|
|
3218
|
+
};
|
|
3219
|
+
};
|
|
3220
|
+
|
|
3221
|
+
//#endregion
|
|
3222
|
+
//#region ../../packages/canvas-document/src/canvas-css-fill.lib.ts
|
|
3223
|
+
const PERCENT = 100;
|
|
3224
|
+
const DEFAULT_ANGLE = 180;
|
|
3225
|
+
const gradientStops = (id, parts) => {
|
|
3226
|
+
const stops = parts.map((part, index) => {
|
|
3227
|
+
const [colorText = "", positionText, ...extra] = canvasCssTokens(part);
|
|
3228
|
+
const color = canvasColorFromCss(colorText);
|
|
3229
|
+
const position = positionText === void 0 ? index / (parts.length - 1) : /^\d+(?:\.\d+)?%$/u.test(positionText) ? Number(positionText.slice(0, -1)) / PERCENT : NaN;
|
|
3230
|
+
return color === null || extra.length > 0 ? null : {
|
|
3231
|
+
id: `${id}-stop-${String(index)}`,
|
|
3232
|
+
color,
|
|
3233
|
+
position
|
|
3234
|
+
};
|
|
3235
|
+
});
|
|
3236
|
+
if (stops.includes(null)) return null;
|
|
3237
|
+
return stops.filter((stop) => stop !== null);
|
|
3238
|
+
};
|
|
3239
|
+
const gradientPaint = (id, value) => {
|
|
3240
|
+
const match = /^(linear|radial)-gradient\((.*)\)$/su.exec(value);
|
|
3241
|
+
if (match === null) return null;
|
|
3242
|
+
const parts = [...canvasCssTokens(match[2] ?? "", ",")];
|
|
3243
|
+
const first = parts[0] ?? "";
|
|
3244
|
+
const angle = /^(-?(?:\d+(?:\.\d*)?|\.\d+))deg$/u.exec(first);
|
|
3245
|
+
const radial = /^ellipse ([\d.]+)% ([\d.]+)% at (-?[\d.]+)% (-?[\d.]+)%$/u.exec(first);
|
|
3246
|
+
if (angle !== null && match[1] !== "linear" || radial !== null && match[1] !== "radial") return null;
|
|
3247
|
+
if (angle !== null || radial !== null) parts.shift();
|
|
3248
|
+
const hasPositions = parts.map((part) => canvasCssTokens(part).length > 1);
|
|
3249
|
+
if (hasPositions.some(Boolean) && !hasPositions.every(Boolean)) return null;
|
|
3250
|
+
const stops = gradientStops(id, parts);
|
|
3251
|
+
if (stops === null) return null;
|
|
3252
|
+
const base = {
|
|
3253
|
+
id,
|
|
3254
|
+
visible: true,
|
|
3255
|
+
opacity: 1,
|
|
3256
|
+
stops
|
|
3257
|
+
};
|
|
3258
|
+
const result = canvasPaintSchema.safeParse(match[1] === "linear" ? {
|
|
3259
|
+
...base,
|
|
3260
|
+
kind: "linear-gradient",
|
|
3261
|
+
angle: Number(angle?.[1] ?? DEFAULT_ANGLE)
|
|
3262
|
+
} : radial === null ? null : {
|
|
3263
|
+
...base,
|
|
3264
|
+
kind: "radial-gradient",
|
|
3265
|
+
radius: {
|
|
3266
|
+
x: Number(radial[1]) / PERCENT,
|
|
3267
|
+
y: Number(radial[2]) / PERCENT
|
|
3268
|
+
},
|
|
3269
|
+
center: {
|
|
3270
|
+
x: Number(radial[3]) / PERCENT,
|
|
3271
|
+
y: Number(radial[4]) / PERCENT
|
|
3272
|
+
}
|
|
3273
|
+
});
|
|
3274
|
+
if (!result.success) return null;
|
|
3275
|
+
const paint = result.data;
|
|
3276
|
+
const firstStop = "stops" in paint ? paint.stops[0] : void 0;
|
|
3277
|
+
if (firstStop !== void 0 && paint.kind === "linear-gradient" && paint.stops.every((stop) => JSON.stringify(stop.color) === JSON.stringify(firstStop.color))) return {
|
|
3278
|
+
id,
|
|
3279
|
+
kind: "solid",
|
|
3280
|
+
visible: true,
|
|
3281
|
+
opacity: 1,
|
|
3282
|
+
color: firstStop.color
|
|
3283
|
+
};
|
|
3284
|
+
return paint;
|
|
3285
|
+
};
|
|
3286
|
+
const layerValue = (css, property, index, fallback) => {
|
|
3287
|
+
const parts = canvasCssTokens(css[property] ?? fallback, ",");
|
|
3288
|
+
return parts[index % parts.length] ?? fallback;
|
|
3289
|
+
};
|
|
3290
|
+
const imagePaint = (id, value, css, index) => {
|
|
3291
|
+
const match = /^url\((?:"([^"\\]*)"|'([^'\\]*)'|([^\s'"()\\]+))\)$/u.exec(value);
|
|
3292
|
+
const assetId = match?.[1] ?? match?.[2] ?? match?.[3];
|
|
3293
|
+
if (assetId === void 0 || assetId === "" || assetId.startsWith("data:image/svg+xml")) return null;
|
|
3294
|
+
const position = layerValue(css, "background-position", index, "0% 0%");
|
|
3295
|
+
const size = layerValue(css, "background-size", index, "auto");
|
|
3296
|
+
const repeat = layerValue(css, "background-repeat", index, "repeat");
|
|
3297
|
+
const isCentered = [
|
|
3298
|
+
"center",
|
|
3299
|
+
"center center",
|
|
3300
|
+
"50% 50%"
|
|
3301
|
+
].includes(position);
|
|
3302
|
+
const base = {
|
|
3303
|
+
id,
|
|
3304
|
+
kind: "image",
|
|
3305
|
+
visible: true,
|
|
3306
|
+
opacity: 1,
|
|
3307
|
+
assetId
|
|
3308
|
+
};
|
|
3309
|
+
if (repeat === "repeat" && size === "auto" && (position === "0% 0%" || isCentered)) return {
|
|
3310
|
+
...base,
|
|
3311
|
+
fit: "tile",
|
|
3312
|
+
tileOrigin: isCentered ? "center" : "top-left"
|
|
3313
|
+
};
|
|
3314
|
+
if (repeat !== "no-repeat" || !isCentered) return null;
|
|
3315
|
+
const mode = Object.entries({
|
|
3316
|
+
cover: "cover",
|
|
3317
|
+
contain: "fit",
|
|
3318
|
+
"100% 100%": "fill"
|
|
3319
|
+
}).find(([key]) => key === size)?.[1];
|
|
3320
|
+
return mode === void 0 ? null : {
|
|
3321
|
+
...base,
|
|
3322
|
+
fit: mode
|
|
3323
|
+
};
|
|
3324
|
+
};
|
|
3325
|
+
/** Decode the lossless CSS forms emitted by the legacy importer; other syntax stays authored. */
|
|
3326
|
+
const canvasCssFills = (nodeId, css) => {
|
|
3327
|
+
const background = css["background"];
|
|
3328
|
+
const colorText = css["background-color"] ?? background;
|
|
3329
|
+
const color = colorText === void 0 || colorText === "none" ? null : solidCanvasPaintFromCss(`${nodeId}-background`, colorText);
|
|
3330
|
+
if (colorText !== void 0 && colorText !== "none" && color === null) return null;
|
|
3331
|
+
const image = css["background-image"];
|
|
3332
|
+
if (image === void 0 || image === "none") return color === null ? [] : [color];
|
|
3333
|
+
const layers = canvasCssTokens(image, ",").map((value, index) => {
|
|
3334
|
+
const id = `${nodeId}-fill-${String(index)}`;
|
|
3335
|
+
const gradient = gradientPaint(id, value);
|
|
3336
|
+
const size = layerValue(css, "background-size", index, "auto");
|
|
3337
|
+
if (gradient !== null && ![
|
|
3338
|
+
"auto",
|
|
3339
|
+
"auto auto",
|
|
3340
|
+
"100% 100%"
|
|
3341
|
+
].includes(size)) return null;
|
|
3342
|
+
const paint = gradient ?? imagePaint(id, value, css, index);
|
|
3343
|
+
const mode = canvasBlendModeSchema.safeParse(layerValue(css, "background-blend-mode", index, "normal"));
|
|
3344
|
+
return paint === null || !mode.success ? null : {
|
|
3345
|
+
...paint,
|
|
3346
|
+
blendMode: mode.data
|
|
3347
|
+
};
|
|
3348
|
+
});
|
|
3349
|
+
if (layers.includes(null)) return null;
|
|
3350
|
+
return [...color === null ? [] : [color], ...layers.filter((paint) => paint !== null).toReversed()];
|
|
3351
|
+
};
|
|
3352
|
+
|
|
3353
|
+
//#endregion
|
|
3354
|
+
//#region ../../packages/canvas-document/src/canvas-style-ownership.lib.ts
|
|
3355
|
+
/** The CSS properties each native appearance setting paints, and so is replaced by when written. */
|
|
3356
|
+
const APPEARANCE_OWNERS = [
|
|
3357
|
+
["fills", /^background(?:-color|-image)?$/u],
|
|
3358
|
+
["radius", /^border(?:-(?:top|bottom)-(?:left|right))?-radius$/u],
|
|
3359
|
+
["border", /^border(?:-(?:top|right|bottom|left))?(?:-(?:width|style|color))?$|^border-(?:width|style|color)$/u],
|
|
3360
|
+
["outline", /^outline(?:-(?:width|style|color|offset))?$/u],
|
|
3361
|
+
["shadows", /^(?:box|text)-shadow$/u],
|
|
3362
|
+
["filters", /^filter$/u],
|
|
3363
|
+
["backdropFilters", /^backdrop-filter$/u],
|
|
3364
|
+
["opacity", /^opacity$/u],
|
|
3365
|
+
["blendMode", /^mix-blend-mode$/u]
|
|
3366
|
+
];
|
|
3367
|
+
const TEXT_FILL_PROPERTIES = /* @__PURE__ */ new Set(["color", "-webkit-text-fill-color"]);
|
|
3368
|
+
/**
|
|
3369
|
+
* The native settings of a layer that written CSS replaces: each is cleared, so that the written
|
|
3370
|
+
* CSS paints instead of being drawn over. A text layer's fills are its colour, not a background.
|
|
3371
|
+
*/
|
|
3372
|
+
const canvasAppearanceOwnedBy = (node, properties) => {
|
|
3373
|
+
const owned = /* @__PURE__ */ new Set();
|
|
3374
|
+
for (const written of properties) {
|
|
3375
|
+
const property = written.toLowerCase();
|
|
3376
|
+
const isText = node.component === "text";
|
|
3377
|
+
if (isText && TEXT_FILL_PROPERTIES.has(property)) owned.add("fills");
|
|
3378
|
+
for (const [setting, pattern] of APPEARANCE_OWNERS) if (pattern.test(property) && (!isText || setting !== "fills")) owned.add(setting);
|
|
3379
|
+
}
|
|
3380
|
+
return [...owned].filter((setting) => node.appearance?.[setting] !== void 0);
|
|
3381
|
+
};
|
|
3382
|
+
|
|
3383
|
+
//#endregion
|
|
3384
|
+
//#region ../../packages/canvas-document/src/canvas-fill-ownership.lib.ts
|
|
3385
|
+
const PAINT_PROPERTIES = /* @__PURE__ */ new Set([
|
|
3386
|
+
"background",
|
|
3387
|
+
"background-color",
|
|
3388
|
+
"background-image"
|
|
3389
|
+
]);
|
|
3390
|
+
const GEOMETRY_PROPERTIES = /* @__PURE__ */ new Set([
|
|
3391
|
+
"background-position",
|
|
3392
|
+
"background-size",
|
|
3393
|
+
"background-repeat",
|
|
3394
|
+
"background-origin",
|
|
3395
|
+
"background-blend-mode"
|
|
3396
|
+
]);
|
|
3397
|
+
const backgroundCss = (node) => {
|
|
3398
|
+
if ((node.additionalStyles?.declarations ?? []).some(({ property, enabled }) => property.toLowerCase().startsWith("background") && !enabled)) return null;
|
|
3399
|
+
if (Object.keys(node.styles).some((property) => property.toLowerCase().startsWith("background") && property !== property.toLowerCase())) return null;
|
|
3400
|
+
const entries = Object.entries(canvasAuthoredStyleDeclarations(node)).filter(([property, value]) => property.toLowerCase().startsWith("background") && value !== "").map(([property, value]) => [property.toLowerCase(), String(value).trim()]);
|
|
3401
|
+
if (entries.some(([, value]) => value.includes("!"))) return null;
|
|
3402
|
+
let css = {};
|
|
3403
|
+
for (const [property, value] of entries) {
|
|
3404
|
+
if (property === "background") {
|
|
3405
|
+
const blend = css["background-blend-mode"];
|
|
3406
|
+
css = blend === void 0 ? {} : { "background-blend-mode": blend };
|
|
3407
|
+
}
|
|
3408
|
+
css[property] = value;
|
|
3409
|
+
}
|
|
3410
|
+
return css;
|
|
3411
|
+
};
|
|
3412
|
+
/** Reading never mutates a legacy layer. Its first fill edit transfers the same paint atomically. */
|
|
3413
|
+
const canvasFillOwnershipOf = (node) => {
|
|
3414
|
+
const css = backgroundCss(node);
|
|
3415
|
+
if (css === null) return { kind: "custom" };
|
|
3416
|
+
const fills = node.appearance?.fills;
|
|
3417
|
+
if (fills !== void 0 && fills.every((paint) => !paint.visible) && css["background"] !== void 0 && css["background-image"] !== void 0 && css["background-image"] !== "none") return { kind: "custom" };
|
|
3418
|
+
if (fills !== void 0) return {
|
|
3419
|
+
kind: "native",
|
|
3420
|
+
fills,
|
|
3421
|
+
owned: PAINT_PROPERTIES
|
|
3422
|
+
};
|
|
3423
|
+
if (Object.entries(css).some(([property, value]) => !PAINT_PROPERTIES.has(property) && !GEOMETRY_PROPERTIES.has(property) && !["background-blend-mode", "background-clip"].includes(property) && value !== "") || css["background-origin"] !== void 0 && css["background-origin"] !== "padding-box" || css["background-clip"] !== void 0 && css["background-clip"] !== "border-box") return { kind: "custom" };
|
|
3424
|
+
const converted = canvasCssFills(node.id, css);
|
|
3425
|
+
if (converted === null) return { kind: "custom" };
|
|
3426
|
+
if (css["background-image"] !== void 0 && converted.some((paint) => paint.kind !== "image") && (node.appearance?.border !== void 0 || Object.keys(node.styles).some((property) => /^border(?:-|$)/u.test(property)))) return { kind: "custom" };
|
|
3427
|
+
const owned = new Set(PAINT_PROPERTIES);
|
|
3428
|
+
for (const property of GEOMETRY_PROPERTIES) owned.add(property);
|
|
3429
|
+
return {
|
|
3430
|
+
kind: "native",
|
|
3431
|
+
fills: converted,
|
|
3432
|
+
owned
|
|
3433
|
+
};
|
|
3434
|
+
};
|
|
3435
|
+
|
|
3436
|
+
//#endregion
|
|
3437
|
+
//#region ../../packages/canvas-document/src/canvas-fill-paint.lib.ts
|
|
3438
|
+
/**
|
|
3439
|
+
* The layer gives up its background when its fills are paint elements. Only a progressive blur
|
|
3440
|
+
* makes it a stacking context, for the blur layers that sit behind it.
|
|
3441
|
+
*/
|
|
3442
|
+
const canvasFillOwnerDeclarations = (node) => ({
|
|
3443
|
+
...canvasFillElementsOf(canvasPaintElementPlanOf(node)).length > 0 && { background: "none" },
|
|
3444
|
+
...canvasProgressiveBlurOf(node) !== null && { isolation: "isolate" }
|
|
3445
|
+
});
|
|
3446
|
+
/** One fill's paint element: its paint as a background, with its own filter and blend. */
|
|
3447
|
+
const canvasFillPaintDeclarations = (paint) => ({
|
|
3448
|
+
position: "absolute",
|
|
3449
|
+
inset: 0,
|
|
3450
|
+
...canvasPaintLayerDeclarations([paint]),
|
|
3451
|
+
...paint.kind === "image" && paint.filters !== void 0 && { filter: canvasFilterListCss(paint.filters) },
|
|
3452
|
+
...paint.blendMode !== void 0 && paint.blendMode !== "normal" && { "mix-blend-mode": paint.blendMode }
|
|
3453
|
+
});
|
|
3454
|
+
|
|
3455
|
+
//#endregion
|
|
3456
|
+
//#region ../../packages/canvas-document/src/canvas-outline-paint.lib.ts
|
|
3457
|
+
const CORNERS = [
|
|
3458
|
+
["topLeft", "top-left"],
|
|
3459
|
+
["topRight", "top-right"],
|
|
3460
|
+
["bottomRight", "bottom-right"],
|
|
3461
|
+
["bottomLeft", "bottom-left"]
|
|
3462
|
+
];
|
|
3463
|
+
/** The outline drawn as rings of its paints, when CSS outline cannot draw them. */
|
|
3464
|
+
const hasCanvasOutlinePaint = (node) => canvasStrokeElementsOf(canvasPaintElementPlanOf(node), "outline").length > 0;
|
|
3465
|
+
/** The layer stops drawing its outline; the outline's paint element draws it. */
|
|
3466
|
+
const canvasOutlinePaintOwnerDeclarations = (node) => hasCanvasOutlinePaint(node) ? { "outline-style": "none" } : {};
|
|
3467
|
+
/**
|
|
3468
|
+
* Around smoothed corners the ring's paint shows only along the smoothed contour, as the editor's
|
|
3469
|
+
* contour outline draws it: a mask strokes the contour, with the outline's dashes.
|
|
3470
|
+
*/
|
|
3471
|
+
const smoothedOutlineMaskDeclarations = (node, outline, size) => {
|
|
3472
|
+
const radius = node.appearance?.radius;
|
|
3473
|
+
if (radius === void 0) return {};
|
|
3474
|
+
const reach = outline.offset + outline.width;
|
|
3475
|
+
const pattern = canvasGeometryStrokePatternOf(outline.style, outline.width, outline);
|
|
3476
|
+
const contour = offsetCornerContour(radius, size, outline.offset + outline.width / 2);
|
|
3477
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${String(size.width + 2 * reach)}" height="${String(size.height + 2 * reach)}"><path d="${contour}" transform="translate(${String(reach)} ${String(reach)})" fill="none" stroke="#000" stroke-width="${String(outline.width)}" stroke-dasharray="${pattern.dash ?? "none"}" stroke-linecap="${pattern.linecap}"/></svg>`;
|
|
3478
|
+
return {
|
|
3479
|
+
"background-clip": "border-box",
|
|
3480
|
+
"mask-image": `url("data:image/svg+xml,${encodeURIComponent(svg)}")`,
|
|
3481
|
+
"mask-size": "100% 100%",
|
|
3482
|
+
"mask-repeat": "no-repeat",
|
|
3483
|
+
"mask-origin": "border-box"
|
|
3484
|
+
};
|
|
3485
|
+
};
|
|
3486
|
+
/**
|
|
3487
|
+
* One of the outline's paint elements: a border of the outline's width, its offset outside the
|
|
3488
|
+
* layer's border box, with the given paints stacked as backgrounds on that ring.
|
|
3489
|
+
*/
|
|
3490
|
+
const canvasOutlinePaintDeclarations = (node, size = node.box, ringPaints) => {
|
|
3491
|
+
const outline = node.appearance?.outline;
|
|
3492
|
+
const [firstRing] = canvasStrokeElementsOf(canvasPaintElementPlanOf(node), "outline");
|
|
3493
|
+
if (outline === void 0 || firstRing === void 0) return null;
|
|
3494
|
+
const reach = outline.offset + outline.width;
|
|
3495
|
+
const radius = node.appearance?.radius;
|
|
3496
|
+
const paints = ringPaints ?? firstRing;
|
|
3497
|
+
const [only] = paints;
|
|
3498
|
+
const border = node.appearance?.border;
|
|
3499
|
+
const widths = border === void 0 ? {
|
|
3500
|
+
top: 0,
|
|
3501
|
+
right: 0,
|
|
3502
|
+
bottom: 0,
|
|
3503
|
+
left: 0
|
|
3504
|
+
} : canvasBorderLayoutWidths(border);
|
|
3505
|
+
const grown = (corner) => {
|
|
3506
|
+
const value = radius?.[corner] ?? 0;
|
|
3507
|
+
return value <= 0 ? 0 : value + reach;
|
|
3508
|
+
};
|
|
3509
|
+
return {
|
|
3510
|
+
position: "absolute",
|
|
3511
|
+
top: -(widths.top + reach),
|
|
3512
|
+
right: -(widths.right + reach),
|
|
3513
|
+
bottom: -(widths.bottom + reach),
|
|
3514
|
+
left: -(widths.left + reach),
|
|
3515
|
+
"box-sizing": "border-box",
|
|
3516
|
+
"pointer-events": "none",
|
|
3517
|
+
"border-style": outline.style,
|
|
3518
|
+
"border-width": outline.width,
|
|
3519
|
+
"border-color": "transparent",
|
|
3520
|
+
...Object.fromEntries(CORNERS.map(([corner, property]) => [`border-${property}-radius`, grown(corner)])),
|
|
3521
|
+
...canvasPaintLayerDeclarations(paints),
|
|
3522
|
+
"background-origin": "border-box",
|
|
3523
|
+
"background-clip": "border-area",
|
|
3524
|
+
...paints.length === 1 && only?.blendMode !== void 0 && only.blendMode !== "normal" && { "mix-blend-mode": only.blendMode },
|
|
3525
|
+
...size !== void 0 && (radius?.smoothing ?? 0) > 0 && smoothedOutlineMaskDeclarations(node, outline, size),
|
|
3526
|
+
...size !== void 0 && (radius?.smoothing ?? 0) <= 0 && canvasDashMaskDeclarations({
|
|
3527
|
+
width: size.width + 2 * reach,
|
|
3528
|
+
height: size.height + 2 * reach,
|
|
3529
|
+
corners: {
|
|
3530
|
+
topLeft: [grown("topLeft"), grown("topLeft")],
|
|
3531
|
+
topRight: [grown("topRight"), grown("topRight")],
|
|
3532
|
+
bottomRight: [grown("bottomRight"), grown("bottomRight")],
|
|
3533
|
+
bottomLeft: [grown("bottomLeft"), grown("bottomLeft")]
|
|
3534
|
+
},
|
|
3535
|
+
widest: outline.width,
|
|
3536
|
+
stroke: outline
|
|
3537
|
+
})
|
|
3538
|
+
};
|
|
3539
|
+
};
|
|
3540
|
+
|
|
3541
|
+
//#endregion
|
|
3542
|
+
//#region ../../packages/canvas-document/src/canvas-text-paint-layers.lib.ts
|
|
3543
|
+
/** Decorated paint stacks separate glyph paint from independently colored lines. */
|
|
3544
|
+
const hasCanvasTextRunPaints = (node) => {
|
|
3545
|
+
if (hasCanvasRichTextPaints(node)) return true;
|
|
3546
|
+
if (node.typography?.decoration === void 0) return false;
|
|
3547
|
+
const paints = node.appearance?.fills?.filter((paint) => paint.visible) ?? [];
|
|
3548
|
+
return paints.length > 1 || paints.some((paint) => paint.kind !== "solid");
|
|
3549
|
+
};
|
|
3550
|
+
|
|
3551
|
+
//#endregion
|
|
3552
|
+
//#region ../../packages/canvas-document/src/canvas-appearance.lib.ts
|
|
3553
|
+
const numericRatio = (value, fallback) => {
|
|
3554
|
+
const parsed = typeof value === "number" ? value : Number(value);
|
|
3555
|
+
return Number.isFinite(parsed) ? Math.min(1, Math.max(0, parsed)) : fallback;
|
|
3556
|
+
};
|
|
3557
|
+
const blendMode = (value) => CANVAS_BLEND_MODES.find((mode) => mode === value) ?? "normal";
|
|
3558
|
+
const boundedLength = (value, minimum) => {
|
|
3559
|
+
const parsed = Number(String(value ?? "").replace("px", ""));
|
|
3560
|
+
return Number.isFinite(parsed) ? Math.max(minimum, parsed) : 0;
|
|
3561
|
+
};
|
|
3562
|
+
const numericLength = (value) => boundedLength(value, 0);
|
|
3563
|
+
const nonZeroOr = (value, fallback) => value === 0 ? fallback : value;
|
|
3564
|
+
const radiusFromStyles = (styles) => {
|
|
3565
|
+
const [first = 0, second = first, third = first, fourth = second] = String(styles["border-radius"] ?? "0").split(/\s+/u).map((value) => numericLength(value));
|
|
3566
|
+
return {
|
|
3567
|
+
topLeft: nonZeroOr(numericLength(styles["border-top-left-radius"]), first),
|
|
3568
|
+
topRight: nonZeroOr(numericLength(styles["border-top-right-radius"]), second),
|
|
3569
|
+
bottomRight: nonZeroOr(numericLength(styles["border-bottom-right-radius"]), third),
|
|
3570
|
+
bottomLeft: nonZeroOr(numericLength(styles["border-bottom-left-radius"]), fourth)
|
|
3571
|
+
};
|
|
3572
|
+
};
|
|
3573
|
+
const canvasAppearanceOf = (node) => {
|
|
3574
|
+
const empty = emptyCanvasAppearance();
|
|
3575
|
+
const border = canvasBorderOf(node);
|
|
3576
|
+
const outline = canvasOutlineOf(node);
|
|
3577
|
+
const fill = solidCanvasPaintFromCss(`${node.id}-fill`, String(node.styles[node.component === "text" ? "color" : "background"] ?? ""));
|
|
3578
|
+
const fillOwner = node.component === "text" ? null : canvasFillOwnershipOf(node);
|
|
3579
|
+
return {
|
|
3580
|
+
...empty,
|
|
3581
|
+
opacity: node.appearance?.opacity ?? numericRatio(node.styles["opacity"], 1),
|
|
3582
|
+
blendMode: node.appearance?.blendMode ?? blendMode(node.styles["mix-blend-mode"]),
|
|
3583
|
+
fills: fillOwner?.kind === "native" ? [...fillOwner.fills] : node.appearance?.fills ?? (fill === null ? [] : [fill]),
|
|
3584
|
+
border: border.kind === "native" ? border.value : node.appearance?.border ?? empty.border,
|
|
3585
|
+
outline: outline.kind === "native" ? outline.value : node.appearance?.outline ?? empty.outline,
|
|
3586
|
+
radius: node.appearance?.radius ?? radiusFromStyles(node.styles),
|
|
3587
|
+
...node.appearance?.retainedBorder !== void 0 && { retainedBorder: node.appearance.retainedBorder },
|
|
3588
|
+
shadows: node.appearance?.shadows ?? [],
|
|
3589
|
+
filters: node.appearance?.filters ?? [],
|
|
3590
|
+
backdropFilters: node.appearance?.backdropFilters ?? []
|
|
3591
|
+
};
|
|
3592
|
+
};
|
|
3593
|
+
const fillDeclarations = (node) => {
|
|
3594
|
+
const fills = node.appearance?.fills;
|
|
3595
|
+
if (node.component === "text" && hasCanvasTextRunPaints(node)) return {
|
|
3596
|
+
...fills !== void 0 && { color: canvasTextPaintDeclarations(fills)["color"] ?? "transparent" },
|
|
3597
|
+
"background-image": "none"
|
|
3598
|
+
};
|
|
3599
|
+
return fills === void 0 ? {} : node.component === "text" ? canvasTextPaintDeclarations(fills) : canvasPaintDeclarations(fills);
|
|
3600
|
+
};
|
|
3601
|
+
const canvasAppearanceDeclarations = (node) => {
|
|
3602
|
+
const appearance = node.appearance;
|
|
3603
|
+
const declarations = {
|
|
3604
|
+
...fillDeclarations(node),
|
|
3605
|
+
...canvasFillOwnerDeclarations(node)
|
|
3606
|
+
};
|
|
3607
|
+
if ((appearance?.opacity ?? numericRatio(node.styles["opacity"], 1)) === 0) declarations["pointer-events"] = "none";
|
|
3608
|
+
if (appearance === void 0) return declarations;
|
|
3609
|
+
if (appearance.opacity !== void 0) declarations["opacity"] = appearance.opacity;
|
|
3610
|
+
if (appearance.blendMode !== void 0) declarations["mix-blend-mode"] = appearance.blendMode;
|
|
3611
|
+
if (appearance.radius !== void 0 && node.geometry?.kind !== "path") Object.assign(declarations, canvasCornerRadiusDeclarations(appearance.radius), canvasCornerShapeDeclarations(node));
|
|
3612
|
+
Object.assign(declarations, canvasBoxDecorationDeclarations(appearance), canvasBoxStrokeRootDeclarations(node), canvasOutlinePaintOwnerDeclarations(node));
|
|
3613
|
+
if (appearance.filters !== void 0) declarations["filter"] = canvasFilterListCss(appearance.filters);
|
|
3614
|
+
if (appearance.shadows !== void 0) Object.assign(declarations, canvasShadowDeclarations(node, appearance.shadows));
|
|
3615
|
+
if (appearance.backdropFilters !== void 0) declarations["backdrop-filter"] = canvasFilterListCss(canvasUniformBackdropFilters(node, appearance.backdropFilters));
|
|
3616
|
+
return declarations;
|
|
3617
|
+
};
|
|
3618
|
+
|
|
3619
|
+
//#endregion
|
|
3620
|
+
//#region ../../packages/canvas-document/src/canvas-mask-source.lib.ts
|
|
3621
|
+
const hasSquareCorners = (node) => {
|
|
3622
|
+
const radius = canvasAppearanceOf(node).radius;
|
|
3623
|
+
return radius.topLeft === 0 && radius.topRight === 0 && radius.bottomRight === 0 && radius.bottomLeft === 0;
|
|
3624
|
+
};
|
|
3625
|
+
/** Text masks through background-clip, which shows only a layer's own fills. */
|
|
3626
|
+
const isFillOnly = (node) => {
|
|
3627
|
+
const appearance = canvasAppearanceOf(node);
|
|
3628
|
+
return canvasBorderOf(node).kind !== "native" && canvasOutlineOf(node).kind !== "native" && appearance.shadows.every((shadow) => !shadow.visible) && appearance.filters.every((filter) => !filter.visible) && appearance.backdropFilters.every((filter) => !filter.visible);
|
|
3629
|
+
};
|
|
3630
|
+
/** Whether text can mask the layer: an image or unrounded rectangle whose paint is fills only. */
|
|
3631
|
+
const canCanvasTextMask = (node) => node !== void 0 && (node.component === "image" || node.component === "rectangle" && hasSquareCorners(node)) && isFillOnly(node);
|
|
3632
|
+
|
|
3633
|
+
//#endregion
|
|
3634
|
+
//#region ../../packages/canvas-document/src/canvas-text-mask.lib.ts
|
|
3635
|
+
/** A native image layer's stored natural size, written when the image was added or imported. */
|
|
3636
|
+
const nativeImageSizeOf = (node) => {
|
|
3637
|
+
const width = node.props?.["naturalWidth"];
|
|
3638
|
+
const height = node.props?.["naturalHeight"];
|
|
3639
|
+
return typeof width === "number" && typeof height === "number" && width > 0 && height > 0 ? {
|
|
3640
|
+
width,
|
|
3641
|
+
height
|
|
3642
|
+
} : void 0;
|
|
3643
|
+
};
|
|
3644
|
+
const textMaskGroupOf = (document, node) => {
|
|
3645
|
+
if (node.component !== "text") return void 0;
|
|
3646
|
+
const parentId = document.relationships[node.id]?.parentId;
|
|
3647
|
+
const parent = parentId === void 0 ? void 0 : document.nodes[parentId];
|
|
3648
|
+
return parent?.geometry?.kind === "mask" && parent.geometry.maskId === node.id ? parent : void 0;
|
|
3649
|
+
};
|
|
3650
|
+
/**
|
|
3651
|
+
* The layers a text mask source shows through its letters, backmost first, when it masks only
|
|
3652
|
+
* images and unrounded rectangles whose paint is fills; otherwise null.
|
|
3653
|
+
*/
|
|
3654
|
+
const canvasTextMaskContentsOf = (document, node) => {
|
|
3655
|
+
const group = textMaskGroupOf(document, node);
|
|
3656
|
+
if (group === void 0) return null;
|
|
3657
|
+
const contents = childIdsOf(document.relationships, group.id).flatMap((id) => id === node.id ? [] : document.nodes[id] ?? []);
|
|
3658
|
+
const text = node.box;
|
|
3659
|
+
return text !== void 0 && contents.length > 0 && contents.every((content) => canCanvasTextMask(content) && layersOf(content, text) !== null) ? contents : null;
|
|
3660
|
+
};
|
|
3661
|
+
/** Where an image of the given natural size draws within a box, for each fit. */
|
|
3662
|
+
const fittedBox = (fit, box, natural) => {
|
|
3663
|
+
const scale = (fit === "cover" ? Math.max : Math.min)(box.width / natural.width, box.height / natural.height);
|
|
3664
|
+
const width = natural.width * scale;
|
|
3665
|
+
const height = natural.height * scale;
|
|
3666
|
+
return {
|
|
3667
|
+
x: box.x + (box.width - width) / 2,
|
|
3668
|
+
y: box.y + (box.height - height) / 2,
|
|
3669
|
+
width,
|
|
3670
|
+
height
|
|
3671
|
+
};
|
|
3672
|
+
};
|
|
3673
|
+
/** One image fill placed in the content's box, or null when its natural size is unknown. */
|
|
3674
|
+
const imageLayer = (paint, box) => {
|
|
3675
|
+
const image = canvasPaintLayerCss(paint);
|
|
3676
|
+
if (paint.fit === "fill") return {
|
|
3677
|
+
image,
|
|
3678
|
+
box
|
|
3679
|
+
};
|
|
3680
|
+
if (paint.fit === "crop" && paint.crop !== void 0) {
|
|
3681
|
+
const width = box.width / Math.max(paint.crop.width, Number.EPSILON);
|
|
3682
|
+
const height = box.height / Math.max(paint.crop.height, Number.EPSILON);
|
|
3683
|
+
return {
|
|
3684
|
+
image,
|
|
3685
|
+
box: {
|
|
3686
|
+
x: box.x - paint.crop.x * width,
|
|
3687
|
+
y: box.y - paint.crop.y * height,
|
|
3688
|
+
width,
|
|
3689
|
+
height
|
|
3690
|
+
}
|
|
3691
|
+
};
|
|
3692
|
+
}
|
|
3693
|
+
const natural = paint.naturalSize;
|
|
3694
|
+
if (natural === void 0) return null;
|
|
3695
|
+
if (paint.fit === "tile") {
|
|
3696
|
+
const scale = paint.tileScale ?? 1;
|
|
3697
|
+
return {
|
|
3698
|
+
image,
|
|
3699
|
+
box: {
|
|
3700
|
+
x: box.x,
|
|
3701
|
+
y: box.y,
|
|
3702
|
+
width: natural.width * scale,
|
|
3703
|
+
height: natural.height * scale
|
|
3704
|
+
},
|
|
3705
|
+
repeat: "repeat"
|
|
3706
|
+
};
|
|
3707
|
+
}
|
|
3708
|
+
return {
|
|
3709
|
+
image,
|
|
3710
|
+
box: fittedBox(paint.fit === "fit" ? "fit" : "cover", box, natural)
|
|
3711
|
+
};
|
|
3712
|
+
};
|
|
3713
|
+
/** A native image layer's source placed in its box, or null when its natural size is unknown. */
|
|
3714
|
+
const nativeImageLayer = (node, box) => {
|
|
3715
|
+
const source = node.props?.["src"];
|
|
3716
|
+
if (typeof source !== "string" || source === "") return [];
|
|
3717
|
+
const image = canvasPaintImageUrl(source);
|
|
3718
|
+
const fit = node.props?.["fit"];
|
|
3719
|
+
if (fit !== "cover" && fit !== "contain") return [{
|
|
3720
|
+
image,
|
|
3721
|
+
box
|
|
3722
|
+
}];
|
|
3723
|
+
const natural = nativeImageSizeOf(node);
|
|
3724
|
+
return natural === void 0 ? null : [{
|
|
3725
|
+
image,
|
|
3726
|
+
box: fittedBox(fit === "cover" ? "cover" : "fit", box, natural)
|
|
3727
|
+
}];
|
|
3728
|
+
};
|
|
3729
|
+
/** A content layer's visible fills as layers in the text's box, topmost first. */
|
|
3730
|
+
const layersOf = (content, text) => {
|
|
3731
|
+
if (content.box === void 0) return [];
|
|
3732
|
+
const box = {
|
|
3733
|
+
...content.box,
|
|
3734
|
+
x: content.box.x - text.x,
|
|
3735
|
+
y: content.box.y - text.y
|
|
3736
|
+
};
|
|
3737
|
+
if (content.component === "image" && content.appearance?.fills === void 0) return nativeImageLayer(content, box);
|
|
3738
|
+
const { opacity } = canvasAppearanceOf(content);
|
|
3739
|
+
const layers = [];
|
|
3740
|
+
const fills = canvasAppearanceOf(content).fills.filter((held) => held.visible).toReversed();
|
|
3741
|
+
for (const paint of fills) if (paint.kind === "image") {
|
|
3742
|
+
const layer = imageLayer(paint, box);
|
|
3743
|
+
if (layer === null) return null;
|
|
3744
|
+
layers.push(layer);
|
|
3745
|
+
} else layers.push({
|
|
3746
|
+
image: canvasPaintLayerCss({
|
|
3747
|
+
...paint,
|
|
3748
|
+
opacity: paint.opacity * opacity
|
|
3749
|
+
}),
|
|
3750
|
+
box
|
|
3751
|
+
});
|
|
3752
|
+
return layers;
|
|
3753
|
+
};
|
|
3754
|
+
|
|
3755
|
+
//#endregion
|
|
3756
|
+
//#region ../../packages/canvas-document/src/canvas-geometry-clip.lib.ts
|
|
3757
|
+
const canvasMaskSourceOf = (document, node) => node.geometry?.kind === "mask" ? document.nodes[node.geometry.maskId] : void 0;
|
|
3758
|
+
const IDENTITY = {
|
|
3759
|
+
a: 1,
|
|
3760
|
+
b: 0,
|
|
3761
|
+
c: 0,
|
|
3762
|
+
d: 1,
|
|
3763
|
+
e: 0,
|
|
3764
|
+
f: 0
|
|
3765
|
+
};
|
|
3766
|
+
const multiplied = (left, right) => ({
|
|
3767
|
+
a: left.a * right.a + left.c * right.b,
|
|
3768
|
+
b: left.b * right.a + left.d * right.b,
|
|
3769
|
+
c: left.a * right.c + left.c * right.d,
|
|
3770
|
+
d: left.b * right.c + left.d * right.d,
|
|
3771
|
+
e: left.a * right.e + left.c * right.f + left.e,
|
|
3772
|
+
f: left.b * right.e + left.d * right.f + left.f
|
|
3773
|
+
});
|
|
3774
|
+
/** The alpha of a layer's own fills stacked over each other, then its opacity. */
|
|
3775
|
+
const fillAlphaOf = (node) => {
|
|
3776
|
+
const { fills, opacity } = canvasAppearanceOf(node);
|
|
3777
|
+
return (1 - fills.filter((paint) => paint.visible).reduce((held, paint) => held * (1 - paint.opacity * (paint.kind === "solid" ? paint.color.alpha : 1)), 1)) * opacity;
|
|
3778
|
+
};
|
|
3779
|
+
const maskShapeOf = (operand, parent, opacity) => {
|
|
3780
|
+
const [a, b, c, d, e, f] = operand.matrix;
|
|
3781
|
+
const placed = multiplied(parent, {
|
|
3782
|
+
a,
|
|
3783
|
+
b,
|
|
3784
|
+
c,
|
|
3785
|
+
d,
|
|
3786
|
+
e,
|
|
3787
|
+
f
|
|
3788
|
+
});
|
|
3789
|
+
return {
|
|
3790
|
+
path: operand.path,
|
|
3791
|
+
fillRule: operand.fillRule,
|
|
3792
|
+
transform: `matrix(${[
|
|
3793
|
+
placed.a,
|
|
3794
|
+
placed.b,
|
|
3795
|
+
placed.c,
|
|
3796
|
+
placed.d,
|
|
3797
|
+
placed.e,
|
|
3798
|
+
placed.f
|
|
3799
|
+
].map(String).join(" ")})`,
|
|
3800
|
+
opacity
|
|
3801
|
+
};
|
|
3802
|
+
};
|
|
3803
|
+
/**
|
|
3804
|
+
* The shapes of a group mask source, placed in the space of the source's parent, backmost first.
|
|
3805
|
+
* A frame counts as its own box and fill, then its children. Null when the source is no group.
|
|
3806
|
+
*/
|
|
3807
|
+
const canvasGroupMaskShapesOf = (document, source) => {
|
|
3808
|
+
if (source.component !== "group" || source.geometry !== void 0) return null;
|
|
3809
|
+
const shapes = [];
|
|
3810
|
+
const visit = (node, parent, alpha) => {
|
|
3811
|
+
if (node.visible === false) return;
|
|
3812
|
+
const isGroup = node.component === "group" && node.geometry === void 0;
|
|
3813
|
+
const operand = isGroup ? null : canvasShapeOperandOf(node);
|
|
3814
|
+
if (operand !== null && typeof operand !== "string") shapes.push(maskShapeOf(operand, parent, alpha * fillAlphaOf(node)));
|
|
3815
|
+
if (!isGroup && node.component !== "frame") return;
|
|
3816
|
+
const local = canvasNodeLocalMatrixOf(node);
|
|
3817
|
+
if (local === null) return;
|
|
3818
|
+
const placed = multiplied(parent, local);
|
|
3819
|
+
const opacity = alpha * canvasAppearanceOf(node).opacity;
|
|
3820
|
+
for (const childId of childIdsOf(document.relationships, node.id)) {
|
|
3821
|
+
const child = document.nodes[childId];
|
|
3822
|
+
if (child !== void 0) visit(child, placed, opacity);
|
|
3823
|
+
}
|
|
3824
|
+
};
|
|
3825
|
+
visit(source, IDENTITY, 1);
|
|
3826
|
+
return shapes;
|
|
3827
|
+
};
|
|
3828
|
+
const HASH_SEED = 2166136261;
|
|
3829
|
+
const HASH_PRIME = 16777619;
|
|
3830
|
+
const HASH_RADIX = 16;
|
|
3831
|
+
const clipIdentity = (encoded) => {
|
|
3832
|
+
let hash = HASH_SEED;
|
|
3833
|
+
for (const character of encoded) hash = Math.imul(hash ^ (character.codePointAt(0) ?? 0), HASH_PRIME);
|
|
3834
|
+
return (hash >>> 0).toString(HASH_RADIX);
|
|
3835
|
+
};
|
|
3836
|
+
/**
|
|
3837
|
+
* Text that masks images and filled rectangles shows them in its letters, so the group needs no
|
|
3838
|
+
* clip. Over other content, text clips it to the text's box.
|
|
3839
|
+
*/
|
|
3840
|
+
const textMaskClipOf = (document, source, box) => {
|
|
3841
|
+
if (canvasTextMaskContentsOf(document, source) !== null) return null;
|
|
3842
|
+
const text = source.box;
|
|
3843
|
+
if (text === void 0) return {
|
|
3844
|
+
path: "",
|
|
3845
|
+
fillRule: "nonzero",
|
|
3846
|
+
matrix: [
|
|
3847
|
+
1,
|
|
3848
|
+
0,
|
|
3849
|
+
0,
|
|
3850
|
+
1,
|
|
3851
|
+
0,
|
|
3852
|
+
0
|
|
3853
|
+
]
|
|
3854
|
+
};
|
|
3855
|
+
const { width, height } = text;
|
|
3856
|
+
return {
|
|
3857
|
+
path: `M0 0H${String(width)}V${String(height)}H0Z`,
|
|
3858
|
+
fillRule: "nonzero",
|
|
3859
|
+
matrix: [
|
|
3860
|
+
1 / box.width,
|
|
3861
|
+
0,
|
|
3862
|
+
0,
|
|
3863
|
+
1 / box.height,
|
|
3864
|
+
text.x / box.width,
|
|
3865
|
+
text.y / box.height
|
|
3866
|
+
]
|
|
3867
|
+
};
|
|
3868
|
+
};
|
|
3869
|
+
const clipPartsOf = (document, node, maskSource) => {
|
|
3870
|
+
const geometry = node.geometry;
|
|
3871
|
+
const box = node.box;
|
|
3872
|
+
if (geometry === void 0 || box === void 0 || box.width <= 0 || box.height <= 0) return null;
|
|
3873
|
+
if (geometry.kind === "path" || geometry.kind === "polygon") {
|
|
3874
|
+
const contour = canvasShapePathOf(node);
|
|
3875
|
+
if (typeof contour === "string") return null;
|
|
3876
|
+
const view = contour.viewBox;
|
|
3877
|
+
return {
|
|
3878
|
+
path: contour.path,
|
|
3879
|
+
fillRule: contour.fillRule,
|
|
3880
|
+
matrix: [
|
|
3881
|
+
1 / view.width,
|
|
3882
|
+
0,
|
|
3883
|
+
0,
|
|
3884
|
+
1 / view.height,
|
|
3885
|
+
-view.x / view.width,
|
|
3886
|
+
-view.y / view.height
|
|
3887
|
+
]
|
|
3888
|
+
};
|
|
812
3889
|
}
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
3890
|
+
if (geometry.kind === "boolean") {
|
|
3891
|
+
const contour = canvasShapePathOf(node);
|
|
3892
|
+
return {
|
|
3893
|
+
path: typeof contour === "string" ? "" : contour.path,
|
|
3894
|
+
fillRule: geometry.result.fillRule,
|
|
3895
|
+
matrix: [
|
|
3896
|
+
1 / box.width,
|
|
3897
|
+
0,
|
|
3898
|
+
0,
|
|
3899
|
+
1 / box.height,
|
|
3900
|
+
0,
|
|
3901
|
+
0
|
|
3902
|
+
]
|
|
3903
|
+
};
|
|
3904
|
+
}
|
|
3905
|
+
const source = maskSource ?? canvasMaskSourceOf(document, node);
|
|
3906
|
+
if (source?.component === "text" && source.visible !== false) return textMaskClipOf(document, source, box);
|
|
3907
|
+
const shapes = source === void 0 || source.visible === false ? null : canvasGroupMaskShapesOf(document, source);
|
|
3908
|
+
if (shapes !== null) return {
|
|
3909
|
+
path: "",
|
|
3910
|
+
fillRule: "nonzero",
|
|
3911
|
+
matrix: [
|
|
3912
|
+
1 / box.width,
|
|
3913
|
+
0,
|
|
3914
|
+
0,
|
|
3915
|
+
1 / box.height,
|
|
3916
|
+
0,
|
|
3917
|
+
0
|
|
3918
|
+
],
|
|
3919
|
+
shapes
|
|
3920
|
+
};
|
|
3921
|
+
const operand = source === void 0 || source.visible === false ? null : canvasShapeOperandOf(source);
|
|
3922
|
+
if (operand === null || typeof operand === "string") return {
|
|
3923
|
+
path: "",
|
|
3924
|
+
fillRule: "nonzero",
|
|
3925
|
+
matrix: [
|
|
3926
|
+
1,
|
|
3927
|
+
0,
|
|
3928
|
+
0,
|
|
3929
|
+
1,
|
|
3930
|
+
0,
|
|
3931
|
+
0
|
|
3932
|
+
]
|
|
3933
|
+
};
|
|
3934
|
+
const [a, b, c, d, e, f] = operand.matrix;
|
|
817
3935
|
return {
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
3936
|
+
path: operand.path,
|
|
3937
|
+
fillRule: operand.fillRule,
|
|
3938
|
+
matrix: [
|
|
3939
|
+
a / box.width,
|
|
3940
|
+
b / box.height,
|
|
3941
|
+
c / box.width,
|
|
3942
|
+
d / box.height,
|
|
3943
|
+
e / box.width,
|
|
3944
|
+
f / box.height
|
|
3945
|
+
]
|
|
823
3946
|
};
|
|
824
3947
|
};
|
|
825
|
-
const
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
const
|
|
3948
|
+
const canvasGeometryClipOf = (document, node, maskSource) => {
|
|
3949
|
+
const parts = clipPartsOf(document, node, maskSource);
|
|
3950
|
+
if (parts === null) return null;
|
|
3951
|
+
const { path, fillRule, matrix, shapes } = parts;
|
|
3952
|
+
const transform = `matrix(${matrix.map(String).join(" ")})`;
|
|
829
3953
|
return {
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
}
|
|
841
|
-
moves,
|
|
842
|
-
affectedParents: Array.from(state.affected, (parentId) => ({
|
|
843
|
-
parentId,
|
|
844
|
-
children: [...state.children.get(parentId) ?? []]
|
|
845
|
-
}))
|
|
3954
|
+
id: `canvas-geometry-${encodeURIComponent(node.id).replaceAll("%", "_")}-${clipIdentity(JSON.stringify([
|
|
3955
|
+
path,
|
|
3956
|
+
fillRule,
|
|
3957
|
+
transform,
|
|
3958
|
+
shapes
|
|
3959
|
+
]))}`,
|
|
3960
|
+
path,
|
|
3961
|
+
fillRule,
|
|
3962
|
+
transform,
|
|
3963
|
+
matrix,
|
|
3964
|
+
...shapes !== void 0 && { shapes }
|
|
846
3965
|
};
|
|
847
3966
|
};
|
|
848
3967
|
|
|
@@ -928,14 +4047,11 @@ const operationsForNode = (document, node, source) => {
|
|
|
928
4047
|
else next.styles[property] = value;
|
|
929
4048
|
const layout = layoutOperation(document, node, next, source);
|
|
930
4049
|
const typography = canvasTypographyOperation(node, styles);
|
|
931
|
-
const
|
|
932
|
-
|
|
933
|
-
"background-color",
|
|
934
|
-
"background-image"
|
|
935
|
-
]).some((property) => Object.hasOwn(styles, property)) && node.appearance?.fills !== void 0 ? [{
|
|
4050
|
+
const replaced = canvasAppearanceOwnedBy(node, Object.keys(styles));
|
|
4051
|
+
const clearNative = replaced.length > 0 ? [{
|
|
936
4052
|
op: "setAppearance",
|
|
937
4053
|
nodeId: node.id,
|
|
938
|
-
appearance: { clear: [
|
|
4054
|
+
appearance: { clear: [...replaced] }
|
|
939
4055
|
}] : [];
|
|
940
4056
|
return [
|
|
941
4057
|
...Object.keys(stylePatch).length > 0 ? [{
|
|
@@ -943,7 +4059,7 @@ const operationsForNode = (document, node, source) => {
|
|
|
943
4059
|
nodeId: node.id,
|
|
944
4060
|
styles: canvasNodeStylePatchSchema.parse(stylePatch)
|
|
945
4061
|
}] : [],
|
|
946
|
-
...
|
|
4062
|
+
...clearNative,
|
|
947
4063
|
...typography === null ? [] : [typography],
|
|
948
4064
|
...layout === null ? [] : [layout],
|
|
949
4065
|
...additional === null ? [] : [additional]
|
|
@@ -1325,7 +4441,7 @@ const createEditCanvasComposite = (remote) => ({ execute: async (input) => {
|
|
|
1325
4441
|
const parsed = applyCanvasOperationsInputSchema.safeParse({
|
|
1326
4442
|
canvasId: input.canvasId,
|
|
1327
4443
|
mutationId: input.mutationId,
|
|
1328
|
-
documentFormatVersion:
|
|
4444
|
+
documentFormatVersion: 13,
|
|
1329
4445
|
baseVersion: input.baseVersion,
|
|
1330
4446
|
operations: plan.operations
|
|
1331
4447
|
});
|
|
@@ -2731,7 +5847,7 @@ const commitPreparation = async (remote, input, job, fingerprint) => {
|
|
|
2731
5847
|
const request = applyCanvasOperationsInputSchema.parse({
|
|
2732
5848
|
canvasId: job.canvasId,
|
|
2733
5849
|
mutationId: input.clientToken,
|
|
2734
|
-
documentFormatVersion:
|
|
5850
|
+
documentFormatVersion: 13,
|
|
2735
5851
|
baseVersion: input.baseVersion,
|
|
2736
5852
|
operations: job.result.operations,
|
|
2737
5853
|
requestContext: {
|
|
@@ -2788,81 +5904,288 @@ const createPrepareCanvasCommandComposite = (remote) => ({ execute: async (input
|
|
|
2788
5904
|
} });
|
|
2789
5905
|
|
|
2790
5906
|
//#endregion
|
|
2791
|
-
//#region src/
|
|
5907
|
+
//#region ../../packages/canvas-document/src/canvas-path-transform.lib.ts
|
|
5908
|
+
const COMMAND = /^[MLHVCSQTAZ]$/iu;
|
|
5909
|
+
const TOKENS = /[MLHVCSQTAZ]|[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/giu;
|
|
5910
|
+
const ARGUMENTS = {
|
|
5911
|
+
M: 2,
|
|
5912
|
+
L: 2,
|
|
5913
|
+
H: 1,
|
|
5914
|
+
V: 1,
|
|
5915
|
+
C: 6,
|
|
5916
|
+
S: 4,
|
|
5917
|
+
Q: 4,
|
|
5918
|
+
T: 2,
|
|
5919
|
+
A: 7,
|
|
5920
|
+
Z: 0
|
|
5921
|
+
};
|
|
5922
|
+
/** The path's commands with their arguments; a command's repeated arguments are new segments. */
|
|
5923
|
+
const segmentsOf = (path) => {
|
|
5924
|
+
const tokens = path.match(TOKENS) ?? [];
|
|
5925
|
+
if (tokens.join("") !== path.replaceAll(/[\s,]/gu, "")) return null;
|
|
5926
|
+
const segments = [];
|
|
5927
|
+
let command = "";
|
|
5928
|
+
let index = 0;
|
|
5929
|
+
while (index < tokens.length) {
|
|
5930
|
+
const token = tokens[index] ?? "";
|
|
5931
|
+
if (COMMAND.test(token)) {
|
|
5932
|
+
command = token;
|
|
5933
|
+
index += 1;
|
|
5934
|
+
} else if (command === "" || command.toUpperCase() === "Z") return null;
|
|
5935
|
+
const count = ARGUMENTS[command.toUpperCase()] ?? 0;
|
|
5936
|
+
const values = tokens.slice(index, index + count).map(Number);
|
|
5937
|
+
if (values.length !== count || values.some((value) => !Number.isFinite(value))) return null;
|
|
5938
|
+
index += count;
|
|
5939
|
+
segments.push({
|
|
5940
|
+
command,
|
|
5941
|
+
values
|
|
5942
|
+
});
|
|
5943
|
+
if (command.toUpperCase() === "M") command = command === "M" ? "L" : "l";
|
|
5944
|
+
}
|
|
5945
|
+
return segments;
|
|
5946
|
+
};
|
|
5947
|
+
const applied = ([a, b, c, d, e, f], { x, y }) => ({
|
|
5948
|
+
x: a * x + c * y + e,
|
|
5949
|
+
y: b * x + d * y + f
|
|
5950
|
+
});
|
|
5951
|
+
const format = (point) => `${String(point.x)} ${String(point.y)}`;
|
|
5952
|
+
const HALF_TURN_DEGREES = 180;
|
|
5953
|
+
const QUARTERS = 4;
|
|
5954
|
+
const CUBIC_POINTS = 3;
|
|
5955
|
+
const QUARTER_TURN = Math.PI / 2;
|
|
5956
|
+
const FULL_TURN = Math.PI * 2;
|
|
5957
|
+
/** Below this, an arc's last quarter is rounding, not a turn. */
|
|
5958
|
+
const TURN_TOLERANCE = 1e-9;
|
|
5959
|
+
const turnBetween = (ux, uy, vx, vy) => Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);
|
|
5960
|
+
/**
|
|
5961
|
+
* The ellipse an arc lies on, as the matrix that places the unit circle there, and the turn the
|
|
5962
|
+
* arc makes on it from its start angle (SVG 2, appendix B.2.4, with radii scaled up to reach).
|
|
5963
|
+
*/
|
|
5964
|
+
const arcEllipseOf = (from, values, end) => {
|
|
5965
|
+
const [rx0 = 0, ry0 = 0, degrees = 0, large = 0, sweep = 0] = values;
|
|
5966
|
+
const phi = degrees * Math.PI / HALF_TURN_DEGREES;
|
|
5967
|
+
const [cos, sin] = [Math.cos(phi), Math.sin(phi)];
|
|
5968
|
+
const [dx, dy] = [(from.x - end.x) / 2, (from.y - end.y) / 2];
|
|
5969
|
+
const [x1, y1] = [cos * dx + sin * dy, -sin * dx + cos * dy];
|
|
5970
|
+
const reach = Math.max(1, Math.hypot(x1 / rx0, y1 / ry0));
|
|
5971
|
+
const [rx, ry] = [Math.abs(rx0) * reach, Math.abs(ry0) * reach];
|
|
5972
|
+
const spread = rx * rx * y1 * y1 + ry * ry * x1 * x1;
|
|
5973
|
+
const root = (large === sweep ? -1 : 1) * Math.sqrt(Math.max(0, (rx * rx * ry * ry - spread) / spread));
|
|
5974
|
+
const [cx, cy] = [root * rx * y1 / ry, -root * ry * x1 / rx];
|
|
5975
|
+
const [ux, uy, vx, vy] = [
|
|
5976
|
+
(x1 - cx) / rx,
|
|
5977
|
+
(y1 - cy) / ry,
|
|
5978
|
+
(-x1 - cx) / rx,
|
|
5979
|
+
(-y1 - cy) / ry
|
|
5980
|
+
];
|
|
5981
|
+
let turn = turnBetween(ux, uy, vx, vy);
|
|
5982
|
+
if (sweep === 0 && turn > 0) turn -= FULL_TURN;
|
|
5983
|
+
if (sweep === 1 && turn < 0) turn += FULL_TURN;
|
|
5984
|
+
return {
|
|
5985
|
+
ellipse: [
|
|
5986
|
+
cos * rx,
|
|
5987
|
+
sin * rx,
|
|
5988
|
+
-sin * ry,
|
|
5989
|
+
cos * ry,
|
|
5990
|
+
cos * cx - sin * cy + (from.x + end.x) / 2,
|
|
5991
|
+
sin * cx + cos * cy + (from.y + end.y) / 2
|
|
5992
|
+
],
|
|
5993
|
+
start: turnBetween(1, 0, ux, uy),
|
|
5994
|
+
turn
|
|
5995
|
+
};
|
|
5996
|
+
};
|
|
5997
|
+
/**
|
|
5998
|
+
* An arc as cubic curves of at most a quarter turn each, as SVG renderers draw it; each is within
|
|
5999
|
+
* 0.03% of the radius of the true arc, and a matrix places curves exactly.
|
|
6000
|
+
*/
|
|
6001
|
+
const arcCurves = (from, values, end) => {
|
|
6002
|
+
const [rx = 0, ry = 0] = values;
|
|
6003
|
+
if (rx === 0 || ry === 0 || from.x === end.x && from.y === end.y) return [
|
|
6004
|
+
from,
|
|
6005
|
+
end,
|
|
6006
|
+
end
|
|
6007
|
+
];
|
|
6008
|
+
const { ellipse, start, turn } = arcEllipseOf(from, values, end);
|
|
6009
|
+
const count = Math.ceil(Math.abs(turn) / QUARTER_TURN - TURN_TOLERANCE);
|
|
6010
|
+
const step = turn / count;
|
|
6011
|
+
const handle = QUARTERS / CUBIC_POINTS * Math.tan(step / QUARTERS);
|
|
6012
|
+
const unit = (theta, length) => ({
|
|
6013
|
+
x: Math.cos(theta) - Math.sin(theta) * length,
|
|
6014
|
+
y: Math.sin(theta) + Math.cos(theta) * length
|
|
6015
|
+
});
|
|
6016
|
+
const points = [];
|
|
6017
|
+
for (let index = 0; index < count; index += 1) {
|
|
6018
|
+
const [before, after] = [start + step * index, start + step * (index + 1)];
|
|
6019
|
+
points.push(applied(ellipse, unit(before, handle)), applied(ellipse, unit(after, -handle)), index === count - 1 ? end : applied(ellipse, unit(after, 0)));
|
|
6020
|
+
}
|
|
6021
|
+
return points;
|
|
6022
|
+
};
|
|
6023
|
+
/** One segment in absolute coordinates of the matrix's space, and where it leaves the pen. */
|
|
6024
|
+
const placed = (segment, pen, matrix) => {
|
|
6025
|
+
const upper = segment.command.toUpperCase();
|
|
6026
|
+
const isRelative = segment.command !== upper;
|
|
6027
|
+
const { current } = pen;
|
|
6028
|
+
const at = (x = 0, y = 0) => isRelative ? {
|
|
6029
|
+
x: current.x + x,
|
|
6030
|
+
y: current.y + y
|
|
6031
|
+
} : {
|
|
6032
|
+
x,
|
|
6033
|
+
y
|
|
6034
|
+
};
|
|
6035
|
+
const [first = 0] = segment.values;
|
|
6036
|
+
if (upper === "Z") return {
|
|
6037
|
+
data: "Z",
|
|
6038
|
+
pen: {
|
|
6039
|
+
...pen,
|
|
6040
|
+
current: pen.start
|
|
6041
|
+
}
|
|
6042
|
+
};
|
|
6043
|
+
if (upper === "A") {
|
|
6044
|
+
const end = at(segment.values[5], segment.values[6]);
|
|
6045
|
+
const points = arcCurves(current, segment.values, end);
|
|
6046
|
+
const curves = [];
|
|
6047
|
+
for (let offset = 0; offset < points.length; offset += CUBIC_POINTS) curves.push(`C${points.slice(offset, offset + CUBIC_POINTS).map((point) => format(applied(matrix, point))).join(" ")}`);
|
|
6048
|
+
return {
|
|
6049
|
+
data: curves.join(""),
|
|
6050
|
+
pen: {
|
|
6051
|
+
...pen,
|
|
6052
|
+
current: end
|
|
6053
|
+
}
|
|
6054
|
+
};
|
|
6055
|
+
}
|
|
6056
|
+
if (upper === "H" || upper === "V") {
|
|
6057
|
+
const end = upper === "H" ? at(first, isRelative ? 0 : current.y) : at(isRelative ? 0 : current.x, first);
|
|
6058
|
+
return {
|
|
6059
|
+
data: `L${format(applied(matrix, end))}`,
|
|
6060
|
+
pen: {
|
|
6061
|
+
...pen,
|
|
6062
|
+
current: end
|
|
6063
|
+
}
|
|
6064
|
+
};
|
|
6065
|
+
}
|
|
6066
|
+
const points = [];
|
|
6067
|
+
for (let offset = 0; offset < segment.values.length; offset += 2) points.push(at(segment.values[offset], segment.values[offset + 1]));
|
|
6068
|
+
const end = points.at(-1) ?? current;
|
|
6069
|
+
return {
|
|
6070
|
+
data: `${upper}${points.map((point) => format(applied(matrix, point))).join(" ")}`,
|
|
6071
|
+
pen: {
|
|
6072
|
+
current: end,
|
|
6073
|
+
start: upper === "M" ? end : pen.start
|
|
6074
|
+
}
|
|
6075
|
+
};
|
|
6076
|
+
};
|
|
6077
|
+
/**
|
|
6078
|
+
* The path drawn in the matrix's space, with absolute coordinates and arcs as cubic curves. Null
|
|
6079
|
+
* when the path cannot be read.
|
|
6080
|
+
*/
|
|
6081
|
+
const canvasPathTransformedBy = (path, matrix) => {
|
|
6082
|
+
const segments = segmentsOf(path);
|
|
6083
|
+
if (segments === null) return null;
|
|
6084
|
+
const parts = [];
|
|
6085
|
+
let pen = {
|
|
6086
|
+
current: {
|
|
6087
|
+
x: 0,
|
|
6088
|
+
y: 0
|
|
6089
|
+
},
|
|
6090
|
+
start: {
|
|
6091
|
+
x: 0,
|
|
6092
|
+
y: 0
|
|
6093
|
+
}
|
|
6094
|
+
};
|
|
6095
|
+
for (const segment of segments) {
|
|
6096
|
+
const next = placed(segment, pen, matrix);
|
|
6097
|
+
parts.push(next.data);
|
|
6098
|
+
pen = next.pen;
|
|
6099
|
+
}
|
|
6100
|
+
return parts.join("");
|
|
6101
|
+
};
|
|
6102
|
+
|
|
6103
|
+
//#endregion
|
|
6104
|
+
//#region ../../packages/canvas-document/src/canvas-mask-css.lib.ts
|
|
6105
|
+
/**
|
|
6106
|
+
* A mask group's own element takes the CSS mask, computed from its source each time it is drawn:
|
|
6107
|
+
* the source's visible fills, with its opacity folded in, become mask layers at its box. An
|
|
6108
|
+
* outline mask uses only the clip of the source's shape; a group with no kind is an alpha mask.
|
|
6109
|
+
*/
|
|
6110
|
+
const canvasMaskLayerDeclarations = (node, source) => {
|
|
6111
|
+
const geometry = node.geometry;
|
|
6112
|
+
if (geometry?.kind !== "mask" || geometry.mode === "outline" || source?.box === void 0 || source.component === "text") return {};
|
|
6113
|
+
const opacity = canvasAppearanceOf(source).opacity;
|
|
6114
|
+
const layers = canvasAppearanceOf(source).fills.filter((paint) => paint.visible).toReversed().map((paint) => canvasPaintLayerCss({
|
|
6115
|
+
...paint,
|
|
6116
|
+
opacity: paint.opacity * opacity
|
|
6117
|
+
}));
|
|
6118
|
+
if (layers.length === 0) return {};
|
|
6119
|
+
const { x, y, width, height } = source.box;
|
|
6120
|
+
const each = (value) => layers.map(() => value).join(", ");
|
|
6121
|
+
return {
|
|
6122
|
+
"mask-image": layers.join(", "),
|
|
6123
|
+
"mask-mode": each(geometry.mode === "luminance" ? "luminance" : "alpha"),
|
|
6124
|
+
"mask-position": each(`${String(x)}px ${String(y)}px`),
|
|
6125
|
+
"mask-size": each(`${String(width)}px ${String(height)}px`),
|
|
6126
|
+
"mask-repeat": each("no-repeat")
|
|
6127
|
+
};
|
|
6128
|
+
};
|
|
6129
|
+
/**
|
|
6130
|
+
* The clip a mask group's element takes from its source's shape, written as a CSS path in the
|
|
6131
|
+
* group's own pixels: the editor draws the same contour through an SVG clip. A group of shapes
|
|
6132
|
+
* keeps each shape's alpha, which a CSS clip cannot, so it has none here; nor has text that shows
|
|
6133
|
+
* the content in its letters. Null when the shape cannot be written as a CSS path.
|
|
6134
|
+
*/
|
|
6135
|
+
const canvasMaskClipDeclarations = (document, node) => {
|
|
6136
|
+
const clip = node.geometry?.kind === "mask" ? canvasGeometryClipOf(document, node) : null;
|
|
6137
|
+
const box = node.box;
|
|
6138
|
+
if (box === void 0 || clip === null || clip.shapes !== void 0) return {};
|
|
6139
|
+
if (clip.path === "") return { "clip-path": "inset(50%)" };
|
|
6140
|
+
const [a, b, c, d, e, f] = clip.matrix;
|
|
6141
|
+
const path = canvasPathTransformedBy(clip.path, [
|
|
6142
|
+
a * box.width,
|
|
6143
|
+
b * box.height,
|
|
6144
|
+
c * box.width,
|
|
6145
|
+
d * box.height,
|
|
6146
|
+
e * box.width,
|
|
6147
|
+
f * box.height
|
|
6148
|
+
]);
|
|
6149
|
+
return path === null ? null : { "clip-path": `path(${clip.fillRule}, "${path}")` };
|
|
6150
|
+
};
|
|
6151
|
+
|
|
6152
|
+
//#endregion
|
|
6153
|
+
//#region src/application/canvas-editable-html-source.use-case.ts
|
|
2792
6154
|
const ATTRIBUTES = /* @__PURE__ */ new Set([
|
|
2793
6155
|
"data-enhance-id",
|
|
6156
|
+
"data-enhance-locked",
|
|
2794
6157
|
"data-enhance-name",
|
|
2795
6158
|
"data-enhance-opaque",
|
|
2796
6159
|
"style"
|
|
2797
6160
|
]);
|
|
2798
|
-
const fail = (message) => {
|
|
6161
|
+
const fail$1 = (message) => {
|
|
2799
6162
|
throw new CliError("BAD_REQUEST", message, "Use a complete current editable read and preserve its identity and opaque markers.");
|
|
2800
6163
|
};
|
|
2801
|
-
|
|
6164
|
+
/** An inline declaration list as one value per property, refusing what CSS cannot hold. */
|
|
2802
6165
|
const styleValues = (source) => {
|
|
2803
6166
|
const ast = parse(source, {
|
|
2804
6167
|
context: "declarationList",
|
|
2805
|
-
onParseError: (error) => fail(error.message)
|
|
6168
|
+
onParseError: (error) => fail$1(error.message)
|
|
2806
6169
|
});
|
|
2807
|
-
if (ast.type !== "DeclarationList") return fail("Expected an inline CSS declaration list.");
|
|
6170
|
+
if (ast.type !== "DeclarationList") return fail$1("Expected an inline CSS declaration list.");
|
|
2808
6171
|
const styles = /* @__PURE__ */ new Map();
|
|
2809
6172
|
ast.children.forEach((declaration) => {
|
|
2810
|
-
if (declaration.type !== "Declaration" || declaration.important !== false) return fail("Use ordinary inline CSS properties without !important or at-rules.");
|
|
6173
|
+
if (declaration.type !== "Declaration" || declaration.important !== false) return fail$1("Use ordinary inline CSS properties without !important or at-rules.");
|
|
2811
6174
|
const property = declaration.property.startsWith("--") ? declaration.property : declaration.property.toLowerCase();
|
|
2812
|
-
if (styles.has(property)) return fail(`Duplicate CSS property: ${property}.`);
|
|
6175
|
+
if (styles.has(property)) return fail$1(`Duplicate CSS property: ${property}.`);
|
|
2813
6176
|
styles.set(property, generate(declaration.value));
|
|
2814
6177
|
});
|
|
2815
6178
|
return Object.fromEntries(styles);
|
|
2816
6179
|
};
|
|
2817
|
-
const serialize$1 = (node) => {
|
|
2818
|
-
const style = Object.entries(node.styles).toSorted(([left], [right]) => left.localeCompare(right)).map(([key, value]) => `${key}:${value}`).join(";");
|
|
2819
|
-
const attrs = `data-enhance-id="${escape(node.id)}" data-enhance-name="${escape(node.label)}"${node.opaque ? " data-enhance-opaque=\"true\"" : ""}${style === "" ? "" : ` style="${escape(style)}"`}`;
|
|
2820
|
-
return `<${node.tag} ${attrs}>${escape(node.text)}${node.children.map((child) => serialize$1(child)).join("")}</${node.tag}>`;
|
|
2821
|
-
};
|
|
2822
|
-
const projectCanvasEditableHtml = (document, rootNodeId) => {
|
|
2823
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2824
|
-
const opaqueNodeIds = [];
|
|
2825
|
-
const childrenByParent = canvasChildrenByParent(document);
|
|
2826
|
-
const visit = (nodeId) => {
|
|
2827
|
-
if (seen.has(nodeId)) return fail("The document contains repeated node identity.");
|
|
2828
|
-
seen.add(nodeId);
|
|
2829
|
-
const node = requireCanvasNode(document, nodeId);
|
|
2830
|
-
const children = childrenByParent.get(nodeId) ?? [];
|
|
2831
|
-
const isOpaque = isCanvasNodeLocked(document, nodeId) || node.component === "text" && children.length > 0 || ![
|
|
2832
|
-
"root",
|
|
2833
|
-
"frame",
|
|
2834
|
-
"group",
|
|
2835
|
-
"text"
|
|
2836
|
-
].includes(node.component);
|
|
2837
|
-
if (isOpaque) opaqueNodeIds.push(node.id);
|
|
2838
|
-
const styles = isOpaque ? {} : styleValues(Object.entries(canvasAuthoredStyleDeclarations(node)).map(([property, value]) => `${property}:${canvasCssValue(property, value)}`).join(";"));
|
|
2839
|
-
return {
|
|
2840
|
-
id: node.id,
|
|
2841
|
-
tag: node.component === "text" ? "span" : "div",
|
|
2842
|
-
label: node.label,
|
|
2843
|
-
opaque: isOpaque,
|
|
2844
|
-
styles,
|
|
2845
|
-
text: isOpaque || node.component !== "text" ? "" : textOf(node) ?? "",
|
|
2846
|
-
children: isOpaque ? [] : children.map((id) => visit(id))
|
|
2847
|
-
};
|
|
2848
|
-
};
|
|
2849
|
-
const root = visit(rootNodeId);
|
|
2850
|
-
return {
|
|
2851
|
-
projectionVersion: 1,
|
|
2852
|
-
root,
|
|
2853
|
-
html: serialize$1(root),
|
|
2854
|
-
opaqueNodeIds
|
|
2855
|
-
};
|
|
2856
|
-
};
|
|
2857
6180
|
const elements = (children) => children.flatMap((child) => {
|
|
2858
6181
|
if ("tagName" in child) return [child];
|
|
2859
6182
|
if (child.nodeName === "#text" && "value" in child && child.value.trim() === "") return [];
|
|
2860
|
-
return fail("Container content must contain identified elements; text belongs inside its retained span.");
|
|
6183
|
+
return fail$1("Container content must contain identified elements; text belongs inside its retained span.");
|
|
2861
6184
|
});
|
|
2862
6185
|
const canvasEditableHtmlFragment = (html) => {
|
|
2863
6186
|
const fragment = parseFragment(html, {
|
|
2864
6187
|
sourceCodeLocationInfo: true,
|
|
2865
|
-
onParseError: (error) => fail(`Invalid HTML at line ${String(error.startLine)}: ${error.code}.`)
|
|
6188
|
+
onParseError: (error) => fail$1(`Invalid HTML at line ${String(error.startLine)}: ${error.code}.`)
|
|
2866
6189
|
});
|
|
2867
6190
|
const pending = [fragment];
|
|
2868
6191
|
while (pending.length > 0) {
|
|
@@ -2877,42 +6200,623 @@ const canvasEditableHtmlFragment = (html) => {
|
|
|
2877
6200
|
}
|
|
2878
6201
|
return fragment;
|
|
2879
6202
|
};
|
|
6203
|
+
const SVG_ATTRIBUTES = /* @__PURE__ */ new Set([
|
|
6204
|
+
...ATTRIBUTES,
|
|
6205
|
+
"viewBox",
|
|
6206
|
+
"preserveAspectRatio"
|
|
6207
|
+
]);
|
|
6208
|
+
/** A vector element holds exactly one path. */
|
|
6209
|
+
const parsedPath = (element, viewBox) => {
|
|
6210
|
+
const [path, ...rest] = elements(element.childNodes);
|
|
6211
|
+
if (path?.tagName !== "path" || rest.length > 0) return fail$1("A vector element must hold exactly one path.");
|
|
6212
|
+
const value = (name) => path.attrs.find((attribute) => attribute.name === name)?.value;
|
|
6213
|
+
const fillRule = value("fill-rule") ?? "nonzero";
|
|
6214
|
+
if (fillRule !== "nonzero" && fillRule !== "evenodd") return fail$1(`Unsupported fill-rule: ${fillRule}.`);
|
|
6215
|
+
return {
|
|
6216
|
+
d: value("d") ?? "",
|
|
6217
|
+
fillRule,
|
|
6218
|
+
fill: value("fill") ?? "none",
|
|
6219
|
+
viewBox
|
|
6220
|
+
};
|
|
6221
|
+
};
|
|
6222
|
+
/** An element's attributes, refusing any the agent's HTML does not carry. */
|
|
6223
|
+
const attributesOf = (element) => {
|
|
6224
|
+
const allowed = element.tagName === "svg" ? SVG_ATTRIBUTES : ATTRIBUTES;
|
|
6225
|
+
return Object.fromEntries(element.attrs.map((attr) => {
|
|
6226
|
+
if (!allowed.has(attr.name) || attr.namespace !== void 0) return fail$1(`Unsupported attribute: ${attr.name}.`);
|
|
6227
|
+
return [attr.name, attr.value];
|
|
6228
|
+
}));
|
|
6229
|
+
};
|
|
6230
|
+
/** The identity, name and markers every retained element carries. */
|
|
6231
|
+
const retainedOf = (attrs) => {
|
|
6232
|
+
const id = attrs["data-enhance-id"];
|
|
6233
|
+
const label = attrs["data-enhance-name"];
|
|
6234
|
+
if (id === void 0 || id === "" || label === void 0) return fail$1("Every retained element requires its identity and name.");
|
|
6235
|
+
const marker = attrs["data-enhance-opaque"];
|
|
6236
|
+
if (marker !== void 0 && marker !== "true") return fail$1(`Invalid opaque marker on ${id}.`);
|
|
6237
|
+
const locked = attrs["data-enhance-locked"];
|
|
6238
|
+
if (locked !== void 0 && locked !== "true") return fail$1(`Invalid locked marker on ${id}.`);
|
|
6239
|
+
return {
|
|
6240
|
+
id,
|
|
6241
|
+
label,
|
|
6242
|
+
opaque: marker === "true",
|
|
6243
|
+
locked: locked === "true",
|
|
6244
|
+
styles: styleValues(attrs["style"] ?? "")
|
|
6245
|
+
};
|
|
6246
|
+
};
|
|
6247
|
+
/** A layer's paint elements, which are no layers, apart from its retained children. */
|
|
6248
|
+
const paintsAndChildren = (element) => {
|
|
6249
|
+
const paints = [];
|
|
6250
|
+
const children = [];
|
|
6251
|
+
for (const child of elements(element.childNodes)) {
|
|
6252
|
+
const owner = child.attrs.find((attribute) => attribute.name === "data-enhance-paint")?.value;
|
|
6253
|
+
if (owner === void 0) {
|
|
6254
|
+
children.push(child);
|
|
6255
|
+
continue;
|
|
6256
|
+
}
|
|
6257
|
+
const style = child.attrs.find((attribute) => attribute.name === "style")?.value ?? "";
|
|
6258
|
+
paints.push(owner === "border" || owner === "outline" ? {
|
|
6259
|
+
owner,
|
|
6260
|
+
styles: styleValues(style)
|
|
6261
|
+
} : {
|
|
6262
|
+
owner: "paint",
|
|
6263
|
+
paintId: owner,
|
|
6264
|
+
styles: styleValues(style)
|
|
6265
|
+
});
|
|
6266
|
+
}
|
|
6267
|
+
return [paints, children];
|
|
6268
|
+
};
|
|
6269
|
+
/** A rich text layer's run spans, each marked with its place among the runs. */
|
|
6270
|
+
const runsOfSpan = (element, id) => elements(element.childNodes).map((run, index) => {
|
|
6271
|
+
const place = run.attrs.find((attribute) => attribute.name === "data-enhance-run")?.value;
|
|
6272
|
+
if (run.tagName !== "span" || place !== String(index)) return fail$1(`Text ${id} holds run spans only, each with its data-enhance-run place.`);
|
|
6273
|
+
const style = run.attrs.find((attribute) => attribute.name === "style")?.value ?? "";
|
|
6274
|
+
return {
|
|
6275
|
+
text: textOfSpan(run, id),
|
|
6276
|
+
styles: styleValues(style)
|
|
6277
|
+
};
|
|
6278
|
+
});
|
|
6279
|
+
const textOfSpan = (element, id) => element.childNodes.map((child) => {
|
|
6280
|
+
if ("value" in child) return child.value;
|
|
6281
|
+
return fail$1(`Retained text ${id} must contain text only; its existing rich formatting is preserved by the text owner.`);
|
|
6282
|
+
}).join("");
|
|
2880
6283
|
const parseCanvasEditableHtml = (html) => {
|
|
2881
6284
|
const fragment = canvasEditableHtmlFragment(html);
|
|
2882
6285
|
const seen = /* @__PURE__ */ new Set();
|
|
2883
6286
|
const visit = (element) => {
|
|
2884
|
-
if (element.tagName !== "div" && element.tagName !== "span") return fail(`Unsupported retained element: ${element.tagName}.`);
|
|
2885
|
-
const attrs =
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
const
|
|
2897
|
-
|
|
2898
|
-
return fail(`Retained text ${id} must contain text only; its existing rich formatting is preserved by the text owner.`);
|
|
2899
|
-
}).join("") : "";
|
|
6287
|
+
if (element.tagName !== "div" && element.tagName !== "span" && element.tagName !== "svg") return fail$1(`Unsupported retained element: ${element.tagName}.`);
|
|
6288
|
+
const attrs = attributesOf(element);
|
|
6289
|
+
const retained = retainedOf(attrs);
|
|
6290
|
+
if (seen.has(retained.id)) return fail$1(`Duplicate node identity: ${retained.id}.`);
|
|
6291
|
+
seen.add(retained.id);
|
|
6292
|
+
if (element.tagName === "svg") return {
|
|
6293
|
+
...retained,
|
|
6294
|
+
tag: "svg",
|
|
6295
|
+
path: parsedPath(element, attrs["viewBox"] ?? ""),
|
|
6296
|
+
text: "",
|
|
6297
|
+
children: []
|
|
6298
|
+
};
|
|
6299
|
+
const hasRuns = element.tagName === "span" && element.childNodes.some((child) => "tagName" in child);
|
|
6300
|
+
const [paints, children] = element.tagName === "span" ? [[], []] : paintsAndChildren(element);
|
|
2900
6301
|
return {
|
|
2901
|
-
|
|
6302
|
+
...retained,
|
|
2902
6303
|
tag: element.tagName,
|
|
2903
|
-
|
|
2904
|
-
|
|
2905
|
-
text,
|
|
2906
|
-
|
|
2907
|
-
children: element.tagName === "span" ? [] : elements(element.childNodes).map((child) => visit(child))
|
|
6304
|
+
...hasRuns && { runs: runsOfSpan(element, retained.id) },
|
|
6305
|
+
...paints.length > 0 && { paints },
|
|
6306
|
+
text: !hasRuns && element.tagName === "span" ? textOfSpan(element, retained.id) : "",
|
|
6307
|
+
children: children.map((child) => visit(child))
|
|
2908
6308
|
};
|
|
2909
6309
|
};
|
|
2910
6310
|
const roots = elements(fragment.childNodes);
|
|
2911
6311
|
const root = roots[0];
|
|
2912
|
-
if (root === void 0 || roots.length !== 1) return fail("An editable update must contain exactly its original root.");
|
|
6312
|
+
if (root === void 0 || roots.length !== 1) return fail$1("An editable update must contain exactly its original root.");
|
|
2913
6313
|
return visit(root);
|
|
2914
6314
|
};
|
|
2915
6315
|
|
|
6316
|
+
//#endregion
|
|
6317
|
+
//#region src/application/canvas-editable-image.use-case.ts
|
|
6318
|
+
const invalid$6 = (message) => {
|
|
6319
|
+
throw new CliError("BAD_REQUEST", message, "Read the current editable subtree and apply only the intended change. No changes were committed.");
|
|
6320
|
+
};
|
|
6321
|
+
/** An image's fit as a background size; scale-down reads as contain, which it is for large images. */
|
|
6322
|
+
const SIZE_OF_FIT = {
|
|
6323
|
+
fill: "100% 100%",
|
|
6324
|
+
cover: "cover",
|
|
6325
|
+
contain: "contain",
|
|
6326
|
+
"scale-down": "contain",
|
|
6327
|
+
none: "auto"
|
|
6328
|
+
};
|
|
6329
|
+
const FIT_OF_SIZE = {
|
|
6330
|
+
"100% 100%": "fill",
|
|
6331
|
+
cover: "cover",
|
|
6332
|
+
contain: "contain",
|
|
6333
|
+
auto: "none"
|
|
6334
|
+
};
|
|
6335
|
+
const IMAGE_PROPERTY = /^background(?:-.+)?$/u;
|
|
6336
|
+
const URL$1 = /^url\((?:"([^"]*)"|'([^']*)'|([^"'()\s]*))\)$/u;
|
|
6337
|
+
/** A native image: one with its own source rather than fills. */
|
|
6338
|
+
const nativeSourceOf = (node) => {
|
|
6339
|
+
if (node.component !== "image") return void 0;
|
|
6340
|
+
const source = node.props?.["src"];
|
|
6341
|
+
return typeof source === "string" && source !== "" ? source : void 0;
|
|
6342
|
+
};
|
|
6343
|
+
/** A native image's CSS: its source painted once as the element's background. */
|
|
6344
|
+
const canvasEditableImageDeclarations = (node) => {
|
|
6345
|
+
const source = nativeSourceOf(node);
|
|
6346
|
+
if (source === void 0) return {};
|
|
6347
|
+
const fit = node.props?.["fit"];
|
|
6348
|
+
const position = node.props?.["position"];
|
|
6349
|
+
return {
|
|
6350
|
+
"background-image": `url(${JSON.stringify(source)})`,
|
|
6351
|
+
"background-size": SIZE_OF_FIT[typeof fit === "string" ? fit : "fill"] ?? "100% 100%",
|
|
6352
|
+
"background-position": typeof position === "string" ? position : "50% 50%",
|
|
6353
|
+
"background-repeat": "no-repeat"
|
|
6354
|
+
};
|
|
6355
|
+
};
|
|
6356
|
+
/** Whether the property belongs to a native image's own source, not to its CSS. */
|
|
6357
|
+
const isCanvasEditableImageProperty = (node, property) => nativeSourceOf(node) !== void 0 && IMAGE_PROPERTY.test(property);
|
|
6358
|
+
/** A written background on a native image sets its source, fit and position. */
|
|
6359
|
+
const canvasEditableImageOperations = (node, before, after) => {
|
|
6360
|
+
if (nativeSourceOf(node) === void 0) return [];
|
|
6361
|
+
const changed = [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].filter((property) => IMAGE_PROPERTY.test(property) && before[property] !== after[property]);
|
|
6362
|
+
if (changed.length === 0) return [];
|
|
6363
|
+
if (changed.some((property) => ![
|
|
6364
|
+
"background-image",
|
|
6365
|
+
"background-size",
|
|
6366
|
+
"background-position"
|
|
6367
|
+
].includes(property))) return invalid$6(`An image paints once from its source on ${node.id}; change only its background-image URL, background-size (100% 100%, cover, contain or auto) and background-position.`);
|
|
6368
|
+
const url = URL$1.exec(after["background-image"] ?? "");
|
|
6369
|
+
const source = url?.[1] ?? url?.[2] ?? url?.[3];
|
|
6370
|
+
const fit = FIT_OF_SIZE[after["background-size"] ?? ""];
|
|
6371
|
+
const position = after["background-position"];
|
|
6372
|
+
if (source === void 0 || source === "" || fit === void 0 || position === void 0) return invalid$6(`An image on ${node.id} needs a background-image URL, a background-size of 100% 100%, cover, contain or auto, and a background-position.`);
|
|
6373
|
+
return [{
|
|
6374
|
+
op: "setProps",
|
|
6375
|
+
nodeId: node.id,
|
|
6376
|
+
props: {
|
|
6377
|
+
...node.props,
|
|
6378
|
+
...changed.includes("background-image") && { src: source },
|
|
6379
|
+
...changed.includes("background-size") && { fit },
|
|
6380
|
+
...changed.includes("background-position") && { position }
|
|
6381
|
+
}
|
|
6382
|
+
}];
|
|
6383
|
+
};
|
|
6384
|
+
|
|
6385
|
+
//#endregion
|
|
6386
|
+
//#region src/application/canvas-editable-paint.use-case.ts
|
|
6387
|
+
const invalid$5 = (message) => {
|
|
6388
|
+
throw new CliError("BAD_REQUEST", message, "Read the current editable subtree and apply only the intended change. No changes were committed.");
|
|
6389
|
+
};
|
|
6390
|
+
/** The layer CSS a paint element takes over, and so leaves out of the layer's own read. */
|
|
6391
|
+
const TAKEN_OVER = {
|
|
6392
|
+
border: /^border(?:-(?:top|right|bottom|left))?(?:-(?:width|style|color))?$|^border-(?:width|style|color)$/u,
|
|
6393
|
+
outline: /^outline(?:-.+)?$/u,
|
|
6394
|
+
paint: /^$/u
|
|
6395
|
+
};
|
|
6396
|
+
/** In the order the HTML writes them, so a read compares equal to its own write-back. */
|
|
6397
|
+
const sortedStyles = (source) => Object.fromEntries(Object.entries(styleValues(source)).toSorted(([left], [right]) => left.localeCompare(right)));
|
|
6398
|
+
/** The paint element's CSS, written as the parser reads it back, without editor resources. */
|
|
6399
|
+
const readable = (styles) => sortedStyles(Object.entries(styles).flatMap(([property, value]) => {
|
|
6400
|
+
const css = canvasCssValue(property, value);
|
|
6401
|
+
return property.startsWith("--") || css.includes("var(--canvas") || css.includes("url(#") ? [] : [`${property}:${css}`];
|
|
6402
|
+
}).join(";"));
|
|
6403
|
+
/**
|
|
6404
|
+
* The layer's paint elements as the agent reads them, in the order they paint: its shadow and fill
|
|
6405
|
+
* elements with their paint's identity, then the border's and the outline's.
|
|
6406
|
+
*/
|
|
6407
|
+
const canvasEditablePaints = (node) => {
|
|
6408
|
+
const plan = canvasPaintElementPlanOf(node);
|
|
6409
|
+
const shadow = (kind) => canvasShadowElementsOf(plan, kind).map((held) => ({
|
|
6410
|
+
owner: "paint",
|
|
6411
|
+
paintId: held.id,
|
|
6412
|
+
styles: readable(canvasShadowPaintDeclarations(node, held))
|
|
6413
|
+
}));
|
|
6414
|
+
const border = canvasBoxStrokeDeclarations(node);
|
|
6415
|
+
const outline = canvasOutlinePaintDeclarations(node);
|
|
6416
|
+
return [
|
|
6417
|
+
...shadow("outer-shadow"),
|
|
6418
|
+
...canvasFillElementsOf(plan).map((paint) => ({
|
|
6419
|
+
owner: "paint",
|
|
6420
|
+
paintId: paint.id,
|
|
6421
|
+
styles: readable(canvasFillPaintDeclarations(paint))
|
|
6422
|
+
})),
|
|
6423
|
+
...shadow("inner-shadow"),
|
|
6424
|
+
...border === null ? [] : [{
|
|
6425
|
+
owner: "border",
|
|
6426
|
+
styles: readable(border)
|
|
6427
|
+
}],
|
|
6428
|
+
...outline === null ? [] : [{
|
|
6429
|
+
owner: "outline",
|
|
6430
|
+
styles: readable(outline)
|
|
6431
|
+
}]
|
|
6432
|
+
];
|
|
6433
|
+
};
|
|
6434
|
+
/** Whether the layer's own read leaves a property to one of its paint elements. */
|
|
6435
|
+
const isCanvasPaintElementProperty = (paints, property) => paints.some((paint) => TAKEN_OVER[paint.owner].test(property));
|
|
6436
|
+
const blendOf = (value) => {
|
|
6437
|
+
return CANVAS_BLEND_MODES.find((held) => held === (value ?? "normal")) ?? invalid$5(`Unsupported mix-blend-mode: ${value ?? ""}.`);
|
|
6438
|
+
};
|
|
6439
|
+
const DASH_ATTRIBUTES = /stroke-(?:dasharray|linecap)="[^"]*"/gu;
|
|
6440
|
+
/** The dash mask's SVG, decoded from its data URL, with or without quotes around it. */
|
|
6441
|
+
const dashMaskSvg = (value) => {
|
|
6442
|
+
const data = /^url\(["']?data:image\/svg\+xml,(.*?)["']?\)$/u.exec(value ?? "")?.[1];
|
|
6443
|
+
return data === void 0 ? void 0 : decodeURIComponent(data);
|
|
6444
|
+
};
|
|
6445
|
+
/** A changed dash mask sets the stroke's dash pattern and cap; nothing else of it can change. */
|
|
6446
|
+
const dashOf = (node, held, written) => {
|
|
6447
|
+
const before = dashMaskSvg(held);
|
|
6448
|
+
const after = dashMaskSvg(written);
|
|
6449
|
+
if (after === void 0 || before?.replaceAll(DASH_ATTRIBUTES, "") !== after.replaceAll(DASH_ATTRIBUTES, "")) return invalid$5(`Only stroke-dasharray and stroke-linecap of the dash mask can change on ${node.id}.`);
|
|
6450
|
+
const pattern = (/stroke-dasharray="([^"]*)"/u.exec(after)?.[1] ?? "").split(/[\s,]+/u).filter((length) => length !== "").map(Number);
|
|
6451
|
+
if (pattern.length === 0 || pattern.some((length) => !Number.isFinite(length) || length < 0)) return invalid$5(`A dash pattern is one or more lengths of 0 or more, on ${node.id}.`);
|
|
6452
|
+
const cap = /stroke-linecap="([^"]*)"/u.exec(after)?.[1];
|
|
6453
|
+
if (cap !== "butt" && cap !== "round" && cap !== "square") return invalid$5(`A dash cap is butt, round or square, on ${node.id}.`);
|
|
6454
|
+
return {
|
|
6455
|
+
dashPattern: pattern,
|
|
6456
|
+
dashCap: cap === "butt" ? "none" : cap
|
|
6457
|
+
};
|
|
6458
|
+
};
|
|
6459
|
+
/** The one visible paint of the stroke takes the written blend. */
|
|
6460
|
+
const blendedPaints = (node, owner, stroke, written) => {
|
|
6461
|
+
const visible = stroke.paints.filter((paint) => paint.visible);
|
|
6462
|
+
const [only] = visible;
|
|
6463
|
+
if (only === void 0 || visible.length !== 1) return invalid$5(`Set a blend on one paint of the ${owner} of ${node.id} in the editor.`);
|
|
6464
|
+
const blendMode = blendOf(written);
|
|
6465
|
+
return stroke.paints.map((paint) => paint === only ? {
|
|
6466
|
+
...paint,
|
|
6467
|
+
blendMode
|
|
6468
|
+
} : paint);
|
|
6469
|
+
};
|
|
6470
|
+
/** Written fill and shadow elements set the modes of their paints only, in one write each. */
|
|
6471
|
+
const paintBlendOperations = (node, modes) => {
|
|
6472
|
+
if (modes.size === 0) return [];
|
|
6473
|
+
const fills = node.appearance?.fills ?? [];
|
|
6474
|
+
const shadows = node.appearance?.shadows ?? [];
|
|
6475
|
+
for (const id of modes.keys()) if (fills.every((paint) => paint.id !== id) && shadows.every((shadow) => shadow.id !== id)) return invalid$5(`${node.id} has no fill or shadow ${id}.`);
|
|
6476
|
+
const blended = (items) => items.map((item) => modes.has(item.id) ? {
|
|
6477
|
+
...item,
|
|
6478
|
+
blendMode: blendOf(modes.get(item.id))
|
|
6479
|
+
} : item);
|
|
6480
|
+
return [...fills.some((paint) => modes.has(paint.id)) ? [{
|
|
6481
|
+
op: "setAppearance",
|
|
6482
|
+
nodeId: node.id,
|
|
6483
|
+
appearance: { fills: blended(fills) }
|
|
6484
|
+
}] : [], ...shadows.some((shadow) => modes.has(shadow.id)) ? [{
|
|
6485
|
+
op: "setAppearance",
|
|
6486
|
+
nodeId: node.id,
|
|
6487
|
+
appearance: { shadows: blended(shadows) }
|
|
6488
|
+
}] : []];
|
|
6489
|
+
};
|
|
6490
|
+
/**
|
|
6491
|
+
* A written paint element changes only its paint: its blend is the paint's blend, and its dash
|
|
6492
|
+
* mask is the stroke's dash pattern and cap. The rest of it follows the border or outline, which
|
|
6493
|
+
* the agent changes on the layer.
|
|
6494
|
+
*/
|
|
6495
|
+
const canvasEditablePaintOperations = (node, before, after) => {
|
|
6496
|
+
const identities = (paints) => JSON.stringify(paints.map((paint) => paint.paintId ?? paint.owner));
|
|
6497
|
+
const unknown = after.find((paint) => paint.paintId !== void 0 && before.every((held) => held.paintId !== paint.paintId));
|
|
6498
|
+
if (unknown?.paintId !== void 0) return invalid$5(`${node.id} has no fill or shadow ${unknown.paintId}.`);
|
|
6499
|
+
if (identities(before) !== identities(after)) return invalid$5(`Keep each paint element of ${node.id}.`);
|
|
6500
|
+
const modes = /* @__PURE__ */ new Map();
|
|
6501
|
+
return [...after.flatMap((written, index) => {
|
|
6502
|
+
const held = before[index];
|
|
6503
|
+
if (held === void 0 || JSON.stringify(held.styles) === JSON.stringify(written.styles)) return [];
|
|
6504
|
+
const changed = [.../* @__PURE__ */ new Set([...Object.keys(held.styles), ...Object.keys(written.styles)])].filter((key) => held.styles[key] !== written.styles[key]);
|
|
6505
|
+
if (written.owner === "paint" && written.paintId !== void 0) {
|
|
6506
|
+
if (changed.some((key) => key !== "mix-blend-mode")) return invalid$5(`The paint element ${written.paintId} of ${node.id} follows its paint, so only its mix-blend-mode can change there; change ${changed.join(", ")} through the appearance operation.`);
|
|
6507
|
+
modes.set(written.paintId, written.styles["mix-blend-mode"]);
|
|
6508
|
+
return [];
|
|
6509
|
+
}
|
|
6510
|
+
if (changed.some((key) => key !== "mix-blend-mode" && key !== "mask-image")) return invalid$5(`The ${written.owner}'s paint element of ${node.id} follows its ${written.owner}, so ${changed.join(", ")} cannot change there; change the ${written.owner} CSS on the layer, or the paint element's mix-blend-mode or dash mask.`);
|
|
6511
|
+
const owner = written.owner === "outline" ? "outline" : "border";
|
|
6512
|
+
const stroke = node.appearance?.[owner];
|
|
6513
|
+
if (stroke === void 0) return invalid$5(`The ${owner} of ${node.id} has no paint element to write.`);
|
|
6514
|
+
const paints = changed.includes("mix-blend-mode") ? blendedPaints(node, owner, stroke, written.styles["mix-blend-mode"]) : stroke.paints;
|
|
6515
|
+
const dash = changed.includes("mask-image") ? dashOf(node, held.styles["mask-image"], written.styles["mask-image"]) : {};
|
|
6516
|
+
return [{
|
|
6517
|
+
op: "setAppearance",
|
|
6518
|
+
nodeId: node.id,
|
|
6519
|
+
appearance: { [owner]: {
|
|
6520
|
+
...stroke,
|
|
6521
|
+
paints,
|
|
6522
|
+
...dash
|
|
6523
|
+
} }
|
|
6524
|
+
}];
|
|
6525
|
+
}), ...paintBlendOperations(node, modes)];
|
|
6526
|
+
};
|
|
6527
|
+
|
|
6528
|
+
//#endregion
|
|
6529
|
+
//#region src/application/canvas-editable-text.use-case.ts
|
|
6530
|
+
const TEXT_BLEND_REASON = "Text paints have no blend of their own. Set mix-blend-mode on the text layer.";
|
|
6531
|
+
const invalid$4 = (message) => {
|
|
6532
|
+
throw new CliError("BAD_REQUEST", message, "Read the current editable subtree and apply only the intended change. No changes were committed.");
|
|
6533
|
+
};
|
|
6534
|
+
/** A flat run: plain text, or one span of plain text with its own formatting. */
|
|
6535
|
+
const isFlatRun = (run) => run.kind === "text" || run.kind === "span" && run.children.every((child) => child.kind === "text");
|
|
6536
|
+
const runTextOf = (run) => canvasRichTextValueOf([run]);
|
|
6537
|
+
/** Run formatting is stored by its script name; the agent reads and writes its CSS name. */
|
|
6538
|
+
const cssPropertyOf = (property) => property.replaceAll(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`);
|
|
6539
|
+
const storedPropertyOf = (property) => property.replaceAll(/-([a-z])/gu, (_match, letter) => letter.toUpperCase());
|
|
6540
|
+
const storedStylesOf = (written, index) => Object.fromEntries(Object.entries(written).map(([property, value]) => {
|
|
6541
|
+
const stored = storedPropertyOf(property);
|
|
6542
|
+
return CANVAS_RICH_TEXT_STYLE_PROPERTIES.has(stored) ? [stored, value] : invalid$4(`Run ${String(index + 1)} cannot hold ${property}; set it on the text layer.`);
|
|
6543
|
+
}));
|
|
6544
|
+
const runStylesOf = (run) => {
|
|
6545
|
+
if (run.kind !== "span") return {};
|
|
6546
|
+
const [fill, ...others] = (run.fills ?? []).filter((paint) => paint.visible);
|
|
6547
|
+
const color = fill === void 0 || others.length > 0 ? void 0 : canvasSolidPaintColor(fill);
|
|
6548
|
+
const declarations = [...Object.entries(run.styles).map(([property, value]) => {
|
|
6549
|
+
const css = cssPropertyOf(property);
|
|
6550
|
+
return `${css}:${canvasCssValue(css, value)}`;
|
|
6551
|
+
}), ...color === void 0 ? [] : [`color:${color}`]];
|
|
6552
|
+
return Object.fromEntries(Object.entries(styleValues(declarations.join(";"))).toSorted(([left], [right]) => left.localeCompare(right)));
|
|
6553
|
+
};
|
|
6554
|
+
/**
|
|
6555
|
+
* A rich text layer's runs as the agent reads them, one span each, or null when its text is plain
|
|
6556
|
+
* or its runs nest. A plain text layer is one span of text, as before.
|
|
6557
|
+
*/
|
|
6558
|
+
const canvasEditableTextRuns = (node) => {
|
|
6559
|
+
const runs = canvasRichTextOf(node);
|
|
6560
|
+
if (runs.length === 0 || runs.some((run) => !isFlatRun(run))) return null;
|
|
6561
|
+
return runs.map((run) => ({
|
|
6562
|
+
text: runTextOf(run),
|
|
6563
|
+
styles: runStylesOf(run)
|
|
6564
|
+
}));
|
|
6565
|
+
};
|
|
6566
|
+
/** Whether the layer's rich text is something the agent's run spans cannot hold. */
|
|
6567
|
+
const hasCanvasNestedTextRuns = (node) => {
|
|
6568
|
+
return canvasRichTextOf(node).some((run) => !isFlatRun(run));
|
|
6569
|
+
};
|
|
6570
|
+
const writtenRun = (node, index, run, written) => {
|
|
6571
|
+
if ("mix-blend-mode" in written.styles) return invalid$4(TEXT_BLEND_REASON);
|
|
6572
|
+
const { color, ...writtenStyles } = written.styles;
|
|
6573
|
+
const styles = storedStylesOf(writtenStyles, index);
|
|
6574
|
+
const paint = color === void 0 ? void 0 : solidCanvasPaintFromCss(`${node.id}-run-${String(index)}`, color);
|
|
6575
|
+
if (color !== void 0 && paint === null) return invalid$4(`The color of run ${String(index + 1)} is not a colour.`);
|
|
6576
|
+
const { fills: held, ...rest } = run.kind === "span" ? run : {
|
|
6577
|
+
kind: "span",
|
|
6578
|
+
styles: {},
|
|
6579
|
+
children: []
|
|
6580
|
+
};
|
|
6581
|
+
const isUnshown = held !== void 0 && runStylesOf(run)["color"] === void 0;
|
|
6582
|
+
const fills = paint === void 0 || paint === null ? isUnshown ? held : void 0 : [paint];
|
|
6583
|
+
return {
|
|
6584
|
+
...rest,
|
|
6585
|
+
styles,
|
|
6586
|
+
...fills !== void 0 && { fills },
|
|
6587
|
+
children: [{
|
|
6588
|
+
kind: "text",
|
|
6589
|
+
text: written.text
|
|
6590
|
+
}]
|
|
6591
|
+
};
|
|
6592
|
+
};
|
|
6593
|
+
/** A written run span changes only that run: its words, its colour and its CSS. */
|
|
6594
|
+
const canvasEditableTextOperations = (node, before, after) => {
|
|
6595
|
+
if (before.length !== after.length) return invalid$4(`Keep each run span of ${node.id}; change a run's words or CSS in place.`);
|
|
6596
|
+
const runs = canvasRichTextOf(node);
|
|
6597
|
+
const next = runs.map((run, index) => {
|
|
6598
|
+
const was = before[index];
|
|
6599
|
+
const now = after[index];
|
|
6600
|
+
if (was === void 0 || now === void 0) return run;
|
|
6601
|
+
return JSON.stringify(was) === JSON.stringify(now) ? run : writtenRun(node, index, run, now);
|
|
6602
|
+
});
|
|
6603
|
+
if (next.every((run, index) => run === runs[index])) return [];
|
|
6604
|
+
const props = {
|
|
6605
|
+
...node.props,
|
|
6606
|
+
richText: next,
|
|
6607
|
+
text: canvasRichTextValueOf(next)
|
|
6608
|
+
};
|
|
6609
|
+
return [{
|
|
6610
|
+
op: "editText",
|
|
6611
|
+
nodeId: node.id,
|
|
6612
|
+
change: canvasTextChangeBetween(node, {
|
|
6613
|
+
...node,
|
|
6614
|
+
props
|
|
6615
|
+
})
|
|
6616
|
+
}];
|
|
6617
|
+
};
|
|
6618
|
+
|
|
6619
|
+
//#endregion
|
|
6620
|
+
//#region src/application/canvas-editable-vector.use-case.ts
|
|
6621
|
+
const VECTOR_GEOMETRY = /* @__PURE__ */ new Set([
|
|
6622
|
+
"path",
|
|
6623
|
+
"polygon",
|
|
6624
|
+
"boolean"
|
|
6625
|
+
]);
|
|
6626
|
+
const PAINT_REASON = "A vector with a gradient, image or blended fill keeps its paint in the editor.";
|
|
6627
|
+
/** Vectors, polygons, stars and Boolean groups are one inline SVG path in the agent's HTML. */
|
|
6628
|
+
const isCanvasEditableVector = (node) => VECTOR_GEOMETRY.has(node.geometry?.kind ?? "");
|
|
6629
|
+
/**
|
|
6630
|
+
* Why a vector cannot be read as one path with one solid fill, or null when it can. A blended fill
|
|
6631
|
+
* has no plain colour, so the path's fill could only show it wrong.
|
|
6632
|
+
*/
|
|
6633
|
+
const canvasVectorSealedReason = (node) => {
|
|
6634
|
+
const fills = (node.appearance?.fills ?? []).filter((paint) => paint.visible);
|
|
6635
|
+
return fills.length > 1 || fills.some((paint) => paint.kind !== "solid" || (paint.blendMode ?? "normal") !== "normal") ? PAINT_REASON : null;
|
|
6636
|
+
};
|
|
6637
|
+
/** The path a vector paints, with its one solid fill, or null when it has no closed path. */
|
|
6638
|
+
const canvasEditableVectorPath = (node) => {
|
|
6639
|
+
const shape = canvasShapePathOf(node);
|
|
6640
|
+
if (typeof shape === "string") return null;
|
|
6641
|
+
const fill = (node.appearance?.fills ?? []).find((paint) => paint.visible);
|
|
6642
|
+
const { x, y, width, height } = shape.viewBox;
|
|
6643
|
+
return {
|
|
6644
|
+
d: shape.path,
|
|
6645
|
+
fillRule: shape.fillRule,
|
|
6646
|
+
fill: fill === void 0 ? "none" : canvasSolidPaintColor(fill) ?? "none",
|
|
6647
|
+
viewBox: [
|
|
6648
|
+
x,
|
|
6649
|
+
y,
|
|
6650
|
+
width,
|
|
6651
|
+
height
|
|
6652
|
+
].map(String).join(" ")
|
|
6653
|
+
};
|
|
6654
|
+
};
|
|
6655
|
+
const invalid$3 = (message) => {
|
|
6656
|
+
throw new CliError("BAD_REQUEST", message, "Read the current editable subtree and apply only the intended change. No changes were committed.");
|
|
6657
|
+
};
|
|
6658
|
+
const viewBoxOf = (value) => {
|
|
6659
|
+
const [x = 0, y = 0, width = 0, height = 0] = value.split(/\s+/u).map(Number);
|
|
6660
|
+
return width > 0 && height > 0 ? {
|
|
6661
|
+
x,
|
|
6662
|
+
y,
|
|
6663
|
+
width,
|
|
6664
|
+
height
|
|
6665
|
+
} : invalid$3(`Invalid viewBox: ${value}.`);
|
|
6666
|
+
};
|
|
6667
|
+
/** A written path makes the layer a vector with that path; a Boolean group gives up its operands. */
|
|
6668
|
+
const pathOperations = (document, node, path) => {
|
|
6669
|
+
if (path.d.trim() === "") return invalid$3(`The path of ${node.id} is empty.`);
|
|
6670
|
+
return [{
|
|
6671
|
+
op: "setGeometry",
|
|
6672
|
+
nodeId: node.id,
|
|
6673
|
+
geometry: {
|
|
6674
|
+
kind: "path",
|
|
6675
|
+
path: path.d,
|
|
6676
|
+
fillRule: path.fillRule,
|
|
6677
|
+
viewBox: viewBoxOf(path.viewBox)
|
|
6678
|
+
}
|
|
6679
|
+
}, ...node.geometry?.kind === "boolean" ? canvasChildIds(document, node.id).map((operandId) => ({
|
|
6680
|
+
op: "remove",
|
|
6681
|
+
nodeId: operandId
|
|
6682
|
+
})) : []];
|
|
6683
|
+
};
|
|
6684
|
+
/**
|
|
6685
|
+
* A written fill becomes the layer's one solid fill, or no fill for none. A colour written on a
|
|
6686
|
+
* stored solid fill keeps that paint's identity and mode.
|
|
6687
|
+
*/
|
|
6688
|
+
const fillOperation = (node, fill) => {
|
|
6689
|
+
const stored = (node.appearance?.fills ?? []).find((held) => held.visible);
|
|
6690
|
+
const id = stored?.kind === "solid" ? stored.id : `${node.id}-fill`;
|
|
6691
|
+
const paint = fill === "none" ? null : solidCanvasPaintFromCss(id, fill);
|
|
6692
|
+
if (paint === null && fill !== "none") return invalid$3(`The fill of ${node.id} is not a colour.`);
|
|
6693
|
+
return {
|
|
6694
|
+
op: "setAppearance",
|
|
6695
|
+
nodeId: node.id,
|
|
6696
|
+
appearance: { fills: paint === null ? [] : [{
|
|
6697
|
+
...paint,
|
|
6698
|
+
...stored?.kind === "solid" && stored.blendMode !== void 0 && { blendMode: stored.blendMode }
|
|
6699
|
+
}] }
|
|
6700
|
+
};
|
|
6701
|
+
};
|
|
6702
|
+
const canvasEditableVectorOperations = (document, node, before, after) => [...before.d === after.d && before.fillRule === after.fillRule && before.viewBox === after.viewBox ? [] : pathOperations(document, node, after), ...before.fill === after.fill ? [] : [fillOperation(node, after.fill)]];
|
|
6703
|
+
|
|
6704
|
+
//#endregion
|
|
6705
|
+
//#region src/application/canvas-editable-html.use-case.ts
|
|
6706
|
+
const READABLE_KINDS = /* @__PURE__ */ new Set([
|
|
6707
|
+
"root",
|
|
6708
|
+
"frame",
|
|
6709
|
+
"group",
|
|
6710
|
+
"rectangle",
|
|
6711
|
+
"image",
|
|
6712
|
+
"text"
|
|
6713
|
+
]);
|
|
6714
|
+
const SEALED_REASONS = {
|
|
6715
|
+
screen: "Its pixels come from a recorded page. Use Make editable to edit it as layers.",
|
|
6716
|
+
recording: "Its pixels come from a recording.",
|
|
6717
|
+
prototype: "Its pixels come from a running build."
|
|
6718
|
+
};
|
|
6719
|
+
/** A mask group's CSS mask, made from its source each time it is drawn. */
|
|
6720
|
+
const MASK_PROPERTY = /^(?:mask(?:-.+)?|clip-path)$/u;
|
|
6721
|
+
const UNREAD_REASON = "This layer kind has no editable HTML form yet; edit it in the editor.";
|
|
6722
|
+
const RICH_TEXT_REASON = "Text with nested layers or nested formatting keeps its formatting in the editor.";
|
|
6723
|
+
const MASK_SHAPE_REASON = "This mask's shape cannot be read; edit it in the editor.";
|
|
6724
|
+
/** Why a layer is sealed in the agent's HTML, or null when the agent reads and writes it. */
|
|
6725
|
+
const sealedReasonOf = (document, node, childCount) => {
|
|
6726
|
+
const sealed = SEALED_REASONS[node.component];
|
|
6727
|
+
if (sealed !== void 0) return sealed;
|
|
6728
|
+
if (canvasMaskClipDeclarations(document, node) === null) return MASK_SHAPE_REASON;
|
|
6729
|
+
if (node.component === "text" && (childCount > 0 || hasCanvasNestedTextRuns(node))) return RICH_TEXT_REASON;
|
|
6730
|
+
if (isCanvasEditableVector(node)) return canvasVectorSealedReason(node) ?? (canvasEditableVectorPath(node) === null ? UNREAD_REASON : null);
|
|
6731
|
+
return READABLE_KINDS.has(node.component) && (node.geometry === void 0 || node.geometry.kind === "mask") ? null : UNREAD_REASON;
|
|
6732
|
+
};
|
|
6733
|
+
/**
|
|
6734
|
+
* The CSS the editor paints for the layer's native appearance, under its authored CSS, so a read
|
|
6735
|
+
* shows what is drawn. Values that name the editor's own resources stay out of the read.
|
|
6736
|
+
*/
|
|
6737
|
+
const paintedDeclarations = (document, node) => {
|
|
6738
|
+
const painted = {
|
|
6739
|
+
...canvasAppearanceDeclarations(node),
|
|
6740
|
+
...canvasMaskLayerDeclarations(node, canvasMaskSourceOf(document, node)),
|
|
6741
|
+
...canvasMaskClipDeclarations(document, node)
|
|
6742
|
+
};
|
|
6743
|
+
const authored = canvasAuthoredStyleDeclarations(node);
|
|
6744
|
+
const entries = Object.entries(painted).flatMap(([property, value]) => {
|
|
6745
|
+
const css = canvasCssValue(property, value);
|
|
6746
|
+
return property.startsWith("--") || css.includes("var(--canvas") || css.includes("url(#") || canvasAppearanceOwnedBy(node, [property]).length === 0 && !MASK_PROPERTY.test(property) ? [] : [[property, css]];
|
|
6747
|
+
});
|
|
6748
|
+
return {
|
|
6749
|
+
...Object.fromEntries(entries),
|
|
6750
|
+
...canvasEditableImageDeclarations(node),
|
|
6751
|
+
...Object.fromEntries(Object.entries(authored).map(([property, value]) => [property, canvasCssValue(property, value)]))
|
|
6752
|
+
};
|
|
6753
|
+
};
|
|
6754
|
+
const fail = (message) => {
|
|
6755
|
+
throw new CliError("BAD_REQUEST", message, "Use a complete current editable read and preserve its identity and opaque markers.");
|
|
6756
|
+
};
|
|
6757
|
+
const escape = (value) => value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """);
|
|
6758
|
+
const vectorPathOf = (node) => isCanvasEditableVector(node) ? canvasEditableVectorPath(node) : null;
|
|
6759
|
+
/** A vector's fill is its path's fill, not a background of its element. */
|
|
6760
|
+
const FILL_PROPERTY = /^background(?:-.+)?$/u;
|
|
6761
|
+
const pathMarkup = (path) => `<path d="${escape(path.d)}" fill-rule="${path.fillRule}" fill="${escape(path.fill)}"></path>`;
|
|
6762
|
+
const styleAttributeOf = (styles) => {
|
|
6763
|
+
const style = Object.entries(styles).toSorted(([left], [right]) => left.localeCompare(right)).map(([key, value]) => `${key}:${value}`).join(";");
|
|
6764
|
+
return style === "" ? "" : ` style="${escape(style)}"`;
|
|
6765
|
+
};
|
|
6766
|
+
const paintMarkup = (paint) => `<div data-enhance-paint="${escape(paint.paintId ?? paint.owner)}"${styleAttributeOf(paint.styles)}></div>`;
|
|
6767
|
+
const runMarkup = (run, index) => `<span data-enhance-run="${String(index)}"${styleAttributeOf(run.styles)}>${escape(run.text)}</span>`;
|
|
6768
|
+
const serialize$1 = (node) => {
|
|
6769
|
+
const style = Object.entries(node.styles).toSorted(([left], [right]) => left.localeCompare(right)).map(([key, value]) => `${key}:${value}`).join(";");
|
|
6770
|
+
const attrs = `data-enhance-id="${escape(node.id)}" data-enhance-name="${escape(node.label)}"${node.opaque ? " data-enhance-opaque=\"true\"" : ""}${node.locked ? " data-enhance-locked=\"true\"" : ""}${style === "" ? "" : ` style="${escape(style)}"`}`;
|
|
6771
|
+
if (node.path !== void 0) return `<svg ${attrs} viewBox="${escape(node.path.viewBox)}" preserveAspectRatio="none">${pathMarkup(node.path)}</svg>`;
|
|
6772
|
+
const runs = (node.runs ?? []).map((run, index) => runMarkup(run, index)).join("");
|
|
6773
|
+
const paints = (node.paints ?? []).map((paint) => paintMarkup(paint)).join("");
|
|
6774
|
+
return `<${node.tag} ${attrs}>${escape(node.text)}${runs}${paints}${node.children.map((child) => serialize$1(child)).join("")}</${node.tag}>`;
|
|
6775
|
+
};
|
|
6776
|
+
const projectCanvasEditableHtml = (document, rootNodeId) => {
|
|
6777
|
+
const seen = /* @__PURE__ */ new Set();
|
|
6778
|
+
const opaqueNodeIds = [];
|
|
6779
|
+
const sealedReasons = {};
|
|
6780
|
+
const childrenByParent = canvasChildrenByParent(document);
|
|
6781
|
+
const visit = (nodeId) => {
|
|
6782
|
+
if (seen.has(nodeId)) return fail("The document contains repeated node identity.");
|
|
6783
|
+
seen.add(nodeId);
|
|
6784
|
+
const node = requireCanvasNode(document, nodeId);
|
|
6785
|
+
const children = childrenByParent.get(nodeId) ?? [];
|
|
6786
|
+
const reason = sealedReasonOf(document, node, children.length);
|
|
6787
|
+
const isOpaque = reason !== null;
|
|
6788
|
+
if (isOpaque) {
|
|
6789
|
+
opaqueNodeIds.push(node.id);
|
|
6790
|
+
sealedReasons[node.id] = reason;
|
|
6791
|
+
}
|
|
6792
|
+
const path = isOpaque ? null : vectorPathOf(node);
|
|
6793
|
+
const runs = isOpaque || node.component !== "text" ? null : canvasEditableTextRuns(node);
|
|
6794
|
+
const paints = isOpaque || path !== null ? [] : canvasEditablePaints(node);
|
|
6795
|
+
const styles = isOpaque ? {} : styleValues(Object.entries(paintedDeclarations(document, node)).filter(([property]) => path === null || !FILL_PROPERTY.test(property)).filter(([property]) => !isCanvasPaintElementProperty(paints, property)).map(([property, value]) => `${property}:${value}`).join(";"));
|
|
6796
|
+
return {
|
|
6797
|
+
id: node.id,
|
|
6798
|
+
tag: path === null ? node.component === "text" ? "span" : "div" : "svg",
|
|
6799
|
+
...path !== null && { path },
|
|
6800
|
+
label: node.label,
|
|
6801
|
+
opaque: isOpaque,
|
|
6802
|
+
locked: isCanvasNodeLocked(document, nodeId),
|
|
6803
|
+
styles,
|
|
6804
|
+
...runs !== null && { runs },
|
|
6805
|
+
...paints.length > 0 && { paints },
|
|
6806
|
+
text: runs !== null || isOpaque || node.component !== "text" ? "" : textOf(node) ?? "",
|
|
6807
|
+
children: isOpaque || path !== null ? [] : children.map((id) => visit(id))
|
|
6808
|
+
};
|
|
6809
|
+
};
|
|
6810
|
+
const root = visit(rootNodeId);
|
|
6811
|
+
return {
|
|
6812
|
+
projectionVersion: 2,
|
|
6813
|
+
root,
|
|
6814
|
+
html: serialize$1(root),
|
|
6815
|
+
opaqueNodeIds,
|
|
6816
|
+
sealedReasons
|
|
6817
|
+
};
|
|
6818
|
+
};
|
|
6819
|
+
|
|
2916
6820
|
//#endregion
|
|
2917
6821
|
//#region src/application/canvas-outline-read.use-case.ts
|
|
2918
6822
|
const rootsFor = (input, reference, scene) => {
|
|
@@ -3295,6 +7199,7 @@ const editable = (input, snapshot) => {
|
|
|
3295
7199
|
rootNodeId: input.rootNodeId,
|
|
3296
7200
|
html: projection.html,
|
|
3297
7201
|
opaqueNodeIds: [...projection.opaqueNodeIds],
|
|
7202
|
+
sealedReasons: { ...projection.sealedReasons },
|
|
3298
7203
|
snapshotToken: canvasSnapshotToken({
|
|
3299
7204
|
reference,
|
|
3300
7205
|
version,
|
|
@@ -3364,7 +7269,7 @@ const createRevisionedCanvasCommandComposite = (remote) => ({ execute: async (in
|
|
|
3364
7269
|
};
|
|
3365
7270
|
const request = applyCanvasOperationsInputSchema.safeParse({
|
|
3366
7271
|
canvasId,
|
|
3367
|
-
documentFormatVersion:
|
|
7272
|
+
documentFormatVersion: 13,
|
|
3368
7273
|
mutationId: input.clientToken,
|
|
3369
7274
|
baseVersion: input.baseVersion,
|
|
3370
7275
|
operations,
|
|
@@ -3511,6 +7416,8 @@ const finishCanvasHtmlReconciliation = (document, prepared, compiled = EMPTY_COM
|
|
|
3511
7416
|
|
|
3512
7417
|
//#endregion
|
|
3513
7418
|
//#region src/application/canvas-html-update-source.use-case.ts
|
|
7419
|
+
/** A paint element belongs to its layer and carries no identity of its own. */
|
|
7420
|
+
const isPaintElement = (element) => element.attrs.some((attribute) => attribute.name === "data-enhance-paint");
|
|
3514
7421
|
const identity = (element) => element.attrs.find((attribute) => attribute.name === "data-enhance-id")?.value;
|
|
3515
7422
|
const invalid$1 = (message) => {
|
|
3516
7423
|
throw new CliError("BAD_REQUEST", message, "Preserve retained identities and opaque placeholders. Add new populated subtrees without identity markers. No canvas changes were committed.");
|
|
@@ -3525,9 +7432,10 @@ const parseCanvasHtmlUpdate = (html) => {
|
|
|
3525
7432
|
const fragments = [];
|
|
3526
7433
|
const visit = (element, parentId) => {
|
|
3527
7434
|
const id = identity(element);
|
|
7435
|
+
if (id !== void 0 && (element.tagName === "svg" || element.tagName === "span")) return element;
|
|
3528
7436
|
if (id !== void 0) return {
|
|
3529
7437
|
...element,
|
|
3530
|
-
childNodes: element.childNodes.map((child) => "tagName" in child ? visit(child, id) : child)
|
|
7438
|
+
childNodes: element.childNodes.map((child) => "tagName" in child && !isPaintElement(child) ? visit(child, id) : child)
|
|
3531
7439
|
};
|
|
3532
7440
|
if (parentId === void 0) return invalid$1("The submitted HTML must retain its original root identity.");
|
|
3533
7441
|
if ([element, ...collectElements(element.childNodes)].some((node) => node.attrs.some((attribute) => ["data-enhance-id", "data-enhance-opaque"].includes(attribute.name)))) return invalid$1("A new HTML subtree cannot wrap retained identities or opaque placeholders. Insert the container and use canvas_arrange to move retained content into it.");
|
|
@@ -3598,9 +7506,28 @@ const removedIds = (before, after, roots, rootNodeId) => {
|
|
|
3598
7506
|
for (const id of before.keys()) if (!after.has(id) && !removed.has(id)) return invalid(`Missing retained node ${id}; declare intentional deletion in removeNodeIds.`);
|
|
3599
7507
|
return removed;
|
|
3600
7508
|
};
|
|
7509
|
+
/** The changed CSS of a layer, written through its owners. */
|
|
7510
|
+
const styleChangeOperations = (document, node, before, after) => {
|
|
7511
|
+
const properties = /* @__PURE__ */ new Set([...Object.keys(before.styles), ...Object.keys(after.styles)]);
|
|
7512
|
+
const styles = Object.fromEntries([...properties].filter((key) => before.styles[key] !== after.styles[key]).filter((key) => !isCanvasEditableImageProperty(node, key)).map((key) => [key, after.styles[key] ?? null]));
|
|
7513
|
+
return [
|
|
7514
|
+
...node.geometry?.kind === "mask" && Object.keys(styles).some((key) => MASK_PROPERTY.test(key)) ? [{
|
|
7515
|
+
op: "setGeometry",
|
|
7516
|
+
nodeId: node.id,
|
|
7517
|
+
geometry: "default"
|
|
7518
|
+
}] : [],
|
|
7519
|
+
...canvasEditableImageOperations(node, before.styles, after.styles),
|
|
7520
|
+
...Object.keys(styles).length === 0 ? [] : canvasStyleOperations(document, [{
|
|
7521
|
+
nodeIds: [node.id],
|
|
7522
|
+
styles
|
|
7523
|
+
}])
|
|
7524
|
+
];
|
|
7525
|
+
};
|
|
3601
7526
|
const fieldOperations = (document, before, after) => {
|
|
3602
|
-
if (before.tag !== after.tag || before.opaque !== after.opaque) return invalid(`The kind or
|
|
7527
|
+
if (before.tag !== after.tag || before.opaque !== after.opaque || before.locked !== after.locked) return invalid(`The kind, opaque marker or locked marker of ${before.id} changed.`);
|
|
3603
7528
|
const hasStyleChange = !arePropertiesEqual(before.styles, after.styles);
|
|
7529
|
+
const hasPathChange = JSON.stringify(before.path) !== JSON.stringify(after.path) || JSON.stringify(before.runs) !== JSON.stringify(after.runs) || JSON.stringify(before.paints) !== JSON.stringify(after.paints);
|
|
7530
|
+
if (before.locked && (hasStyleChange || hasPathChange || before.label !== after.label || before.text !== after.text)) return invalid(`Locked node ${before.id} cannot be changed through HTML.`);
|
|
3604
7531
|
if (before.opaque && (hasStyleChange || before.label !== after.label || before.text !== after.text || after.children.length > 0)) return invalid(`Opaque node ${before.id} cannot be changed through HTML.`);
|
|
3605
7532
|
const node = document.nodes[before.id];
|
|
3606
7533
|
if (node === void 0) return invalid(`Node ${before.id} no longer exists.`);
|
|
@@ -3619,14 +7546,10 @@ const fieldOperations = (document, before, after) => {
|
|
|
3619
7546
|
props: canvasTextPropsWithContent(node, after.text)
|
|
3620
7547
|
})
|
|
3621
7548
|
});
|
|
3622
|
-
|
|
3623
|
-
|
|
3624
|
-
|
|
3625
|
-
|
|
3626
|
-
nodeIds: [before.id],
|
|
3627
|
-
styles
|
|
3628
|
-
}]));
|
|
3629
|
-
}
|
|
7549
|
+
operations.push(...canvasEditablePaintOperations(node, before.paints ?? [], after.paints ?? []));
|
|
7550
|
+
if (before.runs !== void 0 || after.runs !== void 0) operations.push(...canvasEditableTextOperations(node, before.runs ?? [], after.runs ?? []));
|
|
7551
|
+
if (before.path !== void 0 && after.path !== void 0) operations.push(...canvasEditableVectorOperations(document, node, before.path, after.path));
|
|
7552
|
+
if (hasStyleChange) operations.push(...styleChangeOperations(document, node, before, after));
|
|
3630
7553
|
return operations;
|
|
3631
7554
|
};
|
|
3632
7555
|
const prepareCanvasHtmlReconciliation = (document, rootNodeId, html, removeNodeIds) => {
|
|
@@ -3655,7 +7578,7 @@ const prepareCanvasHtmlReconciliation = (document, rootNodeId, html, removeNodeI
|
|
|
3655
7578
|
}
|
|
3656
7579
|
for (const fragment of parsed.fragments) {
|
|
3657
7580
|
const parent = before.get(fragment.parentNodeId);
|
|
3658
|
-
if (parent === void 0 || parent.opaque || parent.tag !== "div") return invalid(`Node ${fragment.parentNodeId} cannot contain new HTML.`);
|
|
7581
|
+
if (parent === void 0 || parent.opaque || parent.locked || parent.tag !== "div") return invalid(`Node ${fragment.parentNodeId} cannot contain new HTML.`);
|
|
3659
7582
|
}
|
|
3660
7583
|
return {
|
|
3661
7584
|
root: requested,
|
|
@@ -4720,4 +8643,4 @@ const createMutationKeyAdapter = () => {
|
|
|
4720
8643
|
};
|
|
4721
8644
|
|
|
4722
8645
|
//#endregion
|
|
4723
|
-
export { createAuthUseCase as S, assertCanvasReferenceOperations as _, readRemoteMcpEnvironment as a, createCanvasActivityComposite as b, createPrototypeArtifactAdapter as c, createRenderFileAdapter as d, readCanvasReferenceScene as f, createEditCanvasComposite as g, fromCapabilityReference as h, readLocalMcpEnvironment as i, createPublishCanvasPrototypeComposite as l, boundedResultPage as m, createHttpRemoteAdapter as n, createOauthLoopbackAdapter as o, createWriteHtmlCanvasComposite as p, readCliEnvironment as r, createCapabilityInvocationAdapter as s, createMutationKeyAdapter as t, createImportCanvasAssetComposite as u, sceneAtVersion as v, createRenderCanvasComposite as x, createApplyCanvasComposite as y };
|
|
8646
|
+
export { canvasRadialGradientSvg as C, canvasAngularGradientSvg as D, canvasDiamondGradientSvg as E, canvasColorCss as O, createAuthUseCase as S, canvasFilterListCss as T, assertCanvasReferenceOperations as _, readRemoteMcpEnvironment as a, createCanvasActivityComposite as b, createPrototypeArtifactAdapter as c, createRenderFileAdapter as d, readCanvasReferenceScene as f, createEditCanvasComposite as g, fromCapabilityReference as h, readLocalMcpEnvironment as i, compareCanvasSortKeys as k, createPublishCanvasPrototypeComposite as l, boundedResultPage as m, createHttpRemoteAdapter as n, createOauthLoopbackAdapter as o, createWriteHtmlCanvasComposite as p, readCliEnvironment as r, createCapabilityInvocationAdapter as s, createMutationKeyAdapter as t, createImportCanvasAssetComposite as u, sceneAtVersion as v, canvasLinearGradientSvg as w, createRenderCanvasComposite as x, createApplyCanvasComposite as y };
|