-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
257 lines (221 loc) · 7.14 KB
/
mod.ts
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import { FontStyle, IThemedToken } from "../../shiki/mod.ts";
import { measureMonospaceTypeface } from "./measure_monospace_typeface.ts";
interface RemoteFontFamily {
/**
* Name of the font
*/
name: string;
/**
* URL pointing to the CSS that loads the font
*/
cssURL: string;
}
interface SVGRendererOptions {
/**
* A monospace font.
*
* If using in Node context and the font is not available in the host machine,
* provide `cssURL` that loads the font remotely.
* If using in the browser context, make sure the font is available in the webpage.
*
* ```js
* getSVGRenderer({ fontFamily: 'SF Mono Regular' })
*
* getSVGRenderer({ fontFamily: {
* name: 'Inconsolata',
* cssURL: 'https://fonts.googleapis.com/css2?family=Inconsolata&display=swap'
* }})
*/
fontFamily: string | RemoteFontFamily;
/**
* URL of the CSS that loads the `fontFamily` font remotely.
*/
remoteFontCSSURL?: string;
/**
* Default to 16px.
*/
fontSize?: number;
/**
* How high should a line be, in relation to `fontSize`. Default to 1.4.
* Extra spaces are distributed evenly on top/bottom of each line.
*/
lineHeightToFontSizeRatio?: number;
/**
* Background color. Default to `#fff`.
*/
bg?: string;
/**
* Background corner radius. Default to `4px`.
*/
bgCornerRadius?: number;
/**
* How much padding should be left to the left/right in relation to font width. Default to 4.
*/
bgSideCharPadding?: number;
/**
* How much padding should be left to the top/bottom in relation to
* line height (`fontSize * lineHeightToFontSizeRatio`). Default to 2.
*/
bgVerticalCharPadding?: number;
/**
* Background minimal width. Default to longest line calculated by font-measurements done by Playwright.
*/
bgMinWidth?: number;
}
interface TokenOptions {
fill: string;
opacity?: string;
"font-weight"?: string;
"font-style"?: string;
}
const collectTokenOptions = (options: TokenOptions) => {
return Object.entries(options)
.reduce(
(acc, [key, value]: [string, string | undefined]) =>
value ? `${acc}${key}="${value}" ` : acc,
"",
)
.trim();
};
function getTokenSVGAttributes(token: IThemedToken) {
const options: TokenOptions = {
fill: "#fff",
opacity: undefined,
"font-weight": undefined,
"font-style": undefined,
};
if (token.fontStyle === FontStyle.Bold) {
options["font-weight"] = "bold";
}
if (token.fontStyle === FontStyle.Italic) {
options["font-style"] = "italic";
}
if (!token.color) {
return collectTokenOptions(options);
}
if (token.color.slice(1).length <= 6) {
options.fill = token.color;
} else if (token.color.slice(1).length === 8) {
const opacity = parseInt(token.color.slice(1 + 6), 16) / 255;
const roughRoundedOpacity = String(Math.floor(opacity * 100) / 100);
options.fill = token.color.slice(0, 1 + 6);
options.opacity = roughRoundedOpacity;
}
return collectTokenOptions(options);
}
const htmlEscapes = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
} as const;
function escapeHtml(html: string) {
return html.replace(
/[&<>"']/g,
(chr) => htmlEscapes[chr as keyof typeof htmlEscapes],
);
}
export async function getSVGRenderer(options: SVGRendererOptions) {
const fontNameStr = typeof options.fontFamily === "string"
? options.fontFamily
: options.fontFamily.name;
const remoteFontCSSURL = typeof options.fontFamily === "string"
? undefined
: options.fontFamily.cssURL;
const fontSize = options.fontSize ?? 16;
const lineHeightToFontSizeRatio = options.lineHeightToFontSizeRatio ?? 1.4;
const _bg = options.bg ?? "#fff";
const bgCornerRadius = options.bgCornerRadius ?? 4;
const bgSideCharPadding = options.bgSideCharPadding ?? 4;
const bgVerticalCharPadding = options.bgVerticalCharPadding ?? 2;
const measurement = await measureMonospaceTypeface(
fontNameStr,
fontSize,
remoteFontCSSURL,
);
const lineheight = measurement.height * lineHeightToFontSizeRatio;
return {
renderToSVG(lines: IThemedToken[][], { bg } = { bg: _bg }) {
let longestLineTextLength = 0;
lines.forEach((lTokens) => {
let lineTextLength = 0;
lTokens.forEach((l) => (lineTextLength += l.content.length));
if (lineTextLength > longestLineTextLength) {
longestLineTextLength = lineTextLength;
}
});
/**
* longest line + left/right 4 char width
*/
const bgWidth = Math.max(
options.bgMinWidth ?? 0,
(longestLineTextLength + bgSideCharPadding * 2) * measurement.width,
);
/**
* all rows + 2 rows top/bot
*/
const bgHeight = (lines.length + bgVerticalCharPadding * 2) * lineheight;
let svg =
`<svg viewBox="0 0 ${bgWidth} ${bgHeight}" width="${bgWidth}" height="${bgHeight}" xmlns="http://www.w3.org/2000/svg">\n`;
svg +=
`<rect id="bg" fill="${bg}" width="${bgWidth}" height="${bgHeight}" rx="${bgCornerRadius}"></rect>`;
svg += `<g id="tokens" transform="translate(${
measurement.width * bgSideCharPadding
}, ${lineheight * bgVerticalCharPadding})">`;
lines.forEach((l: IThemedToken[], index: number) => {
if (l.length === 0) {
svg += "\n";
} else {
svg +=
`<text font-family="${fontNameStr}" font-size="${fontSize}" y="${
lineheight * (index + 1)
}">\n`;
let indent = 0;
l.forEach((token) => {
const tokenAttributes = getTokenSVGAttributes(token);
/**
* SVG rendering in Sketch/Affinity Photos: `<tspan>` with leading whitespace will render without whitespace
* Need to manually offset `x`
*/
if (
token.content.startsWith(" ") && token.content.search(/\S/) !== -1
) {
const firstNonWhitespaceIndex = token.content.search(/\S/);
// Whitespace + content, such as ` foo`
// Render as `<tspan> </tspan><tspan>foo</tspan>`, where the second `tspan` is offset by whitespace * width
svg += `<tspan x="${
indent * measurement.width
}" ${tokenAttributes}>${
escapeHtml(
token.content.slice(0, firstNonWhitespaceIndex),
)
}</tspan>`;
svg += `<tspan x="${
(indent + firstNonWhitespaceIndex) * measurement.width
}" ${tokenAttributes}>${
escapeHtml(
token.content.slice(firstNonWhitespaceIndex),
)
}</tspan>`;
} else {
svg += `<tspan x="${
indent * measurement.width
}" ${tokenAttributes}>${
escapeHtml(
token.content,
)
}</tspan>`;
}
indent += token.content.length;
});
svg += "\n</text>\n";
}
});
svg = svg.replace(/\n*$/, ""); // Get rid of final new lines
svg += "</g>";
svg += "\n</svg>\n";
return svg;
},
};
}