@ggraphic/editor 0.1.0-alpha.4 → 0.1.0-alpha.6
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/CanvasEditorProvider.d.ts +6 -1
- package/dist/collab/useYjsPageStateSync.d.ts +1 -1
- package/dist/collab/useYjsPageStateSync.js +5 -2
- package/dist/components/CanvasEditor/CanvasEditorShell.js +139 -36
- package/dist/components/CanvasEditor/editorShell.d.ts +6 -0
- package/dist/components/CanvasEditor/types.d.ts +28 -0
- package/dist/components/GenericCanvas.d.ts +19 -2
- package/dist/components/GenericCanvas.js +30 -5
- package/dist/components/PagePreview.d.ts +8 -1
- package/dist/components/PagePreview.js +4 -1
- package/dist/components/TopBar/DownloadSection.d.ts +24 -3
- package/dist/components/TopBar/DownloadSection.js +45 -7
- package/dist/components/TopBar/ShareDropdown.d.ts +4 -2
- package/dist/components/TopBar/ShareDropdown.js +2 -2
- package/dist/entries/export.d.ts +14 -1
- package/dist/entries/export.js +14 -1
- package/dist/entries/services.d.ts +1 -1
- package/dist/export/fonts/fontFiles.d.ts +100 -0
- package/dist/export/fonts/fontFiles.js +333 -0
- package/dist/export/fonts/glyphs.d.ts +113 -0
- package/dist/export/fonts/glyphs.js +120 -0
- package/dist/export/fonts/variation.d.ts +23 -0
- package/dist/export/fonts/variation.js +43 -0
- package/dist/export/pdf/pdfContent.d.ts +108 -0
- package/dist/export/pdf/pdfContent.js +566 -0
- package/dist/export/pdf/pdfFontkit.d.ts +54 -0
- package/dist/export/pdf/pdfFontkit.js +159 -0
- package/dist/export/pdf/pdfGeometry.d.ts +54 -0
- package/dist/export/pdf/pdfGeometry.js +228 -0
- package/dist/export/pdf/pdfResources.d.ts +109 -0
- package/dist/export/pdf/pdfResources.js +314 -0
- package/dist/export/pdf/writePdf.d.ts +34 -0
- package/dist/export/pdf/writePdf.js +165 -0
- package/dist/export/pptx/exportPptxDeck.d.ts +10 -2
- package/dist/export/pptx/exportPptxDeck.js +5 -2
- package/dist/export/pptx/svgPicture.d.ts +19 -0
- package/dist/export/pptx/svgPicture.js +64 -0
- package/dist/export/pptx/vectorizeElement.d.ts +9 -0
- package/dist/export/pptx/vectorizeElement.js +118 -0
- package/dist/export/pptx/writePptx.d.ts +13 -0
- package/dist/export/pptx/writePptx.js +17 -0
- package/dist/export/printPdf.d.ts +1 -0
- package/dist/export/printPdf.js +1 -1
- package/dist/export/scene/browserDeps.d.ts +32 -0
- package/dist/export/scene/browserDeps.js +174 -0
- package/dist/export/scene/imageBytes.d.ts +79 -0
- package/dist/export/scene/imageBytes.js +330 -0
- package/dist/export/scene/itemBounds.d.ts +9 -0
- package/dist/export/scene/itemBounds.js +40 -0
- package/dist/export/scene/matrix.d.ts +13 -0
- package/dist/export/scene/matrix.js +32 -0
- package/dist/export/scene/rasterLimit.d.ts +13 -0
- package/dist/export/scene/rasterLimit.js +24 -0
- package/dist/export/scene/rebaseOps.d.ts +8 -0
- package/dist/export/scene/rebaseOps.js +51 -0
- package/dist/export/scene/recordPageScene.d.ts +28 -0
- package/dist/export/scene/recordPageScene.js +224 -0
- package/dist/export/scene/recordingCanvas.d.ts +55 -0
- package/dist/export/scene/recordingCanvas.js +71 -0
- package/dist/export/scene/recordingContext.d.ts +162 -0
- package/dist/export/scene/recordingContext.js +1031 -0
- package/dist/export/scene/replayScene.d.ts +31 -0
- package/dist/export/scene/replayScene.js +213 -0
- package/dist/export/scene/resolveScene.d.ts +48 -0
- package/dist/export/scene/resolveScene.js +236 -0
- package/dist/export/scene/trustedSvgImages.d.ts +3 -0
- package/dist/export/scene/trustedSvgImages.js +21 -0
- package/dist/export/scene/types.d.ts +241 -0
- package/dist/export/scene/types.js +38 -0
- package/dist/export/slidesPdf.d.ts +10 -2
- package/dist/export/slidesPdf.js +8 -4
- package/dist/export/svg/__fixtures__/barChart.svg +1 -0
- package/dist/export/svg/__golden__/fixture-editable.svg +87 -0
- package/dist/export/svg/__golden__/fixture-outlines.svg +88 -0
- package/dist/export/svg/inlineSvg.d.ts +10 -0
- package/dist/export/svg/inlineSvg.js +119 -0
- package/dist/export/svg/scopeCss.d.ts +45 -0
- package/dist/export/svg/scopeCss.js +214 -0
- package/dist/export/svg/svgColor.d.ts +8 -0
- package/dist/export/svg/svgColor.js +46 -0
- package/dist/export/svg/svgImageScene.d.ts +41 -0
- package/dist/export/svg/svgImageScene.js +128 -0
- package/dist/export/svg/svgPathData.d.ts +31 -0
- package/dist/export/svg/svgPathData.js +466 -0
- package/dist/export/svg/svgToScene.d.ts +19 -0
- package/dist/export/svg/svgToScene.js +1183 -0
- package/dist/export/svg/writeSvg.d.ts +33 -0
- package/dist/export/svg/writeSvg.js +594 -0
- package/dist/export/svg/xml.d.ts +23 -0
- package/dist/export/svg/xml.js +49 -0
- package/dist/export/vectorDeps.d.ts +27 -0
- package/dist/export/vectorDeps.js +37 -0
- package/dist/export/vectorExport.d.ts +85 -0
- package/dist/export/vectorExport.js +287 -0
- package/dist/hostServices.d.ts +15 -0
- package/dist/i18n/de.d.ts +26 -9
- package/dist/i18n/de.js +26 -10
- package/dist/i18n/en.js +24 -0
- package/dist/primitives/AssetPrimitive.js +7 -2
- package/dist/primitives/CanvasIcons.js +6 -0
- package/dist/primitives/CanvasStage.js +2 -2
- package/dist/primitives/ChartPrimitive.d.ts +11 -1
- package/dist/primitives/ChartPrimitive.js +73 -19
- package/dist/primitives/IconPrimitive.js +3 -0
- package/dist/primitives/IllustrationPrimitive.js +14 -1
- package/dist/primitives/chartFont.d.ts +30 -0
- package/dist/primitives/chartFont.js +127 -0
- package/dist/sidebar/sections/ImageAdjustSection.js +5 -4
- package/dist/sidebar/sections/assets/ElementsPanel.js +4 -2
- package/dist/sidebar/sections/assets/assetAudience.d.ts +12 -0
- package/dist/sidebar/sections/assets/assetAudience.js +18 -0
- package/dist/sidebar/sections/assets/useElementCatalog.js +3 -2
- package/dist/stores/createCanvasEditorStore.d.ts +5 -2
- package/dist/stores/createCanvasEditorStore.js +9 -5
- package/dist/styles/compiled.css +1 -1
- package/dist/utils/canvasAssets.d.ts +11 -1
- package/dist/utils/canvasAssets.js +8 -0
- package/dist/utils/canvasIcons.js +5 -3
- package/dist/utils/captureStage.d.ts +19 -0
- package/dist/utils/captureStage.js +14 -1
- package/dist/utils/externalIcons.d.ts +7 -0
- package/dist/utils/externalIcons.js +70 -3
- package/dist/utils/illustrations/svgCache.js +6 -1
- package/dist/utils/imageFilters.d.ts +13 -0
- package/dist/utils/imageFilters.js +11 -0
- package/dist/utils/rebaseHistoryState.d.ts +9 -0
- package/dist/utils/rebaseHistoryState.js +26 -0
- package/dist/utils/zipPageImages.d.ts +8 -0
- package/dist/utils/zipPageImages.js +16 -4
- package/package.json +6 -2
- package/skills/ggraphic-embed/SKILL.md +33 -1
|
@@ -0,0 +1,1031 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-only
|
|
2
|
+
/**
|
|
3
|
+
* A Canvas 2D look-alike that records what Konva draws into scene ops (`types.ts`) instead of
|
|
4
|
+
* painting. It implements the members Konva 10.9 calls on `Context._context`, not the whole
|
|
5
|
+
* interface; callers cast it at that one boundary.
|
|
6
|
+
*
|
|
7
|
+
* How it models the canvas:
|
|
8
|
+
* - **Paths** are kept as the raw commands plus the matrix that was current when each command was
|
|
9
|
+
* added (canvas semantics: a path point is transformed when it is added, not when it is
|
|
10
|
+
* painted). `fill`, `stroke` and `clip` emit the path in the user space of the CTM of THAT
|
|
11
|
+
* call, and the op's `matrix` is that CTM. Gradients, pattern matrices and the stroke width are
|
|
12
|
+
* also interpreted in the space of the call, so this keeps them exact. When every command was
|
|
13
|
+
* added under the same matrix as the call (the usual case) the commands are emitted untouched;
|
|
14
|
+
* when not (Konva's Ellipse scales for the arc, restores, then strokes) each command is mapped
|
|
15
|
+
* through `inverse(CTM at call) · matrix at add`.
|
|
16
|
+
* - **Unknown calls.** Anything the IR cannot express (other composite operations, filters,
|
|
17
|
+
* pixel access, Path2D arguments, patterns that do not repeat, paint objects not made here,
|
|
18
|
+
* letter spacing on the context, right-to-left text, ...) is passed to `onUnknown` with a call
|
|
19
|
+
* name; the caller turns the element into a raster island. Where the draw can still be recorded
|
|
20
|
+
* it is, best effort; the caller discards it.
|
|
21
|
+
* - **Text** is recorded at the alphabetic baseline with one x per code point: the x of glyph i is
|
|
22
|
+
* `width(text[0..i]) - width(text[i])`, measured on the real context so kerning is kept.
|
|
23
|
+
* Konva's per-glyph letter-spacing calls merge into one op while everything else matches.
|
|
24
|
+
* Interleaved fill/stroke glyph calls are not merged: each glyph stays its own op.
|
|
25
|
+
* - **Shadow** values are device px, as on a canvas: the CTM does not scale them.
|
|
26
|
+
*/
|
|
27
|
+
import { IDENTITY, apply, invert, multiply } from './matrix.js';
|
|
28
|
+
/** Longest arc one cubic covers. The radial error is about 4e-6 · r at this angle (2.7e-4 · r at a quarter turn). */
|
|
29
|
+
const MAX_SEGMENT = Math.PI / 4;
|
|
30
|
+
/**
|
|
31
|
+
* Approximates an elliptical arc by cubic beziers.
|
|
32
|
+
*
|
|
33
|
+
* The ellipse is centred on `(cx, cy)` with radii `rx`, `ry`, rotated by `rotation` (radians).
|
|
34
|
+
* `startAngle` is the parametric angle of the start and `sweep` the signed angle to travel, in
|
|
35
|
+
* the canvas convention: y points down, so a positive sweep runs clockwise on screen.
|
|
36
|
+
*
|
|
37
|
+
* Returns the start point and the cubics from it. The caller emits the `M`/`L` to `start`
|
|
38
|
+
* first, because whether it is a move or a line depends on the path it extends.
|
|
39
|
+
*/
|
|
40
|
+
export function arcToBeziers(cx, cy, rx, ry, rotation, startAngle, sweep) {
|
|
41
|
+
const cos = Math.cos(rotation);
|
|
42
|
+
const sin = Math.sin(rotation);
|
|
43
|
+
const point = (t) => {
|
|
44
|
+
const px = rx * Math.cos(t);
|
|
45
|
+
const py = ry * Math.sin(t);
|
|
46
|
+
return { x: cx + px * cos - py * sin, y: cy + px * sin + py * cos };
|
|
47
|
+
};
|
|
48
|
+
const tangent = (t) => {
|
|
49
|
+
const dx = -rx * Math.sin(t);
|
|
50
|
+
const dy = ry * Math.cos(t);
|
|
51
|
+
return { x: dx * cos - dy * sin, y: dx * sin + dy * cos };
|
|
52
|
+
};
|
|
53
|
+
const start = point(startAngle);
|
|
54
|
+
const segments = Math.ceil(Math.abs(sweep) / MAX_SEGMENT);
|
|
55
|
+
const curves = [];
|
|
56
|
+
if (segments === 0)
|
|
57
|
+
return { start, curves };
|
|
58
|
+
const delta = sweep / segments;
|
|
59
|
+
const k = (4 / 3) * Math.tan(delta / 4);
|
|
60
|
+
let from = start;
|
|
61
|
+
for (let i = 0; i < segments; i++) {
|
|
62
|
+
const t0 = startAngle + i * delta;
|
|
63
|
+
const t1 = t0 + delta;
|
|
64
|
+
const to = point(t1);
|
|
65
|
+
const d0 = tangent(t0);
|
|
66
|
+
const d1 = tangent(t1);
|
|
67
|
+
curves.push({
|
|
68
|
+
op: 'C',
|
|
69
|
+
x1: from.x + k * d0.x,
|
|
70
|
+
y1: from.y + k * d0.y,
|
|
71
|
+
x2: to.x - k * d1.x,
|
|
72
|
+
y2: to.y - k * d1.y,
|
|
73
|
+
x: to.x,
|
|
74
|
+
y: to.y,
|
|
75
|
+
});
|
|
76
|
+
from = to;
|
|
77
|
+
}
|
|
78
|
+
return { start, curves };
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The signed sweep of `arc()`/`ellipse()` from `start` to `end`, the way the canvas spec and
|
|
82
|
+
* Chromium (`AdjustEndAngle`) have it: a span of a full turn or more in the drawn direction is the
|
|
83
|
+
* whole circle, and so is a span that is a whole number of turns against it (`arc(0, 2π, true)`: the
|
|
84
|
+
* hole of a ring is drawn that way). Only `start === end` is a zero-length arc.
|
|
85
|
+
*
|
|
86
|
+
* Chromium decides on 32-bit floats, where angles a turn apart "up to rounding" are a turn; `NOISE`
|
|
87
|
+
* stands in for that, so `arc(s, s + 2π)` is the circle whatever the last bit of `s + 2π` is.
|
|
88
|
+
*/
|
|
89
|
+
function arcSweep(start, end, counterclockwise) {
|
|
90
|
+
const TAU = Math.PI * 2;
|
|
91
|
+
const NOISE = 1e-6;
|
|
92
|
+
// The span in the drawn direction: positive when the arc runs the way it was asked to.
|
|
93
|
+
const forward = counterclockwise ? start - end : end - start;
|
|
94
|
+
let sweep;
|
|
95
|
+
if (forward >= TAU - NOISE)
|
|
96
|
+
sweep = TAU;
|
|
97
|
+
else if (forward >= 0)
|
|
98
|
+
sweep = forward;
|
|
99
|
+
else {
|
|
100
|
+
// The end lies behind the start: the arc takes the rest of the turn.
|
|
101
|
+
const back = -forward % TAU;
|
|
102
|
+
sweep = TAU - back < NOISE ? TAU : TAU - back;
|
|
103
|
+
}
|
|
104
|
+
return counterclockwise ? -sweep : sweep;
|
|
105
|
+
}
|
|
106
|
+
const HEX_RE = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/;
|
|
107
|
+
const RGB_RE = /^rgba?\(([^)]*)\)$/;
|
|
108
|
+
const clamp01 = (n) => Math.min(1, Math.max(0, n));
|
|
109
|
+
const byteHex = (n) => Math.min(255, Math.max(0, Math.round(n)))
|
|
110
|
+
.toString(16)
|
|
111
|
+
.padStart(2, '0');
|
|
112
|
+
/** `#rgb[a]`, `#rrggbb[aa]`, `rgb[a](...)` and `transparent`; anything else is `null`. */
|
|
113
|
+
export function parseCssColor(value) {
|
|
114
|
+
const v = value.trim().toLowerCase();
|
|
115
|
+
if (v === 'transparent')
|
|
116
|
+
return { hex: '#000000', alpha: 0 };
|
|
117
|
+
const hex = HEX_RE.exec(v)?.[1];
|
|
118
|
+
if (hex) {
|
|
119
|
+
const full = hex.length <= 4 ? [...hex].map((c) => c + c).join('') : hex;
|
|
120
|
+
return {
|
|
121
|
+
hex: `#${full.slice(0, 6)}`,
|
|
122
|
+
alpha: full.length === 8 ? parseInt(full.slice(6), 16) / 255 : 1,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
const args = RGB_RE.exec(v)?.[1];
|
|
126
|
+
if (args !== undefined) {
|
|
127
|
+
const parts = args.split(/[\s,/]+/).filter(Boolean);
|
|
128
|
+
if (parts.length < 3 || parts.length > 4)
|
|
129
|
+
return null;
|
|
130
|
+
const channel = (p) => (p.endsWith('%') ? parseFloat(p) * 2.55 : parseFloat(p));
|
|
131
|
+
const [r, g, b] = [channel(parts[0]), channel(parts[1]), channel(parts[2])];
|
|
132
|
+
const a = parts[3];
|
|
133
|
+
const alpha = a === undefined ? 1 : a.endsWith('%') ? parseFloat(a) / 100 : parseFloat(a);
|
|
134
|
+
if (![r, g, b, alpha].every(Number.isFinite))
|
|
135
|
+
return null;
|
|
136
|
+
return { hex: `#${byteHex(r)}${byteHex(g)}${byteHex(b)}`, alpha: clamp01(alpha) };
|
|
137
|
+
}
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
const SIZE_RE = /^(\d*\.?\d+)(px|pt)(?:\/\S+)?$/;
|
|
141
|
+
const WEIGHT_WORDS = { normal: 400, bold: 700, bolder: 700, lighter: 100 };
|
|
142
|
+
/**
|
|
143
|
+
* Reads a CSS font shorthand: `[style] [variant] [weight] [stretch] size[/line-height] family,...`.
|
|
144
|
+
* `null` for what cannot be recorded: no size, a unit other than px/pt, `small-caps`, an unknown word.
|
|
145
|
+
*/
|
|
146
|
+
function parseFont(value) {
|
|
147
|
+
const tokens = value.trim().split(/\s+/);
|
|
148
|
+
const sizeAt = tokens.findIndex((t) => SIZE_RE.test(t));
|
|
149
|
+
if (sizeAt < 0)
|
|
150
|
+
return null;
|
|
151
|
+
let weight = 400;
|
|
152
|
+
let style = 'normal';
|
|
153
|
+
for (const token of tokens.slice(0, sizeAt)) {
|
|
154
|
+
const word = token.toLowerCase();
|
|
155
|
+
if (word === 'normal')
|
|
156
|
+
continue;
|
|
157
|
+
if (word === 'italic' || word === 'oblique')
|
|
158
|
+
style = 'italic';
|
|
159
|
+
else if (Object.hasOwn(WEIGHT_WORDS, word))
|
|
160
|
+
weight = WEIGHT_WORDS[word];
|
|
161
|
+
else if (/^\d+$/.test(word) && Number(word) >= 1 && Number(word) <= 1000)
|
|
162
|
+
weight = Number(word);
|
|
163
|
+
else if (/^(ultra-|extra-|semi-)?(condensed|expanded)$/.test(word))
|
|
164
|
+
continue;
|
|
165
|
+
else
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
const [, amount, unit] = SIZE_RE.exec(tokens[sizeAt]);
|
|
169
|
+
const size = Number(amount) * (unit === 'pt' ? 4 / 3 : 1);
|
|
170
|
+
const [family, ...fallback] = fontFamilies(tokens.slice(sizeAt + 1).join(' '));
|
|
171
|
+
if (!family || !(size > 0))
|
|
172
|
+
return null;
|
|
173
|
+
return { family, weight, style, size, ...(fallback.length > 0 && { fallback }) };
|
|
174
|
+
}
|
|
175
|
+
/** The families of a CSS `font-family` list, in order, unquoted. */
|
|
176
|
+
export function fontFamilies(list) {
|
|
177
|
+
const names = [];
|
|
178
|
+
const family = /\s*(?:"([^"]*)"|'([^']*)'|([^,]+?))\s*(?:,|$)/y;
|
|
179
|
+
while (family.lastIndex < list.length) {
|
|
180
|
+
const match = family.exec(list);
|
|
181
|
+
if (!match)
|
|
182
|
+
break;
|
|
183
|
+
const name = match[1] ?? match[2] ?? match[3];
|
|
184
|
+
if (name)
|
|
185
|
+
names.push(name);
|
|
186
|
+
}
|
|
187
|
+
return names;
|
|
188
|
+
}
|
|
189
|
+
class RecordedGradient {
|
|
190
|
+
geometry;
|
|
191
|
+
resolveColor;
|
|
192
|
+
report;
|
|
193
|
+
stops = [];
|
|
194
|
+
constructor(geometry, resolveColor, report) {
|
|
195
|
+
this.geometry = geometry;
|
|
196
|
+
this.resolveColor = resolveColor;
|
|
197
|
+
this.report = report;
|
|
198
|
+
}
|
|
199
|
+
addColorStop(offset, color) {
|
|
200
|
+
if (!(offset >= 0 && offset <= 1)) {
|
|
201
|
+
throw new RangeError(`colour stop offset ${offset} is outside 0..1`);
|
|
202
|
+
}
|
|
203
|
+
const parsed = this.resolveColor(color);
|
|
204
|
+
if (!parsed) {
|
|
205
|
+
this.report(`color:${color}`);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
this.stops.push({ offset, hex: parsed.hex, alpha: parsed.alpha });
|
|
209
|
+
}
|
|
210
|
+
/** `null` where a canvas paints nothing: no stops, or a degenerate geometry. */
|
|
211
|
+
toPaint() {
|
|
212
|
+
const first = this.stops[0];
|
|
213
|
+
if (!first)
|
|
214
|
+
return null;
|
|
215
|
+
if (this.stops.length === 1)
|
|
216
|
+
return { type: 'solid', hex: first.hex, alpha: first.alpha };
|
|
217
|
+
const g = this.geometry;
|
|
218
|
+
if (g.x0 === g.x1 && g.y0 === g.y1 && (g.type === 'linear' || g.r0 === g.r1))
|
|
219
|
+
return null;
|
|
220
|
+
const stops = this.stops.map((s) => ({ ...s })).sort((a, b) => a.offset - b.offset);
|
|
221
|
+
return { ...g, stops };
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
class RecordedPattern {
|
|
225
|
+
image;
|
|
226
|
+
matrix = IDENTITY;
|
|
227
|
+
constructor(image) {
|
|
228
|
+
this.image = image;
|
|
229
|
+
}
|
|
230
|
+
setTransform(m) {
|
|
231
|
+
this.matrix = m ? [m.a ?? 1, m.b ?? 0, m.c ?? 0, m.d ?? 1, m.e ?? 0, m.f ?? 0] : IDENTITY;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
const BLACK = { kind: 'color', raw: '#000000', color: { hex: '#000000', alpha: 1 } };
|
|
235
|
+
const sameMatrix = (a, b) => a.every((v, i) => v === b[i]);
|
|
236
|
+
const sameJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
|
237
|
+
function samePaint(a, b) {
|
|
238
|
+
if (a.type === 'pattern' || b.type === 'pattern') {
|
|
239
|
+
return (a.type === 'pattern' &&
|
|
240
|
+
b.type === 'pattern' &&
|
|
241
|
+
a.image === b.image &&
|
|
242
|
+
sameMatrix(a.matrix, b.matrix));
|
|
243
|
+
}
|
|
244
|
+
return sameJson(a, b);
|
|
245
|
+
}
|
|
246
|
+
function mapCommand(m, c) {
|
|
247
|
+
switch (c.op) {
|
|
248
|
+
case 'M':
|
|
249
|
+
case 'L': {
|
|
250
|
+
const p = apply(m, c.x, c.y);
|
|
251
|
+
return { op: c.op, x: p.x, y: p.y };
|
|
252
|
+
}
|
|
253
|
+
case 'C': {
|
|
254
|
+
const a = apply(m, c.x1, c.y1);
|
|
255
|
+
const b = apply(m, c.x2, c.y2);
|
|
256
|
+
const p = apply(m, c.x, c.y);
|
|
257
|
+
return { op: 'C', x1: a.x, y1: a.y, x2: b.x, y2: b.y, x: p.x, y: p.y };
|
|
258
|
+
}
|
|
259
|
+
case 'Q': {
|
|
260
|
+
const a = apply(m, c.x1, c.y1);
|
|
261
|
+
const p = apply(m, c.x, c.y);
|
|
262
|
+
return { op: 'Q', x1: a.x, y1: a.y, x: p.x, y: p.y };
|
|
263
|
+
}
|
|
264
|
+
case 'Z':
|
|
265
|
+
return c;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
const finite = (...values) => values.every(Number.isFinite);
|
|
269
|
+
/** Width and height of an image source: natural size for an `<img>`, else the element's own. */
|
|
270
|
+
function sourceSize(image) {
|
|
271
|
+
const el = image;
|
|
272
|
+
return { width: el.naturalWidth || el.width || 0, height: el.naturalHeight || el.height || 0 };
|
|
273
|
+
}
|
|
274
|
+
const imageData = (width, height) => {
|
|
275
|
+
const w = Math.max(0, Math.trunc(width) || 0);
|
|
276
|
+
const h = Math.max(0, Math.trunc(height) || 0);
|
|
277
|
+
return {
|
|
278
|
+
width: w,
|
|
279
|
+
height: h,
|
|
280
|
+
data: new Uint8ClampedArray(w * h * 4),
|
|
281
|
+
colorSpace: 'srgb',
|
|
282
|
+
};
|
|
283
|
+
};
|
|
284
|
+
// ---------------------------------------------------------------------------------------------
|
|
285
|
+
export class RecordingContext {
|
|
286
|
+
ops = [];
|
|
287
|
+
page;
|
|
288
|
+
measure;
|
|
289
|
+
size;
|
|
290
|
+
onUnknown;
|
|
291
|
+
colors = new Map();
|
|
292
|
+
stack = [];
|
|
293
|
+
s = {
|
|
294
|
+
matrix: IDENTITY,
|
|
295
|
+
clips: [],
|
|
296
|
+
fill: BLACK,
|
|
297
|
+
stroke: BLACK,
|
|
298
|
+
lineWidth: 1,
|
|
299
|
+
lineCap: 'butt',
|
|
300
|
+
lineJoin: 'miter',
|
|
301
|
+
miterLimit: 10,
|
|
302
|
+
dash: [],
|
|
303
|
+
dashOffset: 0,
|
|
304
|
+
alpha: 1,
|
|
305
|
+
composite: 'source-over',
|
|
306
|
+
filter: 'none',
|
|
307
|
+
fontRaw: '10px sans-serif',
|
|
308
|
+
font: { family: 'sans-serif', weight: 400, style: 'normal', size: 10 },
|
|
309
|
+
textAlign: 'start',
|
|
310
|
+
textBaseline: 'alphabetic',
|
|
311
|
+
direction: 'ltr',
|
|
312
|
+
letterSpacing: '0px',
|
|
313
|
+
shadowColor: { raw: 'rgba(0, 0, 0, 0)', color: { hex: '#000000', alpha: 0 } },
|
|
314
|
+
shadowBlur: 0,
|
|
315
|
+
shadowOffsetX: 0,
|
|
316
|
+
shadowOffsetY: 0,
|
|
317
|
+
smoothing: true,
|
|
318
|
+
smoothingQuality: 'low',
|
|
319
|
+
};
|
|
320
|
+
segs = [];
|
|
321
|
+
/** Current point in device space; the user-space point is `inverse(CTM)` of it. */
|
|
322
|
+
cur = null;
|
|
323
|
+
subpathStart = null;
|
|
324
|
+
constructor(options) {
|
|
325
|
+
this.measure = options.measure;
|
|
326
|
+
this.page = options.page;
|
|
327
|
+
this.size = { width: options.width, height: options.height };
|
|
328
|
+
this.onUnknown = options.onUnknown;
|
|
329
|
+
}
|
|
330
|
+
// -- state ------------------------------------------------------------------------------
|
|
331
|
+
save() {
|
|
332
|
+
this.stack.push({ ...this.s });
|
|
333
|
+
}
|
|
334
|
+
restore() {
|
|
335
|
+
const previous = this.stack.pop();
|
|
336
|
+
if (previous)
|
|
337
|
+
this.s = previous;
|
|
338
|
+
}
|
|
339
|
+
get canvas() {
|
|
340
|
+
return { ...this.size };
|
|
341
|
+
}
|
|
342
|
+
get fillStyle() {
|
|
343
|
+
return this.s.fill.raw;
|
|
344
|
+
}
|
|
345
|
+
set fillStyle(value) {
|
|
346
|
+
const slot = this.styleSlot(value);
|
|
347
|
+
if (slot)
|
|
348
|
+
this.s.fill = slot;
|
|
349
|
+
}
|
|
350
|
+
get strokeStyle() {
|
|
351
|
+
return this.s.stroke.raw;
|
|
352
|
+
}
|
|
353
|
+
set strokeStyle(value) {
|
|
354
|
+
const slot = this.styleSlot(value);
|
|
355
|
+
if (slot)
|
|
356
|
+
this.s.stroke = slot;
|
|
357
|
+
}
|
|
358
|
+
get lineWidth() {
|
|
359
|
+
return this.s.lineWidth;
|
|
360
|
+
}
|
|
361
|
+
set lineWidth(value) {
|
|
362
|
+
if (Number.isFinite(value) && value > 0)
|
|
363
|
+
this.s.lineWidth = value;
|
|
364
|
+
}
|
|
365
|
+
get lineCap() {
|
|
366
|
+
return this.s.lineCap;
|
|
367
|
+
}
|
|
368
|
+
set lineCap(value) {
|
|
369
|
+
if (value === 'butt' || value === 'round' || value === 'square')
|
|
370
|
+
this.s.lineCap = value;
|
|
371
|
+
}
|
|
372
|
+
get lineJoin() {
|
|
373
|
+
return this.s.lineJoin;
|
|
374
|
+
}
|
|
375
|
+
set lineJoin(value) {
|
|
376
|
+
if (value === 'round' || value === 'bevel' || value === 'miter')
|
|
377
|
+
this.s.lineJoin = value;
|
|
378
|
+
}
|
|
379
|
+
get miterLimit() {
|
|
380
|
+
return this.s.miterLimit;
|
|
381
|
+
}
|
|
382
|
+
set miterLimit(value) {
|
|
383
|
+
if (Number.isFinite(value) && value > 0)
|
|
384
|
+
this.s.miterLimit = value;
|
|
385
|
+
}
|
|
386
|
+
get lineDashOffset() {
|
|
387
|
+
return this.s.dashOffset;
|
|
388
|
+
}
|
|
389
|
+
set lineDashOffset(value) {
|
|
390
|
+
if (Number.isFinite(value))
|
|
391
|
+
this.s.dashOffset = value;
|
|
392
|
+
}
|
|
393
|
+
setLineDash(segments) {
|
|
394
|
+
const list = Array.from(segments);
|
|
395
|
+
if (list.some((v) => !Number.isFinite(v) || v < 0))
|
|
396
|
+
return;
|
|
397
|
+
this.s.dash = list.length % 2 === 1 ? [...list, ...list] : list;
|
|
398
|
+
}
|
|
399
|
+
getLineDash() {
|
|
400
|
+
return [...this.s.dash];
|
|
401
|
+
}
|
|
402
|
+
get globalAlpha() {
|
|
403
|
+
return this.s.alpha;
|
|
404
|
+
}
|
|
405
|
+
set globalAlpha(value) {
|
|
406
|
+
if (value >= 0 && value <= 1)
|
|
407
|
+
this.s.alpha = value;
|
|
408
|
+
}
|
|
409
|
+
get globalCompositeOperation() {
|
|
410
|
+
return this.s.composite;
|
|
411
|
+
}
|
|
412
|
+
set globalCompositeOperation(value) {
|
|
413
|
+
this.s.composite = String(value);
|
|
414
|
+
}
|
|
415
|
+
get filter() {
|
|
416
|
+
return this.s.filter;
|
|
417
|
+
}
|
|
418
|
+
set filter(value) {
|
|
419
|
+
this.s.filter = String(value);
|
|
420
|
+
}
|
|
421
|
+
get imageSmoothingEnabled() {
|
|
422
|
+
return this.s.smoothing;
|
|
423
|
+
}
|
|
424
|
+
set imageSmoothingEnabled(value) {
|
|
425
|
+
this.s.smoothing = Boolean(value);
|
|
426
|
+
}
|
|
427
|
+
get imageSmoothingQuality() {
|
|
428
|
+
return this.s.smoothingQuality;
|
|
429
|
+
}
|
|
430
|
+
set imageSmoothingQuality(value) {
|
|
431
|
+
this.s.smoothingQuality = value;
|
|
432
|
+
}
|
|
433
|
+
get shadowColor() {
|
|
434
|
+
return this.s.shadowColor.raw;
|
|
435
|
+
}
|
|
436
|
+
set shadowColor(value) {
|
|
437
|
+
const text = String(value);
|
|
438
|
+
const color = this.parseColor(text);
|
|
439
|
+
if (color)
|
|
440
|
+
this.s.shadowColor = { raw: text, color };
|
|
441
|
+
else
|
|
442
|
+
this.onUnknown(`color:${text}`);
|
|
443
|
+
}
|
|
444
|
+
get shadowBlur() {
|
|
445
|
+
return this.s.shadowBlur;
|
|
446
|
+
}
|
|
447
|
+
set shadowBlur(value) {
|
|
448
|
+
if (Number.isFinite(value) && value >= 0)
|
|
449
|
+
this.s.shadowBlur = value;
|
|
450
|
+
}
|
|
451
|
+
get shadowOffsetX() {
|
|
452
|
+
return this.s.shadowOffsetX;
|
|
453
|
+
}
|
|
454
|
+
set shadowOffsetX(value) {
|
|
455
|
+
if (Number.isFinite(value))
|
|
456
|
+
this.s.shadowOffsetX = value;
|
|
457
|
+
}
|
|
458
|
+
get shadowOffsetY() {
|
|
459
|
+
return this.s.shadowOffsetY;
|
|
460
|
+
}
|
|
461
|
+
set shadowOffsetY(value) {
|
|
462
|
+
if (Number.isFinite(value))
|
|
463
|
+
this.s.shadowOffsetY = value;
|
|
464
|
+
}
|
|
465
|
+
get font() {
|
|
466
|
+
return this.s.fontRaw;
|
|
467
|
+
}
|
|
468
|
+
set font(value) {
|
|
469
|
+
const text = String(value);
|
|
470
|
+
const font = parseFont(text);
|
|
471
|
+
if (font) {
|
|
472
|
+
this.s.fontRaw = text;
|
|
473
|
+
this.s.font = font;
|
|
474
|
+
}
|
|
475
|
+
else {
|
|
476
|
+
this.onUnknown(`font:${text}`);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
get textAlign() {
|
|
480
|
+
return this.s.textAlign;
|
|
481
|
+
}
|
|
482
|
+
set textAlign(value) {
|
|
483
|
+
if (['start', 'end', 'left', 'right', 'center'].includes(value))
|
|
484
|
+
this.s.textAlign = value;
|
|
485
|
+
}
|
|
486
|
+
get textBaseline() {
|
|
487
|
+
return this.s.textBaseline;
|
|
488
|
+
}
|
|
489
|
+
set textBaseline(value) {
|
|
490
|
+
if (['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom'].includes(value)) {
|
|
491
|
+
this.s.textBaseline = value;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
get direction() {
|
|
495
|
+
return this.s.direction;
|
|
496
|
+
}
|
|
497
|
+
set direction(value) {
|
|
498
|
+
if (value === 'ltr' || value === 'rtl' || value === 'inherit')
|
|
499
|
+
this.s.direction = value;
|
|
500
|
+
}
|
|
501
|
+
get letterSpacing() {
|
|
502
|
+
return this.s.letterSpacing;
|
|
503
|
+
}
|
|
504
|
+
set letterSpacing(value) {
|
|
505
|
+
this.s.letterSpacing = String(value);
|
|
506
|
+
}
|
|
507
|
+
// -- transform --------------------------------------------------------------------------
|
|
508
|
+
getTransform() {
|
|
509
|
+
const [a, b, c, d, e, f] = this.s.matrix;
|
|
510
|
+
const isIdentity = sameMatrix(this.s.matrix, IDENTITY);
|
|
511
|
+
return { a, b, c, d, e, f, is2D: true, isIdentity };
|
|
512
|
+
}
|
|
513
|
+
setTransform(a, b, c, d, e, f) {
|
|
514
|
+
if (finite(a, b, c, d, e, f))
|
|
515
|
+
this.s.matrix = [a, b, c, d, e, f];
|
|
516
|
+
}
|
|
517
|
+
resetTransform() {
|
|
518
|
+
this.s.matrix = IDENTITY;
|
|
519
|
+
}
|
|
520
|
+
transform(a, b, c, d, e, f) {
|
|
521
|
+
if (finite(a, b, c, d, e, f))
|
|
522
|
+
this.s.matrix = multiply(this.s.matrix, [a, b, c, d, e, f]);
|
|
523
|
+
}
|
|
524
|
+
translate(x, y) {
|
|
525
|
+
this.transform(1, 0, 0, 1, x, y);
|
|
526
|
+
}
|
|
527
|
+
scale(x, y) {
|
|
528
|
+
this.transform(x, 0, 0, y, 0, 0);
|
|
529
|
+
}
|
|
530
|
+
rotate(angle) {
|
|
531
|
+
const cos = Math.cos(angle);
|
|
532
|
+
const sin = Math.sin(angle);
|
|
533
|
+
this.transform(cos, sin, -sin, cos, 0, 0);
|
|
534
|
+
}
|
|
535
|
+
// -- path construction ------------------------------------------------------------------
|
|
536
|
+
beginPath() {
|
|
537
|
+
this.segs = [];
|
|
538
|
+
this.cur = null;
|
|
539
|
+
this.subpathStart = null;
|
|
540
|
+
}
|
|
541
|
+
closePath() {
|
|
542
|
+
if (this.segs.length > 0 && this.segs[this.segs.length - 1].c.op !== 'Z')
|
|
543
|
+
this.add({ op: 'Z' });
|
|
544
|
+
}
|
|
545
|
+
moveTo(x, y) {
|
|
546
|
+
if (finite(x, y))
|
|
547
|
+
this.add({ op: 'M', x, y });
|
|
548
|
+
}
|
|
549
|
+
lineTo(x, y) {
|
|
550
|
+
if (!finite(x, y))
|
|
551
|
+
return;
|
|
552
|
+
this.add({ op: this.segs.length === 0 ? 'M' : 'L', x, y });
|
|
553
|
+
}
|
|
554
|
+
bezierCurveTo(x1, y1, x2, y2, x, y) {
|
|
555
|
+
if (!finite(x1, y1, x2, y2, x, y))
|
|
556
|
+
return;
|
|
557
|
+
if (this.segs.length === 0)
|
|
558
|
+
this.add({ op: 'M', x: x1, y: y1 });
|
|
559
|
+
this.add({ op: 'C', x1, y1, x2, y2, x, y });
|
|
560
|
+
}
|
|
561
|
+
quadraticCurveTo(x1, y1, x, y) {
|
|
562
|
+
if (!finite(x1, y1, x, y))
|
|
563
|
+
return;
|
|
564
|
+
if (this.segs.length === 0)
|
|
565
|
+
this.add({ op: 'M', x: x1, y: y1 });
|
|
566
|
+
this.add({ op: 'Q', x1, y1, x, y });
|
|
567
|
+
}
|
|
568
|
+
rect(x, y, width, height) {
|
|
569
|
+
if (!finite(x, y, width, height))
|
|
570
|
+
return;
|
|
571
|
+
for (const c of rectCommands(x, y, width, height))
|
|
572
|
+
this.add(c);
|
|
573
|
+
}
|
|
574
|
+
arc(x, y, radius, startAngle, endAngle, counterclockwise = false) {
|
|
575
|
+
this.ellipse(x, y, radius, radius, 0, startAngle, endAngle, counterclockwise);
|
|
576
|
+
}
|
|
577
|
+
ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, counterclockwise = false) {
|
|
578
|
+
if (!finite(x, y, radiusX, radiusY, rotation, startAngle, endAngle))
|
|
579
|
+
return;
|
|
580
|
+
if (radiusX < 0 || radiusY < 0)
|
|
581
|
+
return;
|
|
582
|
+
const sweep = arcSweep(startAngle, endAngle, counterclockwise);
|
|
583
|
+
const { start, curves } = arcToBeziers(x, y, radiusX, radiusY, rotation, startAngle, sweep);
|
|
584
|
+
this.add({ op: this.segs.length === 0 ? 'M' : 'L', x: start.x, y: start.y });
|
|
585
|
+
for (const c of curves)
|
|
586
|
+
this.add(c);
|
|
587
|
+
}
|
|
588
|
+
arcTo(x1, y1, x2, y2, radius) {
|
|
589
|
+
if (!finite(x1, y1, x2, y2, radius) || radius < 0)
|
|
590
|
+
return;
|
|
591
|
+
if (this.segs.length === 0 || !this.cur) {
|
|
592
|
+
this.add({ op: 'M', x: x1, y: y1 });
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
let p0;
|
|
596
|
+
try {
|
|
597
|
+
p0 = apply(invert(this.s.matrix), this.cur.x, this.cur.y);
|
|
598
|
+
}
|
|
599
|
+
catch {
|
|
600
|
+
return; // A singular CTM draws nothing.
|
|
601
|
+
}
|
|
602
|
+
const v1x = p0.x - x1;
|
|
603
|
+
const v1y = p0.y - y1;
|
|
604
|
+
const v2x = x2 - x1;
|
|
605
|
+
const v2y = y2 - y1;
|
|
606
|
+
const l1 = Math.hypot(v1x, v1y);
|
|
607
|
+
const l2 = Math.hypot(v2x, v2y);
|
|
608
|
+
if (l1 === 0 || l2 === 0 || radius === 0 || v1x * v2y - v1y * v2x === 0) {
|
|
609
|
+
this.add({ op: 'L', x: x1, y: y1 });
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
const u1x = v1x / l1;
|
|
613
|
+
const u1y = v1y / l1;
|
|
614
|
+
const u2x = v2x / l2;
|
|
615
|
+
const u2y = v2y / l2;
|
|
616
|
+
// The corner at (x1, y1) opens by `theta`; the circle touches both legs `t` from the corner.
|
|
617
|
+
const theta = Math.acos(Math.min(1, Math.max(-1, u1x * u2x + u1y * u2y)));
|
|
618
|
+
const t = radius / Math.tan(theta / 2);
|
|
619
|
+
const bx = u1x + u2x;
|
|
620
|
+
const by = u1y + u2y;
|
|
621
|
+
const blen = Math.hypot(bx, by);
|
|
622
|
+
const centreDistance = radius / Math.sin(theta / 2);
|
|
623
|
+
const cx = x1 + (bx / blen) * centreDistance;
|
|
624
|
+
const cy = y1 + (by / blen) * centreDistance;
|
|
625
|
+
const t1 = { x: x1 + u1x * t, y: y1 + u1y * t };
|
|
626
|
+
const t2 = { x: x1 + u2x * t, y: y1 + u2y * t };
|
|
627
|
+
if (Math.hypot(t1.x - p0.x, t1.y - p0.y) > 1e-9)
|
|
628
|
+
this.add({ op: 'L', x: t1.x, y: t1.y });
|
|
629
|
+
const a1 = Math.atan2(t1.y - cy, t1.x - cx);
|
|
630
|
+
const a2 = Math.atan2(t2.y - cy, t2.x - cx);
|
|
631
|
+
// The arc is the short way round: less than half a turn.
|
|
632
|
+
const sweep = ((((a2 - a1 + Math.PI) % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI)) - Math.PI;
|
|
633
|
+
for (const c of arcToBeziers(cx, cy, radius, radius, 0, a1, sweep).curves)
|
|
634
|
+
this.add(c);
|
|
635
|
+
}
|
|
636
|
+
roundRect(x, y, width, height, radii = 0) {
|
|
637
|
+
if (!finite(x, y, width, height))
|
|
638
|
+
return;
|
|
639
|
+
const list = Array.isArray(radii) ? radii : [radii];
|
|
640
|
+
if (list.length < 1 || list.length > 4 || list.some((r) => typeof r !== 'number')) {
|
|
641
|
+
this.onUnknown('roundRect:radii');
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
const r = list;
|
|
645
|
+
if (r.some((v) => !finite(v) || v < 0))
|
|
646
|
+
return;
|
|
647
|
+
const [tl0, tr0, br0, bl0] = r.length === 1
|
|
648
|
+
? [r[0], r[0], r[0], r[0]]
|
|
649
|
+
: r.length === 2
|
|
650
|
+
? [r[0], r[1], r[0], r[1]]
|
|
651
|
+
: r.length === 3
|
|
652
|
+
? [r[0], r[1], r[2], r[1]]
|
|
653
|
+
: r;
|
|
654
|
+
const w = Math.abs(width);
|
|
655
|
+
const h = Math.abs(height);
|
|
656
|
+
const left = width < 0 ? x + width : x;
|
|
657
|
+
const top = height < 0 ? y + height : y;
|
|
658
|
+
// Radii that do not fit a side shrink together, as in the spec.
|
|
659
|
+
const fit = (side, sum) => (sum > 0 ? side / sum : 1);
|
|
660
|
+
const f = Math.min(1, fit(w, tl0 + tr0), fit(w, bl0 + br0), fit(h, tl0 + bl0), fit(h, tr0 + br0));
|
|
661
|
+
const [tl, tr, br, bl] = [tl0 * f, tr0 * f, br0 * f, bl0 * f];
|
|
662
|
+
const corner = (cx, cy, radius, from) => {
|
|
663
|
+
if (radius <= 0)
|
|
664
|
+
return;
|
|
665
|
+
for (const c of arcToBeziers(cx, cy, radius, radius, 0, from, Math.PI / 2).curves) {
|
|
666
|
+
this.add(c);
|
|
667
|
+
}
|
|
668
|
+
};
|
|
669
|
+
this.add({ op: 'M', x: left + tl, y: top });
|
|
670
|
+
this.add({ op: 'L', x: left + w - tr, y: top });
|
|
671
|
+
corner(left + w - tr, top + tr, tr, -Math.PI / 2);
|
|
672
|
+
this.add({ op: 'L', x: left + w, y: top + h - br });
|
|
673
|
+
corner(left + w - br, top + h - br, br, 0);
|
|
674
|
+
this.add({ op: 'L', x: left + bl, y: top + h });
|
|
675
|
+
corner(left + bl, top + h - bl, bl, Math.PI / 2);
|
|
676
|
+
this.add({ op: 'L', x: left, y: top + tl });
|
|
677
|
+
corner(left + tl, top + tl, tl, Math.PI);
|
|
678
|
+
this.add({ op: 'Z' });
|
|
679
|
+
}
|
|
680
|
+
fill(first, second) {
|
|
681
|
+
if (typeof first === 'object')
|
|
682
|
+
return this.onUnknown('fill:path2d');
|
|
683
|
+
this.drawPath('fill', this.segs, first ?? second ?? 'nonzero');
|
|
684
|
+
}
|
|
685
|
+
stroke(path) {
|
|
686
|
+
if (path)
|
|
687
|
+
return this.onUnknown('stroke:path2d');
|
|
688
|
+
this.drawPath('stroke', this.segs, 'nonzero');
|
|
689
|
+
}
|
|
690
|
+
clip(first, second) {
|
|
691
|
+
if (typeof first === 'object')
|
|
692
|
+
return this.onUnknown('clip:path2d');
|
|
693
|
+
// An empty or degenerate path clips everything away, as on a canvas.
|
|
694
|
+
const path = this.inCallSpace(this.segs);
|
|
695
|
+
this.s.clips = [
|
|
696
|
+
...this.s.clips,
|
|
697
|
+
{
|
|
698
|
+
matrix: this.s.matrix,
|
|
699
|
+
commands: path ?? [],
|
|
700
|
+
rule: first ?? second ?? 'nonzero',
|
|
701
|
+
},
|
|
702
|
+
];
|
|
703
|
+
}
|
|
704
|
+
fillRect(x, y, width, height) {
|
|
705
|
+
if (!finite(x, y, width, height) || width === 0 || height === 0)
|
|
706
|
+
return;
|
|
707
|
+
this.drawPath('fill', this.rectSegments(x, y, width, height), 'nonzero');
|
|
708
|
+
}
|
|
709
|
+
strokeRect(x, y, width, height) {
|
|
710
|
+
if (!finite(x, y, width, height) || (width === 0 && height === 0))
|
|
711
|
+
return;
|
|
712
|
+
this.drawPath('stroke', this.rectSegments(x, y, width, height), 'nonzero');
|
|
713
|
+
}
|
|
714
|
+
clearRect(x, y, width, height) {
|
|
715
|
+
const [a, b, c, d, e, f] = this.s.matrix;
|
|
716
|
+
const left = Math.min(x, x + width);
|
|
717
|
+
const right = Math.max(x, x + width);
|
|
718
|
+
const top = Math.min(y, y + height);
|
|
719
|
+
const bottom = Math.max(y, y + height);
|
|
720
|
+
const coversCanvas = b === 0 &&
|
|
721
|
+
c === 0 &&
|
|
722
|
+
a > 0 &&
|
|
723
|
+
d > 0 &&
|
|
724
|
+
this.s.clips.length === 0 &&
|
|
725
|
+
left * a + e <= 0 &&
|
|
726
|
+
top * d + f <= 0 &&
|
|
727
|
+
right * a + e >= this.size.width &&
|
|
728
|
+
bottom * d + f >= this.size.height;
|
|
729
|
+
// The recording starts empty, so clearing all of it changes nothing.
|
|
730
|
+
if (!coversCanvas)
|
|
731
|
+
this.onUnknown('clearRect');
|
|
732
|
+
}
|
|
733
|
+
// -- text -------------------------------------------------------------------------------
|
|
734
|
+
fillText(text, x, y, maxWidth) {
|
|
735
|
+
this.drawText('fill', text, x, y, maxWidth);
|
|
736
|
+
}
|
|
737
|
+
strokeText(text, x, y, maxWidth) {
|
|
738
|
+
this.drawText('stroke', text, x, y, maxWidth);
|
|
739
|
+
}
|
|
740
|
+
measureText(text) {
|
|
741
|
+
this.syncMeasure();
|
|
742
|
+
return this.measure.measureText(text);
|
|
743
|
+
}
|
|
744
|
+
drawImage(image, ...n) {
|
|
745
|
+
const size = sourceSize(image);
|
|
746
|
+
let rect;
|
|
747
|
+
if (n.length === 2)
|
|
748
|
+
rect = [0, 0, size.width, size.height, n[0], n[1], size.width, size.height];
|
|
749
|
+
else if (n.length === 4)
|
|
750
|
+
rect = [0, 0, size.width, size.height, n[0], n[1], n[2], n[3]];
|
|
751
|
+
else if (n.length === 8)
|
|
752
|
+
rect = n;
|
|
753
|
+
else
|
|
754
|
+
return;
|
|
755
|
+
if (!finite(...rect))
|
|
756
|
+
return;
|
|
757
|
+
this.effects();
|
|
758
|
+
const [sx, sy, sw, sh, dx, dy, dw, dh] = rect;
|
|
759
|
+
this.ops.push({
|
|
760
|
+
kind: 'image',
|
|
761
|
+
image: { kind: 'element', element: image, ...size },
|
|
762
|
+
sx,
|
|
763
|
+
sy,
|
|
764
|
+
sw,
|
|
765
|
+
sh,
|
|
766
|
+
dx,
|
|
767
|
+
dy,
|
|
768
|
+
dw,
|
|
769
|
+
dh,
|
|
770
|
+
...this.base(this.s.matrix),
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
createLinearGradient(x0, y0, x1, y1) {
|
|
774
|
+
return this.gradient({ type: 'linear', x0, y0, x1, y1 });
|
|
775
|
+
}
|
|
776
|
+
createRadialGradient(x0, y0, r0, x1, y1, r1) {
|
|
777
|
+
return this.gradient({ type: 'radial', x0, y0, r0, x1, y1, r1 });
|
|
778
|
+
}
|
|
779
|
+
createPattern(image, repetition) {
|
|
780
|
+
const repeat = repetition === null || repetition === '' ? 'repeat' : repetition;
|
|
781
|
+
if (repeat !== 'repeat') {
|
|
782
|
+
this.onUnknown(`createPattern:${repeat}`);
|
|
783
|
+
return null;
|
|
784
|
+
}
|
|
785
|
+
const ref = { kind: 'element', element: image, ...sourceSize(image) };
|
|
786
|
+
return new RecordedPattern(ref);
|
|
787
|
+
}
|
|
788
|
+
// -- pixel access: not modelled ---------------------------------------------------------
|
|
789
|
+
getImageData(_sx, _sy, sw, sh) {
|
|
790
|
+
this.onUnknown('getImageData');
|
|
791
|
+
return imageData(Math.abs(sw), Math.abs(sh));
|
|
792
|
+
}
|
|
793
|
+
putImageData(_imageData, _dx, _dy, ..._dirty) {
|
|
794
|
+
this.onUnknown('putImageData');
|
|
795
|
+
}
|
|
796
|
+
createImageData(sw, sh) {
|
|
797
|
+
return typeof sw === 'number'
|
|
798
|
+
? imageData(Math.abs(sw), Math.abs(sh ?? 0))
|
|
799
|
+
: imageData(sw.width, sw.height);
|
|
800
|
+
}
|
|
801
|
+
isPointInPath(..._args) {
|
|
802
|
+
return false;
|
|
803
|
+
}
|
|
804
|
+
// -- internals --------------------------------------------------------------------------
|
|
805
|
+
add(c) {
|
|
806
|
+
this.segs.push({ m: this.s.matrix, c });
|
|
807
|
+
if (c.op === 'Z') {
|
|
808
|
+
this.cur = this.subpathStart;
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
const p = apply(this.s.matrix, c.x, c.y);
|
|
812
|
+
this.cur = p;
|
|
813
|
+
if (c.op === 'M')
|
|
814
|
+
this.subpathStart = p;
|
|
815
|
+
}
|
|
816
|
+
rectSegments(x, y, width, height) {
|
|
817
|
+
return rectCommands(x, y, width, height).map((c) => ({ m: this.s.matrix, c }));
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* The path as commands in the user space of the current CTM, or `null` when it draws nothing:
|
|
821
|
+
* no segment beyond moves, or a singular CTM that cannot be inverted.
|
|
822
|
+
*/
|
|
823
|
+
inCallSpace(segs) {
|
|
824
|
+
if (!segs.some((s) => s.c.op !== 'M'))
|
|
825
|
+
return null;
|
|
826
|
+
const ctm = this.s.matrix;
|
|
827
|
+
if (segs.every((s) => s.c.op === 'Z' || sameMatrix(s.m, ctm)))
|
|
828
|
+
return segs.map((s) => s.c);
|
|
829
|
+
let inverse;
|
|
830
|
+
try {
|
|
831
|
+
inverse = invert(ctm);
|
|
832
|
+
}
|
|
833
|
+
catch {
|
|
834
|
+
return null;
|
|
835
|
+
}
|
|
836
|
+
let seen = null;
|
|
837
|
+
let combined = IDENTITY;
|
|
838
|
+
return segs.map((s) => {
|
|
839
|
+
if (s.m !== seen) {
|
|
840
|
+
seen = s.m;
|
|
841
|
+
combined = multiply(inverse, s.m);
|
|
842
|
+
}
|
|
843
|
+
return mapCommand(combined, s.c);
|
|
844
|
+
});
|
|
845
|
+
}
|
|
846
|
+
drawPath(mode, segs, rule) {
|
|
847
|
+
this.effects();
|
|
848
|
+
const paint = this.paintOf(mode === 'fill' ? 'fillStyle' : 'strokeStyle');
|
|
849
|
+
const commands = this.inCallSpace(segs);
|
|
850
|
+
if (!paint || !commands)
|
|
851
|
+
return;
|
|
852
|
+
this.ops.push({
|
|
853
|
+
kind: 'path',
|
|
854
|
+
mode,
|
|
855
|
+
commands,
|
|
856
|
+
rule,
|
|
857
|
+
paint,
|
|
858
|
+
stroke: mode === 'stroke' ? this.strokeState() : null,
|
|
859
|
+
...this.base(this.s.matrix),
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
drawText(mode, text, x, y, maxWidth) {
|
|
863
|
+
if (text === '' || !finite(x, y))
|
|
864
|
+
return;
|
|
865
|
+
this.effects();
|
|
866
|
+
const s = this.s;
|
|
867
|
+
if (parseFloat(s.letterSpacing) !== 0)
|
|
868
|
+
this.onUnknown('letterSpacing');
|
|
869
|
+
if (s.direction === 'rtl')
|
|
870
|
+
this.onUnknown('direction:rtl');
|
|
871
|
+
const paint = this.paintOf(mode === 'fill' ? 'fillStyle' : 'strokeStyle');
|
|
872
|
+
if (!paint)
|
|
873
|
+
return;
|
|
874
|
+
this.syncMeasure();
|
|
875
|
+
const aligned = s.textAlign === 'center' || s.textAlign === 'right' || s.textAlign === 'end';
|
|
876
|
+
const needsMetrics = aligned || maxWidth !== undefined || s.textBaseline !== 'alphabetic';
|
|
877
|
+
const metrics = needsMetrics ? this.measure.measureText(text) : null;
|
|
878
|
+
if (metrics && maxWidth !== undefined && metrics.width > maxWidth) {
|
|
879
|
+
this.onUnknown(`${mode === 'fill' ? 'fillText' : 'strokeText'}:maxWidth`);
|
|
880
|
+
}
|
|
881
|
+
// The IR is always at the alphabetic baseline. `alphabeticBaseline` is the distance from the
|
|
882
|
+
// line `textBaseline` names UP to the alphabetic baseline, so it is subtracted in y-down space.
|
|
883
|
+
let baselineShift = 0;
|
|
884
|
+
if (metrics && s.textBaseline !== 'alphabetic') {
|
|
885
|
+
if (Number.isFinite(metrics.alphabeticBaseline))
|
|
886
|
+
baselineShift = metrics.alphabeticBaseline;
|
|
887
|
+
else {
|
|
888
|
+
// The same glyph top seen from both lines: ascent(requested) - ascent(alphabetic).
|
|
889
|
+
const ascent = metrics.actualBoundingBoxAscent;
|
|
890
|
+
this.measure.textBaseline = 'alphabetic';
|
|
891
|
+
const alphabetic = this.measure.measureText(text).actualBoundingBoxAscent;
|
|
892
|
+
this.measure.textBaseline = s.textBaseline;
|
|
893
|
+
if (Number.isFinite(ascent) && Number.isFinite(alphabetic))
|
|
894
|
+
baselineShift = ascent - alphabetic;
|
|
895
|
+
else
|
|
896
|
+
this.onUnknown('measureText:alphabeticBaseline');
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
const baseline = y - baselineShift;
|
|
900
|
+
const width = metrics ? metrics.width : 0;
|
|
901
|
+
const x0 = s.textAlign === 'center' ? x - width / 2 : aligned ? x - width : x;
|
|
902
|
+
const chars = Array.from(text);
|
|
903
|
+
const xs = [x0];
|
|
904
|
+
for (let i = 1; i < chars.length; i++) {
|
|
905
|
+
const through = this.measure.measureText(chars.slice(0, i + 1).join('')).width;
|
|
906
|
+
xs.push(x0 + through - this.measure.measureText(chars[i]).width);
|
|
907
|
+
}
|
|
908
|
+
const base = this.base(s.matrix);
|
|
909
|
+
const stroke = mode === 'stroke' ? this.strokeState() : null;
|
|
910
|
+
const last = this.ops[this.ops.length - 1];
|
|
911
|
+
if (last?.kind === 'text' &&
|
|
912
|
+
last.mode === mode &&
|
|
913
|
+
last.y === baseline &&
|
|
914
|
+
last.alpha === base.alpha &&
|
|
915
|
+
sameMatrix(last.matrix, base.matrix) &&
|
|
916
|
+
last.clips.length === base.clips.length &&
|
|
917
|
+
last.clips.every((c, i) => c === base.clips[i]) &&
|
|
918
|
+
sameJson(last.shadow, base.shadow) &&
|
|
919
|
+
sameJson(last.font, s.font) &&
|
|
920
|
+
sameJson(last.stroke, stroke) &&
|
|
921
|
+
samePaint(last.paint, paint)) {
|
|
922
|
+
last.text += text;
|
|
923
|
+
last.xs.push(...xs);
|
|
924
|
+
return;
|
|
925
|
+
}
|
|
926
|
+
this.ops.push({
|
|
927
|
+
kind: 'text',
|
|
928
|
+
mode,
|
|
929
|
+
text,
|
|
930
|
+
xs,
|
|
931
|
+
y: baseline,
|
|
932
|
+
font: s.font,
|
|
933
|
+
paint,
|
|
934
|
+
stroke,
|
|
935
|
+
...base,
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
/** What the canvas would apply that the IR cannot express. */
|
|
939
|
+
effects() {
|
|
940
|
+
if (this.s.composite !== 'source-over') {
|
|
941
|
+
this.onUnknown(`globalCompositeOperation:${this.s.composite}`);
|
|
942
|
+
}
|
|
943
|
+
if (this.s.filter !== 'none')
|
|
944
|
+
this.onUnknown(`filter:${this.s.filter}`);
|
|
945
|
+
}
|
|
946
|
+
base(matrix) {
|
|
947
|
+
return { matrix, alpha: this.s.alpha, clips: this.s.clips, shadow: this.shadowState() };
|
|
948
|
+
}
|
|
949
|
+
shadowState() {
|
|
950
|
+
const s = this.s;
|
|
951
|
+
const { hex, alpha } = s.shadowColor.color;
|
|
952
|
+
if (alpha === 0)
|
|
953
|
+
return null;
|
|
954
|
+
if (s.shadowBlur === 0 && s.shadowOffsetX === 0 && s.shadowOffsetY === 0)
|
|
955
|
+
return null;
|
|
956
|
+
return { hex, alpha, blur: s.shadowBlur, offsetX: s.shadowOffsetX, offsetY: s.shadowOffsetY };
|
|
957
|
+
}
|
|
958
|
+
strokeState() {
|
|
959
|
+
const s = this.s;
|
|
960
|
+
return {
|
|
961
|
+
width: s.lineWidth,
|
|
962
|
+
cap: s.lineCap,
|
|
963
|
+
join: s.lineJoin,
|
|
964
|
+
miterLimit: s.miterLimit,
|
|
965
|
+
dash: [...s.dash],
|
|
966
|
+
dashOffset: s.dashOffset,
|
|
967
|
+
};
|
|
968
|
+
}
|
|
969
|
+
paintOf(which) {
|
|
970
|
+
const slot = which === 'fillStyle' ? this.s.fill : this.s.stroke;
|
|
971
|
+
if (slot.kind === 'color')
|
|
972
|
+
return { type: 'solid', ...slot.color };
|
|
973
|
+
const raw = slot.raw;
|
|
974
|
+
if (raw instanceof RecordedGradient)
|
|
975
|
+
return raw.toPaint();
|
|
976
|
+
if (raw instanceof RecordedPattern) {
|
|
977
|
+
return { type: 'pattern', image: raw.image, repeat: 'repeat', matrix: raw.matrix };
|
|
978
|
+
}
|
|
979
|
+
// Konva makes its own gradients and patterns on a private native context; they cannot be read.
|
|
980
|
+
this.onUnknown(`${which}:foreign-paint`);
|
|
981
|
+
return null;
|
|
982
|
+
}
|
|
983
|
+
styleSlot(value) {
|
|
984
|
+
if (typeof value === 'object' && value !== null) {
|
|
985
|
+
return { kind: 'object', raw: value };
|
|
986
|
+
}
|
|
987
|
+
const text = String(value);
|
|
988
|
+
const color = this.parseColor(text);
|
|
989
|
+
if (color)
|
|
990
|
+
return { kind: 'color', raw: text, color };
|
|
991
|
+
this.onUnknown(`color:${text}`);
|
|
992
|
+
return null;
|
|
993
|
+
}
|
|
994
|
+
gradient(geometry) {
|
|
995
|
+
const gradient = new RecordedGradient(geometry, (value) => this.parseColor(value), this.onUnknown);
|
|
996
|
+
return gradient;
|
|
997
|
+
}
|
|
998
|
+
/** Our own parser first; names, `hsl()` and the like are canonicalised by the measuring context. */
|
|
999
|
+
parseColor(value) {
|
|
1000
|
+
const known = this.colors.get(value);
|
|
1001
|
+
if (known !== undefined)
|
|
1002
|
+
return known;
|
|
1003
|
+
let color = parseCssColor(value);
|
|
1004
|
+
if (!color) {
|
|
1005
|
+
const sentinel = '#010203';
|
|
1006
|
+
this.measure.fillStyle = sentinel;
|
|
1007
|
+
this.measure.fillStyle = value;
|
|
1008
|
+
const canonical = String(this.measure.fillStyle);
|
|
1009
|
+
color = canonical === sentinel ? null : parseCssColor(canonical);
|
|
1010
|
+
}
|
|
1011
|
+
this.colors.set(value, color);
|
|
1012
|
+
return color;
|
|
1013
|
+
}
|
|
1014
|
+
syncMeasure() {
|
|
1015
|
+
const m = this.measure;
|
|
1016
|
+
m.font = this.s.fontRaw;
|
|
1017
|
+
m.textAlign = this.s.textAlign;
|
|
1018
|
+
m.textBaseline = this.s.textBaseline;
|
|
1019
|
+
m.letterSpacing = this.s.letterSpacing;
|
|
1020
|
+
m.direction = this.s.direction;
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
function rectCommands(x, y, width, height) {
|
|
1024
|
+
return [
|
|
1025
|
+
{ op: 'M', x, y },
|
|
1026
|
+
{ op: 'L', x: x + width, y },
|
|
1027
|
+
{ op: 'L', x: x + width, y: y + height },
|
|
1028
|
+
{ op: 'L', x, y: y + height },
|
|
1029
|
+
{ op: 'Z' },
|
|
1030
|
+
];
|
|
1031
|
+
}
|