report-studio 0.0.1 → 1.0.0

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.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +238 -4
  3. package/dist/designer.js +3209 -0
  4. package/dist/index.js +2 -4
  5. package/dist/viewer-D-c0lKzQ.js +1576 -0
  6. package/package.json +66 -33
  7. package/src/asset/images/icon.png +0 -0
  8. package/src/asset/images/logo.png +0 -0
  9. package/src/cli/index.js +282 -0
  10. package/src/cli/serve.js +135 -0
  11. package/src/designer/blank.js +53 -0
  12. package/src/designer/canvas.js +518 -0
  13. package/src/designer/designer.js +1900 -0
  14. package/src/designer/dialog.js +708 -0
  15. package/src/designer/fields.js +584 -0
  16. package/src/designer/geometry.js +154 -0
  17. package/src/designer/guides.js +370 -0
  18. package/src/designer/history.js +113 -0
  19. package/src/designer/icons.js +118 -0
  20. package/src/designer/index.html +28 -0
  21. package/src/designer/main.js +39 -0
  22. package/src/designer/menu.js +126 -0
  23. package/src/designer/panel.js +478 -0
  24. package/src/designer/preview.js +95 -0
  25. package/src/designer/rulers.js +231 -0
  26. package/src/designer/sample-data.js +240 -0
  27. package/src/designer/select.js +699 -0
  28. package/src/designer/structure.js +604 -0
  29. package/src/designer/styles.css +1616 -0
  30. package/src/designer/toast.js +62 -0
  31. package/src/designer/tokens.js +284 -0
  32. package/src/engine/csv.js +315 -0
  33. package/src/engine/group.js +304 -0
  34. package/src/engine/index.js +34 -0
  35. package/src/engine/measure.js +390 -0
  36. package/src/engine/paginate.js +861 -0
  37. package/src/engine/regions.js +175 -0
  38. package/src/engine/resolve.js +171 -0
  39. package/src/engine/search.js +129 -0
  40. package/src/engine/text-metrics.js +206 -0
  41. package/src/engine/validate.js +328 -0
  42. package/src/index.html +79 -0
  43. package/src/index.js +50 -0
  44. package/src/preview/chrome.css +505 -0
  45. package/src/preview/chrome.js +147 -0
  46. package/src/preview/index.html +28 -0
  47. package/src/preview/main.js +66 -0
  48. package/src/preview/styles.css +16 -0
  49. package/src/preview/viewer.js +745 -0
  50. package/src/render/items.js +425 -0
  51. package/src/render/render.js +98 -0
  52. package/src/render/report.css +202 -0
  53. package/src/server/routes.js +331 -0
  54. package/src/shared/brand.css +29 -0
  55. package/src/shared/dropdown.css +136 -0
  56. package/src/shared/dropdown.js +166 -0
  57. package/src/shared/modal.css +125 -0
  58. package/src/shared/prefix.js +13 -0
  59. package/src/shared/store.js +145 -0
  60. package/src/shared/theme.css +72 -0
  61. package/src/shared/window.js +138 -0
  62. package/src/vite/index.js +53 -0
  63. package/dist/react.js +0 -4
