@open-slide/core 2.0.0-beta.1 → 2.0.0-beta.2
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/{config-AtA2Bqtn.d.ts → config-DjWifhaA.d.ts} +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/locale/index.d.ts +1 -1
- package/dist/locale/index.js +1 -1
- package/dist/{types-BzPSOxe-.d.ts → types-BWg-Dtbg.d.ts} +1 -2
- package/dist/vite/index.d.ts +1 -1
- package/dist/{zh-tw-BxZ_pYqe.js → zh-tw-DlKyeNX7.js} +4 -8
- package/package.json +1 -1
- package/skills/slide-authoring/SKILL.md +3 -3
- package/skills/slide-authoring/references/morph.md +5 -5
- package/skills/slide-authoring/references/transitions.md +38 -37
- package/skills/slide-authoring/references/webfonts.md +25 -6
- package/src/app/components/command/slide-command-menu.tsx +10 -0
- package/src/app/components/slide-transition-layer.tsx +8 -1
- package/src/app/lib/export-pptx.ts +122 -193
- package/src/app/lib/pptx/color.ts +49 -0
- package/src/app/lib/pptx/css.test.ts +172 -0
- package/src/app/lib/pptx/css.ts +450 -0
- package/src/app/lib/pptx/fonts.ts +145 -0
- package/src/app/lib/pptx/images.ts +116 -0
- package/src/app/lib/pptx/measure.ts +1299 -0
- package/src/app/lib/pptx/ooxml.test.ts +199 -0
- package/src/app/lib/pptx/ooxml.ts +470 -0
- package/src/app/lib/pptx/raster.ts +189 -0
- package/src/app/lib/pptx/render.ts +102 -0
- package/src/app/lib/pptx/scene.ts +116 -0
- package/src/app/lib/pptx/text-lines.test.ts +82 -0
- package/src/app/lib/pptx/text-lines.ts +109 -0
- package/src/app/lib/pptx/units.ts +22 -0
- package/src/app/lib/transition.test.ts +31 -0
- package/src/app/lib/transition.ts +13 -0
- package/src/app/routes/slide.tsx +21 -27
- package/src/locale/en.ts +1 -3
- package/src/locale/ja.ts +1 -3
- package/src/locale/types.ts +1 -2
- package/src/locale/zh-cn.ts +1 -2
- package/src/locale/zh-tw.ts +1 -2
|
@@ -0,0 +1,1299 @@
|
|
|
1
|
+
import { CANVAS_HEIGHT, CANVAS_WIDTH } from '../sdk';
|
|
2
|
+
import {
|
|
3
|
+
applyTextTransform,
|
|
4
|
+
applyToPoint,
|
|
5
|
+
type ColorParser,
|
|
6
|
+
decompose,
|
|
7
|
+
hasRadius,
|
|
8
|
+
IDENTITY,
|
|
9
|
+
isIdentity,
|
|
10
|
+
isVisibleColor,
|
|
11
|
+
type Mat,
|
|
12
|
+
multiply,
|
|
13
|
+
normalizeRadii,
|
|
14
|
+
parseAngleDeg,
|
|
15
|
+
parseBlurPx,
|
|
16
|
+
parseCornerRadius,
|
|
17
|
+
parseLinearGradient,
|
|
18
|
+
parsePx,
|
|
19
|
+
parseShadows,
|
|
20
|
+
parseTransform,
|
|
21
|
+
type Radii,
|
|
22
|
+
type Rgba,
|
|
23
|
+
rotationDeg,
|
|
24
|
+
type Shadow,
|
|
25
|
+
scaling,
|
|
26
|
+
splitTopLevel,
|
|
27
|
+
transformedBounds,
|
|
28
|
+
translation,
|
|
29
|
+
withAlpha,
|
|
30
|
+
} from './css';
|
|
31
|
+
import { resolveFontFamily } from './fonts';
|
|
32
|
+
import type { ImageStore, LoadedImage } from './images';
|
|
33
|
+
import {
|
|
34
|
+
clampToSlide,
|
|
35
|
+
expandRect,
|
|
36
|
+
type Rasterizer,
|
|
37
|
+
type RasterMode,
|
|
38
|
+
type RasterRequest,
|
|
39
|
+
} from './raster';
|
|
40
|
+
import type {
|
|
41
|
+
Bullet,
|
|
42
|
+
Crop,
|
|
43
|
+
Fill,
|
|
44
|
+
Geometry,
|
|
45
|
+
Outline,
|
|
46
|
+
Paragraph,
|
|
47
|
+
PictureNode,
|
|
48
|
+
Rect,
|
|
49
|
+
RunStyle,
|
|
50
|
+
SceneNode,
|
|
51
|
+
ShadowEffect,
|
|
52
|
+
ShapeNode,
|
|
53
|
+
SlideScene,
|
|
54
|
+
TextLine,
|
|
55
|
+
TextNode,
|
|
56
|
+
TextShadow,
|
|
57
|
+
} from './scene';
|
|
58
|
+
import { type Atom, fillEmptyLines, groupAtomsIntoLines, lineToRuns } from './text-lines';
|
|
59
|
+
|
|
60
|
+
const MEASURE_CLASS = 'os-pptx-measure';
|
|
61
|
+
const MIN_SIZE = 0.25;
|
|
62
|
+
const PITCH_TOLERANCE = 0.6;
|
|
63
|
+
const MEDIA_TAGS = new Set(['IMG', 'SVG', 'VIDEO', 'CANVAS', 'PICTURE']);
|
|
64
|
+
const SKIPPED_TAGS = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE', 'IFRAME', 'LINK', 'META']);
|
|
65
|
+
|
|
66
|
+
type Decoration = { underline: boolean; strike: boolean };
|
|
67
|
+
|
|
68
|
+
type Inherited = {
|
|
69
|
+
world: Mat;
|
|
70
|
+
opacity: number;
|
|
71
|
+
clip: Rect | null;
|
|
72
|
+
decoration: Decoration;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
type Slot = { node: SceneNode | null };
|
|
76
|
+
|
|
77
|
+
type Measured = {
|
|
78
|
+
el: Element;
|
|
79
|
+
cs: CSSStyleDeclaration;
|
|
80
|
+
rect: Rect;
|
|
81
|
+
world: Mat;
|
|
82
|
+
opacity: number;
|
|
83
|
+
clip: Rect | null;
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
type Ctx = {
|
|
87
|
+
frame: HTMLElement;
|
|
88
|
+
frameRect: DOMRect;
|
|
89
|
+
transforms: Map<Element, Mat>;
|
|
90
|
+
slots: Slot[];
|
|
91
|
+
rasters: { slot: Slot; request: RasterRequest; svg: Uint8Array | null }[];
|
|
92
|
+
pending: Promise<void>[];
|
|
93
|
+
images: ImageStore;
|
|
94
|
+
color: ColorParser;
|
|
95
|
+
segmenter: Intl.Segmenter | null;
|
|
96
|
+
measureCanvas: CanvasRenderingContext2D | null;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
export type MeasurePageOptions = {
|
|
100
|
+
frame: HTMLElement;
|
|
101
|
+
notes: string | null;
|
|
102
|
+
images: ImageStore;
|
|
103
|
+
rasterizer: Rasterizer;
|
|
104
|
+
color: ColorParser;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
export async function measurePage(options: MeasurePageOptions): Promise<SlideScene> {
|
|
108
|
+
const { frame } = options;
|
|
109
|
+
const ctx: Ctx = {
|
|
110
|
+
frame,
|
|
111
|
+
frameRect: frame.getBoundingClientRect(),
|
|
112
|
+
transforms: snapshotTransforms(frame),
|
|
113
|
+
slots: [],
|
|
114
|
+
rasters: [],
|
|
115
|
+
pending: [],
|
|
116
|
+
images: options.images,
|
|
117
|
+
color: options.color,
|
|
118
|
+
segmenter: typeof Intl !== 'undefined' && 'Segmenter' in Intl ? new Intl.Segmenter() : null,
|
|
119
|
+
measureCanvas: document.createElement('canvas').getContext('2d'),
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const style = document.createElement('style');
|
|
123
|
+
style.textContent = `.${MEASURE_CLASS}, .${MEASURE_CLASS} * { transform: none !important; translate: none !important; rotate: none !important; scale: none !important; }`;
|
|
124
|
+
document.head.appendChild(style);
|
|
125
|
+
frame.classList.add(MEASURE_CLASS);
|
|
126
|
+
let background: Fill | null = null;
|
|
127
|
+
try {
|
|
128
|
+
const hostBg = ctx.color(getComputedStyle(frame).backgroundColor);
|
|
129
|
+
background = isVisibleColor(hostBg) ? { kind: 'solid', color: hostBg } : null;
|
|
130
|
+
const slideClip: Rect = { x: 0, y: 0, w: CANVAS_WIDTH, h: CANVAS_HEIGHT };
|
|
131
|
+
for (const child of Array.from(frame.children)) {
|
|
132
|
+
paintBlock(ctx, child, {
|
|
133
|
+
world: IDENTITY,
|
|
134
|
+
opacity: 1,
|
|
135
|
+
clip: slideClip,
|
|
136
|
+
decoration: { underline: false, strike: false },
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
} finally {
|
|
140
|
+
frame.classList.remove(MEASURE_CLASS);
|
|
141
|
+
style.remove();
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
await Promise.all(ctx.pending);
|
|
145
|
+
if (ctx.rasters.length > 0) {
|
|
146
|
+
const results = await options.rasterizer.rasterize(ctx.rasters.map((r) => r.request));
|
|
147
|
+
ctx.rasters.forEach((entry, i) => {
|
|
148
|
+
const result = results[i];
|
|
149
|
+
if (!result) return;
|
|
150
|
+
const svg = result.format === 'png' ? (entry.svg ?? undefined) : undefined;
|
|
151
|
+
const id = ctx.images.add(result.bytes, result.format, svg);
|
|
152
|
+
entry.slot.node = {
|
|
153
|
+
kind: 'picture',
|
|
154
|
+
name: entry.request.target instanceof SVGElement ? 'Graphic' : 'Rendered image',
|
|
155
|
+
box: result.rect,
|
|
156
|
+
rotationDeg: 0,
|
|
157
|
+
flipV: false,
|
|
158
|
+
imageId: id,
|
|
159
|
+
crop: null,
|
|
160
|
+
alpha: 1,
|
|
161
|
+
geometry: { kind: 'rect' },
|
|
162
|
+
outline: null,
|
|
163
|
+
shadow: null,
|
|
164
|
+
};
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const nodes = ctx.slots.map((s) => s.node).filter((n): n is SceneNode => n !== null);
|
|
169
|
+
const first = nodes[0];
|
|
170
|
+
if (
|
|
171
|
+
first &&
|
|
172
|
+
coversSlide(first) &&
|
|
173
|
+
first.kind === 'shape' &&
|
|
174
|
+
first.fill &&
|
|
175
|
+
!first.outline &&
|
|
176
|
+
!first.shadow &&
|
|
177
|
+
first.geometry.kind === 'rect' &&
|
|
178
|
+
first.rotationDeg === 0
|
|
179
|
+
) {
|
|
180
|
+
background = first.fill;
|
|
181
|
+
nodes.shift();
|
|
182
|
+
}
|
|
183
|
+
return { background, nodes, notes: options.notes };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function coversSlide(node: SceneNode): boolean {
|
|
187
|
+
const b = node.box;
|
|
188
|
+
return (
|
|
189
|
+
b.x <= 0.5 && b.y <= 0.5 && b.x + b.w >= CANVAS_WIDTH - 0.5 && b.y + b.h >= CANVAS_HEIGHT - 0.5
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function snapshotTransforms(frame: HTMLElement): Map<Element, Mat> {
|
|
194
|
+
const out = new Map<Element, Mat>();
|
|
195
|
+
const all = [frame, ...Array.from(frame.querySelectorAll('*'))];
|
|
196
|
+
for (const el of all) {
|
|
197
|
+
const cs = getComputedStyle(el);
|
|
198
|
+
const local = composeLocalTransform(cs);
|
|
199
|
+
if (local) out.set(el, local);
|
|
200
|
+
}
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function composeLocalTransform(cs: CSSStyleDeclaration): Mat | null {
|
|
205
|
+
let m: Mat = IDENTITY;
|
|
206
|
+
const translate = cs.translate;
|
|
207
|
+
if (translate && translate !== 'none') {
|
|
208
|
+
const parts = translate.split(/\s+/);
|
|
209
|
+
m = multiply(m, translation(parsePx(parts[0]), parsePx(parts[1] ?? '0')));
|
|
210
|
+
}
|
|
211
|
+
const rotate = cs.rotate;
|
|
212
|
+
if (rotate && rotate !== 'none') {
|
|
213
|
+
const tokens = rotate.split(/\s+/);
|
|
214
|
+
const angle = parseAngleDeg(tokens[tokens.length - 1]);
|
|
215
|
+
if (angle === null) return null;
|
|
216
|
+
if (tokens.length > 1) {
|
|
217
|
+
const axis = tokens.slice(0, -1).join(' ');
|
|
218
|
+
if (axis !== 'z' && axis !== '0 0 1') return null;
|
|
219
|
+
}
|
|
220
|
+
m = multiply(m, rotationDeg(angle));
|
|
221
|
+
}
|
|
222
|
+
const scale = cs.scale;
|
|
223
|
+
if (scale && scale !== 'none') {
|
|
224
|
+
const parts = scale.split(/\s+/).map(Number);
|
|
225
|
+
if (parts.length > 2 && Math.abs(parts[2] - 1) > 1e-6) return null;
|
|
226
|
+
m = multiply(m, scaling(parts[0], parts[1] ?? parts[0]));
|
|
227
|
+
}
|
|
228
|
+
const t = parseTransform(cs.transform);
|
|
229
|
+
if (!t) return null;
|
|
230
|
+
m = multiply(m, t);
|
|
231
|
+
return m;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function rel(
|
|
235
|
+
ctx: Ctx,
|
|
236
|
+
r: DOMRect | { left: number; top: number; width: number; height: number },
|
|
237
|
+
): Rect {
|
|
238
|
+
return {
|
|
239
|
+
x: r.left - ctx.frameRect.left,
|
|
240
|
+
y: r.top - ctx.frameRect.top,
|
|
241
|
+
w: r.width,
|
|
242
|
+
h: r.height,
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function isHidden(cs: CSSStyleDeclaration): boolean {
|
|
247
|
+
return (
|
|
248
|
+
cs.display === 'none' || cs.visibility === 'hidden' || Number.parseFloat(cs.opacity) <= 0.001
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function isInlineDisplay(display: string): boolean {
|
|
253
|
+
return display === 'inline';
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function isAtomicInline(display: string): boolean {
|
|
257
|
+
return display.startsWith('inline-');
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function measureElement(
|
|
261
|
+
ctx: Ctx,
|
|
262
|
+
el: Element,
|
|
263
|
+
cs: CSSStyleDeclaration,
|
|
264
|
+
parent: Inherited,
|
|
265
|
+
): Measured | null {
|
|
266
|
+
const rect = rel(ctx, el.getBoundingClientRect());
|
|
267
|
+
const local = ctx.transforms.get(el);
|
|
268
|
+
if (!local) return null;
|
|
269
|
+
let world = parent.world;
|
|
270
|
+
if (!isIdentity(local)) {
|
|
271
|
+
const origin = cs.transformOrigin.split(/\s+/);
|
|
272
|
+
const ox = rect.x + parsePx(origin[0]);
|
|
273
|
+
const oy = rect.y + parsePx(origin[1]);
|
|
274
|
+
world = multiply(world, multiply(translation(ox, oy), multiply(local, translation(-ox, -oy))));
|
|
275
|
+
}
|
|
276
|
+
const opacity = parent.opacity * Number.parseFloat(cs.opacity);
|
|
277
|
+
let clip = parent.clip;
|
|
278
|
+
const overflow = cs.overflow;
|
|
279
|
+
const clips =
|
|
280
|
+
overflow.includes('hidden') ||
|
|
281
|
+
overflow.includes('clip') ||
|
|
282
|
+
overflow.includes('auto') ||
|
|
283
|
+
overflow.includes('scroll');
|
|
284
|
+
if (clips && isIdentity(world)) {
|
|
285
|
+
const padding = paddingBox(rect, cs);
|
|
286
|
+
clip = clip ? intersect(clip, padding) : padding;
|
|
287
|
+
} else if (clips) {
|
|
288
|
+
clip = null;
|
|
289
|
+
}
|
|
290
|
+
return { el, cs, rect, world, opacity, clip };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function paddingBox(rect: Rect, cs: CSSStyleDeclaration): Rect {
|
|
294
|
+
const l = parsePx(cs.borderLeftWidth);
|
|
295
|
+
const t = parsePx(cs.borderTopWidth);
|
|
296
|
+
const r = parsePx(cs.borderRightWidth);
|
|
297
|
+
const b = parsePx(cs.borderBottomWidth);
|
|
298
|
+
return {
|
|
299
|
+
x: rect.x + l,
|
|
300
|
+
y: rect.y + t,
|
|
301
|
+
w: Math.max(0, rect.w - l - r),
|
|
302
|
+
h: Math.max(0, rect.h - t - b),
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function intersect(a: Rect, b: Rect): Rect {
|
|
307
|
+
const x = Math.max(a.x, b.x);
|
|
308
|
+
const y = Math.max(a.y, b.y);
|
|
309
|
+
const right = Math.min(a.x + a.w, b.x + b.w);
|
|
310
|
+
const bottom = Math.min(a.y + a.h, b.y + b.h);
|
|
311
|
+
return { x, y, w: Math.max(0, right - x), h: Math.max(0, bottom - y) };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function needsSubtreeRaster(m: Measured): boolean {
|
|
315
|
+
const { cs, el } = m;
|
|
316
|
+
if (MEDIA_TAGS.has(el.tagName.toUpperCase()) && el.tagName.toUpperCase() !== 'IMG') return true;
|
|
317
|
+
if (cs.filter !== 'none') return true;
|
|
318
|
+
const backdrop =
|
|
319
|
+
cs.backdropFilter || (cs as unknown as Record<string, string>).webkitBackdropFilter;
|
|
320
|
+
if (backdrop && backdrop !== 'none') return true;
|
|
321
|
+
if (cs.mixBlendMode !== 'normal') return true;
|
|
322
|
+
if (cs.clipPath !== 'none' && !/^inset\(0(px)?\)$/.test(cs.clipPath)) return true;
|
|
323
|
+
const mask = cs.maskImage || (cs as unknown as Record<string, string>).webkitMaskImage;
|
|
324
|
+
if (mask && mask !== 'none') return true;
|
|
325
|
+
const bgClip =
|
|
326
|
+
cs.backgroundClip || (cs as unknown as Record<string, string>).webkitBackgroundClip;
|
|
327
|
+
if (bgClip === 'text' && cs.backgroundImage !== 'none') return true;
|
|
328
|
+
if (cs.writingMode && cs.writingMode !== 'horizontal-tb') return true;
|
|
329
|
+
const d = decompose(m.world);
|
|
330
|
+
if (!d || d.skewed) return true;
|
|
331
|
+
if (Math.abs(d.scaleX - d.scaleY) > 0.01 * Math.max(d.scaleX, d.scaleY) && el.textContent?.trim())
|
|
332
|
+
return true;
|
|
333
|
+
return false;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function paintsBackgroundSeparately(
|
|
337
|
+
cs: CSSStyleDeclaration,
|
|
338
|
+
w: number,
|
|
339
|
+
h: number,
|
|
340
|
+
color: ColorParser,
|
|
341
|
+
): boolean {
|
|
342
|
+
if (cs.backgroundImage === 'none') return false;
|
|
343
|
+
const layers = splitTopLevel(cs.backgroundImage);
|
|
344
|
+
if (layers.length !== 1) return true;
|
|
345
|
+
const layer = layers[0];
|
|
346
|
+
if (layer.startsWith('url(')) return false;
|
|
347
|
+
return parseLinearGradient(layer, w, h, color) === null;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function pushSlot(ctx: Ctx, node: SceneNode | null): Slot {
|
|
351
|
+
const slot: Slot = { node };
|
|
352
|
+
ctx.slots.push(slot);
|
|
353
|
+
return slot;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function requestRaster(ctx: Ctx, m: Measured, mode: RasterMode): void {
|
|
357
|
+
const shadows = parseShadows(m.cs.boxShadow, ctx.color);
|
|
358
|
+
const shadowExtent = shadows.reduce(
|
|
359
|
+
(max, s) => Math.max(max, Math.hypot(s.x, s.y) + s.blur + Math.max(0, s.spread)),
|
|
360
|
+
0,
|
|
361
|
+
);
|
|
362
|
+
const bounds = transformedBounds(m.world, m.rect.x, m.rect.y, m.rect.w, m.rect.h);
|
|
363
|
+
const svg = vectorCompanion(m);
|
|
364
|
+
const bleed = svg ? 0 : 3 * parseBlurPx(m.cs.filter) + shadowExtent + 8;
|
|
365
|
+
let region = clampToSlide(expandRect(bounds, bleed));
|
|
366
|
+
if (m.clip && isIdentity(m.world) && mode === 'self') {
|
|
367
|
+
region = intersect(region, expandRect(m.clip, shadowExtent));
|
|
368
|
+
}
|
|
369
|
+
if (region.w <= 0 || region.h <= 0) return;
|
|
370
|
+
const slot = pushSlot(ctx, null);
|
|
371
|
+
ctx.rasters.push({ slot, request: { target: m.el, mode, region, trim: !svg }, svg });
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const SVG_UNSUPPORTED =
|
|
375
|
+
'filter, pattern, mask, foreignObject, use, style, image, text, textPath, switch, script, [class]';
|
|
376
|
+
const SVG_PAINT_PROPS = ['fill', 'stroke', 'stop-color', 'flood-color', 'lighting-color'] as const;
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* PowerPoint 2016+ renders an SVG companion instead of the PNG fallback, keeping
|
|
380
|
+
* icons and diagrams vector and editable. Only plain, fully inside-the-slide,
|
|
381
|
+
* untransformed SVGs qualify: anything else would draw differently from the raster.
|
|
382
|
+
*/
|
|
383
|
+
function vectorCompanion(m: Measured): Uint8Array | null {
|
|
384
|
+
const { el, rect, world, opacity } = m;
|
|
385
|
+
if (!(el instanceof SVGSVGElement)) return null;
|
|
386
|
+
if (!isIdentity(world) || opacity < 0.999) return null;
|
|
387
|
+
if (rect.x < 0 || rect.y < 0 || rect.x + rect.w > CANVAS_WIDTH || rect.y + rect.h > CANVAS_HEIGHT)
|
|
388
|
+
return null;
|
|
389
|
+
if (rect.w < 1 || rect.h < 1) return null;
|
|
390
|
+
if (el.hasAttribute('class') || el.querySelector(SVG_UNSUPPORTED)) return null;
|
|
391
|
+
const origs = [el, ...Array.from(el.querySelectorAll('*'))];
|
|
392
|
+
const clone = el.cloneNode(true) as SVGSVGElement;
|
|
393
|
+
const clones = [clone, ...Array.from(clone.querySelectorAll('*'))];
|
|
394
|
+
if (origs.length !== clones.length) return null;
|
|
395
|
+
for (let i = 0; i < origs.length; i++) {
|
|
396
|
+
const orig = origs[i];
|
|
397
|
+
const target = clones[i];
|
|
398
|
+
if (/currentcolor|var\(/i.test(orig.getAttribute('style') ?? '')) return null;
|
|
399
|
+
const cs = getComputedStyle(orig);
|
|
400
|
+
for (const prop of SVG_PAINT_PROPS) {
|
|
401
|
+
const attr = orig.getAttribute(prop) ?? '';
|
|
402
|
+
if (!/currentcolor|var\(/i.test(attr)) continue;
|
|
403
|
+
const resolved = cs.getPropertyValue(prop);
|
|
404
|
+
if (!resolved) return null;
|
|
405
|
+
target.setAttribute(prop, resolved);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
clone.removeAttribute('style');
|
|
409
|
+
clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
|
|
410
|
+
clone.setAttribute('width', String(rect.w));
|
|
411
|
+
clone.setAttribute('height', String(rect.h));
|
|
412
|
+
if (!clone.getAttribute('viewBox')) clone.setAttribute('viewBox', `0 0 ${rect.w} ${rect.h}`);
|
|
413
|
+
clone.setAttribute('color', getComputedStyle(el).color);
|
|
414
|
+
try {
|
|
415
|
+
return new TextEncoder().encode(new XMLSerializer().serializeToString(clone));
|
|
416
|
+
} catch {
|
|
417
|
+
return null;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function paintBlock(ctx: Ctx, el: Element, inherited: Inherited): void {
|
|
422
|
+
if (SKIPPED_TAGS.has(el.tagName.toUpperCase())) return;
|
|
423
|
+
const cs = getComputedStyle(el);
|
|
424
|
+
if (isHidden(cs)) return;
|
|
425
|
+
if (cs.display === 'contents') {
|
|
426
|
+
for (const child of Array.from(el.children)) paintBlock(ctx, child, inherited);
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
const m = measureElement(ctx, el, cs, inherited);
|
|
430
|
+
if (!m) return;
|
|
431
|
+
const tag = el.tagName.toUpperCase();
|
|
432
|
+
|
|
433
|
+
if (tag === 'IMG') {
|
|
434
|
+
paintImage(ctx, m as Measured & { el: HTMLImageElement });
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
if (needsSubtreeRaster(m)) {
|
|
438
|
+
requestRaster(ctx, m, 'subtree');
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const decoration = mergeDecoration(inherited.decoration, cs);
|
|
443
|
+
const childInherited: Inherited = {
|
|
444
|
+
world: m.world,
|
|
445
|
+
opacity: m.opacity,
|
|
446
|
+
clip: m.clip,
|
|
447
|
+
decoration,
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
if (paintsBackgroundSeparately(cs, m.rect.w, m.rect.h, ctx.color)) {
|
|
451
|
+
requestRaster(ctx, m, 'self');
|
|
452
|
+
} else {
|
|
453
|
+
paintBox(ctx, m);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
const atoms: Atom[] = [];
|
|
457
|
+
const blockChildren: Element[] = [];
|
|
458
|
+
const inlineItems: Measured[] = [];
|
|
459
|
+
collectInline(ctx, el, childInherited, atoms, blockChildren, inlineItems);
|
|
460
|
+
|
|
461
|
+
for (const item of inlineItems) paintBox(ctx, item);
|
|
462
|
+
paintText(ctx, m, atoms);
|
|
463
|
+
paintChildren(ctx, blockChildren, childInherited);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function mergeDecoration(parent: Decoration, cs: CSSStyleDeclaration): Decoration {
|
|
467
|
+
const line = cs.textDecorationLine;
|
|
468
|
+
return {
|
|
469
|
+
underline: parent.underline || line.includes('underline'),
|
|
470
|
+
strike: parent.strike || line.includes('line-through'),
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function paintChildren(ctx: Ctx, children: Element[], inherited: Inherited): void {
|
|
475
|
+
type Entry = { el: Element; z: number; order: number; positioned: boolean };
|
|
476
|
+
const entries: Entry[] = children.map((child, order) => {
|
|
477
|
+
const cs = getComputedStyle(child);
|
|
478
|
+
const positioned =
|
|
479
|
+
cs.position !== 'static' ||
|
|
480
|
+
!isIdentity(ctx.transforms.get(child) ?? IDENTITY) ||
|
|
481
|
+
Number.parseFloat(cs.opacity) < 1 ||
|
|
482
|
+
cs.filter !== 'none' ||
|
|
483
|
+
cs.mixBlendMode !== 'normal' ||
|
|
484
|
+
cs.isolation === 'isolate';
|
|
485
|
+
const z = cs.zIndex === 'auto' ? 0 : Number.parseInt(cs.zIndex, 10) || 0;
|
|
486
|
+
return { el: child, z: positioned ? z : 0, order, positioned };
|
|
487
|
+
});
|
|
488
|
+
const negative = entries
|
|
489
|
+
.filter((e) => e.positioned && e.z < 0)
|
|
490
|
+
.sort((a, b) => a.z - b.z || a.order - b.order);
|
|
491
|
+
const flow = entries.filter((e) => !e.positioned);
|
|
492
|
+
const positive = entries
|
|
493
|
+
.filter((e) => e.positioned && e.z >= 0)
|
|
494
|
+
.sort((a, b) => a.z - b.z || a.order - b.order);
|
|
495
|
+
for (const e of [...negative, ...flow, ...positive]) paintBlock(ctx, e.el, inherited);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* Walks the inline formatting context of a block: text nodes become atoms, inline
|
|
500
|
+
* elements contribute their own painted fragments, and any block-level descendant is
|
|
501
|
+
* deferred so it paints after this block's text.
|
|
502
|
+
*/
|
|
503
|
+
function collectInline(
|
|
504
|
+
ctx: Ctx,
|
|
505
|
+
el: Element,
|
|
506
|
+
inherited: Inherited,
|
|
507
|
+
atoms: Atom[],
|
|
508
|
+
blockChildren: Element[],
|
|
509
|
+
inlineItems: Measured[],
|
|
510
|
+
): void {
|
|
511
|
+
const parentCs = getComputedStyle(el);
|
|
512
|
+
for (const node of Array.from(el.childNodes)) {
|
|
513
|
+
if (node.nodeType === Node.TEXT_NODE) {
|
|
514
|
+
collectTextAtoms(ctx, node as Text, parentCs, inherited, atoms);
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if (node.nodeType !== Node.ELEMENT_NODE) continue;
|
|
518
|
+
const child = node as Element;
|
|
519
|
+
const tag = child.tagName.toUpperCase();
|
|
520
|
+
if (SKIPPED_TAGS.has(tag) || tag === 'BR') continue;
|
|
521
|
+
const cs = getComputedStyle(child);
|
|
522
|
+
if (isHidden(cs)) continue;
|
|
523
|
+
if (cs.display === 'contents') {
|
|
524
|
+
collectInline(ctx, child, inherited, atoms, blockChildren, inlineItems);
|
|
525
|
+
continue;
|
|
526
|
+
}
|
|
527
|
+
const inline =
|
|
528
|
+
isInlineDisplay(cs.display) || (isAtomicInline(cs.display) && isPlainInline(ctx, child, cs));
|
|
529
|
+
const local = ctx.transforms.get(child);
|
|
530
|
+
if (
|
|
531
|
+
!inline ||
|
|
532
|
+
MEDIA_TAGS.has(tag) ||
|
|
533
|
+
!local ||
|
|
534
|
+
!isIdentity(local) ||
|
|
535
|
+
cs.position !== 'static'
|
|
536
|
+
) {
|
|
537
|
+
blockChildren.push(child);
|
|
538
|
+
continue;
|
|
539
|
+
}
|
|
540
|
+
const m = measureElement(ctx, child, cs, inherited);
|
|
541
|
+
if (!m) continue;
|
|
542
|
+
if (paintsAnything(cs, ctx.color)) inlineItems.push(m);
|
|
543
|
+
const decoration = mergeDecoration(inherited.decoration, cs);
|
|
544
|
+
collectInline(
|
|
545
|
+
ctx,
|
|
546
|
+
child,
|
|
547
|
+
{ ...inherited, opacity: m.opacity, decoration },
|
|
548
|
+
atoms,
|
|
549
|
+
blockChildren,
|
|
550
|
+
inlineItems,
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function isPlainInline(ctx: Ctx, el: Element, cs: CSSStyleDeclaration): boolean {
|
|
556
|
+
if (paintsAnything(cs, ctx.color)) return false;
|
|
557
|
+
if (cs.overflow !== 'visible') return false;
|
|
558
|
+
for (const child of Array.from(el.children)) {
|
|
559
|
+
const ccs = getComputedStyle(child);
|
|
560
|
+
if (
|
|
561
|
+
!isInlineDisplay(ccs.display) &&
|
|
562
|
+
!isAtomicInline(ccs.display) &&
|
|
563
|
+
ccs.display !== 'contents' &&
|
|
564
|
+
ccs.display !== 'none'
|
|
565
|
+
)
|
|
566
|
+
return false;
|
|
567
|
+
if (MEDIA_TAGS.has(child.tagName.toUpperCase())) return false;
|
|
568
|
+
}
|
|
569
|
+
return true;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function paintsAnything(cs: CSSStyleDeclaration, color: ColorParser): boolean {
|
|
573
|
+
if (cs.backgroundImage !== 'none') return true;
|
|
574
|
+
if (cs.boxShadow !== 'none') return true;
|
|
575
|
+
if (isVisibleColor(color(cs.backgroundColor))) return true;
|
|
576
|
+
return borderSides(cs, color).some((s) => s.visible);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
type BorderSide = { width: number; color: Rgba | null; style: string; visible: boolean };
|
|
580
|
+
|
|
581
|
+
function borderSides(cs: CSSStyleDeclaration, color: ColorParser): BorderSide[] {
|
|
582
|
+
const sides: [string, string, string][] = [
|
|
583
|
+
[cs.borderTopWidth, cs.borderTopStyle, cs.borderTopColor],
|
|
584
|
+
[cs.borderRightWidth, cs.borderRightStyle, cs.borderRightColor],
|
|
585
|
+
[cs.borderBottomWidth, cs.borderBottomStyle, cs.borderBottomColor],
|
|
586
|
+
[cs.borderLeftWidth, cs.borderLeftStyle, cs.borderLeftColor],
|
|
587
|
+
];
|
|
588
|
+
return sides.map(([w, style, c]) => {
|
|
589
|
+
const width = style === 'none' || style === 'hidden' ? 0 : parsePx(w);
|
|
590
|
+
const parsed = color(c);
|
|
591
|
+
return { width, color: parsed, style, visible: width > 0 && isVisibleColor(parsed) };
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
function radiiOf(cs: CSSStyleDeclaration, w: number, h: number): Radii {
|
|
596
|
+
return normalizeRadii(
|
|
597
|
+
[
|
|
598
|
+
parseCornerRadius(cs.borderTopLeftRadius, w, h),
|
|
599
|
+
parseCornerRadius(cs.borderTopRightRadius, w, h),
|
|
600
|
+
parseCornerRadius(cs.borderBottomRightRadius, w, h),
|
|
601
|
+
parseCornerRadius(cs.borderBottomLeftRadius, w, h),
|
|
602
|
+
],
|
|
603
|
+
w,
|
|
604
|
+
h,
|
|
605
|
+
);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
function geometryFor(radii: Radii, w: number, h: number): Geometry {
|
|
609
|
+
if (!hasRadius(radii)) return { kind: 'rect' };
|
|
610
|
+
const [tl, tr, br, bl] = radii;
|
|
611
|
+
const same =
|
|
612
|
+
Math.abs(tl.x - tr.x) < 0.5 &&
|
|
613
|
+
Math.abs(tl.x - br.x) < 0.5 &&
|
|
614
|
+
Math.abs(tl.x - bl.x) < 0.5 &&
|
|
615
|
+
Math.abs(tl.y - tr.y) < 0.5 &&
|
|
616
|
+
Math.abs(tl.y - br.y) < 0.5 &&
|
|
617
|
+
Math.abs(tl.y - bl.y) < 0.5;
|
|
618
|
+
if (same && Math.abs(tl.x - tl.y) < 0.5) {
|
|
619
|
+
if (tl.x >= Math.min(w, h) / 2 - 0.5) return { kind: 'ellipse' };
|
|
620
|
+
return { kind: 'roundRect', radius: tl.x };
|
|
621
|
+
}
|
|
622
|
+
if (same && tl.x >= w / 2 - 0.5 && tl.y >= h / 2 - 0.5) return { kind: 'ellipse' };
|
|
623
|
+
return { kind: 'custom', radii };
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
function shrinkRadii(radii: Radii, by: number): Radii {
|
|
627
|
+
return radii.map((c) => ({ x: Math.max(0, c.x - by), y: Math.max(0, c.y - by) })) as Radii;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function toShadowEffect(shadow: Shadow, opacity: number): ShadowEffect {
|
|
631
|
+
return {
|
|
632
|
+
blur: shadow.blur,
|
|
633
|
+
dist: Math.hypot(shadow.x, shadow.y),
|
|
634
|
+
dirDeg: (Math.atan2(shadow.y, shadow.x) * 180) / Math.PI,
|
|
635
|
+
color: withAlpha(shadow.color, opacity),
|
|
636
|
+
spread: shadow.spread,
|
|
637
|
+
inner: shadow.inset,
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function placed(
|
|
642
|
+
box: Rect,
|
|
643
|
+
world: Mat,
|
|
644
|
+
): { box: Rect; rotationDeg: number; flipV: boolean; scale: number } {
|
|
645
|
+
if (isIdentity(world)) return { box, rotationDeg: 0, flipV: false, scale: 1 };
|
|
646
|
+
const d = decompose(world);
|
|
647
|
+
if (!d) return { box, rotationDeg: 0, flipV: false, scale: 1 };
|
|
648
|
+
const center = applyToPoint(world, box.x + box.w / 2, box.y + box.h / 2);
|
|
649
|
+
const w = box.w * d.scaleX;
|
|
650
|
+
const h = box.h * d.scaleY;
|
|
651
|
+
return {
|
|
652
|
+
box: { x: center.x - w / 2, y: center.y - h / 2, w, h },
|
|
653
|
+
rotationDeg: d.rotationDeg,
|
|
654
|
+
flipV: d.flipV,
|
|
655
|
+
scale: (d.scaleX + d.scaleY) / 2,
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function clipRect(box: Rect, clip: Rect | null, world: Mat): Rect {
|
|
660
|
+
if (!clip || !isIdentity(world)) return box;
|
|
661
|
+
return intersect(box, clip);
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
function shapeName(el: Element, geometry: Geometry): string {
|
|
665
|
+
const base =
|
|
666
|
+
geometry.kind === 'ellipse'
|
|
667
|
+
? 'Ellipse'
|
|
668
|
+
: geometry.kind === 'rect'
|
|
669
|
+
? 'Rectangle'
|
|
670
|
+
: 'Rounded Rectangle';
|
|
671
|
+
const id = el.id ? ` #${el.id}` : '';
|
|
672
|
+
return `${base}${id}`;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
function paintBox(ctx: Ctx, m: Measured): void {
|
|
676
|
+
const { cs, el } = m;
|
|
677
|
+
const rects = isInlineDisplay(cs.display)
|
|
678
|
+
? Array.from(el.getClientRects()).map((r) => rel(ctx, r))
|
|
679
|
+
: [m.rect];
|
|
680
|
+
for (const rect of rects) {
|
|
681
|
+
if (rect.w < MIN_SIZE && rect.h < MIN_SIZE) continue;
|
|
682
|
+
paintBoxRect(ctx, m, rect);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
function paintBoxRect(ctx: Ctx, m: Measured, rect: Rect): void {
|
|
687
|
+
const { cs, el, world, opacity } = m;
|
|
688
|
+
const bg = ctx.color(cs.backgroundColor);
|
|
689
|
+
const sides = borderSides(cs, ctx.color);
|
|
690
|
+
const shadows = parseShadows(cs.boxShadow, ctx.color);
|
|
691
|
+
const outer = shadows.find((s) => !s.inset);
|
|
692
|
+
const inner = shadows.find((s) => s.inset);
|
|
693
|
+
const layers = cs.backgroundImage === 'none' ? [] : splitTopLevel(cs.backgroundImage);
|
|
694
|
+
const gradient =
|
|
695
|
+
layers[0] && !layers[0].startsWith('url(')
|
|
696
|
+
? parseLinearGradient(layers[0], rect.w, rect.h, ctx.color)
|
|
697
|
+
: null;
|
|
698
|
+
const imageLayer = layers[0]?.startsWith('url(') ? layers[0] : null;
|
|
699
|
+
const radii = radiiOf(cs, rect.w, rect.h);
|
|
700
|
+
|
|
701
|
+
const uniform =
|
|
702
|
+
sides.every((s) => s.visible) &&
|
|
703
|
+
sides.every((s) => Math.abs(s.width - sides[0].width) < 0.01 && s.style === sides[0].style) &&
|
|
704
|
+
sides.every((s) => s.color && sides[0].color && sameColor(s.color, sides[0].color));
|
|
705
|
+
const anyBorder = sides.some((s) => s.visible);
|
|
706
|
+
|
|
707
|
+
const fills: Fill[] = [];
|
|
708
|
+
if (isVisibleColor(bg)) fills.push({ kind: 'solid', color: withAlpha(bg, opacity) });
|
|
709
|
+
if (gradient) {
|
|
710
|
+
fills.push({
|
|
711
|
+
kind: 'gradient',
|
|
712
|
+
angleDeg: gradient.angleDeg,
|
|
713
|
+
stops: gradient.stops.map((s) => ({ pos: s.pos, color: withAlpha(s.color, opacity) })),
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
const hasShape = fills.length > 0 || anyBorder || outer;
|
|
718
|
+
if (!hasShape && !imageLayer) return;
|
|
719
|
+
|
|
720
|
+
let outline: Outline | null = null;
|
|
721
|
+
let shapeRect = rect;
|
|
722
|
+
let shapeRadii = radii;
|
|
723
|
+
if (uniform) {
|
|
724
|
+
const w = sides[0].width;
|
|
725
|
+
const c = sides[0].color as Rgba;
|
|
726
|
+
outline = {
|
|
727
|
+
width: w,
|
|
728
|
+
color: withAlpha(c, opacity),
|
|
729
|
+
dash: sides[0].style === 'dashed' ? 'dash' : sides[0].style === 'dotted' ? 'dot' : 'solid',
|
|
730
|
+
};
|
|
731
|
+
shapeRect = {
|
|
732
|
+
x: rect.x + w / 2,
|
|
733
|
+
y: rect.y + w / 2,
|
|
734
|
+
w: Math.max(0, rect.w - w),
|
|
735
|
+
h: Math.max(0, rect.h - w),
|
|
736
|
+
};
|
|
737
|
+
shapeRadii = shrinkRadii(radii, w / 2);
|
|
738
|
+
}
|
|
739
|
+
const geometry = geometryFor(shapeRadii, shapeRect.w, shapeRect.h);
|
|
740
|
+
const canClip = geometry.kind === 'rect' && !outline;
|
|
741
|
+
const finalRect = canClip ? clipRect(shapeRect, m.clip, world) : shapeRect;
|
|
742
|
+
if (finalRect.w < MIN_SIZE && finalRect.h < MIN_SIZE) return;
|
|
743
|
+
if (finalRect.w <= 0 || finalRect.h <= 0) return;
|
|
744
|
+
|
|
745
|
+
const nodes: ShapeNode[] = [];
|
|
746
|
+
const baseName = shapeName(el, geometry);
|
|
747
|
+
if (fills.length === 0 && ((anyBorder && uniform) || outer)) {
|
|
748
|
+
nodes.push(
|
|
749
|
+
makeShape(
|
|
750
|
+
baseName,
|
|
751
|
+
finalRect,
|
|
752
|
+
world,
|
|
753
|
+
geometry,
|
|
754
|
+
null,
|
|
755
|
+
uniform ? outline : null,
|
|
756
|
+
outer ? toShadowEffect(outer, opacity) : null,
|
|
757
|
+
),
|
|
758
|
+
);
|
|
759
|
+
}
|
|
760
|
+
fills.forEach((fill, i) => {
|
|
761
|
+
const last = i === fills.length - 1;
|
|
762
|
+
nodes.push(
|
|
763
|
+
makeShape(
|
|
764
|
+
baseName,
|
|
765
|
+
finalRect,
|
|
766
|
+
world,
|
|
767
|
+
geometry,
|
|
768
|
+
fill,
|
|
769
|
+
last && uniform ? outline : null,
|
|
770
|
+
i === 0 && outer
|
|
771
|
+
? toShadowEffect(outer, opacity)
|
|
772
|
+
: last && inner
|
|
773
|
+
? toShadowEffect(inner, opacity)
|
|
774
|
+
: null,
|
|
775
|
+
),
|
|
776
|
+
);
|
|
777
|
+
});
|
|
778
|
+
for (const node of nodes) pushSlot(ctx, node);
|
|
779
|
+
|
|
780
|
+
if (imageLayer) paintBackgroundImage(ctx, m, rect, imageLayer, geometry, radii);
|
|
781
|
+
|
|
782
|
+
if (anyBorder && !uniform) {
|
|
783
|
+
const [t, r, b, l] = sides;
|
|
784
|
+
const strips: [BorderSide, Rect][] = [
|
|
785
|
+
[t, { x: rect.x, y: rect.y, w: rect.w, h: t.width }],
|
|
786
|
+
[r, { x: rect.x + rect.w - r.width, y: rect.y, w: r.width, h: rect.h }],
|
|
787
|
+
[b, { x: rect.x, y: rect.y + rect.h - b.width, w: rect.w, h: b.width }],
|
|
788
|
+
[l, { x: rect.x, y: rect.y, w: l.width, h: rect.h }],
|
|
789
|
+
];
|
|
790
|
+
for (const [side, strip] of strips) {
|
|
791
|
+
if (!side.visible || !side.color) continue;
|
|
792
|
+
pushSlot(
|
|
793
|
+
ctx,
|
|
794
|
+
makeShape(
|
|
795
|
+
'Border',
|
|
796
|
+
strip,
|
|
797
|
+
world,
|
|
798
|
+
{ kind: 'rect' },
|
|
799
|
+
{ kind: 'solid', color: withAlpha(side.color, opacity) },
|
|
800
|
+
null,
|
|
801
|
+
null,
|
|
802
|
+
),
|
|
803
|
+
);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
function sameColor(a: Rgba, b: Rgba): boolean {
|
|
809
|
+
return a.r === b.r && a.g === b.g && a.b === b.b && Math.abs(a.a - b.a) < 0.01;
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
function makeShape(
|
|
813
|
+
name: string,
|
|
814
|
+
rect: Rect,
|
|
815
|
+
world: Mat,
|
|
816
|
+
geometry: Geometry,
|
|
817
|
+
fill: Fill | null,
|
|
818
|
+
outline: Outline | null,
|
|
819
|
+
shadow: ShadowEffect | null,
|
|
820
|
+
): ShapeNode {
|
|
821
|
+
const p = placed(rect, world);
|
|
822
|
+
const scaledOutline =
|
|
823
|
+
outline && p.scale !== 1 ? { ...outline, width: outline.width * p.scale } : outline;
|
|
824
|
+
const scaledGeometry =
|
|
825
|
+
geometry.kind === 'roundRect' && p.scale !== 1
|
|
826
|
+
? { ...geometry, radius: geometry.radius * p.scale }
|
|
827
|
+
: geometry;
|
|
828
|
+
return {
|
|
829
|
+
kind: 'shape',
|
|
830
|
+
name,
|
|
831
|
+
box: p.box,
|
|
832
|
+
rotationDeg: p.rotationDeg,
|
|
833
|
+
flipV: p.flipV,
|
|
834
|
+
geometry: scaledGeometry,
|
|
835
|
+
fill,
|
|
836
|
+
outline: scaledOutline,
|
|
837
|
+
shadow,
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
function parseBackgroundPosition(value: string): { x: number; y: number } {
|
|
842
|
+
const parts = value.split(/\s+/);
|
|
843
|
+
const pct = (token: string | undefined, fallback: number) => {
|
|
844
|
+
if (!token) return fallback;
|
|
845
|
+
if (token.endsWith('%')) return Number.parseFloat(token) / 100;
|
|
846
|
+
if (token === 'left' || token === 'top') return 0;
|
|
847
|
+
if (token === 'center') return 0.5;
|
|
848
|
+
if (token === 'right' || token === 'bottom') return 1;
|
|
849
|
+
return Number.NaN;
|
|
850
|
+
};
|
|
851
|
+
return { x: pct(parts[0], 0.5), y: pct(parts[1], 0.5) };
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
type Placement = { rect: Rect; crop: Crop | null };
|
|
855
|
+
|
|
856
|
+
function placeImage(
|
|
857
|
+
fit: 'cover' | 'contain' | 'fill' | 'none' | 'scale-down',
|
|
858
|
+
natural: { width: number; height: number },
|
|
859
|
+
box: Rect,
|
|
860
|
+
pos: { x: number; y: number },
|
|
861
|
+
): Placement {
|
|
862
|
+
if (fit === 'fill' || natural.width === 0 || natural.height === 0)
|
|
863
|
+
return { rect: box, crop: null };
|
|
864
|
+
let scale: number;
|
|
865
|
+
switch (fit) {
|
|
866
|
+
case 'cover':
|
|
867
|
+
scale = Math.max(box.w / natural.width, box.h / natural.height);
|
|
868
|
+
break;
|
|
869
|
+
case 'contain':
|
|
870
|
+
scale = Math.min(box.w / natural.width, box.h / natural.height);
|
|
871
|
+
break;
|
|
872
|
+
case 'none':
|
|
873
|
+
scale = 1;
|
|
874
|
+
break;
|
|
875
|
+
case 'scale-down':
|
|
876
|
+
scale = Math.min(1, Math.min(box.w / natural.width, box.h / natural.height));
|
|
877
|
+
break;
|
|
878
|
+
}
|
|
879
|
+
const w = natural.width * scale;
|
|
880
|
+
const h = natural.height * scale;
|
|
881
|
+
const x = box.x + (box.w - w) * pos.x;
|
|
882
|
+
const y = box.y + (box.h - h) * pos.y;
|
|
883
|
+
const drawn = { x, y, w, h };
|
|
884
|
+
const visible = intersect(drawn, box);
|
|
885
|
+
const crop: Crop = {
|
|
886
|
+
l: (visible.x - drawn.x) / w,
|
|
887
|
+
t: (visible.y - drawn.y) / h,
|
|
888
|
+
r: (drawn.x + drawn.w - (visible.x + visible.w)) / w,
|
|
889
|
+
b: (drawn.y + drawn.h - (visible.y + visible.h)) / h,
|
|
890
|
+
};
|
|
891
|
+
const trivial = crop.l < 1e-4 && crop.t < 1e-4 && crop.r < 1e-4 && crop.b < 1e-4;
|
|
892
|
+
return { rect: visible, crop: trivial ? null : crop };
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
function cropToClip(placement: Placement, clip: Rect | null, world: Mat): Placement | null {
|
|
896
|
+
if (!clip || !isIdentity(world)) return placement;
|
|
897
|
+
const { rect, crop } = placement;
|
|
898
|
+
const visible = intersect(rect, clip);
|
|
899
|
+
if (visible.w <= 0 || visible.h <= 0) return null;
|
|
900
|
+
if (visible.x === rect.x && visible.y === rect.y && visible.w === rect.w && visible.h === rect.h)
|
|
901
|
+
return placement;
|
|
902
|
+
const base = crop ?? { l: 0, t: 0, r: 0, b: 0 };
|
|
903
|
+
const spanX = 1 - base.l - base.r;
|
|
904
|
+
const spanY = 1 - base.t - base.b;
|
|
905
|
+
return {
|
|
906
|
+
rect: visible,
|
|
907
|
+
crop: {
|
|
908
|
+
l: base.l + ((visible.x - rect.x) / rect.w) * spanX,
|
|
909
|
+
t: base.t + ((visible.y - rect.y) / rect.h) * spanY,
|
|
910
|
+
r: base.r + ((rect.x + rect.w - (visible.x + visible.w)) / rect.w) * spanX,
|
|
911
|
+
b: base.b + ((rect.y + rect.h - (visible.y + visible.h)) / rect.h) * spanY,
|
|
912
|
+
},
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
function makePicture(
|
|
917
|
+
name: string,
|
|
918
|
+
placement: Placement,
|
|
919
|
+
world: Mat,
|
|
920
|
+
imageId: number,
|
|
921
|
+
alpha: number,
|
|
922
|
+
geometry: Geometry,
|
|
923
|
+
outline: Outline | null,
|
|
924
|
+
shadow: ShadowEffect | null,
|
|
925
|
+
): PictureNode {
|
|
926
|
+
const p = placed(placement.rect, world);
|
|
927
|
+
return {
|
|
928
|
+
kind: 'picture',
|
|
929
|
+
name,
|
|
930
|
+
box: p.box,
|
|
931
|
+
rotationDeg: p.rotationDeg,
|
|
932
|
+
flipV: p.flipV,
|
|
933
|
+
imageId,
|
|
934
|
+
crop: placement.crop,
|
|
935
|
+
alpha,
|
|
936
|
+
geometry:
|
|
937
|
+
geometry.kind === 'roundRect' && p.scale !== 1
|
|
938
|
+
? { ...geometry, radius: geometry.radius * p.scale }
|
|
939
|
+
: geometry,
|
|
940
|
+
outline,
|
|
941
|
+
shadow,
|
|
942
|
+
};
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
function paintImage(ctx: Ctx, m: Measured & { el: HTMLImageElement }): void {
|
|
946
|
+
const { el, cs } = m;
|
|
947
|
+
if (needsSubtreeRaster(m) || el.naturalWidth === 0) {
|
|
948
|
+
if (el.naturalWidth > 0 || el.currentSrc) requestRaster(ctx, m, 'subtree');
|
|
949
|
+
return;
|
|
950
|
+
}
|
|
951
|
+
const content = paddingBox(m.rect, cs);
|
|
952
|
+
const inner = {
|
|
953
|
+
x: content.x + parsePx(cs.paddingLeft),
|
|
954
|
+
y: content.y + parsePx(cs.paddingTop),
|
|
955
|
+
w: Math.max(0, content.w - parsePx(cs.paddingLeft) - parsePx(cs.paddingRight)),
|
|
956
|
+
h: Math.max(0, content.h - parsePx(cs.paddingTop) - parsePx(cs.paddingBottom)),
|
|
957
|
+
};
|
|
958
|
+
const bgOrBorder = paintsAnything(cs, ctx.color);
|
|
959
|
+
if (bgOrBorder) paintBoxRect(ctx, m, m.rect);
|
|
960
|
+
const fit = (cs.objectFit || 'fill') as Parameters<typeof placeImage>[0];
|
|
961
|
+
const pos = parseBackgroundPosition(cs.objectPosition || '50% 50%');
|
|
962
|
+
const natural = { width: el.naturalWidth, height: el.naturalHeight };
|
|
963
|
+
const placement = cropToClip(placeImage(fit, natural, inner, pos), m.clip, m.world);
|
|
964
|
+
if (!placement || placement.rect.w < MIN_SIZE || placement.rect.h < MIN_SIZE) return;
|
|
965
|
+
const radii = radiiOf(cs, m.rect.w, m.rect.h);
|
|
966
|
+
const inset = bgOrBorder ? Math.max(...borderSides(cs, ctx.color).map((side) => side.width)) : 0;
|
|
967
|
+
const geometry = geometryFor(shrinkRadii(radii, inset), placement.rect.w, placement.rect.h);
|
|
968
|
+
const slot = pushSlot(ctx, null);
|
|
969
|
+
const alpha = m.opacity;
|
|
970
|
+
const src = el.currentSrc || el.src;
|
|
971
|
+
const name = el.alt ? `Image: ${el.alt}` : 'Image';
|
|
972
|
+
ctx.pending.push(
|
|
973
|
+
ctx.images.fromUrl(src).then((loaded: LoadedImage | null) => {
|
|
974
|
+
if (!loaded) return;
|
|
975
|
+
slot.node = makePicture(name, placement, m.world, loaded.id, alpha, geometry, null, null);
|
|
976
|
+
}),
|
|
977
|
+
);
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
function paintBackgroundImage(
|
|
981
|
+
ctx: Ctx,
|
|
982
|
+
m: Measured,
|
|
983
|
+
rect: Rect,
|
|
984
|
+
layer: string,
|
|
985
|
+
geometry: Geometry,
|
|
986
|
+
radii: Radii,
|
|
987
|
+
): void {
|
|
988
|
+
const url = /^url\(["']?(.*?)["']?\)$/.exec(layer)?.[1];
|
|
989
|
+
if (!url) return;
|
|
990
|
+
const { cs } = m;
|
|
991
|
+
const repeat = cs.backgroundRepeat.split(/\s+/)[0];
|
|
992
|
+
const size = cs.backgroundSize.split(',')[0].trim();
|
|
993
|
+
const pos = parseBackgroundPosition(cs.backgroundPosition.split(',')[0].trim());
|
|
994
|
+
if (Number.isNaN(pos.x) || Number.isNaN(pos.y)) {
|
|
995
|
+
requestRaster(ctx, m, 'self');
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
998
|
+
const slot = pushSlot(ctx, null);
|
|
999
|
+
ctx.pending.push(
|
|
1000
|
+
ctx.images.fromUrl(url).then((loaded) => {
|
|
1001
|
+
if (!loaded) return;
|
|
1002
|
+
const natural = { width: loaded.width, height: loaded.height };
|
|
1003
|
+
let placement: Placement;
|
|
1004
|
+
if (size === 'cover' || size === 'contain') {
|
|
1005
|
+
placement = placeImage(size, natural, rect, pos);
|
|
1006
|
+
} else if (size === 'auto' || size === 'auto auto') {
|
|
1007
|
+
placement = placeImage('none', natural, rect, pos);
|
|
1008
|
+
} else {
|
|
1009
|
+
const [sw, sh] = size.split(/\s+/);
|
|
1010
|
+
const resolve = (token: string | undefined, base: number): number | null => {
|
|
1011
|
+
if (!token || token === 'auto') return null;
|
|
1012
|
+
if (token.endsWith('%')) return (Number.parseFloat(token) / 100) * base;
|
|
1013
|
+
return parsePx(token);
|
|
1014
|
+
};
|
|
1015
|
+
let w = resolve(sw, rect.w);
|
|
1016
|
+
let h = resolve(sh, rect.h);
|
|
1017
|
+
if (w === null && h === null) {
|
|
1018
|
+
w = natural.width;
|
|
1019
|
+
h = natural.height;
|
|
1020
|
+
} else if (w === null) w = ((h as number) / natural.height) * natural.width;
|
|
1021
|
+
else if (h === null) h = (w / natural.width) * natural.height;
|
|
1022
|
+
const drawn = {
|
|
1023
|
+
x: rect.x + (rect.w - w) * pos.x,
|
|
1024
|
+
y: rect.y + (rect.h - (h as number)) * pos.y,
|
|
1025
|
+
w,
|
|
1026
|
+
h: h as number,
|
|
1027
|
+
};
|
|
1028
|
+
placement = cropToClip({ rect: drawn, crop: null }, rect, IDENTITY) ?? {
|
|
1029
|
+
rect: drawn,
|
|
1030
|
+
crop: null,
|
|
1031
|
+
};
|
|
1032
|
+
}
|
|
1033
|
+
const coversBox = placement.rect.w >= rect.w - 0.5 && placement.rect.h >= rect.h - 0.5;
|
|
1034
|
+
if (repeat !== 'no-repeat' && !coversBox) {
|
|
1035
|
+
ctx.rasters.push({
|
|
1036
|
+
slot,
|
|
1037
|
+
request: { target: m.el, mode: 'self', region: clampToSlide(rect), trim: false },
|
|
1038
|
+
svg: null,
|
|
1039
|
+
});
|
|
1040
|
+
return;
|
|
1041
|
+
}
|
|
1042
|
+
const finalPlacement = cropToClip(placement, m.clip, m.world);
|
|
1043
|
+
if (!finalPlacement) return;
|
|
1044
|
+
slot.node = makePicture(
|
|
1045
|
+
'Background image',
|
|
1046
|
+
finalPlacement,
|
|
1047
|
+
m.world,
|
|
1048
|
+
loaded.id,
|
|
1049
|
+
m.opacity,
|
|
1050
|
+
coversBox
|
|
1051
|
+
? geometryFor(radii, rect.w, rect.h)
|
|
1052
|
+
: geometry.kind === 'rect'
|
|
1053
|
+
? geometry
|
|
1054
|
+
: { kind: 'rect' },
|
|
1055
|
+
null,
|
|
1056
|
+
null,
|
|
1057
|
+
);
|
|
1058
|
+
}),
|
|
1059
|
+
);
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
function collectTextAtoms(
|
|
1063
|
+
ctx: Ctx,
|
|
1064
|
+
node: Text,
|
|
1065
|
+
cs: CSSStyleDeclaration,
|
|
1066
|
+
inherited: Inherited,
|
|
1067
|
+
atoms: Atom[],
|
|
1068
|
+
): void {
|
|
1069
|
+
const text = node.data;
|
|
1070
|
+
if (!text || (!/\S/.test(text) && !text.includes(' '))) return;
|
|
1071
|
+
const range = document.createRange();
|
|
1072
|
+
range.selectNodeContents(node);
|
|
1073
|
+
const rects = Array.from(range.getClientRects()).filter((r) => r.width > 0.01);
|
|
1074
|
+
if (rects.length === 0) return;
|
|
1075
|
+
const whiteSpace = cs.whiteSpace;
|
|
1076
|
+
const preserve = whiteSpace.startsWith('pre') && whiteSpace !== 'pre-line';
|
|
1077
|
+
const style = runStyle(ctx, cs, inherited);
|
|
1078
|
+
const styleKey = JSON.stringify(style);
|
|
1079
|
+
const transform = cs.textTransform;
|
|
1080
|
+
const transformed = applyTextTransform(text, transform);
|
|
1081
|
+
|
|
1082
|
+
if (rects.length === 1 && !(preserve && text.includes('\n'))) {
|
|
1083
|
+
atoms.push({
|
|
1084
|
+
text: transformed,
|
|
1085
|
+
rect: rel(ctx, rects[0]),
|
|
1086
|
+
styleKey,
|
|
1087
|
+
style,
|
|
1088
|
+
preserveSpaces: preserve,
|
|
1089
|
+
});
|
|
1090
|
+
return;
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
const aligned = transformed.length === text.length;
|
|
1094
|
+
const segments = ctx.segmenter
|
|
1095
|
+
? Array.from(ctx.segmenter.segment(text), (s) => ({ index: s.index, segment: s.segment }))
|
|
1096
|
+
: Array.from(text, (ch, i) => ({ index: i, segment: ch }));
|
|
1097
|
+
for (const { index, segment } of segments) {
|
|
1098
|
+
range.setStart(node, index);
|
|
1099
|
+
range.setEnd(node, index + segment.length);
|
|
1100
|
+
const r = range.getBoundingClientRect();
|
|
1101
|
+
if (r.width < 0.01) {
|
|
1102
|
+
if (/^\s+$/.test(segment) || r.height < 0.01) continue;
|
|
1103
|
+
}
|
|
1104
|
+
const piece = aligned
|
|
1105
|
+
? transformed.slice(index, index + segment.length)
|
|
1106
|
+
: applyTextTransform(segment, transform);
|
|
1107
|
+
atoms.push({ text: piece, rect: rel(ctx, r), styleKey, style, preserveSpaces: preserve });
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
function runStyle(ctx: Ctx, cs: CSSStyleDeclaration, inherited: Inherited): RunStyle {
|
|
1112
|
+
const color = ctx.color(cs.color) ?? { r: 0, g: 0, b: 0, a: 1 };
|
|
1113
|
+
const textShadow = parseShadows(cs.textShadow, ctx.color)[0];
|
|
1114
|
+
const strokeWidth = parsePx((cs as unknown as Record<string, string>).webkitTextStrokeWidth);
|
|
1115
|
+
const strokeColor =
|
|
1116
|
+
strokeWidth > 0
|
|
1117
|
+
? ctx.color((cs as unknown as Record<string, string>).webkitTextStrokeColor)
|
|
1118
|
+
: null;
|
|
1119
|
+
const shadow: TextShadow | null = textShadow
|
|
1120
|
+
? {
|
|
1121
|
+
blur: textShadow.blur,
|
|
1122
|
+
dist: Math.hypot(textShadow.x, textShadow.y),
|
|
1123
|
+
dirDeg: (Math.atan2(textShadow.y, textShadow.x) * 180) / Math.PI,
|
|
1124
|
+
color: withAlpha(textShadow.color, inherited.opacity),
|
|
1125
|
+
}
|
|
1126
|
+
: null;
|
|
1127
|
+
return {
|
|
1128
|
+
font: resolveFontFamily(cs.fontFamily),
|
|
1129
|
+
sizePx: parsePx(cs.fontSize),
|
|
1130
|
+
bold: (Number.parseInt(cs.fontWeight, 10) || 400) >= 600,
|
|
1131
|
+
italic: cs.fontStyle !== 'normal',
|
|
1132
|
+
underline: inherited.decoration.underline || cs.textDecorationLine.includes('underline'),
|
|
1133
|
+
strike: inherited.decoration.strike || cs.textDecorationLine.includes('line-through'),
|
|
1134
|
+
color: withAlpha(color, inherited.opacity),
|
|
1135
|
+
letterSpacingPx: cs.letterSpacing === 'normal' ? 0 : parsePx(cs.letterSpacing),
|
|
1136
|
+
baselineShift:
|
|
1137
|
+
cs.verticalAlign === 'super' ? 'super' : cs.verticalAlign === 'sub' ? 'sub' : null,
|
|
1138
|
+
shadow,
|
|
1139
|
+
outline:
|
|
1140
|
+
strokeColor && isVisibleColor(strokeColor)
|
|
1141
|
+
? { width: strokeWidth, color: withAlpha(strokeColor, inherited.opacity) }
|
|
1142
|
+
: null,
|
|
1143
|
+
};
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
function alignOf(cs: CSSStyleDeclaration): Paragraph['align'] {
|
|
1147
|
+
switch (cs.textAlign) {
|
|
1148
|
+
case 'center':
|
|
1149
|
+
return 'ctr';
|
|
1150
|
+
case 'right':
|
|
1151
|
+
case 'end':
|
|
1152
|
+
return 'r';
|
|
1153
|
+
case 'justify':
|
|
1154
|
+
return 'just';
|
|
1155
|
+
default:
|
|
1156
|
+
return 'l';
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
const NUMBER_SCHEMES: Record<string, string> = {
|
|
1161
|
+
decimal: 'arabicPeriod',
|
|
1162
|
+
'decimal-leading-zero': 'arabicPeriod',
|
|
1163
|
+
'lower-alpha': 'alphaLcPeriod',
|
|
1164
|
+
'lower-latin': 'alphaLcPeriod',
|
|
1165
|
+
'upper-alpha': 'alphaUcPeriod',
|
|
1166
|
+
'upper-latin': 'alphaUcPeriod',
|
|
1167
|
+
'lower-roman': 'romanLcPeriod',
|
|
1168
|
+
'upper-roman': 'romanUcPeriod',
|
|
1169
|
+
};
|
|
1170
|
+
|
|
1171
|
+
const BULLET_CHARS: Record<string, string> = { disc: '•', circle: '○', square: '▪' };
|
|
1172
|
+
|
|
1173
|
+
function bulletFor(
|
|
1174
|
+
ctx: Ctx,
|
|
1175
|
+
m: Measured,
|
|
1176
|
+
firstStyle: RunStyle,
|
|
1177
|
+
): { bullet: Bullet; width: number } | null {
|
|
1178
|
+
const { el, cs } = m;
|
|
1179
|
+
if (cs.display !== 'list-item') return null;
|
|
1180
|
+
const type = cs.listStyleType;
|
|
1181
|
+
if (type === 'none' || cs.listStylePosition !== 'outside') return null;
|
|
1182
|
+
const markerColor = ctx.color(getComputedStyle(el, '::marker').color) ?? firstStyle.color;
|
|
1183
|
+
const color = withAlpha(markerColor, m.opacity);
|
|
1184
|
+
const size = firstStyle.sizePx;
|
|
1185
|
+
const scheme = NUMBER_SCHEMES[type];
|
|
1186
|
+
if (scheme) {
|
|
1187
|
+
const list = el.parentElement;
|
|
1188
|
+
let index = 1;
|
|
1189
|
+
if (list) {
|
|
1190
|
+
const items = Array.from(list.children).filter(
|
|
1191
|
+
(c) => getComputedStyle(c).display === 'list-item',
|
|
1192
|
+
);
|
|
1193
|
+
const start = list instanceof HTMLOListElement ? list.start : 1;
|
|
1194
|
+
index = start + items.indexOf(el);
|
|
1195
|
+
}
|
|
1196
|
+
const label = `${index}. `;
|
|
1197
|
+
const width = measureText(ctx, cs, label) || size * 1.2;
|
|
1198
|
+
return { bullet: { kind: 'number', scheme, startAt: index, color }, width };
|
|
1199
|
+
}
|
|
1200
|
+
const char = BULLET_CHARS[type];
|
|
1201
|
+
if (!char) return null;
|
|
1202
|
+
return { bullet: { kind: 'char', char, color, font: 'Arial' }, width: size * 0.5 };
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
function measureText(ctx: Ctx, cs: CSSStyleDeclaration, text: string): number {
|
|
1206
|
+
const c = ctx.measureCanvas;
|
|
1207
|
+
if (!c) return 0;
|
|
1208
|
+
try {
|
|
1209
|
+
c.font = `${cs.fontStyle} ${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`;
|
|
1210
|
+
return c.measureText(text).width;
|
|
1211
|
+
} catch {
|
|
1212
|
+
return 0;
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
function paintText(ctx: Ctx, m: Measured, atoms: Atom[]): void {
|
|
1217
|
+
if (atoms.length === 0) return;
|
|
1218
|
+
const lines = fillEmptyLines(groupAtomsIntoLines(atoms));
|
|
1219
|
+
while (lines.length > 0 && lines[lines.length - 1].atoms.length === 0) lines.pop();
|
|
1220
|
+
if (lines.length === 0) return;
|
|
1221
|
+
const textLines: TextLine[] = lines.map(lineToRuns);
|
|
1222
|
+
if (textLines.every((l) => l.runs.length === 0)) return;
|
|
1223
|
+
|
|
1224
|
+
const cs = m.cs;
|
|
1225
|
+
const cssLineHeight = cs.lineHeight === 'normal' ? null : parsePx(cs.lineHeight);
|
|
1226
|
+
const firstPitch =
|
|
1227
|
+
lines.length >= 2
|
|
1228
|
+
? lines[1].bottom - lines[0].bottom
|
|
1229
|
+
: (cssLineHeight ?? lines[0].bottom - lines[0].top);
|
|
1230
|
+
const boxTop = lines[0].bottom - firstPitch;
|
|
1231
|
+
|
|
1232
|
+
const paragraphs: Paragraph[] = [];
|
|
1233
|
+
const align = alignOf(cs);
|
|
1234
|
+
const firstStyle = textLines.find((l) => l.runs.length > 0)?.runs[0].style ?? atoms[0].style;
|
|
1235
|
+
const marker = bulletFor(ctx, m, firstStyle);
|
|
1236
|
+
let current: Paragraph | null = null;
|
|
1237
|
+
let currentPitch = Number.NaN;
|
|
1238
|
+
let height = 0;
|
|
1239
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1240
|
+
const pitch = i === 0 ? firstPitch : lines[i].bottom - lines[i - 1].bottom;
|
|
1241
|
+
if (!current || Math.abs(pitch - currentPitch) > PITCH_TOLERANCE) {
|
|
1242
|
+
current = {
|
|
1243
|
+
lineSpacingPx: Math.max(1, pitch),
|
|
1244
|
+
lines: [],
|
|
1245
|
+
align,
|
|
1246
|
+
bullet: paragraphs.length === 0 && marker ? marker.bullet : null,
|
|
1247
|
+
marginLeftPx: marker ? marker.width : 0,
|
|
1248
|
+
indentPx: paragraphs.length === 0 && marker ? -marker.width : 0,
|
|
1249
|
+
endSizePx: lines[i].sizePx,
|
|
1250
|
+
};
|
|
1251
|
+
currentPitch = pitch;
|
|
1252
|
+
paragraphs.push(current);
|
|
1253
|
+
}
|
|
1254
|
+
current.lines.push(textLines[i]);
|
|
1255
|
+
height += Math.max(1, pitch);
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
const left = Math.min(...lines.map((l) => l.left)) - (marker ? marker.width : 0);
|
|
1259
|
+
const right = Math.max(...lines.map((l) => l.right));
|
|
1260
|
+
const layoutBox: Rect = {
|
|
1261
|
+
x: left,
|
|
1262
|
+
y: boxTop,
|
|
1263
|
+
w: Math.max(1, right - left),
|
|
1264
|
+
h: Math.max(1, height),
|
|
1265
|
+
};
|
|
1266
|
+
const p = placed(layoutBox, m.world);
|
|
1267
|
+
if (p.scale !== 1) {
|
|
1268
|
+
for (const para of paragraphs) {
|
|
1269
|
+
para.lineSpacingPx *= p.scale;
|
|
1270
|
+
para.marginLeftPx *= p.scale;
|
|
1271
|
+
para.indentPx *= p.scale;
|
|
1272
|
+
para.endSizePx *= p.scale;
|
|
1273
|
+
for (const line of para.lines) {
|
|
1274
|
+
line.sizePx *= p.scale;
|
|
1275
|
+
for (const run of line.runs) {
|
|
1276
|
+
run.style = {
|
|
1277
|
+
...run.style,
|
|
1278
|
+
sizePx: run.style.sizePx * p.scale,
|
|
1279
|
+
letterSpacingPx: run.style.letterSpacingPx * p.scale,
|
|
1280
|
+
};
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
const preview = textLines
|
|
1286
|
+
.flatMap((l) => l.runs.map((r) => r.text))
|
|
1287
|
+
.join(' ')
|
|
1288
|
+
.trim()
|
|
1289
|
+
.slice(0, 40);
|
|
1290
|
+
const node: TextNode = {
|
|
1291
|
+
kind: 'text',
|
|
1292
|
+
name: preview ? `Text: ${preview}` : 'Text',
|
|
1293
|
+
box: p.box,
|
|
1294
|
+
rotationDeg: p.rotationDeg,
|
|
1295
|
+
flipV: p.flipV,
|
|
1296
|
+
paragraphs,
|
|
1297
|
+
};
|
|
1298
|
+
pushSlot(ctx, node);
|
|
1299
|
+
}
|