-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpretext.ts
More file actions
84 lines (73 loc) · 1.98 KB
/
Copy pathpretext.ts
File metadata and controls
84 lines (73 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Pretext - a miniature text layout engine in the spirit of the original:
// measure every glyph run exactly once, then reflow at any width with pure
// arithmetic. No DOM, no reflow cost - layout() is just additions.
export interface PreparedWord {
text: string;
width: number;
}
export interface PreparedText {
words: PreparedWord[];
spaceWidth: number;
lineHeight: number;
font: string;
}
export interface LayoutLine {
words: PreparedWord[];
width: number;
}
export interface LayoutResult {
lines: LayoutLine[];
wordCount: number;
/** layout cost in milliseconds - the number worth bragging about */
ms: number;
}
export function prepare(
text: string,
ctx: CanvasRenderingContext2D,
font: string,
lineHeight: number
): PreparedText {
ctx.font = font;
const cache = new Map<string, number>();
const measure = (word: string) => {
let width = cache.get(word);
if (width === undefined) {
width = ctx.measureText(word).width;
cache.set(word, width);
}
return width;
};
const words = text
.split(/\s+/)
.filter(Boolean)
.map((word) => ({ text: word, width: measure(word) }));
return {
words,
spaceWidth: measure(' '),
lineHeight,
font,
};
}
export function layout(prepared: PreparedText, maxWidth: number): LayoutResult {
const start = performance.now();
const lines: LayoutLine[] = [];
let current: PreparedWord[] = [];
let currentWidth = 0;
for (const word of prepared.words) {
const extra = current.length === 0 ? word.width : prepared.spaceWidth + word.width;
if (currentWidth + extra > maxWidth && current.length > 0) {
lines.push({ words: current, width: currentWidth });
current = [word];
currentWidth = word.width;
} else {
current.push(word);
currentWidth += extra;
}
}
if (current.length > 0) lines.push({ words: current, width: currentWidth });
return {
lines,
wordCount: prepared.words.length,
ms: performance.now() - start,
};
}