UNPKG

2.66 kBJavaScriptView Raw
1/**
2 * @param {string} unsafe
3 * @return {string}
4 */
5export function escapeXml(unsafe) {
6 return unsafe.replace(/[<>&'"]/g, function (c) {
7 switch (c) {
8 case '<': return '&lt;';
9 case '>': return '&gt;';
10 case '&': return '&amp;';
11 case '\'': return '&apos;';
12 case '"': return '&quot;';
13 }
14 });
15}
16
17/**
18 * @param {string} text
19 * @param {string} fontCssClass
20 * @return {{textWidth: number, textHeight: number, descent: number, height: number}}
21 */
22export function getFontInfo(text, fontCssClass) {
23 // TODO: add caching of fontInfo per CssClass
24 // Code inspired from: https://galactic.ink/journal/2011/01/html5-typographic-metrics/
25 const container = document.body;
26 const testDiv = document.createElement("div");
27 testDiv.className = fontCssClass;
28 container.appendChild(testDiv);
29 const computedStyle = window.getComputedStyle(testDiv, null);
30 const fontSize = computedStyle.getPropertyValue('font-size');
31 const fontFamily = computedStyle.getPropertyValue('font-family');
32 container.removeChild(testDiv);
33 const parent = document.createElement("div");
34 parent.style.fontFamily = fontFamily;
35 parent.style.fontSize = fontSize;
36 const image = document.createElement("img");
37 image.width = 1;
38 image.height = 1;
39 //image.src = "./media/1x1.png";
40 image.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVR4nGP6DwABBQECz6AuzQAAAABJRU5ErkJggg==';
41 const sampleHeight = 500;
42 const textNode = document.createTextNode(text);
43 parent.appendChild(textNode);
44 parent.appendChild(image);
45 container.appendChild(parent);
46 // getting css equivalent of ctx.measureText()
47 image.style.display = "none";
48 parent.style.display = "inline";
49 const textHeight = parent.offsetHeight;
50 const textWidth = parent.offsetWidth;
51 // making sure super-wide text stays in-bounds
52 image.style.display = "inline";
53 const forceWidth = textWidth + image.offsetWidth;
54 // capturing the "top" and "bottom" baseline
55 parent.style.cssText = "margin: " + sampleHeight + "px 0; display: block; width: " + forceWidth + "px; white-space: nowrap; overflow: hidden; position: absolute; top: 0;";
56 parent.style.fontFamily = fontFamily;
57 parent.style.fontSize = fontSize;
58 const descent = textHeight - image.offsetTop;
59 const height = parent.offsetHeight;
60 const fontInfo = {
61 textWidth,
62 textHeight,
63 descent,
64 height,
65 };
66 container.removeChild(parent);
67 return fontInfo;
68}
\No newline at end of file