@@ -0,0 +1,175 @@
1
+ /**
2
+ * regions.js decides where each band sits on a page.
3
+ *
4
+ * Bands do not flow. A page is divided into fixed zones, the way a sheet of
5
+ * headed paper is: a strip at the top for the page and report headers, a strip
6
+ * at the bottom for the report and page footers, and the detail in between.
7
+ *
8
+ * The point of anchoring rather than stacking: a page whose detail band ran out
9
+ * of rows must still print its footer on the bottom edge. Stacking pulls the
10
+ * footer up under the last row, which is not where a footer belongs.
11
+ *
12
+ * +--------------------+ <- content top
13
+ * | pageHeader | 10%
14
+ * | reportHeader | 10% (first page only)
15
+ * | |
16
+ * | detail | whatever is left - 60% when every band is present
17
+ * | |
18
+ * | reportFooter | 10% (last page only)
19
+ * | pageFooter | 10% pinned to the bottom edge
20
+ * +--------------------+ <- content bottom
21
+ *
22
+ * Every figure is a default the layout may override, per band, in px or in
23
+ * percent of the printable height.
24
+ */
25
+
26
+
27
+ /**
28
+ * Spec 3.2 gives band order but no sizes, so these are the sheet-of-paper
29
+ * defaults a report gets before anyone opens the designer. groupHeader and
30
+ * groupFooter are absent on purpose: they are drawn inside the detail band, not
31
+ * given a zone of their own.
32
+ */
33
+ export const DEFAULT_BAND_HEIGHTS = {
34
+ pageHeader: '10%',
35
+ reportHeader: '10%',
36
+ reportFooter: '10%',
37
+ pageFooter: '10%'
38
+ };
39
+
40
+ /** bands that own a zone, top to bottom */
41
+ const HEADER_ZONE = ['pageHeader', 'reportHeader'];
42
+ const FOOTER_ZONE = ['reportFooter', 'pageFooter'];
43
+
44
+
45
+ /**
46
+ * A band height as written in the layout: a number of pixels, or a percentage
47
+ * of the printable height. Anything unusable falls back to the default.
48
+ *
49
+ * @param {number|string|undefined} value the band's `height`
50
+ * @param {number} contentHeight the printable height of the page
51
+ * @param {number|string|undefined} fallback used when value is absent or unusable
52
+ * @returns {number} pixels
53
+ */
54
+ export function resolveHeight(value, contentHeight, fallback) {
55
+ const px = toPixels(value, contentHeight);
56
+ if (px !== null) return px;
57
+
58
+ const backup = toPixels(fallback, contentHeight);
59
+ return backup ?? 0;
60
+ }
61
+
62
+
63
+ function toPixels(value, contentHeight) {
64
+ if (typeof value === 'number' && Number.isFinite(value) && value >= 0) {
65
+ return value;
66
+ }
67
+
68
+ if (typeof value === 'string') {
69
+ const percent = value.trim().match(/^(-?[\d.]+)\s*%$/);
70
+ if (percent) {
71
+ const ratio = Number(percent[1]);
72
+ if (Number.isFinite(ratio) && ratio >= 0) {
73
+ return (ratio / 100) * contentHeight;
74
+ }
75
+ return null;
76
+ }
77
+
78
+ const plain = Number(value.trim().replace(/px$/i, ''));
79
+ if (Number.isFinite(plain) && plain >= 0) return plain;
80
+ }
81
+
82
+ return null;
83
+ }
84
+
85
+
86
+ /**
87
+ * The zone height a band should occupy. The declared height is the design
88
+ * intent, but content is never clipped to it - a band whose text wrapped past
89
+ * its zone grows, and says so.
90
+ *
91
+ * @param {object|null} band
92
+ * @param {number} contentHeight
93
+ * @returns {number}
94
+ */
95
+ export function bandZoneHeight(band, contentHeight) {
96
+ if (!band) return 0;
97
+
98
+ const declared = resolveHeight(
99
+ band.height,
100
+ contentHeight,
101
+ DEFAULT_BAND_HEIGHTS[band.type]
102
+ );
103
+
104
+ const measured = band.measuredHeight ?? 0;
105
+
106
+ if (measured > declared) {
107
+ console.warn(
108
+ `Band "${band.type}" needs ${Math.ceil(measured)}px but its zone is ` +
109
+ `${Math.round(declared)}px; the zone has been grown to fit.`
110
+ );
111
+ return measured;
112
+ }
113
+
114
+ return declared;
115
+ }
116
+
117
+
118
+ /**
119
+ * Where every band sits on one page, in coordinates relative to the printable
120
+ * area - so (0, 0) is inside the margins, not the paper edge.
121
+ *
122
+ * @param {object} options
123
+ * @param {object} options.bands the band templates, keyed by type
124
+ * @param {number} options.contentHeight page height less the top and bottom margins
125
+ * @param {boolean} options.isFirstPage the report header only appears here
126
+ * @param {boolean} options.isLastPage and the report footer only here
127
+ * @returns {object} a zone per band type, plus the detail zone
128
+ */
129
+ export function pageRegions({ bands, contentHeight, isFirstPage, isLastPage }) {
130
+ const regions = {};
131
+
132
+ const shows = (type) => {
133
+ if (type === 'reportHeader') return isFirstPage;
134
+ if (type === 'reportFooter') return isLastPage;
135
+ return true;
136
+ };
137
+
138
+ /* headers, downward from the top */
139
+ let top = 0;
140
+
141
+ for (const type of HEADER_ZONE) {
142
+ const band = bands[type];
143
+ if (!band || !shows(type)) continue;
144
+
145
+ const height = bandZoneHeight(band, contentHeight);
146
+ regions[type] = { top, height };
147
+ top += height;
148
+ }
149
+
150
+ const detailTop = top;
151
+
152
+ /* footers, upward from the bottom, so the page footer lands on the edge */
153
+ let bottom = contentHeight;
154
+
155
+ for (const type of [...FOOTER_ZONE].reverse()) {
156
+ const band = bands[type];
157
+ if (!band || !shows(type)) continue;
158
+
159
+ const height = bandZoneHeight(band, contentHeight);
160
+ bottom -= height;
161
+ regions[type] = { top: bottom, height };
162
+ }
163
+
164
+ /**
165
+ * The detail takes what the two zones leave. With the default 10/10/10/10
166
+ * that is the 60% in the middle; change any band's height and the detail
167
+ * absorbs the difference rather than the footer drifting off the edge.
168
+ */
169
+ regions.detail = {
170
+ top: detailTop,
171
+ height: Math.max(bottom - detailTop, 0)
172
+ };
173
+
174
+ return regions;
175
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * The resolve.js is used to analysis the incoming json using regex and
3
+ * replacing the only the text content into actual data given by the user
4
+ * so the input are @param rptJson and @param rptData
5
+ *
6
+ * Two placeholder families are deliberately left alone here:
7
+ * {sum(field)} and friends - group.js and paginate.js know the scope
8
+ * {page} / {totalPages} - paginate.js is the only stage that knows these
9
+ * Both are left in the output text verbatim so the later stage can fill them in
10
+ * without having to re-resolve `value` and lose everything resolved here.
11
+ */
12
+
13
+ import { assertLayout, assertData } from './validate.js';
14
+
15
+
16
+ const REGEX = /\{([^{}]+)\}/g;
17
+
18
+ /** an aggregate expression: name(field) */
19
+ const AGGREGATE = /^\w+\(.*\)$/;
20
+
21
+ /** placeholders paginate.js owns */
22
+ const PAGE_KEYS = ['page', 'totalPages'];
23
+
24
+ /** bands whose placeholders are scoped to a group, not to the root data */
25
+ const GROUP_BANDS = ['groupHeader', 'groupFooter'];
26
+
27
+
28
+ /**
29
+ * The placeholder pattern, and which keys the host is expected to supply.
30
+ *
31
+ * Exported because the designer derives a sample data file from a layout, and a
32
+ * second copy of these rules there would drift from the ones that actually
33
+ * resolve - so it would ask the user for `{page}` and forget `{customer.name}`.
34
+ */
35
+ export const PLACEHOLDER = REGEX;
36
+
37
+
38
+ /**
39
+ * Whether a placeholder is answered by the engine rather than by the data.
40
+ *
41
+ * Aggregates are group.js's, page numbers are paginate.js's, and `today` is the
42
+ * clock's. Everything else has to come from the payload.
43
+ *
44
+ * @param {string} key the text inside the braces, trimmed
45
+ * @returns {boolean}
46
+ */
47
+ export function isEngineKey(key) {
48
+ return AGGREGATE.test(key) || PAGE_KEYS.includes(key) || key === 'today';
49
+ }
50
+
51
+
52
+ /**
53
+ * Whether a band's placeholders are scoped to a row rather than to the root.
54
+ *
55
+ * The group bands, and only those. Spec 3.4's table says a bare `{field}` is
56
+ * "the current row, else root data" in any band, but that is not what this file
57
+ * does: `deferUnknown` above is set for the group bands alone, and every other
58
+ * band - the detail band included - looks its keys up in the root payload.
59
+ *
60
+ * The engine is the thing that runs, so this reports the engine. Saying
61
+ * otherwise put `{name}` in a detail band into the rows of a sample data file,
62
+ * where the engine never looked for it, and the report printed "Name:" and
63
+ * nothing after it.
64
+ *
65
+ * @param {string} type a band type
66
+ * @returns {boolean}
67
+ */
68
+ export function isRowScoped(type) {
69
+ return GROUP_BANDS.includes(type);
70
+ }
71
+
72
+
73
+ /**
74
+ * Resolves the report JSON with the provided data
75
+ * @param {*} rptJson
76
+ * @param {*} rptData
77
+ * @returns
78
+ */
79
+ export function resolve(rptJson, rptData) {
80
+ assertLayout(rptJson, 'resolve');
81
+ assertData(rptData, 'resolve');
82
+
83
+ // cloning the report json and assigning it to new var
84
+ // so that report will not affect
85
+ const resolved = structuredClone(rptJson);
86
+
87
+ for (const band of resolved.bands) {
88
+ /**
89
+ * A group band's placeholders are mostly row fields ({name} is the
90
+ * group's own value), which only the grouping stage can answer. Anything
91
+ * this stage cannot resolve there is deferred rather than blanked, so
92
+ * grouping still has it to work with.
93
+ */
94
+ const deferUnknown = GROUP_BANDS.includes(band.type);
95
+
96
+ for (const item of band.items) {
97
+ if (item.type == "text")
98
+ item.text = resolveTxt(item, rptData, deferUnknown);
99
+ }
100
+ }
101
+
102
+ return resolved;
103
+ }
104
+
105
+
106
+ /**
107
+ * Resolves the text value of an item with the provided data
108
+ * @param {*} item
109
+ * @param {*} rptData
110
+ * @param {boolean} deferUnknown leave an unresolvable key for a later stage
111
+ * @returns
112
+ */
113
+ function resolveTxt(item, rptData, deferUnknown) {
114
+ return item.value.replace(REGEX, (match, key) => {
115
+ return validatePlaceHolder(match, key.trim(), rptData, item, deferUnknown);
116
+ })
117
+ }
118
+
119
+ /**
120
+ * Validate the given and find weather the key is system keys or not
121
+ * in-case of system keys return appropriate value
122
+ * eg : key == today the return current date
123
+ * @param {*} match the whole `{...}` token, returned as-is when a later stage owns it
124
+ * @param {*} key
125
+ * @param {*} rptData
126
+ * @param {*} item
127
+ * @param {boolean} deferUnknown
128
+ * @returns
129
+ */
130
+ function validatePlaceHolder(match, key, rptData, item, deferUnknown) {
131
+ /**
132
+ * Handed on rather than reported. An aggregate belongs to grouping and a
133
+ * page key belongs to pagination, so neither is resolvable here and neither
134
+ * is a surprise - these two were logged on the way past, which meant a
135
+ * footer with a page number wrote a line to the console for every page of
136
+ * every report. Only the unresolvable placeholder below is worth a word.
137
+ */
138
+ if (AGGREGATE.test(key)) return match;
139
+
140
+ if (PAGE_KEYS.includes(key)) return match;
141
+
142
+ if (key == 'today') return new Date().toISOString().slice(0, 10);
143
+
144
+ const value = findVal(key, rptData);
145
+
146
+ if (value === undefined || value === null) {
147
+ /** a group's own field, which only has a value once the rows are split */
148
+ if (deferUnknown) return match;
149
+ console.warn(`Unresolved placeholder "{${key}}" on item "${item.id}".`);
150
+ return '';
151
+ }
152
+
153
+ return String(value);
154
+ }
155
+
156
+
157
+ /**
158
+ * Helps to find the value from the given data.
159
+ * Supports dotted paths and array indexes in either notation,
160
+ * so `items.0.name` and `items[0].name` both resolve.
161
+ * @param {*} key
162
+ * @param {*} rptData
163
+ * @returns
164
+ */
165
+ function findVal(key, rptData) {
166
+ return key
167
+ .replace(/\[(\d+)\]/g, '.$1')
168
+ .split('.')
169
+ .filter(part => part !== '')
170
+ .reduce((obj, part) => obj?.[part], rptData);
171
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * search.js finds text across a built report.
3
+ *
4
+ * Spec 2.2: the page list is the seam, and search is one of the consumers that
5
+ * reads only it. So this walks the same structure the renderer draws and knows
6
+ * nothing about grouping, measurement, or the DOM - which is what lets the
7
+ * vanilla preview and a future React Preview share one implementation.
8
+ */
9
+
10
+
11
+ /**
12
+ * Every occurrence of {query} in a built report, in page order.
13
+ *
14
+ * @param {object[]} pages the `pages` array from buildPages
15
+ * @param {string} query what to look for; blank returns no matches
16
+ * @param {object} [options]
17
+ * @param {boolean} [options.caseSensitive=false]
18
+ * @returns {object[]} matches, each { pageNO, bandType, itemId, field, text, start, end }
19
+ */
20
+ export function search(pages, query, { caseSensitive = false } = {}) {
21
+ const needle = String(query ?? '');
22
+ if (needle === '') return [];
23
+
24
+ const matches = [];
25
+
26
+ for (const page of (pages ?? [])) {
27
+ for (const band of (page.bands ?? [])) {
28
+ collectBand(band, page.pageNO, band.type, needle, caseSensitive, matches);
29
+ }
30
+ }
31
+
32
+ return matches;
33
+ }
34
+
35
+
36
+ /**
37
+ * The distinct pages a query appears on, in order. Handy for a page-at-a-time
38
+ * viewer, which cares which pages to offer before it cares about offsets.
39
+ * @param {object[]} pages
40
+ * @param {string} query
41
+ * @param {object} [options]
42
+ * @returns {number[]}
43
+ */
44
+ export function searchPages(pages, query, options) {
45
+ return [...new Set(search(pages, query, options).map(m => m.pageNO))];
46
+ }
47
+
48
+
49
+ function collectBand(band, pageNO, bandType, needle, caseSensitive, matches) {
50
+ for (const item of (band?.items ?? [])) {
51
+ if (item.type === 'text') {
52
+ push(matches, item.text, {
53
+ pageNO, bandType, itemId: item.id, field: null
54
+ }, needle, caseSensitive);
55
+ continue;
56
+ }
57
+
58
+ if (item.type === 'table') {
59
+ collectTable(item, pageNO, bandType, needle, caseSensitive, matches);
60
+ }
61
+ }
62
+ }
63
+
64
+
65
+ function collectTable(item, pageNO, bandType, needle, caseSensitive, matches) {
66
+ const columns = item.columns ?? [];
67
+
68
+ if (item.showHeader) {
69
+ for (const column of columns) {
70
+ push(matches, column.label, {
71
+ pageNO, bandType, itemId: item.id, field: column.field
72
+ }, needle, caseSensitive);
73
+ }
74
+ }
75
+
76
+ if (item.row) {
77
+ collectRows(item.row, columns, item.id, pageNO, bandType, needle, caseSensitive, matches);
78
+ return;
79
+ }
80
+
81
+ /** a grouped table carries its rows inside per-group fragments */
82
+ for (const fragment of (item.groups ?? [])) {
83
+ collectBand(fragment.headerBand, pageNO, 'groupHeader', needle, caseSensitive, matches);
84
+ collectRows(fragment.rows, columns, item.id, pageNO, bandType, needle, caseSensitive, matches);
85
+ if (fragment.showFooter) {
86
+ collectBand(fragment.footerBand, pageNO, 'groupFooter', needle, caseSensitive, matches);
87
+ }
88
+ }
89
+ }
90
+
91
+
92
+ function collectRows(rows, columns, itemId, pageNO, bandType, needle, caseSensitive, matches) {
93
+ for (const row of (rows ?? [])) {
94
+ for (const column of columns) {
95
+ push(matches, row?.[column.field], {
96
+ pageNO, bandType, itemId, field: column.field
97
+ }, needle, caseSensitive);
98
+ }
99
+ }
100
+ }
101
+
102
+
103
+ /**
104
+ * Records every occurrence within one string, not just the first - a page that
105
+ * says "Cable" three times should count as three hits.
106
+ */
107
+ function push(matches, value, where, needle, caseSensitive) {
108
+ if (value == null) return;
109
+
110
+ const text = String(value);
111
+ const haystack = caseSensitive ? text : text.toLowerCase();
112
+ const target = caseSensitive ? needle : needle.toLowerCase();
113
+
114
+ let from = 0;
115
+
116
+ while (from <= haystack.length - target.length) {
117
+ const at = haystack.indexOf(target, from);
118
+ if (at === -1) break;
119
+
120
+ matches.push({
121
+ ...where,
122
+ text,
123
+ start: at,
124
+ end: at + target.length
125
+ });
126
+
127
+ from = at + target.length;
128
+ }
129
+ }
@@ -0,0 +1,206 @@
1
+ /**
2
+ * text-metrics.js measures text the way the browser will actually draw it.
3
+ *
4
+ * Spec 4.3: text height comes from canvas 2D measureText, wrapping is greedy,
5
+ * and measurements are cached by text + font because the same strings recur
6
+ * constantly across a report.
7
+ *
8
+ * Outside a browser (tests, SSR) there is no canvas, so a documented
9
+ * approximation stands in. The browser path is the authoritative one.
10
+ */
11
+
12
+
13
+ /** CSS line-height multiplier - preview/styles.css draws text at this ratio */
14
+ export const LINE_HEIGHT_RATIO = 1.3;
15
+
16
+
17
+ /** measureText results, keyed by `${font}\u0000${text}` */
18
+ const cache = new Map();
19
+
20
+ /** guards against a cache that grows without bound on very large reports */
21
+ const CACHE_LIMIT = 10000;
22
+
23
+ let ctx;
24
+ let ctxResolved = false;
25
+
26
+
27
+ /**
28
+ * One offscreen 2D context for the life of the module, or null when there is
29
+ * no browser to ask.
30
+ * @returns {CanvasRenderingContext2D|null}
31
+ */
32
+ function context() {
33
+ if (ctxResolved) return ctx;
34
+ ctxResolved = true;
35
+
36
+ try {
37
+ if (typeof OffscreenCanvas !== 'undefined') {
38
+ ctx = new OffscreenCanvas(1, 1).getContext('2d');
39
+ } else if (typeof document !== 'undefined') {
40
+ ctx = document.createElement('canvas').getContext('2d');
41
+ } else {
42
+ ctx = null;
43
+ }
44
+ } catch {
45
+ ctx = null;
46
+ }
47
+
48
+ return ctx;
49
+ }
50
+
51
+
52
+ /**
53
+ * Builds the CSS font shorthand measureText expects.
54
+ * @param {object} style an item's style block
55
+ * @returns {string}
56
+ */
57
+ export function fontString(style = {}) {
58
+ const fontStyle = style.fontStyle || 'normal';
59
+ const fontWeight = style.fontWeight || 'normal';
60
+ const fontSize = style.fontSize ?? 12;
61
+ const fontFamily = style.fontFamily || 'Helvetica, Arial, sans-serif';
62
+ return `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;
63
+ }
64
+
65
+
66
+ /**
67
+ * Width of a single line, in pixels.
68
+ * @param {string} text
69
+ * @param {object} style
70
+ * @returns {number}
71
+ */
72
+ export function measureText(text, style) {
73
+ const str = String(text ?? '');
74
+ if (str === '') return 0;
75
+
76
+ const font = fontString(style);
77
+ const key = `${font}\u0000${str}`;
78
+
79
+ const hit = cache.get(key);
80
+ if (hit !== undefined) return hit;
81
+
82
+ const c = context();
83
+ let width;
84
+
85
+ if (c) {
86
+ c.font = font;
87
+ width = c.measureText(str).width;
88
+ } else {
89
+ width = approximateWidth(str, style);
90
+ }
91
+
92
+ if (cache.size >= CACHE_LIMIT) cache.clear();
93
+ cache.set(key, width);
94
+
95
+ return width;
96
+ }
97
+
98
+
99
+ /**
100
+ * Fallback used only where no canvas exists. Character widths are expressed as
101
+ * a fraction of the font size, coarse-grained by character class. It is close
102
+ * enough to keep pagination sane in tests; it is not a substitute for the real
103
+ * measurement a browser gives.
104
+ * @param {string} str
105
+ * @param {object} style
106
+ * @returns {number}
107
+ */
108
+ function approximateWidth(str, style = {}) {
109
+ const size = style.fontSize ?? 12;
110
+ const bold = String(style.fontWeight) === 'bold' || Number(style.fontWeight) >= 600;
111
+ const mono = /mono|courier|consolas/i.test(style.fontFamily || '');
112
+
113
+ let units = 0;
114
+
115
+ for (const ch of str) {
116
+ if (mono) { units += 0.6; continue; }
117
+ if (ch === ' ') units += 0.26;
118
+ else if (/[iljI.,:;'`|!\[\]()]/.test(ch)) units += 0.28;
119
+ else if (/[ftr]/.test(ch)) units += 0.34;
120
+ else if (/[A-Z]/.test(ch)) units += 0.68;
121
+ else if (/[mwMW@]/.test(ch)) units += 0.88;
122
+ else if (/[0-9]/.test(ch)) units += 0.56;
123
+ else units += 0.52;
124
+ }
125
+
126
+ return units * size * (bold ? 1.06 : 1);
127
+ }
128
+
129
+
130
+ /**
131
+ * Greedy word wrap: add words until the line would exceed {width}, then break.
132
+ * A single word longer than the line is broken character by character rather
133
+ * than allowed to overflow.
134
+ * @param {string} text
135
+ * @param {number} width available width in pixels
136
+ * @param {object} style
137
+ * @returns {string[]} the laid-out lines
138
+ */
139
+ export function wrapLines(text, width, style) {
140
+ const source = String(text ?? '');
141
+
142
+ /** an author's explicit newlines are hard breaks */
143
+ const paragraphs = source.split('\n');
144
+
145
+ if (!(width > 0)) return paragraphs;
146
+
147
+ const lines = [];
148
+
149
+ for (const paragraph of paragraphs) {
150
+ const words = paragraph.split(/(\s+)/).filter(w => w !== '');
151
+
152
+ if (words.length === 0) {
153
+ lines.push('');
154
+ continue;
155
+ }
156
+
157
+ let line = '';
158
+
159
+ for (const word of words) {
160
+ const candidate = line + word;
161
+
162
+ if (line !== '' && measureText(candidate, style) > width) {
163
+ lines.push(line.trimEnd());
164
+ line = word.trimStart();
165
+ } else {
166
+ line = candidate;
167
+ }
168
+
169
+ /**
170
+ * whatever now sits on the line may be a single word wider than the
171
+ * item. Break it rather than let it overflow the box silently.
172
+ */
173
+ while (measureText(line, style) > width && line.trim().length > 1) {
174
+ let cut = line.length;
175
+ while (cut > 1 && measureText(line.slice(0, cut), style) > width) cut--;
176
+ if (cut >= line.length) break;
177
+ lines.push(line.slice(0, cut));
178
+ line = line.slice(cut);
179
+ }
180
+ }
181
+
182
+ lines.push(line.trimEnd());
183
+ }
184
+
185
+ return lines;
186
+ }
187
+
188
+
189
+ /**
190
+ * Rendered height of a text item: however many lines it wraps to, at the
191
+ * line height the preview draws with.
192
+ * @param {string} text
193
+ * @param {number} width available width in pixels
194
+ * @param {object} style
195
+ * @returns {number}
196
+ */
197
+ export function textHeight(text, width, style) {
198
+ const lineHeight = Math.ceil((style?.fontSize ?? 12) * LINE_HEIGHT_RATIO);
199
+ return wrapLines(text, width, style).length * lineHeight;
200
+ }
201
+
202
+
203
+ /** exposed for tests - measurements are cached for the life of the module */
204
+ export function clearMetricsCache() {
205
+ cache.clear();
206
+ }