@x12i/reportic-render-html 0.2.3 → 0.2.4
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/index.d.ts +66 -3
- package/dist/index.js +2535 -37
- package/dist/index.js.map +1 -1
- package/package.json +6 -4
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// packages/reportic-render-html/src/index.ts
|
|
2
2
|
import { marked } from "marked";
|
|
3
3
|
import sanitizeHtml from "sanitize-html";
|
|
4
|
-
import { escapeHtml as
|
|
4
|
+
import { escapeHtml as h3, escapeMd as md, themeTokens as themeTokens4, semanticColors as semanticColors2, walkNodes as walkNodes2, formatValue as formatValue3, safeUrl, safeRelative, fail as fail4, figureSpec as figureSpec2 } from "@x12i/reportic-core";
|
|
5
5
|
|
|
6
6
|
// packages/reportic-render-html/src/visuals.ts
|
|
7
7
|
import { readFile } from "fs/promises";
|
|
@@ -173,14 +173,2453 @@ function chartSvg(node, report, options = {}) {
|
|
|
173
173
|
return svg + "</svg>";
|
|
174
174
|
}
|
|
175
175
|
|
|
176
|
+
// packages/reportic-render-html/src/figures.ts
|
|
177
|
+
import { escapeHtml as h2, themeTokens as themeTokens2, semanticColors } from "@x12i/reportic-core";
|
|
178
|
+
var W = 760;
|
|
179
|
+
var attrs = (a) => Object.entries(a).filter(([, v]) => v !== void 0 && v !== null).map(([k, v]) => ` ${k}="${h2(typeof v === "number" ? Math.round(v * 100) / 100 : v)}"`).join("");
|
|
180
|
+
var el = (tag2, a, text2) => text2 === void 0 ? `<${tag2}${attrs(a)}/>` : `<${tag2}${attrs(a)}>${h2(text2)}</${tag2}>`;
|
|
181
|
+
var glyph = (ch) => ch === " " ? 0.28 : "il.,:;'|!".includes(ch) ? 0.26 : "()[]/\\\xB7-\u2013tfIjr".includes(ch) ? 0.36 : "mwMW@%".includes(ch) ? 0.84 : ch >= "A" && ch <= "Z" ? 0.62 : ch >= "0" && ch <= "9" ? 0.56 : 0.52;
|
|
182
|
+
var textWidth = (s, size) => [...s].reduce((w, ch) => w + glyph(ch), 0) * size;
|
|
183
|
+
var fit = (s, room, size) => {
|
|
184
|
+
if (textWidth(s, size) <= room) return s;
|
|
185
|
+
let out = "";
|
|
186
|
+
for (const ch of s) {
|
|
187
|
+
if (textWidth(out + ch + "\u2026", size) > room) break;
|
|
188
|
+
out += ch;
|
|
189
|
+
}
|
|
190
|
+
return (out || s.slice(0, 1)) + "\u2026";
|
|
191
|
+
};
|
|
192
|
+
var wrapPx = (s, room, size, weight = 1) => {
|
|
193
|
+
const lines = [];
|
|
194
|
+
let line = "";
|
|
195
|
+
for (const word2 of s.split(/\s+/).filter(Boolean)) {
|
|
196
|
+
if (line && textWidth(line + " " + word2, size) * weight > room) {
|
|
197
|
+
lines.push(line);
|
|
198
|
+
line = word2;
|
|
199
|
+
} else line = line ? line + " " + word2 : word2;
|
|
200
|
+
}
|
|
201
|
+
if (line) lines.push(line);
|
|
202
|
+
return lines.length ? lines : [""];
|
|
203
|
+
};
|
|
204
|
+
var nice = (max) => {
|
|
205
|
+
if (max <= 0) return 1;
|
|
206
|
+
const p = Math.pow(10, Math.floor(Math.log10(max))), f = max / p;
|
|
207
|
+
return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * p;
|
|
208
|
+
};
|
|
209
|
+
function draw(f, c, locale) {
|
|
210
|
+
const tone2 = (t, fallback = c.accent) => !t ? fallback : t === "muted" || t === "grey" ? c.grey : c[t];
|
|
211
|
+
const nf = new Intl.NumberFormat(locale);
|
|
212
|
+
const fmt = (v) => v === null || v === void 0 ? "" : (Math.abs(v) >= 1e3 ? nf.format(v) : String(Math.round(v * 10) / 10)) + (f.unit === "%" ? "%" : "");
|
|
213
|
+
const titleLines = wrapPx(f.title, 728, 15, 1.07), subLines = f.subtitle ? wrapPx(f.subtitle, 728, 12) : [];
|
|
214
|
+
const headerHeight = 18 + titleLines.length * 19 + (subLines.length ? subLines.length * 16 + 2 : 0) + 4;
|
|
215
|
+
const header = () => titleLines.map((l, i) => el("text", { x: 16, y: 26 + i * 19, "font-size": 15, "font-weight": 600, fill: c.ink }, l)).join("") + subLines.map((l, i) => el("text", { x: 16, y: 26 + titleLines.length * 19 + 2 + i * 16, "font-size": 12, fill: c.muted }, l)).join("");
|
|
216
|
+
const noteLines = f.note ? wrapPx(f.note, 728, 11.5) : [];
|
|
217
|
+
const note = (y) => noteLines.map((l, i) => el("text", { x: 16, y: y + i * 15, "font-size": 11.5, fill: c.muted }, l)).join("");
|
|
218
|
+
const noteHeight = noteLines.length ? noteLines.length * 15 + 6 : 0;
|
|
219
|
+
const gridY = (x0, x1, yOf, min, max) => {
|
|
220
|
+
let out = "";
|
|
221
|
+
for (let i = 0; i <= 4; i++) {
|
|
222
|
+
const v = min + (max - min) * i / 4, y = yOf(v);
|
|
223
|
+
out += el("line", { x1: x0, x2: x1, y1: y, y2: y, stroke: i ? c.grid : c.axis, "stroke-width": 1 }) + el("text", { x: x0 - 8, y: y + 4, "font-size": 11, fill: c.muted, "text-anchor": "end" }, fmt(v));
|
|
224
|
+
}
|
|
225
|
+
return out;
|
|
226
|
+
};
|
|
227
|
+
const seriesFills = (series, stacked) => {
|
|
228
|
+
const seen = /* @__PURE__ */ new Map(), defs = [];
|
|
229
|
+
const fills = series.map((s, j) => {
|
|
230
|
+
const base = tone2(s.tone, j === 0 ? c.accent : c.grey), n = seen.get(base) ?? 0;
|
|
231
|
+
seen.set(base, n + 1);
|
|
232
|
+
if (!stacked || !n) return base;
|
|
233
|
+
const id = `hatch-${j}`, size = 5 + n;
|
|
234
|
+
defs.push(`<pattern id="${id}" width="${size}" height="${size}" patternUnits="userSpaceOnUse" patternTransform="rotate(${n % 2 ? 45 : 135})"><rect width="${size}" height="${size}" fill="${h2(c.bg ?? "#ffffff")}"/><rect width="${Math.ceil(size / 2)}" height="${size}" fill="${h2(base)}"/></pattern>`);
|
|
235
|
+
return `url(#${id})`;
|
|
236
|
+
});
|
|
237
|
+
return { fills, defs: defs.length ? `<defs>${defs.join("")}</defs>` : "" };
|
|
238
|
+
};
|
|
239
|
+
const legend = (series, x, y, fills) => {
|
|
240
|
+
let out = "";
|
|
241
|
+
series.forEach((s, j) => {
|
|
242
|
+
out += el("rect", { x, y: y - 9, width: 12, height: 12, rx: 2, fill: fills[j], stroke: fills[j].startsWith("url(") ? tone2(s.tone, j === 0 ? c.accent : c.grey) : null, "stroke-width": fills[j].startsWith("url(") ? 1 : null }) + el("text", { x: x + 17, y: y + 1, "font-size": 11.5, fill: c.body }, s.name);
|
|
243
|
+
x += 17 + textWidth(s.name, 11.5) + 18;
|
|
244
|
+
});
|
|
245
|
+
return out;
|
|
246
|
+
};
|
|
247
|
+
if (f.kind === "dots") {
|
|
248
|
+
const cats = f.categories, vals = f.values, rowH = f.rowHeight ?? 24, labelW = f.labelWidth ?? 220;
|
|
249
|
+
const y02 = headerHeight + 6, all2 = [...vals, ...f.reference ? [f.reference.value] : []];
|
|
250
|
+
const max = f.max ?? nice(Math.max(0, ...all2)), min = f.min ?? Math.min(0, ...all2);
|
|
251
|
+
const x0 = labelW + 16, x1 = W - 70, xOf = (v) => x0 + (x1 - x0) * (v - min) / (max - min || 1), r = Math.max(3.5, Math.min(7, rowH / 2 - 4));
|
|
252
|
+
let body2 = header();
|
|
253
|
+
body2 += el("line", { x1: x0, x2: x0, y1: y02, y2: y02 + cats.length * rowH, stroke: c.axis });
|
|
254
|
+
cats.forEach((cat, i) => {
|
|
255
|
+
const y = y02 + i * rowH, cy = y + rowH / 2, v = vals[i], cx = xOf(Math.min(max, Math.max(min, v))), t = f.tones?.[i] ?? (f.highlight?.includes(i) ? "accent" : "grey");
|
|
256
|
+
body2 += el("text", { x: x0 - 10, y: cy + 4, "font-size": 12.5, fill: c.body, "text-anchor": "end" }, fit(cat, labelW - 4, 12.5));
|
|
257
|
+
body2 += el("line", { x1: x0, x2: cx, y1: cy, y2: cy, stroke: c.grid, "stroke-width": 1.5 });
|
|
258
|
+
body2 += el("circle", { cx, cy, r: t === "grey" || t === "muted" ? r : r + 1.5, fill: tone2(t) });
|
|
259
|
+
body2 += el("text", { x: cx + r + 6, y: cy + 4, "font-size": 12, fill: c.ink, "font-weight": 600 }, fmt(v));
|
|
260
|
+
});
|
|
261
|
+
let H2 = y02 + cats.length * rowH + 8;
|
|
262
|
+
if (f.reference) {
|
|
263
|
+
const rx = xOf(f.reference.value);
|
|
264
|
+
body2 += el("line", { x1: rx, x2: rx, y1: y02, y2: H2 - 8, stroke: c.axis, "stroke-dasharray": "4 3" }) + el("text", { x: Math.max(16, Math.min(rx + 4, W - 16 - textWidth(f.reference.label ?? "", 11))), y: H2 + 6, "font-size": 11, fill: c.muted }, f.reference.label ?? "");
|
|
265
|
+
H2 += 14;
|
|
266
|
+
}
|
|
267
|
+
if (noteLines.length) {
|
|
268
|
+
body2 += note(H2 + 10);
|
|
269
|
+
H2 += 10 + noteHeight;
|
|
270
|
+
}
|
|
271
|
+
return { svg: body2, height: H2 + 8 };
|
|
272
|
+
}
|
|
273
|
+
if (f.kind === "hbar") {
|
|
274
|
+
const cats = f.categories, vals = f.values, rowH = f.rowHeight ?? 28, labelW = f.labelWidth ?? 220;
|
|
275
|
+
const y02 = headerHeight + 6, all2 = [...vals, ...f.reference ? [f.reference.value] : []];
|
|
276
|
+
const max = nice(Math.max(0, ...all2)), minv = Math.min(0, ...all2), min = minv < 0 ? -nice(-minv) : 0;
|
|
277
|
+
const x0 = labelW + 16, x1 = W - 70, xOf = (v) => x0 + (x1 - x0) * (v - min) / (max - min), xz = xOf(0);
|
|
278
|
+
let body2 = header();
|
|
279
|
+
cats.forEach((cat, i) => {
|
|
280
|
+
const y = y02 + i * rowH, v = vals[i], t = f.tones?.[i] ?? (f.highlight?.includes(i) ? "accent" : "grey");
|
|
281
|
+
const xa = Math.min(xz, xOf(v)), xb = Math.max(xz, xOf(v));
|
|
282
|
+
body2 += el("text", { x: x0 - 10, y: y + rowH / 2 + 4, "font-size": 12.5, fill: c.body, "text-anchor": "end" }, fit(cat, labelW - 4, 12.5));
|
|
283
|
+
body2 += el("rect", { x: xa, y: y + 6, width: Math.max(0, xb - xa), height: Math.max(1, rowH - 12), rx: 3, fill: tone2(t), "fill-opacity": t === "grey" ? 1 : 0.85 });
|
|
284
|
+
body2 += el("text", { x: v < 0 ? xa - 6 : xb + 6, y: y + rowH / 2 + 4, "font-size": 12, fill: c.ink, "font-weight": 600, "text-anchor": v < 0 ? "end" : "start" }, fmt(v));
|
|
285
|
+
});
|
|
286
|
+
let H2 = y02 + cats.length * rowH + 8;
|
|
287
|
+
if (min < 0) body2 += el("line", { x1: xz, x2: xz, y1: y02, y2: H2 - 8, stroke: c.axis });
|
|
288
|
+
if (f.reference) {
|
|
289
|
+
const rx = xOf(f.reference.value);
|
|
290
|
+
body2 += el("line", { x1: rx, x2: rx, y1: y02, y2: H2 - 8, stroke: c.axis, "stroke-dasharray": "4 3" }) + el("text", { x: rx + 4, y: H2 + 6, "font-size": 11, fill: c.muted }, f.reference.label ?? "");
|
|
291
|
+
H2 += 14;
|
|
292
|
+
}
|
|
293
|
+
if (noteLines.length) {
|
|
294
|
+
body2 += note(H2 + 10);
|
|
295
|
+
H2 += 10 + noteHeight;
|
|
296
|
+
}
|
|
297
|
+
return { svg: body2, height: H2 + 8 };
|
|
298
|
+
}
|
|
299
|
+
if (f.kind === "bar" || f.kind === "grouped" || f.kind === "stacked") {
|
|
300
|
+
const cats = f.categories, S = f.series, stacked = f.kind === "stacked", H2 = f.height ?? 300, top = headerHeight + (S.length > 1 ? 24 : 10);
|
|
301
|
+
const x0 = 56, x1 = W - 16, yb = H2 - 30;
|
|
302
|
+
const totals = cats.map((_, i) => stacked ? S.reduce((a, s) => a + (s.values[i] ?? 0), 0) : Math.max(0, ...S.map((s) => s.values[i] ?? 0)));
|
|
303
|
+
const max = nice(Math.max(0, ...totals, ...f.reference ? [f.reference.value] : []));
|
|
304
|
+
const yOf = (v) => yb - (yb - top) * v / max;
|
|
305
|
+
const { fills, defs } = seriesFills(S, stacked);
|
|
306
|
+
let body2 = defs + header() + gridY(x0, x1, yOf, 0, max);
|
|
307
|
+
const band = (x1 - x0) / cats.length, inner = band * 0.72, bw = stacked ? inner : inner / S.length;
|
|
308
|
+
cats.forEach((cat, i) => {
|
|
309
|
+
const bx = x0 + i * band + (band - inner) / 2;
|
|
310
|
+
let acc = 0;
|
|
311
|
+
S.forEach((s, j) => {
|
|
312
|
+
const v = s.values[i] ?? 0, t = fills[j];
|
|
313
|
+
const y = stacked ? yOf(acc + v) : yOf(v), hgt = stacked ? yOf(acc) - yOf(acc + v) : yb - yOf(v);
|
|
314
|
+
if (!stacked || v > 0) body2 += el("rect", { x: stacked ? bx : bx + j * bw, y, width: Math.max(1, stacked ? bw : bw - 3), height: Math.max(0, hgt), rx: stacked ? 0 : 2, fill: t, "fill-opacity": stacked ? null : 0.9, stroke: stacked ? c.bg ?? "#ffffff" : null, "stroke-width": stacked ? 0.75 : null });
|
|
315
|
+
if (!stacked && cats.length <= 12) body2 += el("text", { x: bx + j * bw + (bw - 3) / 2, y: y - 5, "font-size": 11, fill: c.ink, "text-anchor": "middle" }, fmt(v));
|
|
316
|
+
acc += v;
|
|
317
|
+
});
|
|
318
|
+
if (stacked) body2 += el("text", { x: bx + inner / 2, y: yOf(acc) - 5, "font-size": 11, fill: c.ink, "text-anchor": "middle" }, fmt(acc));
|
|
319
|
+
body2 += el("text", { x: bx + inner / 2, y: yb + 16, "font-size": 11.5, fill: c.muted, "text-anchor": "middle" }, fit(cat, band, 11.5));
|
|
320
|
+
});
|
|
321
|
+
if (f.reference) {
|
|
322
|
+
const ry = yOf(f.reference.value);
|
|
323
|
+
body2 += el("line", { x1: x0, x2: x1, y1: ry, y2: ry, stroke: c.bad, "stroke-dasharray": "5 4" }) + el("text", { x: x1, y: ry - 5, "font-size": 11, fill: c.bad, "text-anchor": "end" }, f.reference.label ?? "");
|
|
324
|
+
}
|
|
325
|
+
if (S.length > 1) body2 += legend(S, 16, top - 10, fills);
|
|
326
|
+
body2 += note(H2 + 32);
|
|
327
|
+
return { svg: body2, height: H2 + 40 + noteHeight };
|
|
328
|
+
}
|
|
329
|
+
if (f.kind === "line") {
|
|
330
|
+
const cats = f.categories, S = f.series, H2 = f.height ?? 300, top = headerHeight + (S.length > 1 ? 24 : 10);
|
|
331
|
+
const x0 = 56, x1 = W - 90, yb = H2 - 30;
|
|
332
|
+
const all2 = S.flatMap((s) => s.values.filter((v) => v !== null));
|
|
333
|
+
if (f.reference) all2.push(f.reference.value);
|
|
334
|
+
const max = f.max ?? nice(Math.max(0, ...all2)), min = f.min ?? 0;
|
|
335
|
+
const yOf = (v) => yb - (yb - top) * (v - min) / (max - min), xOf = (i) => x0 + (x1 - x0) * (cats.length === 1 ? 0.5 : i / (cats.length - 1));
|
|
336
|
+
let body2 = header() + gridY(x0, x1, yOf, min, max);
|
|
337
|
+
const every = Math.ceil(cats.length / 12);
|
|
338
|
+
cats.forEach((cat, i) => {
|
|
339
|
+
if (cats.length <= 14 || i % every === 0) body2 += el("text", { x: xOf(i), y: yb + 16, "font-size": 11.5, fill: c.muted, "text-anchor": "middle" }, fit(cat, (x1 - x0) / Math.max(1, cats.length - 1) * (cats.length <= 14 ? 1 : every), 11.5));
|
|
340
|
+
});
|
|
341
|
+
if (f.reference) {
|
|
342
|
+
const ry = yOf(f.reference.value);
|
|
343
|
+
body2 += el("line", { x1: x0, x2: x1, y1: ry, y2: ry, stroke: c.axis, "stroke-dasharray": "5 4" }) + el("text", { x: x1 + 6, y: ry + 4, "font-size": 11, fill: c.muted }, f.reference.label ?? "");
|
|
344
|
+
}
|
|
345
|
+
S.forEach((s, j) => {
|
|
346
|
+
const t = tone2(s.tone, j === 0 ? c.accent : c.grey);
|
|
347
|
+
let d = "", last = null, pen = false;
|
|
348
|
+
s.values.forEach((v, i) => {
|
|
349
|
+
if (v === null) {
|
|
350
|
+
pen = false;
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
d += `${pen ? " L " : d ? " M " : "M "}${Math.round(xOf(i) * 100) / 100} ${Math.round(yOf(v) * 100) / 100}`;
|
|
354
|
+
pen = true;
|
|
355
|
+
last = i;
|
|
356
|
+
});
|
|
357
|
+
if (d) body2 += el("path", { d, fill: "none", stroke: t, "stroke-width": 2.25, "stroke-linejoin": "round" });
|
|
358
|
+
s.values.forEach((v, i) => {
|
|
359
|
+
if (v !== null) body2 += el("circle", { cx: xOf(i), cy: yOf(v), r: 3.2, fill: t });
|
|
360
|
+
});
|
|
361
|
+
if (last !== null) body2 += el("text", { x: xOf(last) + 8, y: yOf(s.values[last]) + 4, "font-size": 11.5, fill: t, "font-weight": 600 }, fmt(s.values[last]) + (S.length > 1 ? " " + s.name : ""));
|
|
362
|
+
});
|
|
363
|
+
if (S.length > 1) body2 += legend(S, 16, top - 10, seriesFills(S, false).fills);
|
|
364
|
+
body2 += note(H2 + 32);
|
|
365
|
+
return { svg: body2, height: H2 + 40 + noteHeight };
|
|
366
|
+
}
|
|
367
|
+
if (f.kind === "matrix") {
|
|
368
|
+
const rows = f.rows, cols = f.cols, grid = f.matrix, lw = f.labelWidth ?? 150, cw2 = (W - lw - 24) / cols.length, rh = f.rowHeight ?? 30;
|
|
369
|
+
const y02 = headerHeight + 8, maxv = Math.max(0, ...grid.flat().map((v) => v ?? 0));
|
|
370
|
+
let body2 = header();
|
|
371
|
+
cols.forEach((col, j) => {
|
|
372
|
+
body2 += el("text", { x: lw + 16 + j * cw2 + cw2 / 2, y: y02 + 14, "font-size": 11.5, fill: c.body, "text-anchor": "middle" }, fit(col, cw2 - 4, 11.5));
|
|
373
|
+
});
|
|
374
|
+
rows.forEach((r, i) => {
|
|
375
|
+
const y = y02 + 24 + i * rh;
|
|
376
|
+
body2 += el("text", { x: lw + 8, y: y + rh / 2 + 4, "font-size": 12.5, fill: c.body, "text-anchor": "end" }, fit(r, lw + 4, 12.5));
|
|
377
|
+
cols.forEach((_, j) => {
|
|
378
|
+
const v = grid[i][j], x = lw + 16 + j * cw2, op = v === null || v === 0 ? 0 : 0.15 + 0.75 * (v / (maxv || 1));
|
|
379
|
+
const ct = f.cellTones?.[i]?.[j] ?? f.rowTones?.[i] ?? f.colTones?.[j] ?? "accent";
|
|
380
|
+
body2 += el("rect", { x: x + 2, y: y + 2, width: cw2 - 4, height: rh - 4, rx: 3, fill: tone2(ct), "fill-opacity": op, stroke: c.grid });
|
|
381
|
+
if (v !== null && v !== void 0) body2 += el("text", { x: x + cw2 / 2, y: y + rh / 2 + 4, "font-size": 12, "font-weight": 600, fill: v === 0 ? c.muted : op > 0.55 ? "#ffffff" : c.ink, "text-anchor": "middle" }, fmt(v));
|
|
382
|
+
});
|
|
383
|
+
});
|
|
384
|
+
let H2 = y02 + 24 + rows.length * rh + 12;
|
|
385
|
+
if (noteLines.length) {
|
|
386
|
+
body2 += note(H2 + 6);
|
|
387
|
+
H2 += 6 + noteHeight;
|
|
388
|
+
}
|
|
389
|
+
return { svg: body2, height: H2 };
|
|
390
|
+
}
|
|
391
|
+
const columns = f.columns, nC = columns.length, gap = 40, cw = (W - 32 - gap * (nC - 1)) / nC, vg = 14;
|
|
392
|
+
const maxSub = Math.max(1, ...columns.flatMap((col) => col.nodes.map((n) => n.sub?.length ?? 0)));
|
|
393
|
+
const nh = f.nodeHeight ?? 28 + 13 * maxSub + 8, maxN = Math.max(...columns.map((col) => col.nodes.length));
|
|
394
|
+
const y0 = headerHeight + 8, pos = /* @__PURE__ */ new Map();
|
|
395
|
+
const used = /* @__PURE__ */ new Set([...(f.edges ?? []).map((e) => e.tone ?? "grey")]);
|
|
396
|
+
let body = header();
|
|
397
|
+
body += `<defs>${[...used].map((t) => `<marker id="arr-${h2(t)}" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="${h2(tone2(t, c.grey))}"/></marker>`).join("")}</defs>`;
|
|
398
|
+
columns.forEach((col, j) => {
|
|
399
|
+
const x = 16 + j * (cw + gap);
|
|
400
|
+
if (col.title) body += el("text", { x, y: y0 + 12, "font-size": 11, "font-weight": 600, fill: c.muted }, fit(col.title.toUpperCase(), cw, 11));
|
|
401
|
+
const colH = col.nodes.length * (nh + vg) - vg, yStart = y0 + 24 + (maxN * (nh + vg) - vg - colH) / 2;
|
|
402
|
+
col.nodes.forEach((n, i) => {
|
|
403
|
+
const y = yStart + i * (nh + vg), t = n.tone ? tone2(n.tone) : null;
|
|
404
|
+
body += el("rect", { x, y, width: cw, height: nh, rx: 8, fill: t ?? "none", "fill-opacity": t ? 0.1 : 1, stroke: t ?? c.axis, "stroke-width": t ? 2 : 1.25, "stroke-dasharray": n.dashed ? "6 4" : null });
|
|
405
|
+
body += el("text", { x: x + 12, y: y + 21, "font-size": 12.5, "font-weight": 600, fill: c.ink }, fit(n.label, cw - 24, 12.5));
|
|
406
|
+
(n.sub ?? []).forEach((s, k) => {
|
|
407
|
+
body += el("text", { x: x + 12, y: y + 37 + k * 13, "font-size": 10.5, fill: c.muted }, fit(s, cw - 24, 10.5));
|
|
408
|
+
});
|
|
409
|
+
pos.set(n.id, { l: x, r: x + cw, y: y + nh / 2 });
|
|
410
|
+
});
|
|
411
|
+
});
|
|
412
|
+
(f.edges ?? []).forEach((e) => {
|
|
413
|
+
const a = pos.get(e.from), b = pos.get(e.to), t = e.tone ?? "grey", mx = (a.r + b.l) / 2, color = tone2(t, c.grey);
|
|
414
|
+
body += el("path", { d: `M ${a.r} ${a.y} C ${mx} ${a.y}, ${mx} ${b.y}, ${b.l} ${b.y}`, fill: "none", stroke: color, "stroke-width": 1.75, "stroke-dasharray": e.dashed ? "6 4" : null, "marker-end": `url(#arr-${t})` });
|
|
415
|
+
if (e.label) body += el("text", { x: mx, y: (a.y + b.y) / 2 - 6, "font-size": 10.5, fill: color, "text-anchor": "middle" }, e.label);
|
|
416
|
+
});
|
|
417
|
+
let H = y0 + 24 + maxN * (nh + vg) - vg + 12;
|
|
418
|
+
if (noteLines.length) {
|
|
419
|
+
body += note(H + 6);
|
|
420
|
+
H += 6 + noteHeight;
|
|
421
|
+
}
|
|
422
|
+
return { svg: body, height: H };
|
|
423
|
+
}
|
|
424
|
+
function figureSvg(node, report, options = {}) {
|
|
425
|
+
const t = themeTokens2(options.theme ?? report.theme), s = semanticColors(t);
|
|
426
|
+
const colors = { ink: s.ink, body: t.text, muted: t.muted, accent: t.accent, grey: s.grey, grid: s.grid, axis: s.axis, ok: s.ok, warn: s.warn, bad: s.bad, bg: t.background };
|
|
427
|
+
const f = node.props.figure;
|
|
428
|
+
const { svg, height } = draw(f, colors, report.locale);
|
|
429
|
+
const h22 = Math.ceil(height);
|
|
430
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" role="img" aria-label="${h2(node.props.alt)}" viewBox="0 0 ${W} ${h22}" width="${W}" height="${h22}" font-family="${h2(t.fontFamily)}">${svg}</svg>`;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// packages/reportic-render-html/src/import/index.ts
|
|
434
|
+
import { fail as fail3 } from "@x12i/reportic-core";
|
|
435
|
+
|
|
436
|
+
// packages/reportic-render-html/src/import/dom.ts
|
|
437
|
+
import { parse } from "parse5";
|
|
438
|
+
var parseHtml = (html) => parse(html);
|
|
439
|
+
var isEl = (n) => !!n && "tagName" in n;
|
|
440
|
+
var isText = (n) => !!n && n.nodeName === "#text";
|
|
441
|
+
var kids = (n) => "childNodes" in n ? n.childNodes : [];
|
|
442
|
+
var elements = (n) => kids(n).filter(isEl);
|
|
443
|
+
var attr = (el2, name) => el2.attrs.find((a) => a.name === name)?.value;
|
|
444
|
+
var classes = (el2) => (attr(el2, "class") ?? "").split(/\s+/).filter(Boolean);
|
|
445
|
+
var hasClass = (el2, name) => classes(el2).includes(name);
|
|
446
|
+
function textOf(n, keepBreaks = false) {
|
|
447
|
+
const parts = [];
|
|
448
|
+
const visit = (x) => {
|
|
449
|
+
if (isText(x)) parts.push(x.value);
|
|
450
|
+
else if (isEl(x)) {
|
|
451
|
+
if (["script", "style", "template"].includes(x.tagName)) return;
|
|
452
|
+
if (x.tagName === "br") {
|
|
453
|
+
parts.push(keepBreaks ? "\n" : " ");
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
kids(x).forEach(visit);
|
|
457
|
+
}
|
|
458
|
+
};
|
|
459
|
+
visit(n);
|
|
460
|
+
const text2 = parts.join("");
|
|
461
|
+
return keepBreaks ? text2.split("\n").map((l) => l.replace(/\s+/g, " ").trim()).join("\n").trim() : text2.replace(/\s+/g, " ").trim();
|
|
462
|
+
}
|
|
463
|
+
function findAll(n, test, into = []) {
|
|
464
|
+
for (const k of kids(n)) {
|
|
465
|
+
if (isEl(k)) {
|
|
466
|
+
if (test(k)) into.push(k);
|
|
467
|
+
findAll(k, test, into);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return into;
|
|
471
|
+
}
|
|
472
|
+
var find = (n, test) => {
|
|
473
|
+
for (const k of kids(n)) {
|
|
474
|
+
if (isEl(k)) {
|
|
475
|
+
if (test(k)) return k;
|
|
476
|
+
const inner = find(k, test);
|
|
477
|
+
if (inner) return inner;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
return void 0;
|
|
481
|
+
};
|
|
482
|
+
var child = (n, test) => elements(n).find(test);
|
|
483
|
+
var style = (el2, property) => {
|
|
484
|
+
const match2 = new RegExp(`(?:^|;)\\s*${property}\\s*:\\s*([^;]+)`, "i").exec(attr(el2, "style") ?? "");
|
|
485
|
+
return match2?.[1].trim();
|
|
486
|
+
};
|
|
487
|
+
var json = (el2, name) => {
|
|
488
|
+
const value = attr(el2, name);
|
|
489
|
+
if (value === void 0) return void 0;
|
|
490
|
+
try {
|
|
491
|
+
return JSON.parse(value);
|
|
492
|
+
} catch {
|
|
493
|
+
return void 0;
|
|
494
|
+
}
|
|
495
|
+
};
|
|
496
|
+
|
|
497
|
+
// packages/reportic-render-html/src/import/ctx.ts
|
|
498
|
+
import { createHash } from "crypto";
|
|
499
|
+
var EXTENSION = { "image/png": "png", "image/jpeg": "jpg", "image/gif": "gif", "image/webp": "webp", "image/svg+xml": "svg" };
|
|
500
|
+
var Importer = class {
|
|
501
|
+
notes = [];
|
|
502
|
+
unbound = [];
|
|
503
|
+
assets = {};
|
|
504
|
+
ids = /* @__PURE__ */ new Map();
|
|
505
|
+
hashes = /* @__PURE__ */ new Map();
|
|
506
|
+
count = 0;
|
|
507
|
+
note(code, message, extra = {}, severity = "info") {
|
|
508
|
+
if (!this.notes.some((n) => n.code === code && n.message === message && n.elementId === extra.elementId)) this.notes.push({ code, severity, message, ...extra });
|
|
509
|
+
}
|
|
510
|
+
warn(code, message, extra = {}) {
|
|
511
|
+
this.note(code, message, extra, "warning");
|
|
512
|
+
}
|
|
513
|
+
/** An id that is valid in a template and not used yet. */
|
|
514
|
+
uid(base) {
|
|
515
|
+
let id = (base ?? "").replace(/[^\w.-]+/g, "-").replace(/^[^a-zA-Z]+/, "").replace(/-+$/, "") || "element";
|
|
516
|
+
const n = (this.ids.get(id) ?? 0) + 1;
|
|
517
|
+
this.ids.set(id, n);
|
|
518
|
+
if (n > 1) {
|
|
519
|
+
const next = `${id}-${n}`;
|
|
520
|
+
this.ids.set(next, 1);
|
|
521
|
+
return next;
|
|
522
|
+
}
|
|
523
|
+
return id;
|
|
524
|
+
}
|
|
525
|
+
/** Reads an inline image (a data: URI) and keeps its bytes as a managed asset. Returns its name. */
|
|
526
|
+
asset(src, preferred) {
|
|
527
|
+
const match2 = /^data:([\w.+/-]+)(;[^,]*)?,(.*)$/s.exec(src.trim());
|
|
528
|
+
if (!match2) return void 0;
|
|
529
|
+
const mediaType = match2[1].toLowerCase(), encoded = match2[3];
|
|
530
|
+
if (!EXTENSION[mediaType]) {
|
|
531
|
+
this.warn("IMAGE_TYPE_UNSUPPORTED", `An embedded ${mediaType} image was dropped; use PNG, JPEG, GIF, WebP, or SVG.`);
|
|
532
|
+
return void 0;
|
|
533
|
+
}
|
|
534
|
+
let bytes;
|
|
535
|
+
try {
|
|
536
|
+
bytes = /;base64/i.test(match2[2] ?? "") ? new Uint8Array(Buffer.from(encoded, "base64")) : new Uint8Array(Buffer.from(decodeURIComponent(encoded)));
|
|
537
|
+
} catch {
|
|
538
|
+
return void 0;
|
|
539
|
+
}
|
|
540
|
+
if (!bytes.length) return void 0;
|
|
541
|
+
const hash = createHash("sha1").update(bytes).digest("hex");
|
|
542
|
+
const known = this.hashes.get(hash);
|
|
543
|
+
if (known) return known;
|
|
544
|
+
let name = (preferred ?? `image-${++this.count}`).replace(/[^\w-]/g, "-");
|
|
545
|
+
if (this.assets[name]) name = `${name}-${++this.count}`;
|
|
546
|
+
this.assets[name] = { bytes, mediaType, name: `${name}.${EXTENSION[mediaType]}` };
|
|
547
|
+
this.hashes.set(hash, name);
|
|
548
|
+
return name;
|
|
549
|
+
}
|
|
550
|
+
/** Markdown images: a data URI becomes a managed asset under assets/<name>.<ext>; a link to https is kept; a page-relative file cannot be read. */
|
|
551
|
+
markdown() {
|
|
552
|
+
return {
|
|
553
|
+
note: (code, message) => this.note(code, message),
|
|
554
|
+
image: (src, alt) => {
|
|
555
|
+
if (src.startsWith("data:")) {
|
|
556
|
+
const name = this.asset(src);
|
|
557
|
+
return name ? `assets/${name}.${EXTENSION[this.assets[name].mediaType]}` : void 0;
|
|
558
|
+
}
|
|
559
|
+
if (/^https:\/\//i.test(src)) {
|
|
560
|
+
this.warn("REMOTE_IMAGE", `Image ${src.slice(0, 80)} is a remote link. Rendering it needs allowRemoteImages; embed it to keep the report portable.`);
|
|
561
|
+
return src;
|
|
562
|
+
}
|
|
563
|
+
this.warn("IMAGE_NOT_EMBEDDED", `Image "${src.slice(0, 80)}" is not embedded in the page, so its bytes cannot be imported.`);
|
|
564
|
+
return void 0;
|
|
565
|
+
}
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
};
|
|
569
|
+
|
|
570
|
+
// packages/reportic-render-html/src/import/markdown.ts
|
|
571
|
+
var BLOCKS = /* @__PURE__ */ new Set(["h1", "h2", "h3", "h4", "h5", "h6", "p", "ul", "ol", "blockquote", "pre", "hr", "table", "div", "section", "article", "aside", "header", "footer", "main", "nav", "figure", "figcaption", "details", "summary", "dl", "dt", "dd", "address", "fieldset", "form"]);
|
|
572
|
+
var SKIPPED = /* @__PURE__ */ new Set(["script", "style", "noscript", "template", "iframe", "object", "embed", "video", "audio", "canvas", "svg", "form", "button", "select", "textarea", "head", "link", "meta", "title"]);
|
|
573
|
+
var isBlock = (n) => isEl(n) && BLOCKS.has(n.tagName);
|
|
574
|
+
var isSkipped = (n) => isEl(n) && SKIPPED.has(n.tagName);
|
|
575
|
+
function escapeText(s, inTable = false) {
|
|
576
|
+
let out = s.replace(/[\\`*<>~[\]]|_|\|/g, (m, offset) => {
|
|
577
|
+
if (m === "|") return inTable ? "\\|" : m;
|
|
578
|
+
if (m === "_") {
|
|
579
|
+
const before = s[offset - 1] ?? "", after = s[offset + 1] ?? "";
|
|
580
|
+
return /\w/.test(before) && /\w/.test(after) ? m : "\\_";
|
|
581
|
+
}
|
|
582
|
+
return "\\" + m;
|
|
583
|
+
});
|
|
584
|
+
out = out.replace(/&(?=[#\w]+;)/g, "\\&").replace(/\{\{/g, "{{");
|
|
585
|
+
return out;
|
|
586
|
+
}
|
|
587
|
+
var protectLine = (s) => s.replace(/^(\s*)(#{1,6}(?=\s|$)|>|[-+](?=\s)|\d+[.)](?=\s)|={3,}|-{3,})/, "$1\\$2");
|
|
588
|
+
var fence = (text2, char, min = 3) => char.repeat(Math.max(min, ...[...text2.matchAll(new RegExp(`${char === "`" ? "`" : "~"}+`, "g"))].map((m) => m[0].length + 1)));
|
|
589
|
+
var safeHref = (href) => /^(https?:|mailto:|#|\/|\.{0,2}\/|[\w-]+(\/|$))/i.test(href) && !/^(javascript|data|vbscript):/i.test(href) ? href.replace(/ /g, "%20").replace(/\(/g, "%28").replace(/\)/g, "%29") : void 0;
|
|
590
|
+
function inline(nodes, ctx, inTable = false) {
|
|
591
|
+
let out = "";
|
|
592
|
+
for (const n of nodes) {
|
|
593
|
+
if (isText(n)) {
|
|
594
|
+
out += escapeText(n.value.replace(/\s+/g, " "), inTable);
|
|
595
|
+
continue;
|
|
596
|
+
}
|
|
597
|
+
if (!isEl(n) || SKIPPED.has(n.tagName)) continue;
|
|
598
|
+
const inner = () => inline(kids(n), ctx, inTable);
|
|
599
|
+
switch (n.tagName) {
|
|
600
|
+
case "br":
|
|
601
|
+
out += inTable ? " " : "\\\n";
|
|
602
|
+
break;
|
|
603
|
+
case "strong":
|
|
604
|
+
case "b": {
|
|
605
|
+
const t = inner().trim();
|
|
606
|
+
if (t) out += `**${t}**`;
|
|
607
|
+
break;
|
|
608
|
+
}
|
|
609
|
+
case "em":
|
|
610
|
+
case "i": {
|
|
611
|
+
const t = inner().trim();
|
|
612
|
+
if (t) out += `*${t}*`;
|
|
613
|
+
break;
|
|
614
|
+
}
|
|
615
|
+
case "del":
|
|
616
|
+
case "s":
|
|
617
|
+
case "strike": {
|
|
618
|
+
const t = inner().trim();
|
|
619
|
+
if (t) out += `~~${t}~~`;
|
|
620
|
+
break;
|
|
621
|
+
}
|
|
622
|
+
case "code":
|
|
623
|
+
case "kbd":
|
|
624
|
+
case "samp":
|
|
625
|
+
case "tt": {
|
|
626
|
+
const raw = textOf(n);
|
|
627
|
+
if (!raw) break;
|
|
628
|
+
const text2 = raw.replace(/\{\{/g, "{\u200B{");
|
|
629
|
+
if (text2 !== raw) ctx.note("BRACES_SEPARATED", "Two braces in inline code were separated with a zero-width space so a template does not read them as an expression.");
|
|
630
|
+
const ticks = fence(text2, "`", 1);
|
|
631
|
+
out += `${ticks}${/^`|`$/.test(text2) ? ` ${text2} ` : text2}${ticks}`;
|
|
632
|
+
break;
|
|
633
|
+
}
|
|
634
|
+
case "a": {
|
|
635
|
+
const href = attr(n, "href"), label = inner().trim(), safe = href === void 0 ? void 0 : safeHref(href.trim());
|
|
636
|
+
if (!label) break;
|
|
637
|
+
out += safe ? `[${label}](${safe})` : label;
|
|
638
|
+
break;
|
|
639
|
+
}
|
|
640
|
+
case "img": {
|
|
641
|
+
const src = attr(n, "src"), alt = attr(n, "alt") ?? "";
|
|
642
|
+
const path = src ? ctx.image(src, alt) : void 0;
|
|
643
|
+
if (path) out += ``;
|
|
644
|
+
else if (alt) out += escapeText(alt);
|
|
645
|
+
break;
|
|
646
|
+
}
|
|
647
|
+
case "input":
|
|
648
|
+
break;
|
|
649
|
+
default:
|
|
650
|
+
out += inner();
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
return out;
|
|
654
|
+
}
|
|
655
|
+
var paragraph = (nodes, ctx) => protectLine(inline(nodes, ctx).replace(/^\s+|\s+$/g, "").replace(/ *\\\n */g, "\\\n"));
|
|
656
|
+
function listItem(li, ctx, marker, depth) {
|
|
657
|
+
const indent = " ".repeat(marker.length), inlineNodes = [], nested = [];
|
|
658
|
+
let task = "";
|
|
659
|
+
for (const k of kids(li)) {
|
|
660
|
+
if (isEl(k) && k.tagName === "input" && attr(k, "type") === "checkbox") {
|
|
661
|
+
task = attr(k, "checked") !== void 0 ? "[x] " : "[ ] ";
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
if (isEl(k) && (k.tagName === "ul" || k.tagName === "ol")) {
|
|
665
|
+
nested.push(list(k, ctx, depth + 1));
|
|
666
|
+
continue;
|
|
667
|
+
}
|
|
668
|
+
if (isEl(k) && k.tagName === "p") {
|
|
669
|
+
if (inlineNodes.length) inlineNodes.push(...kids(k).length ? [{ nodeName: "#text", value: " " }] : []);
|
|
670
|
+
inlineNodes.push(...kids(k));
|
|
671
|
+
continue;
|
|
672
|
+
}
|
|
673
|
+
inlineNodes.push(k);
|
|
674
|
+
}
|
|
675
|
+
const text2 = inline(inlineNodes, ctx).trim().replace(/\\\n/g, "\\\n" + indent);
|
|
676
|
+
const first = `${marker}${task}${text2}`;
|
|
677
|
+
return [first, ...nested.map((block2) => block2.split("\n").map((line) => indent + line).join("\n"))].join("\n");
|
|
678
|
+
}
|
|
679
|
+
function list(el2, ctx, depth = 0) {
|
|
680
|
+
const ordered = el2.tagName === "ol";
|
|
681
|
+
let n = Number(attr(el2, "start") ?? 1);
|
|
682
|
+
if (!Number.isFinite(n)) n = 1;
|
|
683
|
+
return elements(el2).filter((c) => c.tagName === "li").map((li) => listItem(li, ctx, ordered ? `${n++}. ` : "- ", depth)).join("\n");
|
|
684
|
+
}
|
|
685
|
+
function tableMarkdown(table, ctx) {
|
|
686
|
+
const rows = findAll(table, (e) => e.tagName === "tr");
|
|
687
|
+
if (!rows.length) return "";
|
|
688
|
+
const cellsOf2 = (tr) => elements(tr).filter((c) => c.tagName === "td" || c.tagName === "th");
|
|
689
|
+
const head = cellsOf2(rows[0]), width = Math.max(...rows.map((r) => cellsOf2(r).length));
|
|
690
|
+
const align = (c) => {
|
|
691
|
+
const a = (c && (attr(c, "align") ?? style(c, "text-align"))) ?? "";
|
|
692
|
+
return a === "right" ? "---:" : a === "center" ? ":---:" : a === "left" ? ":---" : "---";
|
|
693
|
+
};
|
|
694
|
+
const line = (cells) => `| ${cells.join(" | ")} |`;
|
|
695
|
+
const pad2 = (cells) => [...cells, ...Array(Math.max(0, width - cells.length)).fill("")];
|
|
696
|
+
const text2 = (c) => inline(kids(c), ctx, true).trim().replace(/\s+/g, " ");
|
|
697
|
+
return [line(pad2(head.map(text2))), line(Array.from({ length: width }, (_, i) => align(head[i]))), ...rows.slice(1).map((r) => line(pad2(cellsOf2(r).map(text2))))].join("\n");
|
|
698
|
+
}
|
|
699
|
+
function blocks(nodes, ctx) {
|
|
700
|
+
const out = [];
|
|
701
|
+
let run = [];
|
|
702
|
+
const flush = () => {
|
|
703
|
+
if (run.length) {
|
|
704
|
+
const p = paragraph(run, ctx);
|
|
705
|
+
if (p) out.push(p);
|
|
706
|
+
run = [];
|
|
707
|
+
}
|
|
708
|
+
};
|
|
709
|
+
for (const n of nodes) {
|
|
710
|
+
if (isText(n) || !isBlock(n)) {
|
|
711
|
+
if (isEl(n) && SKIPPED.has(n.tagName)) continue;
|
|
712
|
+
run.push(n);
|
|
713
|
+
continue;
|
|
714
|
+
}
|
|
715
|
+
flush();
|
|
716
|
+
const el2 = n, name = el2.tagName;
|
|
717
|
+
if (/^h[1-6]$/.test(name)) {
|
|
718
|
+
const t = inline(kids(el2), ctx).replace(/\\\n/g, " ").trim();
|
|
719
|
+
if (t) out.push(`${"#".repeat(Number(name[1]))} ${t}`);
|
|
720
|
+
} else if (name === "p") {
|
|
721
|
+
const p = paragraph(kids(el2), ctx);
|
|
722
|
+
if (p) out.push(p);
|
|
723
|
+
} else if (name === "ul" || name === "ol") {
|
|
724
|
+
const l = list(el2, ctx);
|
|
725
|
+
if (l) out.push(l);
|
|
726
|
+
} else if (name === "blockquote") {
|
|
727
|
+
const inner = blocks(kids(el2), ctx).join("\n\n");
|
|
728
|
+
if (inner) out.push(inner.split("\n").map((l) => l ? `> ${l}` : ">").join("\n"));
|
|
729
|
+
} else if (name === "pre") {
|
|
730
|
+
const code = elements(el2).find((c) => c.tagName === "code") ?? el2, raw = textOf(code, true).length ? kids(code).map((k) => isText(k) ? k.value : textOf(k, true)).join("") : "";
|
|
731
|
+
const text2 = raw.replace(/\n$/, "").replace(/\{\{/g, "{\u200B{");
|
|
732
|
+
if (text2 !== raw.replace(/\n$/, "")) ctx.note("BRACES_SEPARATED", "Two braces in a code block were separated with a zero-width space so a template does not read them as an expression.");
|
|
733
|
+
const language = classes(code).map((c) => /^(?:language|lang)-(.+)$/.exec(c)?.[1]).find(Boolean) ?? "";
|
|
734
|
+
const ticks = fence(text2, "`");
|
|
735
|
+
out.push(`${ticks}${language}
|
|
736
|
+
${text2}
|
|
737
|
+
${ticks}`);
|
|
738
|
+
} else if (name === "hr") out.push("---");
|
|
739
|
+
else if (name === "table") {
|
|
740
|
+
const t = tableMarkdown(el2, ctx);
|
|
741
|
+
if (t) out.push(t);
|
|
742
|
+
} else if (name === "dl") {
|
|
743
|
+
for (const d of elements(el2)) {
|
|
744
|
+
const p = paragraph(kids(d), ctx);
|
|
745
|
+
if (p) out.push(d.tagName === "dt" ? `**${p.replace(/^\*\*|\*\*$/g, "")}**` : p);
|
|
746
|
+
}
|
|
747
|
+
} else if (name === "figcaption" || name === "summary" || name === "dt" || name === "dd") {
|
|
748
|
+
const p = paragraph(kids(el2), ctx);
|
|
749
|
+
if (p) out.push(p);
|
|
750
|
+
} else out.push(...blocks(kids(el2), ctx));
|
|
751
|
+
}
|
|
752
|
+
flush();
|
|
753
|
+
return out;
|
|
754
|
+
}
|
|
755
|
+
var toMarkdown = (nodes, ctx) => blocks(nodes, ctx).join("\n\n");
|
|
756
|
+
|
|
757
|
+
// packages/reportic-render-html/src/import/tables.ts
|
|
758
|
+
var toneOf = (el2) => ["ok", "warn", "bad", "na"].find((t) => hasClass(el2, `rpt-${t}`));
|
|
759
|
+
var kinds = /* @__PURE__ */ new Set(["rating", "status", "date", "code", "list"]);
|
|
760
|
+
function readCell(td) {
|
|
761
|
+
const raw = attr(td, "data-reportic-raw"), text2 = textOf(td, true);
|
|
762
|
+
const nodes = kids(td).filter((n) => !(isText(n) && !n.value.trim()) && !(isEl(n) && n.tagName === "wbr"));
|
|
763
|
+
if (!nodes.length) return { text: "" };
|
|
764
|
+
if (raw !== void 0) {
|
|
765
|
+
const parsed = (() => {
|
|
766
|
+
try {
|
|
767
|
+
return JSON.parse(raw);
|
|
768
|
+
} catch {
|
|
769
|
+
return raw;
|
|
770
|
+
}
|
|
771
|
+
})();
|
|
772
|
+
if (Array.isArray(parsed)) return { text: text2, kind: "list", value: parsed.filter((x) => ["string", "number", "boolean"].includes(typeof x)) };
|
|
773
|
+
if (nodes.length === 1 && isEl(nodes[0]) && hasClass(nodes[0], "rpt-date")) return { text: text2, kind: "date", value: String(raw) };
|
|
774
|
+
}
|
|
775
|
+
if (nodes.length === 1 && isEl(nodes[0])) {
|
|
776
|
+
const only = nodes[0];
|
|
777
|
+
if (only.tagName === "span" && hasClass(only, "rpt-rating") && toneOf(only)) return { text: text2, kind: "rating", value: { tone: toneOf(only), label: textOf(only) } };
|
|
778
|
+
if (only.tagName === "span" && hasClass(only, "rpt-chip") && hasClass(only, "rpt-status")) return { text: text2, kind: "status", value: textOf(only) };
|
|
779
|
+
if (only.tagName === "code") return { text: text2, kind: "code", value: textOf(only) };
|
|
780
|
+
}
|
|
781
|
+
const mixed = nodes.some((n) => isEl(n) && (n.tagName === "span" && hasClass(n, "rpt-rating") || n.tagName === "code" || n.tagName === "strong" || n.tagName === "br"));
|
|
782
|
+
if (mixed) {
|
|
783
|
+
const parts = [];
|
|
784
|
+
const push = (s) => {
|
|
785
|
+
if (typeof parts[parts.length - 1] === "string") parts[parts.length - 1] += s;
|
|
786
|
+
else parts.push(s);
|
|
787
|
+
};
|
|
788
|
+
for (const n of kids(td)) {
|
|
789
|
+
if (isText(n)) {
|
|
790
|
+
push(n.value.replace(/\s+/g, " "));
|
|
791
|
+
continue;
|
|
792
|
+
}
|
|
793
|
+
if (!isEl(n)) continue;
|
|
794
|
+
if (n.tagName === "br") push("\n");
|
|
795
|
+
else if (n.tagName === "span" && hasClass(n, "rpt-rating") && toneOf(n)) parts.push({ value: { tone: toneOf(n), label: textOf(n) }, kind: "rating" });
|
|
796
|
+
else if (n.tagName === "code") parts.push({ value: textOf(n), kind: "code" });
|
|
797
|
+
else if (n.tagName === "strong") parts.push({ value: textOf(n), kind: "strong" });
|
|
798
|
+
else if (n.tagName !== "wbr") push(textOf(n));
|
|
799
|
+
}
|
|
800
|
+
return { text: text2, parts };
|
|
801
|
+
}
|
|
802
|
+
return { text: text2 };
|
|
803
|
+
}
|
|
804
|
+
var alignOf = (el2) => {
|
|
805
|
+
const a = style(el2, "text-align");
|
|
806
|
+
return a === "right" || a === "center" ? a : void 0;
|
|
807
|
+
};
|
|
808
|
+
function readTable(table) {
|
|
809
|
+
const head = child(table, (e) => e.tagName === "thead");
|
|
810
|
+
const bodyRows = [...elements(table).filter((e) => e.tagName === "tbody").flatMap((b) => elements(b).filter((r) => r.tagName === "tr")), ...elements(table).filter((e) => e.tagName === "tr")];
|
|
811
|
+
const headRow = head ? elements(head).find((r) => r.tagName === "tr") : void 0;
|
|
812
|
+
const cellsOf2 = (tr) => elements(tr).filter((c) => c.tagName === "td" || c.tagName === "th");
|
|
813
|
+
let headers = !!headRow, header = headRow ? cellsOf2(headRow) : [];
|
|
814
|
+
let rowsEl = bodyRows;
|
|
815
|
+
if (!headRow && rowsEl.length && cellsOf2(rowsEl[0]).length && cellsOf2(rowsEl[0]).every((c) => c.tagName === "th" && attr(c, "scope") !== "row")) {
|
|
816
|
+
headers = true;
|
|
817
|
+
header = cellsOf2(rowsEl[0]);
|
|
818
|
+
rowsEl = rowsEl.slice(1);
|
|
819
|
+
}
|
|
820
|
+
if (!rowsEl.length) return void 0;
|
|
821
|
+
const width = Math.max(header.length, ...rowsEl.map((r) => cellsOf2(r).length));
|
|
822
|
+
if (!width) return void 0;
|
|
823
|
+
const rowHeader = rowsEl.some((r) => {
|
|
824
|
+
const c = cellsOf2(r)[0];
|
|
825
|
+
return !!c && c.tagName === "th" && (attr(c, "scope") === "row" || hasClass(c, "rpt-rowheader") || !headers);
|
|
826
|
+
}) && rowsEl.every((r) => cellsOf2(r)[0]?.tagName === "th");
|
|
827
|
+
const columns = Array.from({ length: width }, (_, i) => {
|
|
828
|
+
const th = header[i];
|
|
829
|
+
const kind = th ? attr(th, "data-reportic-kind") : void 0;
|
|
830
|
+
const sample = rowsEl.map((r) => cellsOf2(r)[i]).filter(Boolean);
|
|
831
|
+
return {
|
|
832
|
+
label: th ? textOf(th) : headers ? "" : `Column ${i + 1}`,
|
|
833
|
+
...th && alignOf(th) ? { align: alignOf(th) } : sample.length && alignOf(sample[0]) ? { align: alignOf(sample[0]) } : {},
|
|
834
|
+
...kind && kinds.has(kind) ? { kind } : {},
|
|
835
|
+
...th && attr(th, "data-reportic-format") ? { format: attr(th, "data-reportic-format") } : {},
|
|
836
|
+
...sample.some((c) => /white-space:\s*nowrap/.test(attr(c, "style") ?? "")) ? { nowrap: true } : {}
|
|
837
|
+
};
|
|
838
|
+
});
|
|
839
|
+
const rows = [];
|
|
840
|
+
let total;
|
|
841
|
+
for (const tr of rowsEl) {
|
|
842
|
+
const cells = Array.from({ length: width }, (_, i) => {
|
|
843
|
+
const c = cellsOf2(tr)[i];
|
|
844
|
+
return c ? readCell(c) : { text: "" };
|
|
845
|
+
});
|
|
846
|
+
if (hasClass(tr, "rpt-total") && !total) total = cells;
|
|
847
|
+
else rows.push(cells);
|
|
848
|
+
}
|
|
849
|
+
columns.forEach((c, i) => {
|
|
850
|
+
if (c.kind) return;
|
|
851
|
+
const filled = [...rows, ...total ? [total] : []].map((r) => r[i]).filter((x) => x.text !== "");
|
|
852
|
+
const first = filled[0]?.kind;
|
|
853
|
+
if (first && filled.every((x) => x.kind === first) && !filled.some((x) => x.parts)) c.kind = first;
|
|
854
|
+
});
|
|
855
|
+
return { columns, headers, rowHeader, rows, total };
|
|
856
|
+
}
|
|
857
|
+
function gridCell(cell, column) {
|
|
858
|
+
if (cell.parts) return cell.parts;
|
|
859
|
+
if (!cell.kind) return cell.text;
|
|
860
|
+
const value = cell.value ?? cell.text;
|
|
861
|
+
if (cell.kind === column.kind) return cell.kind === "list" ? { value } : value;
|
|
862
|
+
return { value, kind: cell.kind, ...cell.kind === "date" ? { format: "date" } : {} };
|
|
863
|
+
}
|
|
864
|
+
var columnProps = (c, value) => ({ label: c.label, ...value !== void 0 ? { value } : {}, ...c.align ? { align: c.align } : {}, ...c.kind ? { kind: c.kind } : {}, ...c.format && c.kind === "date" ? { format: c.format } : {}, ...c.nowrap ? { nowrap: true } : {} });
|
|
865
|
+
var formatsOf = (columns) => columns.map((c) => c.kind === "date" ? void 0 : c.format);
|
|
866
|
+
function tableElement(model, id, ctx) {
|
|
867
|
+
const { columns, rows, total } = model;
|
|
868
|
+
const flags = { ...model.headers ? {} : { headers: false }, ...model.rowHeader ? { rowHeader: true } : {} };
|
|
869
|
+
if (total) {
|
|
870
|
+
const key2 = (i) => `c${i}`;
|
|
871
|
+
const record = (r) => Object.fromEntries(r.map((cell, i) => [key2(i), cell.kind === "rating" || cell.kind === "list" || cell.kind === "date" || cell.kind === "status" || cell.kind === "code" ? cell.kind === columns[i].kind ? cell.value : cell.text : cell.text]));
|
|
872
|
+
if ([...rows, total].some((r) => r.some((c) => c.parts))) ctx.note("COMPOSED_CELL_FLATTENED", "A table with a total row cannot keep cells made of several runs; those cells became plain text.", { elementId: id });
|
|
873
|
+
return { id, type: "table", props: { rows: rows.map(record), total: record(total), columns: columns.map((c, i) => columnProps(c, { $bind: `row.${key2(i)}` })), ...flags }, meta: { formats: formatsOf(columns) } };
|
|
874
|
+
}
|
|
875
|
+
return { id, type: "reportic.grid.v1", props: { ...flags, columns: columns.map((c) => columnProps(c)), rows: rows.map((r) => r.map((cell, i) => gridCell(cell, columns[i]))) }, meta: { formats: formatsOf(columns) } };
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
// packages/reportic-render-html/src/import/emit.ts
|
|
879
|
+
var baseOf = /* @__PURE__ */ new WeakMap();
|
|
880
|
+
var isMap = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
881
|
+
var word = /^[A-Za-z][A-Za-z0-9 _.-]*$/;
|
|
882
|
+
var reserved = /^(true|false|null|yes|no|on|off|y|n)$/i;
|
|
883
|
+
var quote = (s) => JSON.stringify(s).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029").replace(/\u0085/g, "\\u0085").replace(/\{\{/g, "\\u007B\\u007B").replace(/\{%/g, "\\u007B%");
|
|
884
|
+
var scalar = (v) => typeof v === "string" ? word.test(v) && v.trim() === v && !reserved.test(v) ? v : quote(v) : v === null ? "null" : String(v);
|
|
885
|
+
var key = (k) => /^[A-Za-z$][A-Za-z0-9_$]*$/.test(k) ? k : quote(k);
|
|
886
|
+
var flow = (v) => Array.isArray(v) ? `[${v.map(flow).join(", ")}]` : isMap(v) ? Object.keys(v).length ? `{ ${Object.entries(v).filter(([, x]) => x !== void 0).map(([k, x]) => `${key(k)}: ${flow(x)}`).join(", ")} }` : "{}" : scalar(v);
|
|
887
|
+
var pad = (n) => " ".repeat(n);
|
|
888
|
+
var collection = (v) => Array.isArray(v) || isMap(v);
|
|
889
|
+
function block(v, ind) {
|
|
890
|
+
if (Array.isArray(v)) {
|
|
891
|
+
return v.flatMap((item) => {
|
|
892
|
+
const f = flow(item);
|
|
893
|
+
if (f.length + ind < 96 || !collection(item)) return [`${pad(ind)}- ${f}`];
|
|
894
|
+
const sub = block(item, ind + 2);
|
|
895
|
+
sub[0] = `${pad(ind)}- ${sub[0].trimStart()}`;
|
|
896
|
+
return sub;
|
|
897
|
+
});
|
|
898
|
+
}
|
|
899
|
+
return Object.entries(v).filter(([, x]) => x !== void 0).flatMap(([k, x]) => {
|
|
900
|
+
const f = flow(x);
|
|
901
|
+
if (!collection(x) || f.length + ind + k.length < 96) return [`${pad(ind)}${key(k)}: ${f}`];
|
|
902
|
+
return [`${pad(ind)}${key(k)}:`, ...block(x, ind + 2)];
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
var clean = (v) => Array.isArray(v) ? v.map(clean) : v && typeof v === "object" ? Object.fromEntries(Object.entries(v).filter(([k]) => !(k === "meta" && "props" in v && "type" in v)).map(([k, x]) => [k, clean(x)])) : v;
|
|
906
|
+
var elementText = (e) => {
|
|
907
|
+
const props = clean(e.props);
|
|
908
|
+
return ["~~~reportic", `id: ${e.id}`, `type: ${e.type}`, ...e.when !== void 0 ? [`when: ${flow(e.when)}`] : [], ...Object.keys(props).length ? ["props:", ...block(props, 2)] : ["props: {}"], "~~~"].join("\n");
|
|
909
|
+
};
|
|
910
|
+
function writeTemplate(d) {
|
|
911
|
+
const front = ["---", 'reportic: "0.2"', `id: ${scalar(d.id)}`, `locale: ${scalar(d.locale)}`, `timezone: ${scalar(d.timezone ?? "UTC")}`];
|
|
912
|
+
if (d.logo) front.push("branding:", " logo:", ` src: { asset: ${scalar(d.logo.asset)} }`, ` alt: ${scalar(d.logo.alt)}`);
|
|
913
|
+
if (d.dataSets?.length) front.push("dataSets:", ...d.dataSets.map((n) => ` ${key(n)}: {}`));
|
|
914
|
+
front.push("---");
|
|
915
|
+
const body = d.blocks.map((b) => "md" in b ? b.md.trim() : elementText(b.element)).filter(Boolean);
|
|
916
|
+
return `${front.join("\n")}
|
|
917
|
+
|
|
918
|
+
${body.join("\n\n")}
|
|
919
|
+
`;
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
// packages/reportic-render-html/src/import/exact.ts
|
|
923
|
+
function isReporticHtml(doc) {
|
|
924
|
+
const generator = find(doc, (e) => e.tagName === "meta" && attr(e, "name") === "generator");
|
|
925
|
+
const main = find(doc, (e) => e.tagName === "main" && hasClass(e, "reportic-report"));
|
|
926
|
+
return !!generator && /^Reportic\s+0\.2/i.test(attr(generator, "content") ?? "") && !!main && !!find(main, (e) => attr(e, "data-reportic-type") !== void 0);
|
|
927
|
+
}
|
|
928
|
+
var mainOf = (doc) => find(doc, (e) => e.tagName === "main" && hasClass(e, "reportic-report"));
|
|
929
|
+
var tone = (el2) => ["ok", "warn", "bad", "na"].find((t) => hasClass(el2, `rpt-${t}`));
|
|
930
|
+
var nonEmpty = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0 && v !== "" && v !== null));
|
|
931
|
+
var Exact = class {
|
|
932
|
+
constructor(ctx) {
|
|
933
|
+
this.ctx = ctx;
|
|
934
|
+
}
|
|
935
|
+
ctx;
|
|
936
|
+
logo;
|
|
937
|
+
/** One section of Reportic HTML as an element. Several elements come back for a repeat, which has no element of its own on the page. */
|
|
938
|
+
section(sec) {
|
|
939
|
+
const base = attr(sec, "data-reportic-id"), out = this.build(sec);
|
|
940
|
+
if (base) {
|
|
941
|
+
for (const e of out) if (!baseOf.has(e)) baseOf.set(e, base);
|
|
942
|
+
}
|
|
943
|
+
return out;
|
|
944
|
+
}
|
|
945
|
+
build(sec) {
|
|
946
|
+
const type = attr(sec, "data-reportic-type"), id = this.ctx.uid(attr(sec, "data-reportic-id"));
|
|
947
|
+
const make = (elementType, props, extra = {}) => [{ id, type: elementType, props, ...extra }];
|
|
948
|
+
switch (type) {
|
|
949
|
+
case "logo":
|
|
950
|
+
return this.image(sec, id, true);
|
|
951
|
+
case "image":
|
|
952
|
+
return this.image(sec, id, false);
|
|
953
|
+
case "masthead":
|
|
954
|
+
return make("reportic.masthead.v1", this.masthead(sec));
|
|
955
|
+
case "footer":
|
|
956
|
+
return make("reportic.footer.v1", this.footer(sec));
|
|
957
|
+
case "metrics":
|
|
958
|
+
return make("metrics", this.metrics(sec));
|
|
959
|
+
case "table":
|
|
960
|
+
return this.table(sec, id);
|
|
961
|
+
case "chart":
|
|
962
|
+
return this.chart(sec, id);
|
|
963
|
+
case "diagram":
|
|
964
|
+
return this.diagram(sec, id);
|
|
965
|
+
case "figure":
|
|
966
|
+
return this.figure(sec, id);
|
|
967
|
+
case "narrative":
|
|
968
|
+
return make("narrative", this.narrative(sec));
|
|
969
|
+
case "list":
|
|
970
|
+
return this.list(sec, id);
|
|
971
|
+
case "sources":
|
|
972
|
+
return make("sources", this.sources(sec));
|
|
973
|
+
case "callout":
|
|
974
|
+
return make("reportic.callout.v1", this.callout(sec));
|
|
975
|
+
case "progress":
|
|
976
|
+
return make("reportic.progress.v1", this.progress(sec));
|
|
977
|
+
case "timeline":
|
|
978
|
+
return make("reportic.timeline.v1", this.timeline(sec));
|
|
979
|
+
case "comparison":
|
|
980
|
+
return this.comparison(sec, id);
|
|
981
|
+
case "checklist":
|
|
982
|
+
return make("reportic.checklist.v1", this.checklist(sec));
|
|
983
|
+
case "code":
|
|
984
|
+
return make("reportic.code.v1", this.code(sec));
|
|
985
|
+
case "group": {
|
|
986
|
+
const h22 = this.members(sec)[0];
|
|
987
|
+
const titled = h22?.tagName === "h2";
|
|
988
|
+
return make("group", { ...titled ? { heading: textOf(h22) } : {}, children: this.children(sec, titled) });
|
|
989
|
+
}
|
|
990
|
+
case "repeat":
|
|
991
|
+
return this.repeat(sec, id);
|
|
992
|
+
default:
|
|
993
|
+
this.ctx.warn("SECTION_UNKNOWN", `A section of type "${type}" has no element in the library, so its text was kept as a paragraph.`, { elementId: id });
|
|
994
|
+
return textOf(sec) ? make("narrative", { text: textOf(sec, true) }) : [];
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
/** What a group or repeat holds, in order: sections, and headings (a heading element is plain Markdown on the page, so it has no section). */
|
|
998
|
+
members(sec) {
|
|
999
|
+
return elements(sec).filter((e) => e.tagName === "section" && attr(e, "data-reportic-type") !== void 0 || /^h[1-6]$/.test(e.tagName));
|
|
1000
|
+
}
|
|
1001
|
+
member(e) {
|
|
1002
|
+
if (e.tagName === "section") return this.section(e);
|
|
1003
|
+
const text2 = textOf(e);
|
|
1004
|
+
if (!text2) return [];
|
|
1005
|
+
const heading = { id: this.ctx.uid("heading"), type: "reportic.heading.v1", props: { text: text2, level: Number(e.tagName[1]) } };
|
|
1006
|
+
baseOf.set(heading, e.tagName);
|
|
1007
|
+
return [heading];
|
|
1008
|
+
}
|
|
1009
|
+
children(sec, skipHeading = false) {
|
|
1010
|
+
const list2 = this.members(sec);
|
|
1011
|
+
return (skipHeading && list2[0]?.tagName === "h2" ? list2.slice(1) : list2).flatMap((e) => this.member(e));
|
|
1012
|
+
}
|
|
1013
|
+
image(sec, id, brand) {
|
|
1014
|
+
const img = find(sec, (e) => e.tagName === "img");
|
|
1015
|
+
if (!img) return [];
|
|
1016
|
+
const src = attr(img, "src") ?? "", alt = attr(img, "alt") ?? "";
|
|
1017
|
+
const name = this.ctx.asset(src, brand ? "logo" : void 0);
|
|
1018
|
+
if (!name) {
|
|
1019
|
+
this.ctx.warn("IMAGE_NOT_EMBEDDED", `An image${alt ? ` ("${alt}")` : ""} is not embedded in the page, so it was left out.`, { elementId: id });
|
|
1020
|
+
return [];
|
|
1021
|
+
}
|
|
1022
|
+
if (brand || attr(sec, "data-reportic-id") === "reportic-brand-logo") {
|
|
1023
|
+
this.logo = { asset: name, alt: alt || "Logo" };
|
|
1024
|
+
return [];
|
|
1025
|
+
}
|
|
1026
|
+
const figcaption = find(sec, (e) => e.tagName === "figcaption"), caption = figcaption ? textOf(figcaption) : "";
|
|
1027
|
+
return [{ id, type: "image", props: { src: { asset: name }, alt: alt || "Image", ...caption ? { caption } : {} } }];
|
|
1028
|
+
}
|
|
1029
|
+
masthead(sec) {
|
|
1030
|
+
const header = find(sec, (e) => e.tagName === "header") ?? sec;
|
|
1031
|
+
const byEl = (cls) => find(header, (e) => hasClass(e, cls));
|
|
1032
|
+
const model = json(sec, "data-reportic-model");
|
|
1033
|
+
let byline = model?.byline;
|
|
1034
|
+
const bylineEl = byEl("rpt-byline");
|
|
1035
|
+
if (!byline && bylineEl) {
|
|
1036
|
+
byline = kids(bylineEl).flatMap((n) => isEl(n) && hasClass(n, "rpt-chip") ? [{ value: textOf(n), kind: hasClass(n, "rpt-person") ? "person" : "date" }] : isText(n) ? n.value.split("\xB7").map((s) => s.trim()).filter(Boolean).map((value) => ({ value })) : []);
|
|
1037
|
+
this.ctx.note("BYLINE_APPROXIMATE", "The byline was read from the page text; dates are kept as written.");
|
|
1038
|
+
}
|
|
1039
|
+
return nonEmpty({ marking: byEl("rpt-marking") && textOf(byEl("rpt-marking")), kicker: byEl("rpt-kicker") && textOf(byEl("rpt-kicker")), title: textOf(find(header, (e) => e.tagName === "h1") ?? header), byline: byline?.length ? byline : void 0, lead: byEl("rpt-lead") && textOf(byEl("rpt-lead")) });
|
|
1040
|
+
}
|
|
1041
|
+
footer(sec) {
|
|
1042
|
+
const footer = find(sec, (e) => e.tagName === "footer") ?? sec, img = find(footer, (e) => e.tagName === "img");
|
|
1043
|
+
const text2 = kids(footer).filter((n) => !(isEl(n) && n.tagName === "img")).map((n) => textOf(n)).join(" ").replace(/\s+/g, " ").trim();
|
|
1044
|
+
const name = img ? this.ctx.asset(attr(img, "src") ?? "", "footer-logo") : void 0;
|
|
1045
|
+
return { text: text2, ...name ? { logo: { asset: name }, logoAlt: attr(img, "alt") ?? "Logo" } : {} };
|
|
1046
|
+
}
|
|
1047
|
+
metrics(sec) {
|
|
1048
|
+
const holder = find(sec, (e) => hasClass(e, "metrics"));
|
|
1049
|
+
const items = (holder ? elements(holder) : []).map((div) => {
|
|
1050
|
+
const part = (cls) => {
|
|
1051
|
+
const e = find(div, (x) => hasClass(x, cls));
|
|
1052
|
+
return e ? textOf(e) : void 0;
|
|
1053
|
+
};
|
|
1054
|
+
return nonEmpty({ label: part("metric-label"), value: part("metric-value"), comparison: part("metric-comparison"), tone: tone(div) });
|
|
1055
|
+
});
|
|
1056
|
+
return { items };
|
|
1057
|
+
}
|
|
1058
|
+
table(sec, id) {
|
|
1059
|
+
const table = find(sec, (e) => e.tagName === "table");
|
|
1060
|
+
if (!table) {
|
|
1061
|
+
const empty = textOf(sec);
|
|
1062
|
+
this.ctx.note("TABLE_EMPTY", `A table with no rows shows "${empty}"; its columns are not on the page, so it was kept as a paragraph.`, { elementId: id });
|
|
1063
|
+
return empty ? [{ id, type: "narrative", props: { text: empty } }] : [];
|
|
1064
|
+
}
|
|
1065
|
+
const model = readTable(table);
|
|
1066
|
+
if (!model) return [];
|
|
1067
|
+
return [tableElement(model, id, this.ctx)];
|
|
1068
|
+
}
|
|
1069
|
+
chart(sec, id) {
|
|
1070
|
+
const m = json(sec, "data-reportic-model"), kind = attr(sec, "data-reportic-kind");
|
|
1071
|
+
if (!m || !Array.isArray(m.categories) || !Array.isArray(m.series)) {
|
|
1072
|
+
const empty = textOf(sec);
|
|
1073
|
+
this.ctx.note("CHART_EMPTY", "A chart with no data has nothing to import and was kept as a paragraph.", { elementId: id });
|
|
1074
|
+
return empty ? [{ id, type: "narrative", props: { text: empty } }] : [];
|
|
1075
|
+
}
|
|
1076
|
+
const rows = m.categories.map((c, i) => ({ x: c, ...Object.fromEntries(m.series.map((s, j) => [`s${j}`, s.values[i]])) }));
|
|
1077
|
+
return [{ id, type: "chart", props: { kind: kind === "bar" ? "bar" : "line", title: m.title, alt: m.alt, rows, x: { label: m.x?.label ?? "", value: { $bind: "row.x" } }, series: m.series.map((s, j) => ({ label: s.label, value: { $bind: `row.s${j}` }, ...s.format ? { format: s.format } : {} })) } }];
|
|
1078
|
+
}
|
|
1079
|
+
diagram(sec, id) {
|
|
1080
|
+
const m = json(sec, "data-reportic-model");
|
|
1081
|
+
if (!m) {
|
|
1082
|
+
this.ctx.warn("DIAGRAM_SOURCE_LOST", "A diagram has no source on the page. It was kept as an image.", { elementId: id });
|
|
1083
|
+
return this.image(sec, id, false);
|
|
1084
|
+
}
|
|
1085
|
+
return [{ id, type: "diagram", props: { engine: "mermaid", alt: m.alt, ...m.adapter ? { adapter: m.adapter, model: m.model } : { source: m.source }, ...m.caption && m.caption !== m.alt ? { caption: m.caption } : {} } }];
|
|
1086
|
+
}
|
|
1087
|
+
figure(sec, id) {
|
|
1088
|
+
const spec = json(sec, "data-reportic-spec");
|
|
1089
|
+
if (!spec) {
|
|
1090
|
+
this.ctx.warn("FIGURE_SPEC_LOST", "A figure has no spec on the page. It was kept as an image.", { elementId: id });
|
|
1091
|
+
return this.image(sec, id, false);
|
|
1092
|
+
}
|
|
1093
|
+
const caption = find(sec, (e) => e.tagName === "figcaption"), source = caption ? textOf(caption) : "";
|
|
1094
|
+
const alt = attr(find(sec, (e) => e.tagName === "img") ?? sec, "alt");
|
|
1095
|
+
return [{ id, type: "reportic.figure.v1", props: { spec, ...source ? { source } : {}, ...alt && alt !== spec.title && alt !== `${spec.title} \u2014 ${spec.subtitle}` ? { alt } : {} } }];
|
|
1096
|
+
}
|
|
1097
|
+
narrative(sec) {
|
|
1098
|
+
const heading = find(sec, (e) => e.tagName === "h3"), p = find(sec, (e) => e.tagName === "p");
|
|
1099
|
+
const evidence = p ? findAll(p, (e) => e.tagName === "a" && hasClass(e, "evidence")) : [];
|
|
1100
|
+
const text2 = p ? kids(p).filter((n) => !(isEl(n) && hasClass(n, "evidence"))).map((n) => isText(n) ? n.value : textOf(n, true)).join("").replace(/[ \t]+/g, " ").replace(/ *\n */g, "\n").trim() : "";
|
|
1101
|
+
const ids = evidence.map((a) => (attr(a, "href") ?? "").replace(/^#/, "")).filter(Boolean);
|
|
1102
|
+
return nonEmpty({ heading: heading && textOf(heading), text: text2, evidenceIds: ids.length ? ids : void 0 });
|
|
1103
|
+
}
|
|
1104
|
+
list(sec, id) {
|
|
1105
|
+
const aside = find(sec, (e) => e.tagName === "aside"), listEl = find(sec, (e) => e.tagName === "ul" || e.tagName === "ol");
|
|
1106
|
+
const empty = child(sec, (e) => hasClass(e, "empty"));
|
|
1107
|
+
const itemEls = aside ? elements(aside).filter((e) => e.tagName === "p") : listEl ? elements(listEl).filter((e) => e.tagName === "li") : elements(sec).filter((e) => e.tagName === "p" && !hasClass(e, "empty"));
|
|
1108
|
+
const variant = aside ? "callout" : listEl ? void 0 : "paragraphs";
|
|
1109
|
+
const items = itemEls.map((el2) => {
|
|
1110
|
+
const first = kids(el2).find((n) => isEl(n) || isText(n) && n.value.trim());
|
|
1111
|
+
const lead = isEl(first) && first.tagName === "strong" ? textOf(first) : "";
|
|
1112
|
+
const rest = kids(el2).filter((n) => n !== first || !lead).map((n) => isText(n) ? n.value : textOf(n)).join("").replace(/\s+/g, " ").trim();
|
|
1113
|
+
return { lead, text: lead ? rest : textOf(el2) };
|
|
1114
|
+
});
|
|
1115
|
+
if (!items.length) return [{ id, type: "list", props: { rows: [], text: { $bind: "row" }, ...empty ? { empty: textOf(empty) } : {} } }];
|
|
1116
|
+
const leads = items.some((i) => i.lead);
|
|
1117
|
+
return [{ id, type: "list", props: { rows: leads ? items.map((i) => nonEmpty(i)) : items.map((i) => i.text), ...leads ? { lead: { $bind: "row.lead" }, text: { $bind: "row.text" } } : { text: { $bind: "row" } }, ...variant ? { variant } : {}, ...listEl?.tagName === "ol" ? { ordered: true } : {} } }];
|
|
1118
|
+
}
|
|
1119
|
+
sources(sec) {
|
|
1120
|
+
const records = {};
|
|
1121
|
+
for (const li of findAll(sec, (e) => e.tagName === "li")) {
|
|
1122
|
+
const a = find(li, (e) => e.tagName === "a"), idAttr = attr(li, "id") ?? `source-${Object.keys(records).length + 1}`;
|
|
1123
|
+
records[idAttr] = { label: textOf(li), ...a && attr(a, "href") ? { url: attr(a, "href") } : {} };
|
|
1124
|
+
}
|
|
1125
|
+
return { records };
|
|
1126
|
+
}
|
|
1127
|
+
callout(sec) {
|
|
1128
|
+
const aside = find(sec, (e) => e.tagName === "aside") ?? sec, strong = child(aside, (e) => e.tagName === "strong"), p = child(aside, (e) => e.tagName === "p");
|
|
1129
|
+
const t = ["info", "success", "warning", "danger"].find((x) => hasClass(aside, `tone-${x}`));
|
|
1130
|
+
return { title: strong ? textOf(strong) : "", text: p ? textOf(p, true) : "", ...t && t !== "info" ? { tone: t } : {} };
|
|
1131
|
+
}
|
|
1132
|
+
progress(sec) {
|
|
1133
|
+
return { items: findAll(sec, (e) => hasClass(e, "progress-item")).map((item) => {
|
|
1134
|
+
const bar = find(item, (e) => attr(e, "role") === "progressbar"), now = Number(attr(bar ?? item, "aria-valuenow") ?? 0), small = find(item, (e) => e.tagName === "small");
|
|
1135
|
+
const row = find(item, (e) => hasClass(e, "progress-label")), span = row && child(row, (e) => e.tagName === "span");
|
|
1136
|
+
return nonEmpty({ label: textOf(span ?? item), value: Number((now / 100).toPrecision(10)), detail: small && textOf(small) });
|
|
1137
|
+
}) };
|
|
1138
|
+
}
|
|
1139
|
+
timeline(sec) {
|
|
1140
|
+
return { items: findAll(sec, (e) => hasClass(e, "timeline-item")).map((item) => nonEmpty({ date: textOf(find(item, (e) => hasClass(e, "timeline-date")) ?? item), title: textOf(find(item, (e) => e.tagName === "strong") ?? item), text: (() => {
|
|
1141
|
+
const p = find(item, (e) => e.tagName === "p");
|
|
1142
|
+
return p && textOf(p);
|
|
1143
|
+
})() })) };
|
|
1144
|
+
}
|
|
1145
|
+
comparison(sec, id) {
|
|
1146
|
+
const table = find(sec, (e) => e.tagName === "table"), model = table && readTable(table);
|
|
1147
|
+
if (!model || model.columns.length !== 3) return table ? [tableElement(model ?? readTable(table), id, this.ctx)] : [];
|
|
1148
|
+
return [{ id, type: "reportic.comparison.v1", props: { labels: [model.columns[1].label, model.columns[2].label], rows: model.rows.map((r) => ({ label: r[0].text, left: r[1].text, right: r[2].text })) } }];
|
|
1149
|
+
}
|
|
1150
|
+
checklist(sec) {
|
|
1151
|
+
return { items: findAll(sec, (e) => e.tagName === "li").map((li) => {
|
|
1152
|
+
const mark = find(li, (e) => hasClass(e, "checkmark")), owner = find(li, (e) => e.tagName === "small");
|
|
1153
|
+
const text2 = kids(li).filter((n) => n !== mark && !(isEl(n) && n.tagName === "small")).map((n) => textOf(n)).join("").replace(/\s+/g, " ").trim();
|
|
1154
|
+
return nonEmpty({ text: text2, done: mark ? textOf(mark).includes("\u2611") : false, owner: owner && textOf(owner).replace(/^·\s*/, "") });
|
|
1155
|
+
}) };
|
|
1156
|
+
}
|
|
1157
|
+
code(sec) {
|
|
1158
|
+
const pre = find(sec, (e) => e.tagName === "pre"), small = child(sec, (e) => e.tagName === "small"), caption = child(sec, (e) => e.tagName === "p");
|
|
1159
|
+
return nonEmpty({ code: pre ? kids(find(pre, (e) => e.tagName === "code") ?? pre).map((n) => isText(n) ? n.value : textOf(n, true)).join("") : "", language: small && textOf(small), caption: caption && textOf(caption) });
|
|
1160
|
+
}
|
|
1161
|
+
/** A repeat leaves no trace of its rows, only its children once per row. Each row becomes a group so every one keeps its own text. */
|
|
1162
|
+
repeat(sec, id) {
|
|
1163
|
+
const empty = child(sec, (e) => hasClass(e, "empty"));
|
|
1164
|
+
const secs = this.members(sec);
|
|
1165
|
+
if (!secs.length) {
|
|
1166
|
+
if (empty) this.ctx.note("REPEAT_EMPTY", "A repeat with no rows was dropped.", { elementId: id });
|
|
1167
|
+
return [];
|
|
1168
|
+
}
|
|
1169
|
+
const chunks = [];
|
|
1170
|
+
let seen = /* @__PURE__ */ new Set();
|
|
1171
|
+
for (const s of secs) {
|
|
1172
|
+
const key2 = attr(s, "data-reportic-id") ?? s.tagName;
|
|
1173
|
+
if (!chunks.length || seen.has(key2)) {
|
|
1174
|
+
chunks.push([]);
|
|
1175
|
+
seen = /* @__PURE__ */ new Set();
|
|
1176
|
+
}
|
|
1177
|
+
chunks[chunks.length - 1].push(s);
|
|
1178
|
+
seen.add(key2);
|
|
1179
|
+
}
|
|
1180
|
+
this.ctx.note("REPEAT_EXPANDED", `A repeat showed ${chunks.length} time${chunks.length === 1 ? "" : "s"} and became one group each. Import with a sample to turn them into a repeat again.`, { elementId: id });
|
|
1181
|
+
return chunks.map((chunk, i) => ({ id: this.ctx.uid(`${attr(sec, "data-reportic-id") ?? "repeat"}-row`), type: "group", props: { children: chunk.flatMap((s) => this.member(s)) }, meta: { repeat: attr(sec, "data-reportic-id") ?? id, index: i, count: chunks.length } }));
|
|
1182
|
+
}
|
|
1183
|
+
};
|
|
1184
|
+
function importReportic(doc, ctx) {
|
|
1185
|
+
const main = mainOf(doc), exact = new Exact(ctx), md2 = ctx.markdown();
|
|
1186
|
+
const blocks2 = [];
|
|
1187
|
+
let pending = [];
|
|
1188
|
+
const flush = () => {
|
|
1189
|
+
if (!pending.length) return;
|
|
1190
|
+
const text2 = toMarkdown(pending, md2);
|
|
1191
|
+
pending = [];
|
|
1192
|
+
if (text2) blocks2.push({ md: text2 });
|
|
1193
|
+
};
|
|
1194
|
+
for (const n of kids(main)) {
|
|
1195
|
+
if (isEl(n) && n.tagName === "section" && attr(n, "data-reportic-type") !== void 0) {
|
|
1196
|
+
flush();
|
|
1197
|
+
for (const element of exact.section(n)) blocks2.push({ element });
|
|
1198
|
+
} else pending.push(n);
|
|
1199
|
+
}
|
|
1200
|
+
flush();
|
|
1201
|
+
const html = find(doc, (e) => e.tagName === "html");
|
|
1202
|
+
const title = (() => {
|
|
1203
|
+
const mast = blocks2.find((b) => "element" in b && b.element.type === "reportic.masthead.v1");
|
|
1204
|
+
const h1 = find(main, (e) => e.tagName === "h1"), named = find(doc, (e) => e.tagName === "title");
|
|
1205
|
+
return mast?.element.props.title ?? (h1 ? textOf(h1) : named ? textOf(named) : "").slice(0, 60);
|
|
1206
|
+
})();
|
|
1207
|
+
return { id: `imported-${String(title || "report").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "report"}`, locale: html && attr(html, "lang") || "en-US", blocks: blocks2, logo: exact.logo, assets: ctx.assets };
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
// packages/reportic-render-html/src/import/effort.ts
|
|
1211
|
+
var DROPPED = { script: "scripts", iframe: "embedded frames", video: "video", audio: "audio", canvas: "canvas drawings", object: "embedded objects", embed: "embedded objects", form: "forms", button: "buttons", select: "form controls", textarea: "form controls", nav: "navigation", noscript: "fallback markup" };
|
|
1212
|
+
var CONTAINERS = /* @__PURE__ */ new Set(["div", "section", "article", "main", "header", "aside", "span", "center", "body", "html", "figure", "details", "address", "hgroup", "footer"]);
|
|
1213
|
+
var VALUE = /^[+\-−]?[\p{Sc}]?\s?\d[\d,.\s]*\s?(%|[kKmMbB]|pts?|ms|s|x|d|h|min|GB|MB|TB)?$/u;
|
|
1214
|
+
var DATE = /^(\d{4}-\d{2}-\d{2}|\d{1,2} [A-Z][a-z]{2,8}\.?(?: \d{4})?|[A-Z][a-z]{2,8}\.? \d{1,2}(?:,? \d{4})?|Q[1-4] \d{4}|[A-Z][a-z]{2,8} \d{4})(?=\s|$|[:\-–—·|])/;
|
|
1215
|
+
var TONES = [[/danger|error|critical|alert-danger|bad/i, "danger"], [/warn|caution|attention/i, "warning"], [/success|tip|ok|good|done/i, "success"]];
|
|
1216
|
+
var isValue = (s) => s.length <= 14 && s.split(/\s+/).length <= 2 && VALUE.test(s.trim());
|
|
1217
|
+
var text = (n) => textOf(n);
|
|
1218
|
+
var Effort = class {
|
|
1219
|
+
constructor(ctx) {
|
|
1220
|
+
this.ctx = ctx;
|
|
1221
|
+
}
|
|
1222
|
+
ctx;
|
|
1223
|
+
items = [];
|
|
1224
|
+
dropped = /* @__PURE__ */ new Map();
|
|
1225
|
+
sources;
|
|
1226
|
+
emit(element) {
|
|
1227
|
+
this.items.push({ element });
|
|
1228
|
+
}
|
|
1229
|
+
drop(el2, why) {
|
|
1230
|
+
const label = DROPPED[el2.tagName] ?? why ?? el2.tagName;
|
|
1231
|
+
this.dropped.set(label, (this.dropped.get(label) ?? 0) + 1);
|
|
1232
|
+
}
|
|
1233
|
+
walk(nodes) {
|
|
1234
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
1235
|
+
const n = nodes[i];
|
|
1236
|
+
if (!isEl(n)) {
|
|
1237
|
+
if (isText(n) && n.value.trim()) this.items.push({ node: n });
|
|
1238
|
+
continue;
|
|
1239
|
+
}
|
|
1240
|
+
if (n.tagName in DROPPED) {
|
|
1241
|
+
this.drop(n);
|
|
1242
|
+
continue;
|
|
1243
|
+
}
|
|
1244
|
+
if (isSkipped(n)) {
|
|
1245
|
+
if (n.tagName === "svg") this.ctx.warn("SVG_DROPPED", "An inline SVG drawing was dropped. A picture of a chart is kept only when it is an image with a caption.");
|
|
1246
|
+
continue;
|
|
1247
|
+
}
|
|
1248
|
+
if (attr(n, "hidden") !== void 0 || /display\s*:\s*none/i.test(attr(n, "style") ?? "")) continue;
|
|
1249
|
+
if (this.special(n, nodes, i)) continue;
|
|
1250
|
+
if (CONTAINERS.has(n.tagName) || n.tagName === "li" || n.tagName === "dd") {
|
|
1251
|
+
this.walk(kids(n));
|
|
1252
|
+
continue;
|
|
1253
|
+
}
|
|
1254
|
+
this.items.push({ node: n });
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
/** Tries each structural pattern. Returns true when the element was consumed. */
|
|
1258
|
+
special(n, siblings, index) {
|
|
1259
|
+
const id = (base) => this.ctx.uid(base);
|
|
1260
|
+
const tag2 = n.tagName;
|
|
1261
|
+
if (tag2 === "progress" || tag2 === "meter" || attr(n, "role") === "progressbar") {
|
|
1262
|
+
const item = this.progressItem(n, siblings, index);
|
|
1263
|
+
if (item) {
|
|
1264
|
+
const last = this.items[this.items.length - 1];
|
|
1265
|
+
if (last && "element" in last && last.element.type === "reportic.progress.v1" && last.element.meta?.open) last.element.props.items.push(item);
|
|
1266
|
+
else this.emit({ id: id("progress"), type: "reportic.progress.v1", props: { items: [item] }, meta: { open: true } });
|
|
1267
|
+
return true;
|
|
1268
|
+
}
|
|
1269
|
+
this.ctx.note("PROGRESS_WEAK", "A progress bar without a value between 0 and 1 was left out.");
|
|
1270
|
+
return true;
|
|
1271
|
+
}
|
|
1272
|
+
if (hasClass(n, "mermaid") || tag2 === "pre" && find(n, (e) => e.tagName === "code" && classes(e).includes("language-mermaid")) || tag2 === "code" && classes(n).includes("language-mermaid")) {
|
|
1273
|
+
const source = textOf(n, true).trim();
|
|
1274
|
+
if (source) {
|
|
1275
|
+
this.emit({ id: id("diagram"), type: "diagram", props: { engine: "mermaid", alt: "Diagram", source } });
|
|
1276
|
+
this.ctx.note("DIAGRAM_ALT", 'A Mermaid diagram was imported with the alt text "Diagram"; write a real description in the editor.');
|
|
1277
|
+
return true;
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
if (tag2 === "pre") {
|
|
1281
|
+
const code = find(n, (e) => e.tagName === "code"), language = classes(code ?? n).map((c) => /^(?:language|lang)-(.+)$/.exec(c)?.[1]).find(Boolean);
|
|
1282
|
+
const body = code ?? n;
|
|
1283
|
+
const raw = kids(body).map((k) => isText(k) ? k.value : textOf(k, true)).join("").replace(/\n$/, "");
|
|
1284
|
+
if (raw.trim()) {
|
|
1285
|
+
this.emit({ id: id("code"), type: "reportic.code.v1", props: { code: raw, ...language ? { language } : {} } });
|
|
1286
|
+
return true;
|
|
1287
|
+
}
|
|
1288
|
+
return true;
|
|
1289
|
+
}
|
|
1290
|
+
if (tag2 === "img" || tag2 === "figure" && find(n, (e) => e.tagName === "img") && !find(n, (e) => e.tagName === "table")) {
|
|
1291
|
+
return this.image(n);
|
|
1292
|
+
}
|
|
1293
|
+
if (tag2 === "ul" || tag2 === "ol") {
|
|
1294
|
+
const lis = elements(n).filter((e) => e.tagName === "li");
|
|
1295
|
+
if (lis.length && lis.every((li) => {
|
|
1296
|
+
const first = kids(li).find((k) => isEl(k) || isText(k) && k.value.trim());
|
|
1297
|
+
return isEl(first) && first.tagName === "input" && attr(first, "type") === "checkbox";
|
|
1298
|
+
})) {
|
|
1299
|
+
this.emit({ id: id("checklist"), type: "reportic.checklist.v1", props: { items: lis.map((li) => ({ text: text(li), done: !!find(li, (e) => e.tagName === "input" && attr(e, "checked") !== void 0) })) } });
|
|
1300
|
+
return true;
|
|
1301
|
+
}
|
|
1302
|
+
const bar = (e) => e.tagName === "progress" || e.tagName === "meter" || attr(e, "role") === "progressbar";
|
|
1303
|
+
if (lis.length && lis.every((li) => find(li, bar))) {
|
|
1304
|
+
const items = lis.map((li) => this.progressItem(find(li, bar), kids(li), kids(li).indexOf(find(li, bar))));
|
|
1305
|
+
if (items.every(Boolean)) {
|
|
1306
|
+
this.emit({ id: id("progress"), type: "reportic.progress.v1", props: { items } });
|
|
1307
|
+
return true;
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
if (tag2 === "ol" && lis.length && lis.every((li) => {
|
|
1311
|
+
const a = find(li, (e) => e.tagName === "a" && /^https?:/i.test(attr(e, "href") ?? ""));
|
|
1312
|
+
return !!a;
|
|
1313
|
+
}) && this.trailing(siblings, index)) {
|
|
1314
|
+
const records = {}, ids = [];
|
|
1315
|
+
lis.forEach((li, k) => {
|
|
1316
|
+
const a = find(li, (e) => e.tagName === "a"), key2 = `source-${k + 1}`;
|
|
1317
|
+
ids.push(key2);
|
|
1318
|
+
records[key2] = { label: text(li), url: attr(a, "href") };
|
|
1319
|
+
});
|
|
1320
|
+
this.sources = { ids };
|
|
1321
|
+
this.emit({ id: id("sources"), type: "sources", props: { records } });
|
|
1322
|
+
return true;
|
|
1323
|
+
}
|
|
1324
|
+
return false;
|
|
1325
|
+
}
|
|
1326
|
+
if (tag2 === "dl") {
|
|
1327
|
+
const rows = [];
|
|
1328
|
+
let term = "";
|
|
1329
|
+
for (const e of elements(n)) {
|
|
1330
|
+
if (e.tagName === "dt") term = text(e);
|
|
1331
|
+
else if (e.tagName === "dd") {
|
|
1332
|
+
rows.push([term, text(e)]);
|
|
1333
|
+
term = "";
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
if (rows.length) {
|
|
1337
|
+
this.emit({ id: id("details"), type: "reportic.grid.v1", props: { headers: false, rowHeader: true, columns: [{ label: "Item" }, { label: "Value" }], rows } });
|
|
1338
|
+
return true;
|
|
1339
|
+
}
|
|
1340
|
+
return false;
|
|
1341
|
+
}
|
|
1342
|
+
if (tag2 === "table") return this.table(n);
|
|
1343
|
+
if (tag2 === "footer" && text(n).length < 400 && !find(n, (e) => ["ul", "ol", "table", "h1", "h2", "h3"].includes(e.tagName)) && text(n)) {
|
|
1344
|
+
this.emit({ id: id("footer"), type: "reportic.footer.v1", props: { text: text(n) } });
|
|
1345
|
+
return true;
|
|
1346
|
+
}
|
|
1347
|
+
if (tag2 === "p" && /\[\d{1,2}\]/.test(text(n)) && !n.attrs.some((a) => a.name === "class" && /footnote/.test(a.value))) {
|
|
1348
|
+
this.items.push({ cited: n });
|
|
1349
|
+
return true;
|
|
1350
|
+
}
|
|
1351
|
+
if (CONTAINERS.has(tag2) || tag2 === "li") {
|
|
1352
|
+
if (this.callout(n)) return true;
|
|
1353
|
+
if (this.metrics(n)) return true;
|
|
1354
|
+
if (this.flow(n)) return true;
|
|
1355
|
+
}
|
|
1356
|
+
if (/^h[3-5]$/.test(tag2) || tag2 === "li") {
|
|
1357
|
+
if (this.timeline(n, siblings, index)) return true;
|
|
1358
|
+
}
|
|
1359
|
+
return false;
|
|
1360
|
+
}
|
|
1361
|
+
trailing(siblings, index) {
|
|
1362
|
+
return siblings.slice(index + 1).every((s) => !isEl(s) || ["footer", "script", "style"].includes(s.tagName) || !text(s));
|
|
1363
|
+
}
|
|
1364
|
+
progressItem(n, siblings, index) {
|
|
1365
|
+
let value;
|
|
1366
|
+
if (n.tagName === "progress") {
|
|
1367
|
+
const max = Number(attr(n, "max") ?? 1), v = Number(attr(n, "value"));
|
|
1368
|
+
if (attr(n, "value") !== void 0 && max > 0) value = v / max;
|
|
1369
|
+
} else if (n.tagName === "meter") {
|
|
1370
|
+
const min = Number(attr(n, "min") ?? 0), max = Number(attr(n, "max") ?? 1), v = Number(attr(n, "value"));
|
|
1371
|
+
if (attr(n, "value") !== void 0 && max > min) value = (v - min) / (max - min);
|
|
1372
|
+
} else {
|
|
1373
|
+
const min = Number(attr(n, "aria-valuemin") ?? 0), max = Number(attr(n, "aria-valuemax") ?? 100), v = Number(attr(n, "aria-valuenow"));
|
|
1374
|
+
if (attr(n, "aria-valuenow") !== void 0 && max > min) value = (v - min) / (max - min);
|
|
1375
|
+
}
|
|
1376
|
+
if (value === void 0 || !Number.isFinite(value) || value < 0 || value > 1) return void 0;
|
|
1377
|
+
const prev = [...siblings.slice(0, index)].reverse().find((s) => isEl(s) && text(s) || isText(s) && s.value.trim());
|
|
1378
|
+
const parentLabel = (() => {
|
|
1379
|
+
const p = n.parentNode;
|
|
1380
|
+
return p && isEl(p) ? kids(p).filter((k) => k !== n && (isText(k) || isEl(k) && !["progress", "meter"].includes(k.tagName) && attr(k, "role") !== "progressbar")).map(text).join(" ").replace(/\s+/g, " ").trim() : "";
|
|
1381
|
+
})();
|
|
1382
|
+
const label = attr(n, "aria-label") ?? (parentLabel && parentLabel.length < 80 ? parentLabel : prev ? text(prev).slice(0, 80) : "") ?? "";
|
|
1383
|
+
return { label: label || "Progress", value: Number(value.toPrecision(6)) };
|
|
1384
|
+
}
|
|
1385
|
+
image(n) {
|
|
1386
|
+
const img = n.tagName === "img" ? n : find(n, (e) => e.tagName === "img"), src = attr(img, "src") ?? "", alt = attr(img, "alt") ?? "";
|
|
1387
|
+
const figcaption = n.tagName === "figure" ? find(n, (e) => e.tagName === "figcaption") : void 0, caption = figcaption ? text(figcaption) : "";
|
|
1388
|
+
const name = this.ctx.asset(src);
|
|
1389
|
+
if (!name) {
|
|
1390
|
+
this.ctx.warn(src.startsWith("data:") ? "IMAGE_TYPE_UNSUPPORTED" : "IMAGE_NOT_EMBEDDED", `An image${alt ? ` ("${alt.slice(0, 60)}")` : ""} is not embedded in the page, so its bytes cannot be imported.`);
|
|
1391
|
+
return true;
|
|
1392
|
+
}
|
|
1393
|
+
this.emit({ id: this.ctx.uid("image"), type: "image", props: { src: { asset: name }, alt: alt || caption || "Image", ...caption ? { caption } : {} } });
|
|
1394
|
+
if (!alt && !caption) this.ctx.note("IMAGE_ALT", 'An image had no alt text and was imported with "Image"; describe it in the editor.');
|
|
1395
|
+
return true;
|
|
1396
|
+
}
|
|
1397
|
+
table(n) {
|
|
1398
|
+
const nested = find(n, (e) => e.tagName === "table" && e !== n);
|
|
1399
|
+
const cells = findAll(n, (e) => e.tagName === "td"), blocky = cells.some((c) => elements(c).some((e) => ["div", "p", "ul", "ol", "table", "h1", "h2", "h3", "h4"].includes(e.tagName)));
|
|
1400
|
+
if (nested || blocky && !find(n, (e) => e.tagName === "th")) {
|
|
1401
|
+
this.ctx.note("LAYOUT_TABLE", "A table used for page layout was read as its contents.");
|
|
1402
|
+
for (const td of cells) this.walk(kids(td));
|
|
1403
|
+
return true;
|
|
1404
|
+
}
|
|
1405
|
+
const model = readTable(n);
|
|
1406
|
+
if (!model) return true;
|
|
1407
|
+
const caption = child(n, (e) => e.tagName === "caption");
|
|
1408
|
+
const hasTh = !!find(n, (e) => e.tagName === "th"), thead = !!child(n, (e) => e.tagName === "thead");
|
|
1409
|
+
if (!hasTh && !thead) {
|
|
1410
|
+
model.headers = false;
|
|
1411
|
+
}
|
|
1412
|
+
for (const [j, column] of model.columns.entries()) {
|
|
1413
|
+
if (!column.align && model.rows.length && model.rows.every((r) => r[j].text === "" || isValue(r[j].text))) column.align = "right";
|
|
1414
|
+
}
|
|
1415
|
+
if (caption && text(caption)) this.items.push({ md: `**${escapeText(text(caption))}**` });
|
|
1416
|
+
if (model.headers && model.columns.length === 3 && !model.total && model.columns.slice(1).every((c) => c.label) && (model.columns[0].label === "" || model.rows.every((r) => r[0].text) && !!find(n, (e) => e.tagName === "th" && attr(e, "scope") === "row"))) {
|
|
1417
|
+
this.emit({ id: this.ctx.uid("comparison"), type: "reportic.comparison.v1", props: { labels: [model.columns[1].label, model.columns[2].label], rows: model.rows.map((r) => ({ label: r[0].text, left: r[1].text, right: r[2].text })) } });
|
|
1418
|
+
return true;
|
|
1419
|
+
}
|
|
1420
|
+
this.emit(tableElement(model, this.ctx.uid("table"), this.ctx));
|
|
1421
|
+
return true;
|
|
1422
|
+
}
|
|
1423
|
+
callout(n) {
|
|
1424
|
+
const cls = classes(n).join(" "), role = attr(n, "role") ?? "";
|
|
1425
|
+
const looks = n.tagName === "aside" || /callout|alert|admonition|notice|note|warning|tip|banner/i.test(cls) || /note|alert/.test(role);
|
|
1426
|
+
if (!looks || text(n).length > 900 || text(n).length < 3) return false;
|
|
1427
|
+
if (find(n, (e) => ["ul", "ol", "table", "pre", "img", "h1", "h2"].includes(e.tagName))) return false;
|
|
1428
|
+
const title = child(n, (e) => /^h[1-6]$/.test(e.tagName) || e.tagName === "strong" || e.tagName === "b" || hasClass(e, "title") || hasClass(e, "callout-title"));
|
|
1429
|
+
const rest = kids(n).filter((k) => k !== title).map((k) => text(k)).filter(Boolean).join("\n").trim();
|
|
1430
|
+
if (!rest && !title) return false;
|
|
1431
|
+
const tone2 = TONES.find(([re]) => re.test(cls))?.[1];
|
|
1432
|
+
this.emit({ id: this.ctx.uid("callout"), type: "reportic.callout.v1", props: { title: rest ? title ? text(title) : "" : "", text: rest || (title ? text(title) : ""), ...tone2 ? { tone: tone2 } : {} } });
|
|
1433
|
+
return true;
|
|
1434
|
+
}
|
|
1435
|
+
/** Siblings that each show one short number and one label are summary tiles. */
|
|
1436
|
+
metrics(n) {
|
|
1437
|
+
const tiles = elements(n);
|
|
1438
|
+
if (tiles.length < 2 || tiles.length > 12) return false;
|
|
1439
|
+
const read = tiles.map((t) => this.tile(t));
|
|
1440
|
+
if (!read.every(Boolean)) return false;
|
|
1441
|
+
const hinted = classes(n).concat(...tiles.map(classes)).some((c) => /metric|kpi|stat|tile|figure|summary|number/i.test(c));
|
|
1442
|
+
if (!hinted && read.length < 3) return false;
|
|
1443
|
+
this.emit({ id: this.ctx.uid("metrics"), type: "metrics", props: { items: read.map((t) => t) } });
|
|
1444
|
+
return true;
|
|
1445
|
+
}
|
|
1446
|
+
tile(t) {
|
|
1447
|
+
const blocky = ["div", "p", "ul", "ol", "table", "section", "h1", "h2", "h3", "h4", "h5", "h6", "dl"];
|
|
1448
|
+
const blocks2 = (e) => kids(e).every((k) => isText(k) || isEl(k) && !blocky.includes(k.tagName)) ? elements(e).length > 1 || elements(e).length === 1 && kids(e).some((k) => isText(k) && k.value.trim()) ? kids(e).map((k) => text(k)).filter(Boolean) : text(e) ? [text(e)] : [] : elements(e).flatMap(blocks2);
|
|
1449
|
+
const parts = blocks2(t);
|
|
1450
|
+
if (parts.length < 2 || parts.length > 3) return void 0;
|
|
1451
|
+
const values = parts.filter(isValue);
|
|
1452
|
+
if (values.length < 1) return void 0;
|
|
1453
|
+
const value = values[0], others = parts.filter((p) => p !== value);
|
|
1454
|
+
if (others.some((o) => o.length > 80) || others.every(isValue)) return void 0;
|
|
1455
|
+
const label = others.find((o) => !/^[+\-−▲▼↑↓]/.test(o) && !isValue(o)) ?? others[0];
|
|
1456
|
+
const comparison = others.find((o) => o !== label);
|
|
1457
|
+
return { label, value, ...comparison ? { comparison } : {} };
|
|
1458
|
+
}
|
|
1459
|
+
/** Labeled boxes joined by arrows are a flowchart. */
|
|
1460
|
+
flow(n) {
|
|
1461
|
+
const parts = elements(n);
|
|
1462
|
+
if (parts.length < 3 || parts.length > 15) return false;
|
|
1463
|
+
const arrow = (e) => /^(→|->|➜|⟶|▶|➔|↓|⇒|»)$/.test(text(e)) || hasClass(e, "arrow");
|
|
1464
|
+
const boxes = parts.filter((e) => !arrow(e)), arrows = parts.filter(arrow);
|
|
1465
|
+
if (arrows.length < 1 || arrows.length !== boxes.length - 1 || !parts.every((e, i) => i % 2 === 0 ? !arrow(e) : arrow(e)) || boxes.some((b) => text(b).length > 40 || !text(b))) return false;
|
|
1466
|
+
const nodes = boxes.map((b, i) => ({ id: `n${i + 1}`, label: text(b) })), edges = nodes.slice(1).map((b, i) => ({ from: nodes[i].id, to: b.id }));
|
|
1467
|
+
this.emit({ id: this.ctx.uid("diagram"), type: "diagram", props: { engine: "mermaid", alt: `Flow: ${nodes.map((x) => x.label).join(" to ")}`, adapter: "reportic.flowchart.v1", model: { nodes, edges } } });
|
|
1468
|
+
return true;
|
|
1469
|
+
}
|
|
1470
|
+
/** Three or more headings that start with a date, each with a title after it, are a timeline. */
|
|
1471
|
+
timeline(n, siblings, index) {
|
|
1472
|
+
const dated = (e) => isEl(e) && e.tagName === n.tagName && DATE.test(text(e)) && text(e).replace(DATE, "").replace(/^\s*[:\-–—·|]\s*/, "").length > 2;
|
|
1473
|
+
if (!dated(n) || index > 0 && dated(siblings.slice(0, index).reverse().find(isEl))) return false;
|
|
1474
|
+
const run = [];
|
|
1475
|
+
for (const s of siblings.slice(index)) {
|
|
1476
|
+
if (!isEl(s)) continue;
|
|
1477
|
+
if (s.tagName === n.tagName) {
|
|
1478
|
+
if (!dated(s)) break;
|
|
1479
|
+
run.push(s);
|
|
1480
|
+
} else if (!["p", "ul"].includes(s.tagName)) break;
|
|
1481
|
+
}
|
|
1482
|
+
if (run.length < 3) return false;
|
|
1483
|
+
const items = run.map((h4) => {
|
|
1484
|
+
const full = text(h4), date = DATE.exec(full)[1], title = full.slice(date.length).replace(/^\s*[:\-–—·|]\s*/, "");
|
|
1485
|
+
const after = siblings.slice(siblings.indexOf(h4) + 1).find(isEl);
|
|
1486
|
+
const body = after && after.tagName === "p" ? text(after) : "";
|
|
1487
|
+
return { date, title, ...body ? { text: body } : {} };
|
|
1488
|
+
});
|
|
1489
|
+
const consumed = /* @__PURE__ */ new Set();
|
|
1490
|
+
for (const h4 of run) {
|
|
1491
|
+
consumed.add(h4);
|
|
1492
|
+
const after = siblings.slice(siblings.indexOf(h4) + 1).find(isEl);
|
|
1493
|
+
if (after && after.tagName === "p") consumed.add(after);
|
|
1494
|
+
}
|
|
1495
|
+
this.emit({ id: this.ctx.uid("timeline"), type: "reportic.timeline.v1", props: { items } });
|
|
1496
|
+
for (let k = index; k < siblings.length; k++) if (consumed.has(siblings[k])) siblings[k] = { nodeName: "#comment", data: "" };
|
|
1497
|
+
return true;
|
|
1498
|
+
}
|
|
1499
|
+
};
|
|
1500
|
+
function importBestEffort(doc, ctx) {
|
|
1501
|
+
const body = find(doc, (e) => e.tagName === "body") ?? doc, effort = new Effort(ctx);
|
|
1502
|
+
effort.walk(kids(body));
|
|
1503
|
+
const md2 = ctx.markdown(), blocks2 = [];
|
|
1504
|
+
let pending = [];
|
|
1505
|
+
const flush = () => {
|
|
1506
|
+
if (!pending.length) return;
|
|
1507
|
+
const t = toMarkdown(pending, md2);
|
|
1508
|
+
pending = [];
|
|
1509
|
+
if (t) blocks2.push({ md: t });
|
|
1510
|
+
};
|
|
1511
|
+
const hasSources = !!effort.sources;
|
|
1512
|
+
for (const item of effort.items) {
|
|
1513
|
+
if ("node" in item) pending.push(item.node);
|
|
1514
|
+
else if ("md" in item) {
|
|
1515
|
+
flush();
|
|
1516
|
+
blocks2.push({ md: item.md });
|
|
1517
|
+
} else if ("cited" in item) {
|
|
1518
|
+
if (hasSources && effort.sources.ids.length) {
|
|
1519
|
+
flush();
|
|
1520
|
+
const raw = text(item.cited), ids = [];
|
|
1521
|
+
for (const m of raw.matchAll(/\[(\d{1,2})\]/g)) {
|
|
1522
|
+
const id = effort.sources.ids[Number(m[1]) - 1];
|
|
1523
|
+
if (id && !ids.includes(id)) ids.push(id);
|
|
1524
|
+
}
|
|
1525
|
+
const clean2 = raw.replace(/\s*\[\d{1,2}\]/g, "").replace(/\s+/g, " ").trim();
|
|
1526
|
+
if (ids.length && clean2) blocks2.push({ element: { id: ctx.uid("narrative"), type: "narrative", props: { text: clean2, evidenceIds: ids } } });
|
|
1527
|
+
else pending.push(item.cited);
|
|
1528
|
+
} else pending.push(item.cited);
|
|
1529
|
+
} else if ("element" in item) {
|
|
1530
|
+
flush();
|
|
1531
|
+
const e = item.element;
|
|
1532
|
+
if (e.meta) {
|
|
1533
|
+
const { open, ...rest } = e.meta;
|
|
1534
|
+
void open;
|
|
1535
|
+
e.meta = rest;
|
|
1536
|
+
}
|
|
1537
|
+
blocks2.push({ element: e });
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
flush();
|
|
1541
|
+
for (const [what, n] of effort.dropped) ctx.warn("DROPPED", `Dropped ${n} ${what}: they have no element in the library.`);
|
|
1542
|
+
const html = find(doc, (e) => e.tagName === "html"), title = find(doc, (e) => e.tagName === "h1") ?? find(doc, (e) => e.tagName === "title");
|
|
1543
|
+
return { id: `imported-${String(title ? text(title) : "page").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || "page"}`, locale: html && attr(html, "lang") || "en-US", blocks: blocks2, assets: ctx.assets };
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
// packages/reportic-render-html/src/import/theme.ts
|
|
1547
|
+
import { themeTokens as themeTokens3 } from "@x12i/reportic-core";
|
|
1548
|
+
var PRESETS = ["editorial", "forest", "midnight", "minimal"];
|
|
1549
|
+
var hex = /^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i;
|
|
1550
|
+
var RULE_PROPS = { color: "color", "background-color": "backgroundColor", "font-size": "fontSize", "font-family": "fontFamily", "font-weight": "fontWeight", "text-align": "textAlign", "margin-top": "marginTop", "margin-bottom": "marginBottom", padding: "padding", "border-color": "borderColor", "border-width": "borderWidth" };
|
|
1551
|
+
var unsafe = /@import|url\s*\(|expression\s*\(|<\/?style|behavior\s*:|[<>]|\\/i;
|
|
1552
|
+
var strip = (css) => css.replace(/\/\*[\s\S]*?\*\//g, "");
|
|
1553
|
+
function readBlock(css, from) {
|
|
1554
|
+
let depth = 1, i = from;
|
|
1555
|
+
while (i < css.length && depth) {
|
|
1556
|
+
if (css[i] === "{") depth++;
|
|
1557
|
+
else if (css[i] === "}") depth--;
|
|
1558
|
+
i++;
|
|
1559
|
+
}
|
|
1560
|
+
return i;
|
|
1561
|
+
}
|
|
1562
|
+
function parseCss(source) {
|
|
1563
|
+
const css = strip(source), rules = [], pages = [];
|
|
1564
|
+
let order = 0;
|
|
1565
|
+
const decls = (body) => Object.fromEntries(body.split(";").map((d) => {
|
|
1566
|
+
const i = d.indexOf(":");
|
|
1567
|
+
return i < 0 ? ["", ""] : [d.slice(0, i).trim().toLowerCase(), d.slice(i + 1).replace(/!important/i, "").trim()];
|
|
1568
|
+
}).filter(([k, v]) => k && v));
|
|
1569
|
+
const walk = (text2, media) => {
|
|
1570
|
+
let i = 0;
|
|
1571
|
+
while (i < text2.length) {
|
|
1572
|
+
const open = text2.indexOf("{", i), semi = text2.indexOf(";", i);
|
|
1573
|
+
if (open < 0) break;
|
|
1574
|
+
if (semi >= 0 && semi < open && text2.slice(i, semi).trim().startsWith("@")) {
|
|
1575
|
+
i = semi + 1;
|
|
1576
|
+
continue;
|
|
1577
|
+
}
|
|
1578
|
+
const prelude = text2.slice(i, open).trim(), end = readBlock(text2, open + 1), body = text2.slice(open + 1, end - 1);
|
|
1579
|
+
i = end;
|
|
1580
|
+
if (/^@(media|supports)/i.test(prelude)) walk(body, prelude);
|
|
1581
|
+
else if (/^@page/i.test(prelude)) pages.push(decls(body));
|
|
1582
|
+
else if (prelude.startsWith("@")) continue;
|
|
1583
|
+
else for (const selector of prelude.split(/,(?![^(]*\))/).map((s) => s.trim()).filter(Boolean)) rules.push({ selector, decls: decls(body), media, order: order++ });
|
|
1584
|
+
}
|
|
1585
|
+
};
|
|
1586
|
+
walk(css);
|
|
1587
|
+
return { rules, pages };
|
|
1588
|
+
}
|
|
1589
|
+
function pageOf(css) {
|
|
1590
|
+
const { pages } = parseCss(css);
|
|
1591
|
+
let page;
|
|
1592
|
+
for (const p of pages) {
|
|
1593
|
+
const size = p.size;
|
|
1594
|
+
if (!size) continue;
|
|
1595
|
+
const words = size.toLowerCase().split(/\s+/), next = { ...page };
|
|
1596
|
+
if (words.includes("landscape")) next.landscape = true;
|
|
1597
|
+
if (words.includes("portrait")) next.landscape = false;
|
|
1598
|
+
if (words.includes("a4")) next.size = "A4";
|
|
1599
|
+
if (words.includes("letter")) next.size = "Letter";
|
|
1600
|
+
const dims = words.map((w) => /^([\d.]+)(mm|cm|in|px|pt)$/.exec(w)).filter(Boolean);
|
|
1601
|
+
if (dims.length === 2) {
|
|
1602
|
+
const mm = (m) => Number(m[1]) * { mm: 1, cm: 10, in: 25.4, px: 25.4 / 96, pt: 25.4 / 72 }[m[2]];
|
|
1603
|
+
next.landscape = mm(dims[0]) > mm(dims[1]);
|
|
1604
|
+
const longSide = Math.max(mm(dims[0]), mm(dims[1]));
|
|
1605
|
+
next.size = Math.abs(longSide - 279.4) < 3 ? "Letter" : "A4";
|
|
1606
|
+
}
|
|
1607
|
+
page = next;
|
|
1608
|
+
}
|
|
1609
|
+
return page;
|
|
1610
|
+
}
|
|
1611
|
+
var NAMED = { white: "#ffffff", black: "#000000", red: "#ff0000", green: "#008000", blue: "#0000ff", gray: "#808080", grey: "#808080", navy: "#000080", teal: "#008080", orange: "#ffa500", purple: "#800080", silver: "#c0c0c0", maroon: "#800000", darkgreen: "#006400", darkblue: "#00008b", darkgray: "#a9a9a9", lightgray: "#d3d3d3", lightgrey: "#d3d3d3", whitesmoke: "#f5f5f5", ghostwhite: "#f8f8ff", crimson: "#dc143c", steelblue: "#4682b4", slategray: "#708090", dimgray: "#696969" };
|
|
1612
|
+
function toHex(value) {
|
|
1613
|
+
if (!value) return void 0;
|
|
1614
|
+
const v = value.trim().toLowerCase();
|
|
1615
|
+
if (hex.test(v)) return v.length === 4 ? "#" + [...v.slice(1)].map((c) => c + c).join("") : v;
|
|
1616
|
+
if (NAMED[v]) return NAMED[v];
|
|
1617
|
+
const m = /^rgba?\(\s*(\d+(?:\.\d+)?)[ ,]+(\d+(?:\.\d+)?)[ ,]+(\d+(?:\.\d+)?)(?:[ ,/]+([\d.]+%?))?\s*\)$/.exec(v);
|
|
1618
|
+
if (!m) return void 0;
|
|
1619
|
+
if (m[4] !== void 0 && Number.parseFloat(m[4]) / (m[4].endsWith("%") ? 100 : 1) < 0.5) return void 0;
|
|
1620
|
+
return "#" + [m[1], m[2], m[3]].map((x) => Math.max(0, Math.min(255, Math.round(Number(x)))).toString(16).padStart(2, "0")).join("");
|
|
1621
|
+
}
|
|
1622
|
+
var colorIn = (value) => {
|
|
1623
|
+
for (const part of (value ?? "").split(/\s+(?![^(]*\))/)) {
|
|
1624
|
+
const c = toHex(part);
|
|
1625
|
+
if (c) return c;
|
|
1626
|
+
}
|
|
1627
|
+
return void 0;
|
|
1628
|
+
};
|
|
1629
|
+
function px(value, base = 16) {
|
|
1630
|
+
const m = /^(-?[\d.]+)(px|pt|em|rem|%)?$/.exec((value ?? "").trim());
|
|
1631
|
+
if (!m) return void 0;
|
|
1632
|
+
const n = Number(m[1]);
|
|
1633
|
+
return Math.round({ px: n, pt: n * 4 / 3, em: n * base, rem: n * 16, "%": n / 100 * base }[m[2] ?? "px"] * 10) / 10;
|
|
1634
|
+
}
|
|
1635
|
+
var rgb = (h4) => [1, 3, 5].map((i) => parseInt(h4.slice(i, i + 2), 16));
|
|
1636
|
+
var distance = (a, b) => {
|
|
1637
|
+
const x = rgb(a), y = rgb(b);
|
|
1638
|
+
return Math.hypot(x[0] - y[0], x[1] - y[1], x[2] - y[2]);
|
|
1639
|
+
};
|
|
1640
|
+
var cleanFont = (f) => {
|
|
1641
|
+
const v = (f ?? "").replace(/[;{}<>@"]/g, "").replace(/\s+/g, " ").trim();
|
|
1642
|
+
return v && v.length < 200 ? v : void 0;
|
|
1643
|
+
};
|
|
1644
|
+
function match(found) {
|
|
1645
|
+
let best = "editorial", bestScore = Infinity;
|
|
1646
|
+
for (const name of PRESETS) {
|
|
1647
|
+
const base2 = themeTokens3({ name });
|
|
1648
|
+
let score = 0;
|
|
1649
|
+
for (const k of ["accent", "text", "background", "muted", "border"]) {
|
|
1650
|
+
const f = found[k];
|
|
1651
|
+
if (f && hex.test(f) && hex.test(base2[k])) score += distance(toHex(f), toHex(base2[k]));
|
|
1652
|
+
}
|
|
1653
|
+
for (const k of ["fontFamily", "headingFont"]) if (found[k] && found[k] !== base2[k]) score += 60;
|
|
1654
|
+
for (const k of ["bodySize", "headingSize", "contentWidth", "logoWidth"]) if (found[k] !== void 0 && found[k] !== base2[k]) score += 25;
|
|
1655
|
+
if (score < bestScore) {
|
|
1656
|
+
bestScore = score;
|
|
1657
|
+
best = name;
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
const base = themeTokens3({ name: best }), tokens = {};
|
|
1661
|
+
for (const [k, v] of Object.entries(found)) if (v !== void 0 && JSON.stringify(v) !== JSON.stringify(base[k])) tokens[k] = v;
|
|
1662
|
+
return { name: best, tokens, exact: !Object.keys(tokens).length };
|
|
1663
|
+
}
|
|
1664
|
+
var SELECTORS = [
|
|
1665
|
+
[/^\.reportic-report$/, () => "document"],
|
|
1666
|
+
[/^\.reportic-report :is\(h1,h2,h3,h4\)$/, () => "heading"],
|
|
1667
|
+
[/^\.reportic-report p$/, () => "paragraph"],
|
|
1668
|
+
[/^\.reportic-report \[data-reportic-type="([\w-]+)"\]$/, (m) => m[1] === "metrics" ? "metric" : m[1]],
|
|
1669
|
+
[/^\.reportic-report \[data-reportic-id="([\w.-]+)"\]$/, (m) => m[1]]
|
|
1670
|
+
];
|
|
1671
|
+
var kebabToCamel = Object.fromEntries(Object.entries(RULE_PROPS));
|
|
1672
|
+
function readReporticStyle(css, ctx) {
|
|
1673
|
+
const lines = css.replace(/^\s+/, "").split("\n"), generated = lines[0];
|
|
1674
|
+
if (!generated.startsWith(":root{color-scheme:light}")) return void 0;
|
|
1675
|
+
const grab = (re) => re.exec(generated);
|
|
1676
|
+
const found = {};
|
|
1677
|
+
const accent = grab(/--reportic-accent:(#[\da-fA-F]{3,8})/)?.[1], body = grab(/body\{margin:0;background:(#[\da-fA-F]{3,8});color:(#[\da-fA-F]{3,8})\}/), font = grab(/\.reportic-report\{--reportic-accent:[^;]+;font:([\d.]+)px\/1\.75 ([^;]+);max-width:(\d+)px/);
|
|
1678
|
+
if (accent) found.accent = accent;
|
|
1679
|
+
if (body) {
|
|
1680
|
+
found.background = body[1];
|
|
1681
|
+
found.text = body[2];
|
|
1682
|
+
}
|
|
1683
|
+
if (font) {
|
|
1684
|
+
found.bodySize = Number(font[1]);
|
|
1685
|
+
found.fontFamily = font[2];
|
|
1686
|
+
found.contentWidth = Number(font[3]);
|
|
1687
|
+
}
|
|
1688
|
+
const heading = grab(/\.reportic-report h3\{line-height:1\.2;font-family:([^;]+);font-weight:500/)?.[1];
|
|
1689
|
+
if (heading) found.headingFont = heading;
|
|
1690
|
+
const size = grab(/\.reportic-report h1\{font-size:([\d.]+)px;margin:20px 0 24px\}/)?.[1];
|
|
1691
|
+
if (size) found.headingSize = Number(size);
|
|
1692
|
+
const muted = grab(/\.reportic-report blockquote\{[^}]*?color:(#[\da-fA-F]{3,8});/)?.[1];
|
|
1693
|
+
if (muted) found.muted = muted;
|
|
1694
|
+
const border = grab(/\.reportic-report hr\{border:0;border-top:1px solid (#[\da-fA-F]{3,8})[;}]/)?.[1];
|
|
1695
|
+
if (border) found.border = border;
|
|
1696
|
+
const logo = grab(/\[data-reportic-type=logo\] img\{max-width:(\d+)px/)?.[1];
|
|
1697
|
+
if (logo) found.logoWidth = Number(logo);
|
|
1698
|
+
const layout = grab(/--reportic-layout:(page|card)[;}]/)?.[1];
|
|
1699
|
+
if (layout) found.layout = layout;
|
|
1700
|
+
const palette = grab(/--reportic-palette:((?:#[\da-fA-F]{3,8} ?)+)[;}]/)?.[1].trim().split(" ");
|
|
1701
|
+
if (palette) found.chartPalette = palette;
|
|
1702
|
+
const semantic = Object.fromEntries([...generated.matchAll(/--reportic-semantic-(\w+):(#[\da-fA-F]{3,8})(?=[;}])/g)].map((m) => [m[1], m[2]]));
|
|
1703
|
+
if (Object.keys(semantic).length) found.semantic = semantic;
|
|
1704
|
+
if (!accent || !body || !font) return void 0;
|
|
1705
|
+
const { name, tokens, exact } = match(found);
|
|
1706
|
+
if (!exact) ctx.note("THEME_TOKENS", `The page's colors and fonts are not exactly one of the presets. Imported as ${name} with ${Object.keys(tokens).length} token override${Object.keys(tokens).length === 1 ? "" : "s"}.`);
|
|
1707
|
+
const rules = {};
|
|
1708
|
+
let i = 1;
|
|
1709
|
+
for (; i < lines.length; i++) {
|
|
1710
|
+
const m = /^(.*)\{([^{}]*)\}$/.exec(lines[i]);
|
|
1711
|
+
if (!m) break;
|
|
1712
|
+
const matcher = SELECTORS.map(([re, name2]) => {
|
|
1713
|
+
const r = re.exec(m[1]);
|
|
1714
|
+
return r ? name2(r) : void 0;
|
|
1715
|
+
}).find(Boolean);
|
|
1716
|
+
if (!matcher) break;
|
|
1717
|
+
const rule = {};
|
|
1718
|
+
let ok = true;
|
|
1719
|
+
for (const d of m[2].split(";")) {
|
|
1720
|
+
const j = d.indexOf(":"), k = d.slice(0, j), v = d.slice(j + 1);
|
|
1721
|
+
const prop = kebabToCamel[k];
|
|
1722
|
+
if (!prop) {
|
|
1723
|
+
ok = false;
|
|
1724
|
+
break;
|
|
1725
|
+
}
|
|
1726
|
+
rule[prop] = /^-?[\d.]+px$/.test(v) ? Number(v.slice(0, -2)) : /^\d+$/.test(v) && prop === "fontWeight" ? Number(v) : v;
|
|
1727
|
+
}
|
|
1728
|
+
if (!ok) break;
|
|
1729
|
+
rules[matcher] = { ...rules[matcher], ...rule };
|
|
1730
|
+
}
|
|
1731
|
+
const custom = lines.slice(i).join("\n").trim();
|
|
1732
|
+
const theme = { name, ...Object.keys(tokens).length ? { tokens } : {}, ...Object.keys(rules).length ? { rules } : {} };
|
|
1733
|
+
return { theme, css: custom, page: pageOf(custom) };
|
|
1734
|
+
}
|
|
1735
|
+
function parseSelector(selector) {
|
|
1736
|
+
if (/[:+~]|::/.test(selector.replace(/\[[^\]]*\]/g, ""))) {
|
|
1737
|
+
if (/^(:root|html)$/.test(selector.trim())) return { parts: [{ compound: { tag: "html", classes: [], attrs: [] }, combinator: "" }], specificity: 1 };
|
|
1738
|
+
return void 0;
|
|
1739
|
+
}
|
|
1740
|
+
const tokens = selector.replace(/\s*>\s*/g, " > ").trim().split(/\s+/);
|
|
1741
|
+
const parts = [];
|
|
1742
|
+
let specificity = 0, combinator = "";
|
|
1743
|
+
for (const token of tokens) {
|
|
1744
|
+
if (token === ">") {
|
|
1745
|
+
combinator = ">";
|
|
1746
|
+
continue;
|
|
1747
|
+
}
|
|
1748
|
+
const compound = { classes: [], attrs: [] };
|
|
1749
|
+
for (const m of token.matchAll(/(^|[.#])([\w-]+)|\[([\w-]+)(?:=["']?([^\]"']*)["']?)?\]|(\*)/g)) {
|
|
1750
|
+
if (m[3]) {
|
|
1751
|
+
compound.attrs.push([m[3], m[4]]);
|
|
1752
|
+
specificity += 10;
|
|
1753
|
+
} else if (m[1] === ".") {
|
|
1754
|
+
compound.classes.push(m[2]);
|
|
1755
|
+
specificity += 10;
|
|
1756
|
+
} else if (m[1] === "#") {
|
|
1757
|
+
compound.id = m[2];
|
|
1758
|
+
specificity += 100;
|
|
1759
|
+
} else if (m[2]) {
|
|
1760
|
+
compound.tag = m[2].toLowerCase();
|
|
1761
|
+
specificity += 1;
|
|
1762
|
+
}
|
|
1763
|
+
}
|
|
1764
|
+
parts.push({ compound, combinator: parts.length ? combinator || " " : "" });
|
|
1765
|
+
combinator = "";
|
|
1766
|
+
}
|
|
1767
|
+
return parts.length ? { parts, specificity } : void 0;
|
|
1768
|
+
}
|
|
1769
|
+
var parentEl = (el2) => el2.parentNode && isEl(el2.parentNode) ? el2.parentNode : void 0;
|
|
1770
|
+
function matches(el2, parts, at = parts.length - 1) {
|
|
1771
|
+
const { compound } = parts[at];
|
|
1772
|
+
if (compound.tag && el2.tagName !== compound.tag) return false;
|
|
1773
|
+
if (compound.id && attr(el2, "id") !== compound.id) return false;
|
|
1774
|
+
if (compound.classes.some((c) => !classes(el2).includes(c))) return false;
|
|
1775
|
+
if (compound.attrs.some(([k, v]) => {
|
|
1776
|
+
const a = attr(el2, k);
|
|
1777
|
+
return a === void 0 || v !== void 0 && a !== v;
|
|
1778
|
+
})) return false;
|
|
1779
|
+
if (at === 0) return true;
|
|
1780
|
+
const link = parts[at].combinator;
|
|
1781
|
+
if (link === ">") {
|
|
1782
|
+
const p = parentEl(el2);
|
|
1783
|
+
return !!p && matches(p, parts, at - 1);
|
|
1784
|
+
}
|
|
1785
|
+
for (let p = parentEl(el2); p; p = parentEl(p)) if (matches(p, parts, at - 1)) return true;
|
|
1786
|
+
return false;
|
|
1787
|
+
}
|
|
1788
|
+
var INHERITED = /* @__PURE__ */ new Set(["color", "font-family", "font-size", "font-weight", "text-align", "line-height"]);
|
|
1789
|
+
var Cascade = class {
|
|
1790
|
+
rules = [];
|
|
1791
|
+
constructor(css) {
|
|
1792
|
+
for (const r of parseCss(css).rules) {
|
|
1793
|
+
if (r.media && !/screen|all/i.test(r.media)) continue;
|
|
1794
|
+
const s = parseSelector(r.selector);
|
|
1795
|
+
if (s) this.rules.push({ ...s, decls: r.decls, order: r.order });
|
|
1796
|
+
}
|
|
1797
|
+
this.rules.sort((a, b) => a.specificity - b.specificity || a.order - b.order);
|
|
1798
|
+
}
|
|
1799
|
+
get(el2, property) {
|
|
1800
|
+
let value;
|
|
1801
|
+
for (const r of this.rules) {
|
|
1802
|
+
const v = r.decls[property] ?? (property === "background-color" ? r.decls.background : void 0);
|
|
1803
|
+
if (v !== void 0 && matches(el2, r.parts)) value = v;
|
|
1804
|
+
}
|
|
1805
|
+
const inline2 = attr(el2, "style");
|
|
1806
|
+
if (inline2) {
|
|
1807
|
+
const m = new RegExp(`(?:^|;)\\s*${property.replace("-", "\\-")}\\s*:\\s*([^;]+)`, "i").exec(inline2) ?? (property === "background-color" ? /(?:^|;)\s*background\s*:\s*([^;]+)/i.exec(inline2) : null);
|
|
1808
|
+
if (m) value = m[1].trim();
|
|
1809
|
+
}
|
|
1810
|
+
if (value === void 0 && INHERITED.has(property)) {
|
|
1811
|
+
const p = parentEl(el2);
|
|
1812
|
+
if (p && p.tagName !== "html") return this.get(p, property);
|
|
1813
|
+
}
|
|
1814
|
+
return value;
|
|
1815
|
+
}
|
|
1816
|
+
};
|
|
1817
|
+
var all = (doc, test) => {
|
|
1818
|
+
const out = [];
|
|
1819
|
+
const visit = (n) => {
|
|
1820
|
+
for (const k of kids(n)) if (isEl(k)) {
|
|
1821
|
+
if (test(k)) out.push(k);
|
|
1822
|
+
visit(k);
|
|
1823
|
+
}
|
|
1824
|
+
};
|
|
1825
|
+
visit(doc);
|
|
1826
|
+
return out;
|
|
1827
|
+
};
|
|
1828
|
+
var same = (values) => values.length && values.every((v) => v !== void 0 && v === values[0]) ? values[0] : void 0;
|
|
1829
|
+
function readPageStyle(doc, css, ctx) {
|
|
1830
|
+
const cascade = new Cascade(css), body = all(doc, (e) => e.tagName === "body")[0], first = (name2) => all(doc, (e) => e.tagName === name2)[0];
|
|
1831
|
+
const found = {};
|
|
1832
|
+
if (body) {
|
|
1833
|
+
const bg = toHex(colorIn(cascade.get(body, "background-color")) ?? void 0), text2 = toHex(cascade.get(body, "color"));
|
|
1834
|
+
if (bg) found.background = bg;
|
|
1835
|
+
if (text2) found.text = text2;
|
|
1836
|
+
const family = cleanFont(cascade.get(body, "font-family"));
|
|
1837
|
+
if (family) found.fontFamily = family;
|
|
1838
|
+
const size = px(cascade.get(body, "font-size"));
|
|
1839
|
+
if (size && size >= 8 && size <= 40) found.bodySize = size;
|
|
1840
|
+
}
|
|
1841
|
+
const link = first("a"), h1 = first("h1") ?? first("h2"), th = first("th");
|
|
1842
|
+
const accent = [link && toHex(cascade.get(link, "color")), h1 && toHex(cascade.get(h1, "color")), th && colorIn(cascade.get(th, "background-color"))].find((c) => c && c !== found.text && c !== found.background);
|
|
1843
|
+
if (accent) found.accent = accent;
|
|
1844
|
+
const note = all(doc, (e) => ["figcaption", "small", "caption", "blockquote"].includes(e.tagName))[0] ?? all(doc, (e) => classes(e).some((c) => /muted|subtle|secondary/.test(c)))[0];
|
|
1845
|
+
const muted = note && toHex(cascade.get(note, "color"));
|
|
1846
|
+
if (muted && muted !== found.text) found.muted = muted;
|
|
1847
|
+
const cell = first("td") ?? th, border = cell && ["border-bottom", "border", "border-top", "border-color"].map((p) => colorIn(cascade.get(cell, p))).find(Boolean);
|
|
1848
|
+
if (border) found.border = border;
|
|
1849
|
+
if (h1) {
|
|
1850
|
+
const hf = cleanFont(cascade.get(h1, "font-family"));
|
|
1851
|
+
if (hf && hf !== found.fontFamily) found.headingFont = hf;
|
|
1852
|
+
const hs = px(cascade.get(h1, "font-size"), found.bodySize ?? 16);
|
|
1853
|
+
if (hs && hs >= 14 && hs <= 96 && hs !== found.bodySize) found.headingSize = hs;
|
|
1854
|
+
}
|
|
1855
|
+
const container = all(doc, (e) => ["main", "article"].includes(e.tagName) || classes(e).some((c) => /^(container|wrapper|page|content|report)$/.test(c)))[0] ?? body;
|
|
1856
|
+
const width = container && px(cascade.get(container, "max-width"));
|
|
1857
|
+
if (width && width >= 400 && width <= 2e3) found.contentWidth = width;
|
|
1858
|
+
const { name, tokens } = match(found);
|
|
1859
|
+
const dropped = ["accent", "text", "background"].filter((k) => !found[k]);
|
|
1860
|
+
ctx.note("THEME_REDUCED", `Reduced the page's design to the ${name} preset${Object.keys(tokens).length ? ` with overrides for ${Object.keys(tokens).join(", ")}` : ""}${dropped.length ? `; ${dropped.join(", ")} not found, so the preset's value is used` : ""}.`);
|
|
1861
|
+
const base = themeTokens3({ name, tokens }), rules = {};
|
|
1862
|
+
const rule = (key2, props) => {
|
|
1863
|
+
const clean2 = Object.fromEntries(Object.entries(props).filter(([, v]) => v !== void 0));
|
|
1864
|
+
if (Object.keys(clean2).length) rules[key2] = clean2;
|
|
1865
|
+
};
|
|
1866
|
+
const headings = all(doc, (e) => /^h[1-4]$/.test(e.tagName)), paragraphs = all(doc, (e) => e.tagName === "p"), tables = all(doc, (e) => e.tagName === "table");
|
|
1867
|
+
const diff = (v, expected) => v && v !== expected ? v : void 0;
|
|
1868
|
+
rule("heading", { color: diff(same(headings.map((h4) => toHex(cascade.get(h4, "color")))), base.text), textAlign: /* @__PURE__ */ ((a) => a && a !== "left" && a !== "start" ? a : void 0)(same(headings.map((h4) => cascade.get(h4, "text-align")))) });
|
|
1869
|
+
rule("paragraph", { color: diff(same(paragraphs.map((p) => toHex(cascade.get(p, "color")))), base.text), textAlign: ((a) => a && ["center", "right", "justify"].includes(a) ? a : void 0)(same(paragraphs.map((p) => cascade.get(p, "text-align")))), fontSize: ((s) => s && Math.abs(s - base.bodySize) > 0.5 ? s : void 0)(same(paragraphs.map((p) => px(cascade.get(p, "font-size"), base.bodySize)))) });
|
|
1870
|
+
rule("table", { backgroundColor: ((c) => c && c !== base.background ? c : void 0)(same(tables.map((t) => colorIn(cascade.get(t, "background-color"))))) });
|
|
1871
|
+
const rulesCount = Object.keys(rules).length;
|
|
1872
|
+
if (rulesCount) ctx.note("THEME_RULES", `Kept ${rulesCount} block style${rulesCount === 1 ? "" : "s"} that differ from the document: ${Object.keys(rules).join(", ")}.`);
|
|
1873
|
+
const SAFE = /* @__PURE__ */ new Set(["color", "background-color", "border", "border-top", "border-bottom", "border-left", "border-right", "border-radius", "padding", "margin", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "text-transform", "text-align", "text-decoration", "width", "max-width", "vertical-align"]);
|
|
1874
|
+
const TAGS = /^(h[1-6]|p|a|ul|ol|li|table|thead|tbody|tr|th|td|blockquote|code|pre|hr|img|figure|figcaption|strong|em)$/;
|
|
1875
|
+
const left = [];
|
|
1876
|
+
for (const r of parseCss(css).rules) {
|
|
1877
|
+
if (r.media && !/print|screen|all/i.test(r.media)) continue;
|
|
1878
|
+
const parts = r.selector.split(/\s+/);
|
|
1879
|
+
if (parts.length > 3 || !parts.every((p) => p === ">" || TAGS.test(p))) continue;
|
|
1880
|
+
const decls = Object.entries(r.decls).filter(([k, v]) => SAFE.has(k) && !unsafe.test(v) && !/^var\(/.test(v)).map(([k, v]) => `${k}:${v}`);
|
|
1881
|
+
if (!decls.length) continue;
|
|
1882
|
+
const text2 = `.reportic-report ${r.selector}{${decls.join(";")}}`;
|
|
1883
|
+
left.push(r.media ? `${r.media}{${text2}}` : text2);
|
|
1884
|
+
}
|
|
1885
|
+
const leftover = left.join("\n").slice(0, 16e3);
|
|
1886
|
+
if (leftover) ctx.note("CSS_LEFTOVERS", `${left.length} plain element rule${left.length === 1 ? "" : "s"} from the page were kept as report css. Word and PowerPoint do not use them.`);
|
|
1887
|
+
return { theme: { name, ...Object.keys(tokens).length ? { tokens } : {}, ...rulesCount ? { rules } : {} }, css: leftover, page: pageOf(css) };
|
|
1888
|
+
}
|
|
1889
|
+
|
|
1890
|
+
// packages/reportic-render-html/src/import/rebind.ts
|
|
1891
|
+
import { figureKinds, figureSpec, formatValue as formatValue2, parseFigure } from "@x12i/reportic-core";
|
|
1892
|
+
var isRec = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
1893
|
+
var norm = (s) => s.replace(/\s+/g, " ").trim();
|
|
1894
|
+
var GROUPED = new Intl.NumberFormat("en-US", { maximumFractionDigits: 20 });
|
|
1895
|
+
var SEGMENT = /^[A-Za-z0-9_-]+$/;
|
|
1896
|
+
var UNSAFE = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
1897
|
+
var NUMBERISH = /^[+\-\u2212]?[\p{Sc}]?[\d.,]+\s?%?$/u;
|
|
1898
|
+
var WORD = /[\p{L}\p{N}_]/u;
|
|
1899
|
+
var NUMBER_EDGE = /[\p{L}\p{N}_.,\-:/]/u;
|
|
1900
|
+
var KINDS = new Set(figureKinds);
|
|
1901
|
+
var goodKey = (k) => SEGMENT.test(k) && !UNSAFE.has(k);
|
|
1902
|
+
var shows = (v) => {
|
|
1903
|
+
if (typeof v === "string") {
|
|
1904
|
+
const s = norm(v);
|
|
1905
|
+
return s ? [s] : [];
|
|
1906
|
+
}
|
|
1907
|
+
if (typeof v === "number" && Number.isFinite(v)) return [.../* @__PURE__ */ new Set([String(v), GROUPED.format(v)])];
|
|
1908
|
+
return [];
|
|
1909
|
+
};
|
|
1910
|
+
var add = (map, key2, path) => {
|
|
1911
|
+
const set = map.get(key2);
|
|
1912
|
+
if (set) set.add(path);
|
|
1913
|
+
else map.set(key2, /* @__PURE__ */ new Set([path]));
|
|
1914
|
+
};
|
|
1915
|
+
var valueAt = (rec, field) => field.split(".").reduce((v, k) => isRec(v) ? v[k] : void 0, rec);
|
|
1916
|
+
var truthy = (v) => !(v === void 0 || v === null || v === false || v === 0 || v === "") && (Array.isArray(v) ? v.length > 0 : isRec(v) ? Object.keys(v).length > 0 : true);
|
|
1917
|
+
var canonical = (v) => JSON.stringify(v, (_k, x) => isRec(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => a < b ? -1 : 1)) : x);
|
|
1918
|
+
var Layer = class {
|
|
1919
|
+
scalars = /* @__PURE__ */ new Map();
|
|
1920
|
+
universe = /* @__PURE__ */ new Map();
|
|
1921
|
+
arrays = [];
|
|
1922
|
+
objects = [];
|
|
1923
|
+
joined = /* @__PURE__ */ new Map();
|
|
1924
|
+
nodes = 0;
|
|
1925
|
+
constructor(root, prefix) {
|
|
1926
|
+
this.walk(root, prefix, true, 0);
|
|
1927
|
+
}
|
|
1928
|
+
walk(v, path, bindable, depth) {
|
|
1929
|
+
if (++this.nodes > 6e4 || depth > 10) return;
|
|
1930
|
+
if (typeof v === "string" || typeof v === "number") {
|
|
1931
|
+
for (const s of shows(v)) {
|
|
1932
|
+
this.universe.set(s, (this.universe.get(s) ?? 0) + 1);
|
|
1933
|
+
if (bindable) add(this.scalars, s, path);
|
|
1934
|
+
}
|
|
1935
|
+
return;
|
|
1936
|
+
}
|
|
1937
|
+
if (Array.isArray(v)) {
|
|
1938
|
+
if (bindable) {
|
|
1939
|
+
this.arrays.push({ path, items: v });
|
|
1940
|
+
if (v.length >= 2 && v.every((x) => typeof x === "string" && norm(x))) for (const sep of [" \xB7 ", ", ", "; "]) add(this.joined, `${sep}\0${v.map((x) => norm(x)).join(sep)}`, path);
|
|
1941
|
+
}
|
|
1942
|
+
for (const x of v) this.walk(x, path, false, depth + 1);
|
|
1943
|
+
return;
|
|
1944
|
+
}
|
|
1945
|
+
if (isRec(v)) {
|
|
1946
|
+
if (bindable) this.objects.push({ path, value: v });
|
|
1947
|
+
for (const [k, x] of Object.entries(v)) this.walk(x, `${path}.${k}`, bindable && goodKey(k), depth + 1);
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
};
|
|
1951
|
+
var View = class _View {
|
|
1952
|
+
constructor(layers) {
|
|
1953
|
+
this.layers = layers;
|
|
1954
|
+
}
|
|
1955
|
+
layers;
|
|
1956
|
+
withRow(row) {
|
|
1957
|
+
return new _View([...this.layers, new Layer(row, "row")]);
|
|
1958
|
+
}
|
|
1959
|
+
get arrays() {
|
|
1960
|
+
return this.layers.flatMap((l) => l.arrays);
|
|
1961
|
+
}
|
|
1962
|
+
get objects() {
|
|
1963
|
+
return this.layers.flatMap((l) => l.objects);
|
|
1964
|
+
}
|
|
1965
|
+
paths(text2) {
|
|
1966
|
+
const out = /* @__PURE__ */ new Set();
|
|
1967
|
+
for (const l of this.layers) for (const p of l.scalars.get(text2) ?? []) out.add(p);
|
|
1968
|
+
return out;
|
|
1969
|
+
}
|
|
1970
|
+
seen(text2) {
|
|
1971
|
+
return this.layers.reduce((n, l) => n + (l.universe.get(text2) ?? 0), 0);
|
|
1972
|
+
}
|
|
1973
|
+
shortOrNumber = (s) => s.length < 6 || NUMBERISH.test(s);
|
|
1974
|
+
/** A slot whose whole text is one field. A short or numeric text (Pending, 0, 1) is bound only when no other value in the sample shows the same. */
|
|
1975
|
+
lookup(text2) {
|
|
1976
|
+
const s = norm(text2);
|
|
1977
|
+
if (!s) return void 0;
|
|
1978
|
+
const paths = this.paths(s);
|
|
1979
|
+
if (!paths.size) return void 0;
|
|
1980
|
+
if (paths.size > 1) return { collision: [...paths].slice(0, 6) };
|
|
1981
|
+
if (this.shortOrNumber(s) && this.seen(s) > 1) return { collision: [[...paths][0]] };
|
|
1982
|
+
return { path: [...paths][0] };
|
|
1983
|
+
}
|
|
1984
|
+
/** A text made of several fields: each field found once, the rest written as it was. Anything unclear leaves the text alone. */
|
|
1985
|
+
segment(text2) {
|
|
1986
|
+
if (text2.length < 3) return void 0;
|
|
1987
|
+
const cuts = [];
|
|
1988
|
+
let ambiguous = false;
|
|
1989
|
+
const find2 = (display) => {
|
|
1990
|
+
const at2 = [];
|
|
1991
|
+
for (let i = text2.indexOf(display); i >= 0; i = text2.indexOf(display, i + 1)) {
|
|
1992
|
+
const before = text2[i - 1], after = text2[i + display.length];
|
|
1993
|
+
const edge = NUMBERISH.test(display) ? NUMBER_EDGE : WORD;
|
|
1994
|
+
if (WORD.test(display[0]) && before && edge.test(before)) continue;
|
|
1995
|
+
if (WORD.test(display[display.length - 1]) && after && edge.test(after)) continue;
|
|
1996
|
+
at2.push(i);
|
|
1997
|
+
}
|
|
1998
|
+
return at2;
|
|
1999
|
+
};
|
|
2000
|
+
const seenDisplays = /* @__PURE__ */ new Set();
|
|
2001
|
+
for (const layer of this.layers) for (const display of layer.scalars.keys()) {
|
|
2002
|
+
if (seenDisplays.has(display) || !text2.includes(display)) continue;
|
|
2003
|
+
seenDisplays.add(display);
|
|
2004
|
+
const paths = this.paths(display), at2 = find2(display);
|
|
2005
|
+
if (!at2.length) continue;
|
|
2006
|
+
if (paths.size > 1) {
|
|
2007
|
+
if (display.length >= 6) ambiguous = true;
|
|
2008
|
+
continue;
|
|
2009
|
+
}
|
|
2010
|
+
if (this.shortOrNumber(display) && this.seen(display) > 1) continue;
|
|
2011
|
+
if (at2.length > 1) {
|
|
2012
|
+
ambiguous = true;
|
|
2013
|
+
continue;
|
|
2014
|
+
}
|
|
2015
|
+
cuts.push({ start: at2[0], end: at2[0] + display.length, part: { $bind: [...paths][0] } });
|
|
2016
|
+
}
|
|
2017
|
+
for (const layer of this.layers) for (const [key2, paths] of layer.joined) {
|
|
2018
|
+
const [sep, display] = key2.split("\0");
|
|
2019
|
+
if (!text2.includes(display)) continue;
|
|
2020
|
+
const at2 = find2(display);
|
|
2021
|
+
if (!at2.length) continue;
|
|
2022
|
+
if (paths.size > 1 || at2.length > 1) {
|
|
2023
|
+
ambiguous = true;
|
|
2024
|
+
continue;
|
|
2025
|
+
}
|
|
2026
|
+
cuts.push({ start: at2[0], end: at2[0] + display.length, part: { value: { $bind: [...paths][0] }, join: sep } });
|
|
2027
|
+
}
|
|
2028
|
+
if (ambiguous) return "ambiguous";
|
|
2029
|
+
const chosen = [];
|
|
2030
|
+
for (const c of [...cuts].sort((a, b) => b.end - b.start - (a.end - a.start) || a.start - b.start)) if (!chosen.some((o) => c.start < o.end && o.start < c.end)) chosen.push(c);
|
|
2031
|
+
chosen.sort((a, b) => a.start - b.start);
|
|
2032
|
+
const covered = chosen.reduce((n, c) => n + c.end - c.start, 0);
|
|
2033
|
+
if (!chosen.length || covered < text2.trim().length / 2 && !chosen.some((c) => c.end - c.start >= 6)) return void 0;
|
|
2034
|
+
const parts = [];
|
|
2035
|
+
let at = 0;
|
|
2036
|
+
for (const c of chosen) {
|
|
2037
|
+
if (c.start > at) parts.push(text2.slice(at, c.start));
|
|
2038
|
+
parts.push(c.part);
|
|
2039
|
+
at = c.end;
|
|
2040
|
+
}
|
|
2041
|
+
if (at < text2.length) parts.push(text2.slice(at));
|
|
2042
|
+
return parts.length <= 12 ? parts : void 0;
|
|
2043
|
+
}
|
|
2044
|
+
};
|
|
2045
|
+
var slotOf = (st, el2, slot, text2, reason, candidates) => st.sink.push({ elementId: el2.id, slot, text: text2.length > 140 ? `${text2.slice(0, 137)}...` : text2, reason, ...candidates?.length ? { candidates } : {} });
|
|
2046
|
+
function bindText(el2, key2, view, st, holder = el2.props, slot = `props.${key2}`) {
|
|
2047
|
+
const v = holder[key2];
|
|
2048
|
+
if (typeof v !== "string" || !norm(v)) return;
|
|
2049
|
+
const hit = view.lookup(v);
|
|
2050
|
+
if (!hit) slotOf(st, el2, slot, v, "no-match");
|
|
2051
|
+
else if ("collision" in hit) slotOf(st, el2, slot, v, "collision", hit.collision);
|
|
2052
|
+
else {
|
|
2053
|
+
holder[key2] = { $bind: hit.path };
|
|
2054
|
+
st.bound.n++;
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
function want(cell, column) {
|
|
2058
|
+
if (typeof cell === "string") return { kind: "text", text: norm(cell) };
|
|
2059
|
+
if (typeof cell === "number" || typeof cell === "boolean") return { kind: "text", text: String(cell) };
|
|
2060
|
+
if (cell === null) return { kind: "text", text: "" };
|
|
2061
|
+
if (Array.isArray(cell) || !isRec(cell)) return void 0;
|
|
2062
|
+
if (typeof cell.tone === "string" && typeof cell.label === "string" && Object.keys(cell).length === 2) return { kind: "rating", tone: cell.tone, label: norm(cell.label) };
|
|
2063
|
+
if ("value" in cell) {
|
|
2064
|
+
if (["kind", "format"].some((k) => k in cell && cell[k] !== column[k])) return void 0;
|
|
2065
|
+
const inner = cell.value;
|
|
2066
|
+
if (Array.isArray(inner)) return inner.every((x) => typeof x === "string") ? { kind: "list", items: inner.map((x) => norm(x)) } : void 0;
|
|
2067
|
+
return want(inner, column);
|
|
2068
|
+
}
|
|
2069
|
+
return void 0;
|
|
2070
|
+
}
|
|
2071
|
+
function has(w, value, column, st) {
|
|
2072
|
+
if (w.kind === "list") return Array.isArray(value) && value.length === w.items.length && value.every((x, i) => typeof x === "string" && norm(x) === w.items[i]);
|
|
2073
|
+
if (w.kind === "rating") return isRec(value) && value.tone === w.tone && typeof value.label === "string" && norm(value.label) === w.label;
|
|
2074
|
+
if (value === void 0 || value === null) return w.text === "";
|
|
2075
|
+
if (typeof value === "boolean") return w.text === String(value);
|
|
2076
|
+
if (shows(value).includes(w.text)) return true;
|
|
2077
|
+
if (w.text === "" && value === "") return true;
|
|
2078
|
+
if (column.format && typeof value === "number") {
|
|
2079
|
+
try {
|
|
2080
|
+
return norm(formatValue2(value, column.format, st.locale, st.tz)) === w.text;
|
|
2081
|
+
} catch {
|
|
2082
|
+
return false;
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
return false;
|
|
2086
|
+
}
|
|
2087
|
+
function fieldsOf(items) {
|
|
2088
|
+
const out = /* @__PURE__ */ new Set();
|
|
2089
|
+
for (const r of items.slice(0, 50)) for (const [k, v] of Object.entries(r)) {
|
|
2090
|
+
if (!goodKey(k)) continue;
|
|
2091
|
+
out.add(k);
|
|
2092
|
+
if (isRec(v)) {
|
|
2093
|
+
for (const j of Object.keys(v)) if (goodKey(j)) out.add(`${k}.${j}`);
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
return [...out];
|
|
2097
|
+
}
|
|
2098
|
+
var alias = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
2099
|
+
function explain(cells, columns, items, st) {
|
|
2100
|
+
if (!columns.length || items.length !== cells.length) return void 0;
|
|
2101
|
+
const fields = fieldsOf(items), out = [];
|
|
2102
|
+
for (let c = 0; c < columns.length; c++) {
|
|
2103
|
+
const wants = cells.map((r) => want(r[c], columns[c]));
|
|
2104
|
+
if (wants.some((w) => !w)) return void 0;
|
|
2105
|
+
const found = fields.filter((f) => wants.every((w, i) => has(w, valueAt(items[i], f), columns[c], st)));
|
|
2106
|
+
if (found.length) {
|
|
2107
|
+
const named = found.find((f) => alias(f) === alias(String(columns[c].label ?? "")));
|
|
2108
|
+
const field = named ?? found[0];
|
|
2109
|
+
out.push({ field, others: found.filter((f) => f !== field) });
|
|
2110
|
+
} else if (items.length > 1 && wants.every((w) => canonical(w) === canonical(wants[0]))) out.push({ constant: cells[0][c] });
|
|
2111
|
+
else return void 0;
|
|
2112
|
+
}
|
|
2113
|
+
return out.some((x) => x && "field" in x) ? out : void 0;
|
|
2114
|
+
}
|
|
2115
|
+
var clone = (v) => structuredClone(v);
|
|
2116
|
+
function uniqueList(view, test) {
|
|
2117
|
+
const hits = view.arrays.map((a) => ({ ...a, result: test(a) })).filter((a) => a.result !== void 0);
|
|
2118
|
+
if (hits.length === 1) return { hit: hits[0] };
|
|
2119
|
+
if (hits.length > 1) return { collision: hits.map((h4) => h4.path).slice(0, 6) };
|
|
2120
|
+
return void 0;
|
|
2121
|
+
}
|
|
2122
|
+
var withFormats = (columns, el2) => columns.map((c, i) => ({ ...c, ...c.format === void 0 && el2.meta?.formats?.[i] ? { format: el2.meta.formats[i] } : {} }));
|
|
2123
|
+
function boundColumns(columns, explained) {
|
|
2124
|
+
return columns.map((c, i) => {
|
|
2125
|
+
const e = explained[i], { value: _drop, ...rest } = c;
|
|
2126
|
+
if ("field" in e) return { ...rest, value: { $bind: `row.${e.field}`, default: "" } };
|
|
2127
|
+
const { format: _format, ...plain } = rest;
|
|
2128
|
+
return { ...plain, value: clone(e.constant) };
|
|
2129
|
+
});
|
|
2130
|
+
}
|
|
2131
|
+
function bindGrid(el2, view, st) {
|
|
2132
|
+
const p = el2.props, rows = p.rows;
|
|
2133
|
+
if (!Array.isArray(rows) || !rows.length || !Array.isArray(p.columns)) return;
|
|
2134
|
+
const columns = withFormats(p.columns, el2);
|
|
2135
|
+
const found = uniqueList(view, (a) => a.items.every(isRec) ? explain(rows, columns, a.items, st) : void 0);
|
|
2136
|
+
if (found && "hit" in found) {
|
|
2137
|
+
const { path, result } = found.hit;
|
|
2138
|
+
el2.type = "table";
|
|
2139
|
+
delete el2.meta;
|
|
2140
|
+
el2.props = { rows: { $bind: path }, columns: boundColumns(columns, result), ...p.headers === false ? { headers: false } : {}, ...p.rowHeader ? { rowHeader: true } : {} };
|
|
2141
|
+
for (const e of result) if (e && "field" in e && e.others.length) st.ctx.note("BIND_AMBIGUOUS_COLUMN", `A column could be ${e.field} or ${e.others.join(", ")}; ${e.field} was used.`, { elementId: el2.id, candidates: [e.field, ...e.others].slice(0, 6) });
|
|
2142
|
+
st.bound.n++;
|
|
2143
|
+
return;
|
|
2144
|
+
}
|
|
2145
|
+
const detailed = p.rowHeader === true;
|
|
2146
|
+
if (found && "collision" in found) slotOf(st, el2, "props.rows", String(rows[0]?.[0] ?? ""), "collision", found.collision);
|
|
2147
|
+
else if (!detailed) slotOf(st, el2, "props.rows", rows.slice(0, 2).map((r) => r.map((x) => typeof x === "string" ? x : "").join(" | ")).join(" / "), "no-match");
|
|
2148
|
+
rows.forEach((row, r) => {
|
|
2149
|
+
row.forEach((cell, c) => {
|
|
2150
|
+
if (detailed && c === 0) return;
|
|
2151
|
+
const slot = `props.rows[${r}][${c}]`;
|
|
2152
|
+
const piece = (s) => {
|
|
2153
|
+
const whole = view.lookup(s);
|
|
2154
|
+
if (whole && "path" in whole) {
|
|
2155
|
+
st.bound.n++;
|
|
2156
|
+
return { $bind: whole.path };
|
|
2157
|
+
}
|
|
2158
|
+
const parts = view.segment(s);
|
|
2159
|
+
if (parts === "ambiguous") {
|
|
2160
|
+
if (s.length >= 8) slotOf(st, el2, slot, s, "composed-ambiguous");
|
|
2161
|
+
return s;
|
|
2162
|
+
}
|
|
2163
|
+
if (parts) {
|
|
2164
|
+
st.bound.n++;
|
|
2165
|
+
return parts;
|
|
2166
|
+
}
|
|
2167
|
+
if (detailed && s.length >= 3) slotOf(st, el2, slot, s, whole && "collision" in whole ? "collision" : "no-match", whole && "collision" in whole ? whole.collision : void 0);
|
|
2168
|
+
return s;
|
|
2169
|
+
};
|
|
2170
|
+
const flat = (v) => Array.isArray(v) ? v : [v];
|
|
2171
|
+
if (typeof cell === "string") row[c] = piece(cell);
|
|
2172
|
+
else if (Array.isArray(cell) && cell.some((x) => typeof x === "string")) row[c] = cell.flatMap((x) => typeof x === "string" && norm(x) ? flat(piece(x)) : [x]);
|
|
2173
|
+
});
|
|
2174
|
+
});
|
|
2175
|
+
}
|
|
2176
|
+
function unformat(text2, format, st) {
|
|
2177
|
+
const n = Number(text2.replace(/[^\d.\-]/g, "")) / (format.startsWith("percent") ? 100 : 1);
|
|
2178
|
+
if (!Number.isFinite(n) || !/\d/.test(text2)) return void 0;
|
|
2179
|
+
try {
|
|
2180
|
+
return norm(formatValue2(n, format, st.locale, st.tz)) === norm(text2) ? n : void 0;
|
|
2181
|
+
} catch {
|
|
2182
|
+
return void 0;
|
|
2183
|
+
}
|
|
2184
|
+
}
|
|
2185
|
+
function bindLiteralTable(el2, view, st) {
|
|
2186
|
+
const p = el2.props, rows = p.rows, literal = p.columns;
|
|
2187
|
+
if (!Array.isArray(rows) || !rows.length || !Array.isArray(literal) || rows.some((r) => !isRec(r))) return;
|
|
2188
|
+
const keys = literal.map((c) => isRec(c.value) && typeof c.value.$bind === "string" && c.value.$bind.startsWith("row.") ? c.value.$bind.slice(4) : void 0);
|
|
2189
|
+
if (keys.some((k) => !k)) return;
|
|
2190
|
+
const columns = withFormats(literal.map(({ value: _v, ...c }) => c), el2), cells = rows.map((r) => keys.map((k) => r[k]));
|
|
2191
|
+
const found = uniqueList(view, (a) => a.items.every(isRec) ? explain(cells, columns, a.items, st) : void 0);
|
|
2192
|
+
const first = String(cells[0]?.[0] ?? "");
|
|
2193
|
+
if (!found) {
|
|
2194
|
+
slotOf(st, el2, "props.rows", first, "no-match");
|
|
2195
|
+
return;
|
|
2196
|
+
}
|
|
2197
|
+
if ("collision" in found) {
|
|
2198
|
+
slotOf(st, el2, "props.rows", first, "collision", found.collision);
|
|
2199
|
+
return;
|
|
2200
|
+
}
|
|
2201
|
+
const { path, result } = found.hit;
|
|
2202
|
+
let total;
|
|
2203
|
+
if (isRec(p.total)) {
|
|
2204
|
+
total = {};
|
|
2205
|
+
for (const [i, e] of result.entries()) {
|
|
2206
|
+
if (!e || !("field" in e)) continue;
|
|
2207
|
+
const text2 = p.total[keys[i]], format = columns[i].format;
|
|
2208
|
+
if (format && typeof text2 === "string") {
|
|
2209
|
+
const n = unformat(text2, format, st);
|
|
2210
|
+
if (n === void 0) {
|
|
2211
|
+
slotOf(st, el2, "props.total", text2, "no-match");
|
|
2212
|
+
return;
|
|
2213
|
+
}
|
|
2214
|
+
total[e.field] = n;
|
|
2215
|
+
} else total[e.field] = text2;
|
|
2216
|
+
}
|
|
2217
|
+
}
|
|
2218
|
+
p.rows = { $bind: path };
|
|
2219
|
+
p.columns = boundColumns(columns, result);
|
|
2220
|
+
if (total) p.total = total;
|
|
2221
|
+
delete el2.meta;
|
|
2222
|
+
st.bound.n++;
|
|
2223
|
+
}
|
|
2224
|
+
function bindList(el2, view, st) {
|
|
2225
|
+
const p = el2.props, rows = p.rows;
|
|
2226
|
+
if (!Array.isArray(rows) || !rows.length) return;
|
|
2227
|
+
const keys = ["lead", "text"].filter((k) => p[k] !== void 0);
|
|
2228
|
+
if (rows.every((r) => typeof r === "string")) {
|
|
2229
|
+
const found2 = uniqueList(view, (a) => a.items.length === rows.length && a.items.every((x) => typeof x === "string") && a.items.every((x, i) => norm(x) === norm(rows[i])) ? true : void 0);
|
|
2230
|
+
if (found2 && "hit" in found2) {
|
|
2231
|
+
p.rows = { $bind: found2.hit.path };
|
|
2232
|
+
st.bound.n++;
|
|
2233
|
+
} else slotOf(st, el2, "props.rows", String(rows[0]), found2 ? "collision" : "no-match", found2 && "collision" in found2 ? found2.collision : void 0);
|
|
2234
|
+
return;
|
|
2235
|
+
}
|
|
2236
|
+
if (!rows.every(isRec)) return;
|
|
2237
|
+
const cells = rows.map((r) => keys.map((k) => typeof r[k] === "string" ? r[k] : "")), columns = keys.map((k) => ({ label: k }));
|
|
2238
|
+
const found = uniqueList(view, (a) => a.items.every(isRec) ? explain(cells, columns, a.items, st) : void 0);
|
|
2239
|
+
if (found && "hit" in found) {
|
|
2240
|
+
p.rows = { $bind: found.hit.path };
|
|
2241
|
+
keys.forEach((k, i) => {
|
|
2242
|
+
const e = found.hit.result[i];
|
|
2243
|
+
p[k] = "field" in e ? { $bind: `row.${e.field}` } : clone(e.constant);
|
|
2244
|
+
});
|
|
2245
|
+
st.bound.n++;
|
|
2246
|
+
} else slotOf(st, el2, "props.rows", String(rows[0].text ?? ""), found ? "collision" : "no-match", found && "collision" in found ? found.collision : void 0);
|
|
2247
|
+
}
|
|
2248
|
+
function bindRecords(el2, key2, known, view, st) {
|
|
2249
|
+
const lit = el2.props[key2];
|
|
2250
|
+
if (!Array.isArray(lit) || !lit.length || !lit.every(isRec)) return;
|
|
2251
|
+
const same2 = (a, b) => typeof a === "boolean" || typeof b === "boolean" ? a === b : typeof a === "number" && typeof b === "number" ? a === b : (shows(a)[0] ?? "") === (shows(b)[0] ?? "");
|
|
2252
|
+
const found = uniqueList(view, (a) => a.items.length === lit.length && a.items.every(isRec) && lit.every((r, i) => known.every((k) => same2(r[k], a.items[i][k]))) ? true : void 0);
|
|
2253
|
+
if (found && "hit" in found) {
|
|
2254
|
+
el2.props[key2] = { $bind: found.hit.path };
|
|
2255
|
+
st.bound.n++;
|
|
2256
|
+
return;
|
|
2257
|
+
}
|
|
2258
|
+
slotOf(st, el2, `props.${key2}`, String(lit[0][known[0]] ?? ""), found ? "collision" : "no-match", found && "collision" in found ? found.collision : void 0);
|
|
2259
|
+
}
|
|
2260
|
+
function bindMetrics(el2, view, st) {
|
|
2261
|
+
const lit = el2.props.items;
|
|
2262
|
+
if (!Array.isArray(lit) || !lit.length || !lit.every(isRec)) return;
|
|
2263
|
+
const shown = (r) => {
|
|
2264
|
+
try {
|
|
2265
|
+
return norm(String(formatValue2(r.value, r.format, st.locale, st.tz)));
|
|
2266
|
+
} catch {
|
|
2267
|
+
return "";
|
|
2268
|
+
}
|
|
2269
|
+
};
|
|
2270
|
+
const asText = (v) => typeof v === "string" ? norm(v) : "";
|
|
2271
|
+
const found = uniqueList(view, (a) => {
|
|
2272
|
+
if (a.items.length !== lit.length || !a.items.every(isRec)) return void 0;
|
|
2273
|
+
if (!lit.every((t, i) => asText(a.items[i].label) === asText(t.label) && shown(a.items[i]) === asText(t.value) && asText(a.items[i].tone) === asText(t.tone))) return void 0;
|
|
2274
|
+
const wants = lit.map((t) => asText(t.comparison));
|
|
2275
|
+
if (a.items.every((r, i) => asText(r.comparison) === wants[i])) return { key: void 0 };
|
|
2276
|
+
if (a.items.some((r) => asText(r.comparison))) return void 0;
|
|
2277
|
+
const keys = fieldsOf(a.items).filter((f) => !f.includes(".") && !["label", "value", "tone", "format", "comparison"].includes(f) && a.items.every((r, i) => typeof (r[f] ?? "") === "string" && asText(r[f]) === wants[i]));
|
|
2278
|
+
return keys.length ? { key: keys.find((k) => /delta|comparison|change|note/.test(k)) ?? keys[0] } : void 0;
|
|
2279
|
+
});
|
|
2280
|
+
if (found && "hit" in found) {
|
|
2281
|
+
el2.props.items = { $bind: found.hit.path };
|
|
2282
|
+
if (found.hit.result.key) el2.props.comparisonKey = found.hit.result.key;
|
|
2283
|
+
st.bound.n++;
|
|
2284
|
+
return;
|
|
2285
|
+
}
|
|
2286
|
+
if (found) slotOf(st, el2, "props.items", asText(lit[0].label), "collision", found.collision);
|
|
2287
|
+
else {
|
|
2288
|
+
let any = false;
|
|
2289
|
+
for (const t of lit) for (const k of ["label", "value", "comparison"]) {
|
|
2290
|
+
const before = t[k];
|
|
2291
|
+
bindText(el2, k, view, { ...st, sink: [] }, t);
|
|
2292
|
+
if (isRec(t[k]) && t[k] !== before) {
|
|
2293
|
+
any = true;
|
|
2294
|
+
st.bound.n++;
|
|
2295
|
+
}
|
|
2296
|
+
}
|
|
2297
|
+
if (!any) slotOf(st, el2, "props.items", asText(lit[0].label), "no-match");
|
|
2298
|
+
}
|
|
2299
|
+
}
|
|
2300
|
+
function bindSpec(el2, view, st) {
|
|
2301
|
+
const lit = el2.props.spec;
|
|
2302
|
+
if (!isRec(lit)) return;
|
|
2303
|
+
let key2;
|
|
2304
|
+
try {
|
|
2305
|
+
key2 = canonical(figureSpec(parseFigure(lit)));
|
|
2306
|
+
} catch {
|
|
2307
|
+
return;
|
|
2308
|
+
}
|
|
2309
|
+
const hits = view.objects.filter((o) => typeof o.value.type === "string" && KINDS.has(o.value.type)).filter((o) => {
|
|
2310
|
+
try {
|
|
2311
|
+
return canonical(figureSpec(parseFigure(o.value))) === key2;
|
|
2312
|
+
} catch {
|
|
2313
|
+
return false;
|
|
2314
|
+
}
|
|
2315
|
+
});
|
|
2316
|
+
const paths = [...new Set(hits.map((h4) => h4.path))];
|
|
2317
|
+
if (paths.length === 1) {
|
|
2318
|
+
el2.props.spec = { $bind: paths[0] };
|
|
2319
|
+
st.bound.n++;
|
|
2320
|
+
} else slotOf(st, el2, "props.spec", String(lit.title ?? lit.type), paths.length ? "collision" : "no-match", paths.slice(0, 6));
|
|
2321
|
+
}
|
|
2322
|
+
function bindElement(el2, view, st) {
|
|
2323
|
+
const p = el2.props;
|
|
2324
|
+
switch (el2.type) {
|
|
2325
|
+
case "reportic.masthead.v1":
|
|
2326
|
+
for (const k of ["marking", "kicker", "title", "lead"]) bindText(el2, k, view, st);
|
|
2327
|
+
if (Array.isArray(p.byline)) p.byline.forEach((item, i) => {
|
|
2328
|
+
if (isRec(item)) bindText(el2, "value", view, st, item, `props.byline[${i}].value`);
|
|
2329
|
+
else if (typeof item === "string") bindText(el2, String(i), view, st, p.byline, `props.byline[${i}]`);
|
|
2330
|
+
});
|
|
2331
|
+
break;
|
|
2332
|
+
case "reportic.footer.v1":
|
|
2333
|
+
bindText(el2, "text", view, st);
|
|
2334
|
+
break;
|
|
2335
|
+
case "narrative":
|
|
2336
|
+
bindText(el2, "text", view, st);
|
|
2337
|
+
bindText(el2, "heading", view, st);
|
|
2338
|
+
break;
|
|
2339
|
+
case "reportic.callout.v1":
|
|
2340
|
+
bindText(el2, "title", view, st);
|
|
2341
|
+
bindText(el2, "text", view, st);
|
|
2342
|
+
break;
|
|
2343
|
+
case "reportic.heading.v1":
|
|
2344
|
+
bindText(el2, "text", view, st);
|
|
2345
|
+
break;
|
|
2346
|
+
case "reportic.figure.v1":
|
|
2347
|
+
bindSpec(el2, view, st);
|
|
2348
|
+
bindText(el2, "source", view, st);
|
|
2349
|
+
break;
|
|
2350
|
+
case "reportic.grid.v1":
|
|
2351
|
+
bindGrid(el2, view, st);
|
|
2352
|
+
break;
|
|
2353
|
+
case "table":
|
|
2354
|
+
bindLiteralTable(el2, view, st);
|
|
2355
|
+
break;
|
|
2356
|
+
case "list":
|
|
2357
|
+
bindList(el2, view, st);
|
|
2358
|
+
break;
|
|
2359
|
+
case "metrics":
|
|
2360
|
+
bindMetrics(el2, view, st);
|
|
2361
|
+
break;
|
|
2362
|
+
case "reportic.timeline.v1":
|
|
2363
|
+
bindRecords(el2, "items", ["date", "title", "text"], view, st);
|
|
2364
|
+
break;
|
|
2365
|
+
case "reportic.checklist.v1":
|
|
2366
|
+
bindRecords(el2, "items", ["text", "done", "owner"], view, st);
|
|
2367
|
+
break;
|
|
2368
|
+
case "reportic.progress.v1":
|
|
2369
|
+
bindRecords(el2, "items", ["label", "value", "detail"], view, st);
|
|
2370
|
+
break;
|
|
2371
|
+
case "reportic.comparison.v1":
|
|
2372
|
+
bindRecords(el2, "rows", ["label", "left", "right"], view, st);
|
|
2373
|
+
break;
|
|
2374
|
+
case "group":
|
|
2375
|
+
bindText(el2, "heading", view, st);
|
|
2376
|
+
if (Array.isArray(p.children)) p.children = sequence(p.children, view, st);
|
|
2377
|
+
break;
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
function cloneEl(e) {
|
|
2381
|
+
const props = Object.fromEntries(Object.entries(e.props).map(([k, v]) => [k, k === "children" && Array.isArray(v) ? v.map(cloneEl) : clone(v)]));
|
|
2382
|
+
const copy = { id: e.id, type: e.type, props, ...e.when !== void 0 ? { when: clone(e.when) } : {}, ...e.meta ? { meta: e.meta } : {} };
|
|
2383
|
+
const base = baseOf.get(e);
|
|
2384
|
+
if (base) baseOf.set(copy, base);
|
|
2385
|
+
return copy;
|
|
2386
|
+
}
|
|
2387
|
+
var binds = (props) => {
|
|
2388
|
+
const skip = Array.isArray(props.rows) || isRec(props.rows) && "$bind" in props.rows ? /* @__PURE__ */ new Set(["columns", "lead", "text"]) : /* @__PURE__ */ new Set();
|
|
2389
|
+
return Object.entries(props).filter(([k]) => !skip.has(k)).flatMap(([, v]) => isRec(v) && typeof v.$bind === "string" && v.$bind.startsWith("row.") ? [v.$bind] : []);
|
|
2390
|
+
};
|
|
2391
|
+
var sameElement = (a, b) => a.type === b.type && canonical(a.props) === canonical(b.props);
|
|
2392
|
+
function attempt(groups, list2, view, st) {
|
|
2393
|
+
const local = { ...st, sink: [], bound: { n: 0 } }, n = groups.length;
|
|
2394
|
+
const keyed = groups.map((g, k) => {
|
|
2395
|
+
const rowView = view.withRow(list2.items[k]), seen = /* @__PURE__ */ new Map();
|
|
2396
|
+
return sequence(g.props.children.map(cloneEl), rowView, local).map((e) => {
|
|
2397
|
+
const base = baseOf.get(e) ?? e.type, at = (seen.get(base) ?? 0) + 1;
|
|
2398
|
+
seen.set(base, at);
|
|
2399
|
+
return { key: `${base}#${at}`, e };
|
|
2400
|
+
});
|
|
2401
|
+
});
|
|
2402
|
+
const order = [];
|
|
2403
|
+
for (const occ of keyed) {
|
|
2404
|
+
let anchor = -1;
|
|
2405
|
+
for (const { key: key2 } of occ) {
|
|
2406
|
+
const at = order.indexOf(key2);
|
|
2407
|
+
if (at >= 0) anchor = at;
|
|
2408
|
+
else order.splice(++anchor, 0, key2);
|
|
2409
|
+
}
|
|
2410
|
+
}
|
|
2411
|
+
for (const occ of keyed) {
|
|
2412
|
+
let last = -1;
|
|
2413
|
+
for (const { key: key2 } of occ) {
|
|
2414
|
+
const at = order.indexOf(key2);
|
|
2415
|
+
if (at < 0 || at <= last) return void 0;
|
|
2416
|
+
last = at;
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
2419
|
+
const children = [], used = /* @__PURE__ */ new Set();
|
|
2420
|
+
for (const key2 of order) {
|
|
2421
|
+
const present = keyed.map((occ) => occ.find((x) => x.key === key2)?.e);
|
|
2422
|
+
const first = present.find(Boolean);
|
|
2423
|
+
if (present.some((e) => e && !sameElement(first, e))) return void 0;
|
|
2424
|
+
const merged = cloneEl(first);
|
|
2425
|
+
used.add(first.id);
|
|
2426
|
+
if (present.some((e) => !e)) {
|
|
2427
|
+
const flags = present.map(Boolean);
|
|
2428
|
+
const via = binds(merged.props).find((path) => list2.items.every((r, k) => truthy(valueAt(r, path.slice(4))) === flags[k]));
|
|
2429
|
+
if (!via) return void 0;
|
|
2430
|
+
merged.when = { $bind: via };
|
|
2431
|
+
}
|
|
2432
|
+
children.push(merged);
|
|
2433
|
+
}
|
|
2434
|
+
if (children.length === 0 || n === 0) return void 0;
|
|
2435
|
+
return { children, sink: local.sink.filter((s) => used.has(s.elementId)), bound: local.bound.n };
|
|
2436
|
+
}
|
|
2437
|
+
function tryRepeat(groups, view, st) {
|
|
2438
|
+
const id = String(groups[0].meta.repeat), n = groups.length;
|
|
2439
|
+
const ok = view.arrays.filter((a) => a.items.length === n && a.items.every(isRec)).flatMap((a) => {
|
|
2440
|
+
const r = attempt(groups, a, view, st);
|
|
2441
|
+
return r ? [{ path: a.path, ...r }] : [];
|
|
2442
|
+
});
|
|
2443
|
+
if (ok.length === 1) {
|
|
2444
|
+
st.sink.push(...ok[0].sink);
|
|
2445
|
+
st.bound.n += ok[0].bound + 1;
|
|
2446
|
+
st.ctx.note("REPEAT_FORMED", `${n} repeated group${n === 1 ? "" : "s"} became one repeat over ${ok[0].path}.`, { elementId: id });
|
|
2447
|
+
return { id, type: "repeat", props: { rows: { $bind: ok[0].path }, children: ok[0].children } };
|
|
2448
|
+
}
|
|
2449
|
+
slotOf(st, groups[0], "props.rows", `${id}: ${n} rows`, ok.length ? "collision" : "no-match", ok.map((o) => o.path).slice(0, 6));
|
|
2450
|
+
return void 0;
|
|
2451
|
+
}
|
|
2452
|
+
function sequence(items, view, st) {
|
|
2453
|
+
const out = [];
|
|
2454
|
+
for (let i = 0; i < items.length; ) {
|
|
2455
|
+
const e = items[i], rid = e.meta?.repeat;
|
|
2456
|
+
if (rid !== void 0) {
|
|
2457
|
+
let j = i;
|
|
2458
|
+
while (j < items.length && items[j].meta?.repeat === rid && items[j].meta?.index === j - i) j++;
|
|
2459
|
+
const run = items.slice(i, j), merged = tryRepeat(run, view, st);
|
|
2460
|
+
if (merged) out.push(merged);
|
|
2461
|
+
else for (const g of run) {
|
|
2462
|
+
bindElement(g, view, st);
|
|
2463
|
+
out.push(g);
|
|
2464
|
+
}
|
|
2465
|
+
i = j;
|
|
2466
|
+
continue;
|
|
2467
|
+
}
|
|
2468
|
+
bindElement(e, view, st);
|
|
2469
|
+
out.push(e);
|
|
2470
|
+
i++;
|
|
2471
|
+
}
|
|
2472
|
+
return out;
|
|
2473
|
+
}
|
|
2474
|
+
function rebind(draft, sample, ctx, dataSet) {
|
|
2475
|
+
if (!isRec(sample)) {
|
|
2476
|
+
ctx.warn("SAMPLE_INVALID", "The sample must be one JSON object, so nothing was bound.");
|
|
2477
|
+
return;
|
|
2478
|
+
}
|
|
2479
|
+
if (!goodKey(dataSet) || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(dataSet)) {
|
|
2480
|
+
ctx.warn("SAMPLE_INVALID", `"${dataSet}" is not a usable dataset name, so nothing was bound.`);
|
|
2481
|
+
return;
|
|
2482
|
+
}
|
|
2483
|
+
const st = { ctx, ds: dataSet, locale: draft.locale, tz: draft.timezone ?? "UTC", sink: [], bound: { n: 0 } };
|
|
2484
|
+
const view = new View([new Layer(sample, `dataSets.${dataSet}`)]);
|
|
2485
|
+
const out = [];
|
|
2486
|
+
let run = [];
|
|
2487
|
+
const flush = () => {
|
|
2488
|
+
if (run.length) {
|
|
2489
|
+
for (const e of sequence(run, view, st)) out.push({ element: e });
|
|
2490
|
+
run = [];
|
|
2491
|
+
}
|
|
2492
|
+
};
|
|
2493
|
+
for (const b of draft.blocks) {
|
|
2494
|
+
if ("element" in b) run.push(b.element);
|
|
2495
|
+
else {
|
|
2496
|
+
flush();
|
|
2497
|
+
out.push(b);
|
|
2498
|
+
}
|
|
2499
|
+
}
|
|
2500
|
+
flush();
|
|
2501
|
+
draft.blocks = out;
|
|
2502
|
+
if (JSON.stringify(out).includes(`"dataSets.${dataSet}`)) draft.dataSets = [dataSet];
|
|
2503
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2504
|
+
for (const s of st.sink) {
|
|
2505
|
+
const key2 = `${s.elementId}|${s.slot}`;
|
|
2506
|
+
if (!seen.has(key2) && ctx.unbound.length < 300) {
|
|
2507
|
+
seen.add(key2);
|
|
2508
|
+
ctx.unbound.push(s);
|
|
2509
|
+
}
|
|
2510
|
+
}
|
|
2511
|
+
ctx.note("REBOUND", `Bound ${st.bound.n} slot${st.bound.n === 1 ? "" : "s"} to the sample; ${ctx.unbound.length} left as written (see the unbound list).`);
|
|
2512
|
+
}
|
|
2513
|
+
|
|
2514
|
+
// packages/reportic-render-html/src/import/guide.ts
|
|
2515
|
+
var IMPORT_GUIDE = `Reportic reads two kinds of HTML.
|
|
2516
|
+
|
|
2517
|
+
- Reportic HTML is a report Reportic exported: it has the generator tag "Reportic 0.2", a main.reportic-report element, and sections marked with data-reportic-type and data-reportic-id. It is imported exactly: every section comes back as the element that made it, with the same ids, and the colors and fonts are matched to a preset theme.
|
|
2518
|
+
- Any other HTML is imported best effort. A real HTML parser reads it, scripts, forms, frames and event handlers are dropped, and only structure that is clear becomes an element. Everything else stays Markdown, and what was left out is listed in the notes.
|
|
2519
|
+
|
|
2520
|
+
What a best-effort import maps
|
|
2521
|
+
- Headings, paragraphs, lists, quotes and links stay Markdown.
|
|
2522
|
+
- A data table becomes a table (a grid of written-out cells). A table with three columns and a blank first header becomes a comparison.
|
|
2523
|
+
- A definition list becomes a two-column table with row headers.
|
|
2524
|
+
- A group of two or more short number-and-label blocks becomes metrics.
|
|
2525
|
+
- A titled aside, or a block with a callout, alert, note, or warning class, becomes a callout.
|
|
2526
|
+
- A progress or meter element (or role="progressbar") with a value from 0 to 1 becomes a progress list.
|
|
2527
|
+
- A list of checkbox items becomes a checklist.
|
|
2528
|
+
- Three or more headings that start with a date become a timeline.
|
|
2529
|
+
- pre and code become a code block. A mermaid block becomes a diagram. Labeled boxes joined by arrows become a flowchart.
|
|
2530
|
+
- An image with a caption becomes an image. Images must be embedded (data: URIs); linked files cannot be read.
|
|
2531
|
+
- A trailing ordered list of links becomes sources, and earlier paragraphs with [1] style markers become narratives that cite them.
|
|
2532
|
+
- Colors, fonts and sizes are reduced to the nearest preset plus token overrides. A block style that differs from the document becomes a theme rule. Plain element rules are kept as report css. @page size and orientation are kept as the page setup.
|
|
2533
|
+
|
|
2534
|
+
What has no element
|
|
2535
|
+
- Video, audio, frames, forms, scripts and canvases are dropped. A picture of a chart with no table of numbers stays an image.
|
|
2536
|
+
|
|
2537
|
+
To get an exact import
|
|
2538
|
+
- Re-export the report from Reportic as HTML and import that file, or
|
|
2539
|
+
- Mark each block with data-reportic-type and data-reportic-id, using the type names from the component library (metrics, table, chart, diagram, image, list, narrative, sources, group, repeat, reportic.callout.v1 as "callout", progress, timeline, comparison, checklist, code, masthead, footer, figure), put it in a main.reportic-report element, add <meta name="generator" content="Reportic 0.2">, and import again.
|
|
2540
|
+
|
|
2541
|
+
Data
|
|
2542
|
+
- The template written from HTML holds the text of that one report. Import with a JSON sample (one object, used as the dataset "report") and every slot that one field explains completely is bound to it. Slots that several fields could explain, and cells that could be split in more than one way, stay as written and are listed so you can bind them in the editor.`;
|
|
2543
|
+
var guideFor = (mode) => `${mode === "reportic" ? "This page is Reportic HTML, so it was imported exactly." : "This page is not Reportic HTML, so it was imported best effort."}
|
|
2544
|
+
|
|
2545
|
+
${IMPORT_GUIDE}`;
|
|
2546
|
+
|
|
2547
|
+
// packages/reportic-render-html/src/import/index.ts
|
|
2548
|
+
var unsafeCss = /@import|url\s*\(|expression\s*\(|<\/?style|behavior\s*:/i;
|
|
2549
|
+
function importHtml(html, options = {}) {
|
|
2550
|
+
if (typeof html !== "string" || !html.trim()) fail3("INVALID_INPUT", "HTML to import must be a non-empty string.", { phase: "input" });
|
|
2551
|
+
if (Buffer.byteLength(html) > 25e6) fail3("LIMIT_EXCEEDED", "The page is larger than 25 MB.", { phase: "input" });
|
|
2552
|
+
const doc = parseHtml(html), ctx = new Importer();
|
|
2553
|
+
const css = findAll(doc, (e) => e.tagName === "style").map((s) => kids(s).map((k) => isText(k) ? k.value : "").join("")).join("\n");
|
|
2554
|
+
const reportic = isReporticHtml(doc);
|
|
2555
|
+
const draft = reportic ? importReportic(doc, ctx) : importBestEffort(doc, ctx);
|
|
2556
|
+
const style2 = (reportic ? readReporticStyle(css, ctx) : void 0) ?? readPageStyle(doc, css, ctx);
|
|
2557
|
+
if (unsafeCss.test(css)) ctx.warn("CSS_DROPPED", "Style rules that fetch or run something (@import, url(), expression(), behavior) were dropped.");
|
|
2558
|
+
if (unsafeCss.test(style2.css)) style2.css = style2.css.split("\n").filter((line) => !unsafeCss.test(line)).join("\n");
|
|
2559
|
+
const dataSet = options.dataSet ?? "report";
|
|
2560
|
+
if (options.sample !== void 0) rebind(draft, options.sample, ctx, dataSet);
|
|
2561
|
+
const template = writeTemplate(draft);
|
|
2562
|
+
const named = find(doc, (e) => e.tagName === "h1") ?? find(doc, (e) => e.tagName === "title");
|
|
2563
|
+
const result = { mode: reportic ? "reportic" : "best-effort", title: named ? textOf(named).slice(0, 120) : "", template, theme: style2.theme, css: style2.css, assets: draft.assets, notes: ctx.notes, unbound: ctx.unbound, guide: guideFor(reportic ? "reportic" : "best-effort") };
|
|
2564
|
+
if (style2.page) result.page = style2.page;
|
|
2565
|
+
return result;
|
|
2566
|
+
}
|
|
2567
|
+
|
|
176
2568
|
// packages/reportic-render-html/src/index.ts
|
|
2569
|
+
var darken = (hex2, amount) => {
|
|
2570
|
+
const s = hex2.replace("#", "");
|
|
2571
|
+
const full = s.length <= 4 ? s.slice(0, 3).split("").map((c) => c + c).join("") : s.slice(0, 6);
|
|
2572
|
+
return "#" + [0, 2, 4].map((i) => Math.round(parseInt(full.slice(i, i + 2), 16) * (1 - amount)).toString(16).padStart(2, "0")).join("");
|
|
2573
|
+
};
|
|
2574
|
+
var cellsOf = (node) => (node.props.cells ?? []).flat();
|
|
2575
|
+
function featureCss(report, t, c) {
|
|
2576
|
+
const nodes = walkNodes2(report.nodes);
|
|
2577
|
+
const uses = (f) => nodes.some(f);
|
|
2578
|
+
const scope = ".reportic-report";
|
|
2579
|
+
let css = "";
|
|
2580
|
+
const tone2 = (k) => c[k];
|
|
2581
|
+
if (uses((n) => n.type === "table" && cellsOf(n).some((x) => x.kind === "rating" || x.runs || x.kind === "status" || x.kind === "date" || x.kind === "code")) || uses((n) => n.type === "masthead")) {
|
|
2582
|
+
css += `${scope} td code{white-space:nowrap;overflow-wrap:normal}${scope} td code.rpt-long{white-space:normal;overflow-wrap:break-word}${scope} .rpt-rating{font-weight:600;white-space:nowrap;overflow-wrap:normal}${scope} .rpt-rating.rpt-ok{color:${tone2("ok")}}${scope} .rpt-rating.rpt-warn{color:${tone2("warn")}}${scope} .rpt-rating.rpt-bad{color:${tone2("bad")}}${scope} .rpt-rating.rpt-na{color:${tone2("na")};font-weight:400}`;
|
|
2583
|
+
css += `${scope} .rpt-chip{display:inline-block;padding:0 7px;border-radius:5px;font-size:.92em;line-height:1.5;white-space:nowrap}${scope} .rpt-chip.rpt-date{background:${c.head};color:${c.ink};border:1px solid ${t.border}}${scope} .rpt-chip.rpt-person{background:${c.accentSoft};color:${t.accent}}`;
|
|
2584
|
+
css += `${scope} .rpt-chip.rpt-status{background:${c.warnSoft};color:${darken(c.warn, 0.45)};border:1px solid ${c.warn}55}${scope} .rpt-chip.rpt-status.rpt-done{background:${c.okSoft};color:${c.ok};border-color:${c.ok}55}${scope} .rpt-chip.rpt-status.rpt-late{background:${c.badSoft};color:${c.bad};border-color:${c.bad}55}${scope} .rpt-chip.rpt-status.rpt-progress{background:${c.accentSoft};color:${t.accent};border-color:${t.accent}44}`;
|
|
2585
|
+
}
|
|
2586
|
+
if (uses((n) => n.type === "table" && (cellsOf(n).some((x) => x.total) || n.props.rowHeader))) {
|
|
2587
|
+
css += `${scope} tr.rpt-total td{border-top:1px solid ${t.muted}66;font-weight:600;color:${c.ink}}${scope} th.rpt-rowheader{background:${c.zebra};color:${c.ink};font-weight:600;width:28%;padding:11px 12px;border-bottom:1px solid ${t.border}}${scope} tbody tr:last-child th.rpt-rowheader{border-bottom:0}`;
|
|
2588
|
+
}
|
|
2589
|
+
if (uses((n) => n.type === "metrics" && n.props.items.some((i) => i.tone))) {
|
|
2590
|
+
css += `${scope} .rpt-metric.rpt-ok .metric-value{color:${tone2("ok")}}${scope} .rpt-metric.rpt-warn .metric-value{color:${tone2("warn")}}${scope} .rpt-metric.rpt-bad .metric-value{color:${tone2("bad")}}${scope} .rpt-metric.rpt-na .metric-value{color:${tone2("na")}}`;
|
|
2591
|
+
}
|
|
2592
|
+
if (uses((n) => n.type === "list" && n.props.variant === "callout")) {
|
|
2593
|
+
css += `${scope} .callout.rpt-clauses strong{font-size:inherit;letter-spacing:inherit;text-transform:none}${scope} .callout.rpt-clauses p{margin:6px 0}${scope} .callout.rpt-clauses p:first-child{margin-top:0}${scope} .callout.rpt-clauses p:last-child{margin-bottom:0}`;
|
|
2594
|
+
}
|
|
2595
|
+
if (uses((n) => n.type === "masthead")) {
|
|
2596
|
+
css += `${scope} .rpt-masthead{margin:0 0 8px}${scope} .rpt-marking{display:inline-block;border:1.5px solid ${tone2("bad")};color:${tone2("bad")};font-weight:600;padding:2px 8px;border-radius:5px;font-size:12.5px;line-height:1.6;margin:0 0 14px}${scope} .rpt-kicker{font-size:12px;letter-spacing:.1em;text-transform:uppercase;color:${t.accent};font-weight:600;margin:0 0 10px}${scope} .rpt-masthead h1{margin-top:0}${scope} .rpt-byline{font-size:.93em;color:${t.muted};margin:0 0 18px}${scope} .rpt-byline .rpt-chip{margin-right:2px}${scope} .rpt-lead{font-size:1.13em;line-height:1.55;color:${c.ink};margin:0 0 18px}`;
|
|
2597
|
+
}
|
|
2598
|
+
if (uses((n) => n.type === "footer")) {
|
|
2599
|
+
css += `${scope} .rpt-footer{margin:28px 0 0;padding:16px 0 0;font-size:12.5px;line-height:1.5;color:${t.muted};border-top:1px solid ${t.border};break-inside:avoid}${scope} .rpt-footer img{height:18px;width:auto;max-width:none;vertical-align:middle;margin-right:8px}`;
|
|
2600
|
+
}
|
|
2601
|
+
if (uses((n) => n.type === "figure")) {
|
|
2602
|
+
css += `${scope} .rpt-figure{margin:18px 0 22px;break-inside:avoid}${scope} .rpt-figure-box{border:1px solid ${t.border};border-radius:8px;background:${t.background};padding:10px 8px 4px}${scope} .rpt-figure img{display:block;width:100%;height:auto;max-height:none}${scope} .rpt-figure figcaption{font-size:12.5px;color:${t.muted};margin:6px 0 0;padding-left:2px}${scope} .rpt-figure figcaption:before{content:"Source: ";font-weight:600;color:${t.text}}${scope} .rpt-sr-only{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}`;
|
|
2603
|
+
}
|
|
2604
|
+
if (t.layout === "card") css += cardCss(t, c);
|
|
2605
|
+
return css;
|
|
2606
|
+
}
|
|
2607
|
+
function tokenProperties(tokens = {}) {
|
|
2608
|
+
const props = [...tokens.layout ? [`--reportic-layout:${tokens.layout}`] : [], ...tokens.chartPalette ? [`--reportic-palette:${tokens.chartPalette.join(" ")}`] : [], ...Object.entries(tokens.semantic ?? {}).filter(([k]) => /^[a-zA-Z]\w*$/.test(k)).map(([k, v]) => `--reportic-semantic-${k}:${v}`)];
|
|
2609
|
+
return props.length ? `.reportic-report{${props.join(";")}}` : "";
|
|
2610
|
+
}
|
|
2611
|
+
function cardCss(t, c) {
|
|
2612
|
+
const s = ".reportic-report", rule = t.border, strong = `${t.muted}55`;
|
|
2613
|
+
return `@media screen{body{background:${c.page}}}${s}{background:${t.background};border:1px solid ${rule};border-top:5px solid ${t.accent};border-radius:12px;padding:36px 36px 28px;margin:32px auto 48px;line-height:1.6}${s} h1,${s} h2,${s} h3{color:${c.ink};font-weight:600;letter-spacing:0}${s} h1{line-height:1.15;margin:0 0 10px}${s} h2{font-size:22px;line-height:1.3;margin:34px 0 10px;padding-top:14px;border-top:1px solid ${rule}}${s} h3{font-family:${t.fontFamily};font-size:16.5px;margin:24px 0 8px}${s} h2:first-child{border-top:0;padding-top:0;margin-top:0}${s} p{margin:0 0 12px}${s} strong{color:${c.ink};font-weight:600}${s} code{background:${c.head};color:${c.ink};padding:1px 5px;border-radius:4px}${s} pre{background:${c.head};border-radius:8px;padding:12px 14px;font-size:13px}${s} li::marker{color:${t.muted}}${s} ul,${s} ol{margin:0 0 14px;padding-left:22px}${s} li{margin:4px 0}${s},${s} td,${s} th{overflow-wrap:break-word}${s} th{vertical-align:top}${s} th.rpt-rowheader{padding:8px 11px}${s} table{border-collapse:separate;border-spacing:0;border:1px solid ${rule};border-radius:8px;overflow:hidden;font-size:13.5px;line-height:1.45;font-variant-numeric:tabular-nums;margin:14px 0 20px}${s} th{background:${c.head};color:${c.ink};padding:8px 11px;border-bottom:1px solid ${strong}}${s} td{padding:8px 11px;border-bottom:1px solid ${rule}}${s} tbody tr:last-child td{border-bottom:0}${s} tr:nth-child(even) td{background:${c.zebra}}${s} blockquote{background:${c.accentSoft}}${s} .callout{margin:16px 0 18px;padding:14px 18px;background:${t.accent}0d;border:0;border-left:4px solid ${t.accent};border-radius:0 8px 8px 0}${s} .callout.tone-warning{background:${c.warnSoft};border-left-color:${c.warn}}${s} .callout.tone-danger{background:${c.badSoft};border-left-color:${c.bad}}${s} .callout.tone-success{background:${c.okSoft};border-left-color:${c.ok}}${s} .callout p{margin:0 0 8px}${s} .callout p:last-child{margin-bottom:0}${s} .metrics{border:0;padding:0;margin:14px 0 18px;gap:12px;grid-template-columns:repeat(auto-fit,minmax(150px,1fr))}${s} .metrics>div{display:flex;flex-direction:column;border:1px solid ${rule};border-radius:8px;padding:12px 14px;background:${c.zebra}}${s} .metric-value{order:1;font-family:${t.headingFont};font-size:var(--metric-size,28px);line-height:1.1;color:${c.ink};letter-spacing:0}${s} .metric-label{order:2;font-size:12.5px;letter-spacing:0;text-transform:none;color:${t.muted};margin:4px 0 0;line-height:1.35}${s} .metric-comparison{order:3;font-size:12.5px;color:${t.text};margin-top:4px}${s} .rpt-lead{font-size:17px}${s} .rpt-byline{font-size:14px}${s} [data-reportic-type=logo]{margin:0 0 16px}${s} [data-reportic-type=logo] figure{margin:0}${s} [data-reportic-type=logo] img{display:block;height:44px;width:auto;max-width:none;max-height:none}@media(max-width:600px){${s}{padding:22px 18px 18px;border-radius:10px;margin:14px auto 32px}${s} h1{font-size:26px}${s} h2{font-size:19.5px}${s} table{font-size:13px}${s} th,${s} td{padding:7px 9px}}@media print{body{background:#fff}${s}{border:0;border-top:4px solid ${t.accent};border-radius:0;padding:12px 0 0;margin:0;max-width:none;font-size:10.5pt}${s} table{font-size:9pt}${s} tr,${s} .callout{break-inside:avoid}${s} [data-reportic-type=logo] img{height:12mm}${s} .rpt-footer img{height:4mm}}`;
|
|
2614
|
+
}
|
|
177
2615
|
function reportCss(report, options = {}) {
|
|
178
|
-
const t =
|
|
179
|
-
const
|
|
180
|
-
|
|
2616
|
+
const t = themeTokens4(options.theme ?? report.theme);
|
|
2617
|
+
const feature = tokenProperties((options.theme ?? report.theme).tokens) + featureCss(report, t, semanticColors2(t));
|
|
2618
|
+
const rules = Object.entries((options.theme ?? report.theme).rules ?? {}).sort(([a], [b]) => Number(!["document", "heading", "paragraph", "table", "metric", "chart", "diagram", "image", "logo"].includes(a)) - Number(!["document", "heading", "paragraph", "table", "metric", "chart", "diagram", "image", "logo"].includes(b))).map(([key2, value]) => {
|
|
2619
|
+
const selector = key2 === "document" ? ".reportic-report" : key2 === "heading" ? ".reportic-report :is(h1,h2,h3,h4)" : key2 === "paragraph" ? ".reportic-report p" : ["table", "metric", "chart", "diagram", "image", "logo"].includes(key2) ? `.reportic-report [data-reportic-type="${key2 === "metric" ? "metrics" : key2}"]` : `.reportic-report [data-reportic-id="${key2}"]`;
|
|
181
2620
|
return `${selector}{${Object.entries(value).map(([k, v]) => `${k.replace(/[A-Z]/g, (m) => "-" + m.toLowerCase())}:${typeof v === "number" && !["fontWeight", "lineHeight"].includes(k) ? v + "px" : v}`).join(";")}}`;
|
|
182
2621
|
}).join("\n");
|
|
183
|
-
return `:root{color-scheme:light}*{box-sizing:border-box}body{margin:0;background:${t.background};color:${t.text}}.reportic-report{--reportic-accent:${t.accent};font:${t.bodySize}px/1.75 ${t.fontFamily};max-width:${t.contentWidth}px;margin:0 auto;padding:60px 58px;overflow-wrap:anywhere}.reportic-report h1,.reportic-report h2,.reportic-report h3{line-height:1.2;font-family:${t.headingFont};font-weight:500;letter-spacing:-.035em;color:${t.text};break-after:avoid}.reportic-report h1{font-size:${t.headingSize}px;margin:20px 0 24px}.reportic-report h2{font-size:27px;margin:44px 0 19px}.reportic-report h3{font-size:21px;margin:28px 0 14px}.reportic-report p{margin:12px 0}.reportic-report a{color:${t.accent};text-underline-offset:3px}.reportic-report blockquote{border-left:3px solid ${t.accent};padding:8px 20px;margin:24px 0;color:${t.muted};background:${t.accent}08}.reportic-report hr{border:0;border-top:1px solid ${t.border};margin:30px 0}.reportic-report code{font-family:Consolas,monospace;font-size:.87em;background:${t.accent}0b;padding:2px 5px;border-radius:4px}.reportic-report pre{white-space:pre-wrap;overflow-wrap:anywhere;padding:20px;background:${t.accent}08;border:1px solid ${t.border};border-radius:8px;break-inside:avoid}.reportic-report pre code{padding:0;background:none}.reportic-report table{width:100%;border-collapse:collapse;margin:16px 0 24px;font-size:.9em;table-layout:auto}.reportic-report thead{display:table-header-group}.reportic-report th{text-align:left;background:${t.accent}0d;font-weight:600;border-bottom:1px solid ${t.border};color:${t.accent};padding:12px}.reportic-report td{border-bottom:1px solid ${t.border};padding:11px 12px;vertical-align:top;overflow-wrap:anywhere}.reportic-report tr{break-inside:avoid}.reportic-report tr:nth-child(even) td{background:${t.accent}03}.reportic-report section{margin:20px 0}.reportic-report figure{margin:20px 0;break-inside:avoid}.reportic-report img{max-width:100%;height:auto}.reportic-report figcaption{font-size:12px;color:${t.muted};margin:10px 0}.reportic-report [data-reportic-type=logo]{margin:0 0 26px}.reportic-report [data-reportic-type=logo] img{max-width:${t.logoWidth}px;max-height:70px;object-fit:contain}.reportic-report .metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));border-top:1px solid ${t.border};border-bottom:1px solid ${t.border};padding:22px 0;gap:24px;margin:24px 0;break-inside:avoid}.reportic-report .metric-label{font-size:10px;letter-spacing:.09em;text-transform:uppercase;color:${t.muted};margin:0 0 8px}.reportic-report .metric-value{font-size:var(--metric-size,28px);white-space:nowrap;line-height:1.3;letter-spacing:-.04em;font-weight:600}.reportic-report .metric-comparison{font-size:11px;color:${t.accent};margin-top:7px}.reportic-report .callout{border:1px solid ${t.accent}25;border-left:3px solid ${t.accent};padding:16px 20px;border-radius:0 7px 7px 0;background:${t.accent}07;break-inside:avoid}.reportic-report .callout strong{font-size:14px}.reportic-report .callout p{margin:5px 0}.reportic-report .tone-warning{border-left-color:#bf8c3c;background:#c78a190a}.reportic-report .tone-danger{border-left-color:#bb5c53}.reportic-report .progress-item{margin:18px 0;break-inside:avoid}.reportic-report .progress-label{display:flex;justify-content:space-between;font-size:12px}.reportic-report .progress-track{height:7px;border-radius:5px;background:${t.border};margin:8px 0}.reportic-report .progress-track span{display:block;height:100%;background:${t.accent};border-radius:5px}.reportic-report .timeline-item{border-left:1px solid ${t.border};padding:0 0 22px 24px;position:relative;break-inside:avoid}.reportic-report .timeline-item:before{content:'';position:absolute;left:-5px;top:8px;width:9px;height:9px;border-radius:100%;background:${t.accent}}.reportic-report .timeline-date{font-size:11px;color:${t.muted}}.reportic-report .timeline-item p{margin:4px 0}.reportic-report .checklist{list-style:none;padding-left:0}.reportic-report .checklist li{margin:10px 0}.reportic-report .checkmark{color:${t.accent};margin-right:10px}.reportic-report .source-list{font-size:12px;color:${t.muted}}.reportic-report .diagram img{width:100%;max-height:400px;object-fit:contain}.reportic-report .chart img{width:100%}.reportic-report .chart-data{font-size:10px}.reportic-report .empty{color:${t.muted};font-style:italic}.reportic-report .evidence{font-size:10px;vertical-align:super;margin-left:4px}@media(max-width:600px){.reportic-report{padding:30px 22px}.reportic-report h1{font-size:34px}.reportic-report th,.reportic-report td{padding:7px;font-size:11px}}@page{size:A4;margin:17mm 15mm}@media print{.reportic-report{padding:0;max-width:none;font-size:10.5pt}.reportic-report h1{font-size:32pt}.reportic-report h2{font-size:20pt}.reportic-report .metrics{grid-template-columns:repeat(var(--metric-count,4),1fr)}a{text-decoration:none}.reportic-report figure img{max-height:90mm}.reportic-report .chart-data{font-size:8pt}}${rules}
|
|
2622
|
+
return `:root{color-scheme:light}*{box-sizing:border-box}body{margin:0;background:${t.background};color:${t.text}}.reportic-report{--reportic-accent:${t.accent};font:${t.bodySize}px/1.75 ${t.fontFamily};max-width:${t.contentWidth}px;margin:0 auto;padding:60px 58px;overflow-wrap:anywhere}.reportic-report h1,.reportic-report h2,.reportic-report h3{line-height:1.2;font-family:${t.headingFont};font-weight:500;letter-spacing:-.035em;color:${t.text};break-after:avoid}.reportic-report h1{font-size:${t.headingSize}px;margin:20px 0 24px}.reportic-report h2{font-size:27px;margin:44px 0 19px}.reportic-report h3{font-size:21px;margin:28px 0 14px}.reportic-report p{margin:12px 0}.reportic-report a{color:${t.accent};text-underline-offset:3px}.reportic-report blockquote{border-left:3px solid ${t.accent};padding:8px 20px;margin:24px 0;color:${t.muted};background:${t.accent}08}.reportic-report hr{border:0;border-top:1px solid ${t.border};margin:30px 0}.reportic-report code{font-family:Consolas,monospace;font-size:.87em;background:${t.accent}0b;padding:2px 5px;border-radius:4px}.reportic-report pre{white-space:pre-wrap;overflow-wrap:anywhere;padding:20px;background:${t.accent}08;border:1px solid ${t.border};border-radius:8px;break-inside:avoid}.reportic-report pre code{padding:0;background:none}.reportic-report table{width:100%;border-collapse:collapse;margin:16px 0 24px;font-size:.9em;table-layout:auto}.reportic-report thead{display:table-header-group}.reportic-report th{text-align:left;background:${t.accent}0d;font-weight:600;border-bottom:1px solid ${t.border};color:${t.accent};padding:12px}.reportic-report td{border-bottom:1px solid ${t.border};padding:11px 12px;vertical-align:top;overflow-wrap:anywhere}.reportic-report tr{break-inside:avoid}.reportic-report tr:nth-child(even) td{background:${t.accent}03}.reportic-report section{margin:20px 0}.reportic-report figure{margin:20px 0;break-inside:avoid}.reportic-report img{max-width:100%;height:auto}.reportic-report figcaption{font-size:12px;color:${t.muted};margin:10px 0}.reportic-report [data-reportic-type=logo]{margin:0 0 26px}.reportic-report [data-reportic-type=logo] img{max-width:${t.logoWidth}px;max-height:70px;object-fit:contain}.reportic-report .metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));border-top:1px solid ${t.border};border-bottom:1px solid ${t.border};padding:22px 0;gap:24px;margin:24px 0;break-inside:avoid}.reportic-report .metric-label{font-size:10px;letter-spacing:.09em;text-transform:uppercase;color:${t.muted};margin:0 0 8px}.reportic-report .metric-value{font-size:var(--metric-size,28px);white-space:nowrap;line-height:1.3;letter-spacing:-.04em;font-weight:600}.reportic-report .metric-comparison{font-size:11px;color:${t.accent};margin-top:7px}.reportic-report .callout{border:1px solid ${t.accent}25;border-left:3px solid ${t.accent};padding:16px 20px;border-radius:0 7px 7px 0;background:${t.accent}07;break-inside:avoid}.reportic-report .callout strong{font-size:14px}.reportic-report .callout p{margin:5px 0}.reportic-report .tone-warning{border-left-color:#bf8c3c;background:#c78a190a}.reportic-report .tone-danger{border-left-color:#bb5c53}.reportic-report .progress-item{margin:18px 0;break-inside:avoid}.reportic-report .progress-label{display:flex;justify-content:space-between;font-size:12px}.reportic-report .progress-track{height:7px;border-radius:5px;background:${t.border};margin:8px 0}.reportic-report .progress-track span{display:block;height:100%;background:${t.accent};border-radius:5px}.reportic-report .timeline-item{border-left:1px solid ${t.border};padding:0 0 22px 24px;position:relative;break-inside:avoid}.reportic-report .timeline-item:before{content:'';position:absolute;left:-5px;top:8px;width:9px;height:9px;border-radius:100%;background:${t.accent}}.reportic-report .timeline-date{font-size:11px;color:${t.muted}}.reportic-report .timeline-item p{margin:4px 0}.reportic-report .checklist{list-style:none;padding-left:0}.reportic-report .checklist li{margin:10px 0}.reportic-report .checkmark{color:${t.accent};margin-right:10px}.reportic-report .source-list{font-size:12px;color:${t.muted}}.reportic-report .diagram img{width:100%;max-height:400px;object-fit:contain}.reportic-report .chart img{width:100%}.reportic-report .chart-data{font-size:10px}.reportic-report .empty{color:${t.muted};font-style:italic}.reportic-report .evidence{font-size:10px;vertical-align:super;margin-left:4px}@media(max-width:600px){.reportic-report{padding:30px 22px}.reportic-report h1{font-size:34px}.reportic-report th,.reportic-report td{padding:7px;font-size:11px}}@page{size:A4;margin:17mm 15mm}@media print{.reportic-report{padding:0;max-width:none;font-size:10.5pt}.reportic-report h1{font-size:32pt}.reportic-report h2{font-size:20pt}.reportic-report .metrics{grid-template-columns:repeat(var(--metric-count,4),1fr)}a{text-decoration:none}.reportic-report figure img{max-height:90mm}.reportic-report .chart-data{font-size:8pt}}${feature}${rules}
|
|
184
2623
|
${options.css ?? report.css ?? ""}`;
|
|
185
2624
|
}
|
|
186
2625
|
function assetData(asset) {
|
|
@@ -188,26 +2627,44 @@ function assetData(asset) {
|
|
|
188
2627
|
}
|
|
189
2628
|
function cleanMarkdownHtml(markdown, report, options = {}) {
|
|
190
2629
|
const renderer = new marked.Renderer();
|
|
191
|
-
renderer.html = ({ text }) =>
|
|
192
|
-
renderer.image = ({ href, text }) => {
|
|
2630
|
+
renderer.html = ({ text: text2 }) => h3(text2);
|
|
2631
|
+
renderer.image = ({ href, text: text2 }) => {
|
|
193
2632
|
let src = href;
|
|
194
2633
|
if (/^https:\/\//.test(src)) {
|
|
195
2634
|
safeUrl(src, true);
|
|
196
|
-
if (!options.allowRemoteImages)
|
|
2635
|
+
if (!options.allowRemoteImages) fail4("REMOTE_ASSET_DENIED", "Remote Markdown images require an explicit image policy.");
|
|
197
2636
|
} else {
|
|
198
2637
|
safeRelative(src);
|
|
199
2638
|
const asset = report.assets.find((a) => a.path === src);
|
|
200
2639
|
if (asset) src = options.html?.assetMode === "bundled" ? asset.path : assetData(asset);
|
|
201
|
-
else
|
|
2640
|
+
else fail4("ASSET_MISSING", `Markdown image "${src}" needs a registered asset for portable export.`);
|
|
202
2641
|
}
|
|
203
|
-
return `<img src="${
|
|
2642
|
+
return `<img src="${h3(src)}" alt="${h3(text2)}">`;
|
|
204
2643
|
};
|
|
205
2644
|
return sanitizeHtml(marked.parse(markdown, { async: false, gfm: true, renderer }), { allowedTags: [...sanitizeHtml.defaults.allowedTags, "img", "del", "input"], allowedAttributes: { a: ["href", "title"], img: ["src", "alt"], th: ["align", "style"], td: ["align", "style"], input: ["type", "checked", "disabled"] }, allowedStyles: { "*": { "text-align": [/^left$/, /^right$/, /^center$/] } }, allowedSchemes: ["https", "http", "mailto"], allowedSchemesByTag: { img: ["data", "https"] }, allowProtocolRelative: false });
|
|
206
2645
|
}
|
|
207
|
-
var
|
|
2646
|
+
var codeHtml = (raw) => raw.length > 16 ? `<code class="rpt-long">${h3(raw).replace(/([_\-/.,])(?=\S)/g, "$1<wbr>")}</code>` : `<code>${h3(raw)}</code>`;
|
|
2647
|
+
var runHtml = (run) => {
|
|
2648
|
+
const text2 = h3(run.text).replace(/\n/g, "<br>");
|
|
2649
|
+
return run.tone ? `<span class="rpt-rating rpt-${h3(run.tone)}">${text2}</span>` : run.code ? codeHtml(String(run.text)) : run.strong ? `<strong>${text2}</strong>` : text2;
|
|
2650
|
+
};
|
|
2651
|
+
var cellInner = (cell) => {
|
|
2652
|
+
if (cell && typeof cell === "object") {
|
|
2653
|
+
if (cell.runs) return cell.runs.map(runHtml).join("");
|
|
2654
|
+
if (cell.kind === "rating" && cell.tone) return `<span class="rpt-rating rpt-${h3(cell.tone)}">${h3(cell.text)}</span>`;
|
|
2655
|
+
if (cell.kind === "status" && cell.text) return `<span class="rpt-chip rpt-status${cell.status ? ` rpt-${h3(cell.status)}` : ""}">${h3(cell.text)}</span>`;
|
|
2656
|
+
if (cell.kind === "date" && cell.text) return `<span class="rpt-chip rpt-date">${h3(cell.text)}</span>`;
|
|
2657
|
+
if (cell.kind === "code" && cell.text) return codeHtml(String(cell.text));
|
|
2658
|
+
}
|
|
2659
|
+
return h3(cell.text ?? cell);
|
|
2660
|
+
};
|
|
2661
|
+
var rawAttr = (cell) => cell && typeof cell === "object" && cell.text ? cell.kind === "date" && typeof cell.raw === "string" ? ` data-reportic-raw="${h3(cell.raw)}"` : cell.kind === "list" && Array.isArray(cell.raw) && cell.raw.length ? ` data-reportic-raw="${h3(JSON.stringify(cell.raw))}"` : "" : "";
|
|
2662
|
+
var kindAttr = (c) => `${c.kind ? ` data-reportic-kind="${h3(c.kind)}"` : ""}${c.format ? ` data-reportic-format="${h3(c.format)}"` : ""}`;
|
|
2663
|
+
var tableHtml = (columns, cells, className = "", options = {}) => `<table class="${className}">${options.headers === false ? "" : `<thead><tr>${columns.map((c) => `<th scope="col" style="text-align:${c.align ?? "left"}"${kindAttr(c)}>${h3(c.label)}</th>`).join("")}</tr></thead>`}<tbody>${cells.map((row) => `<tr${row[0]?.total ? ' class="rpt-total"' : ""}>${row.map((cell, i) => options.rowHeader && i === 0 ? `<th scope="row" class="rpt-rowheader" style="text-align:${columns[i].align ?? "left"}"${rawAttr(cell)}>${cellInner(cell)}</th>` : `<td style="text-align:${columns[i].align ?? "left"}${columns[i].nowrap ? ";white-space:nowrap" : ""}"${rawAttr(cell)}>${cellInner(cell)}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
|
|
2664
|
+
var stamp = (name, value) => ` data-reportic-${name}="${h3(typeof value === "string" ? value : JSON.stringify(value))}"`;
|
|
208
2665
|
function chartTable(node, report) {
|
|
209
2666
|
const p = node.props;
|
|
210
|
-
return { columns: [{ label: p.x.label }, ...p.series.map((s) => ({ label: s.label, align: "right" }))], cells: p.categories.map((c, i) => [c, ...p.series.map((s) =>
|
|
2667
|
+
return { columns: [{ label: p.x.label }, ...p.series.map((s) => ({ label: s.label, align: "right" }))], cells: p.categories.map((c, i) => [c, ...p.series.map((s) => formatValue3(s.values[i], s.format, report.locale, report.timezone))]) };
|
|
211
2668
|
}
|
|
212
2669
|
async function renderHtml(report, options = {}) {
|
|
213
2670
|
const diagrams = await diagramVisuals(report, options);
|
|
@@ -224,71 +2681,91 @@ async function renderHtml(report, options = {}) {
|
|
|
224
2681
|
};
|
|
225
2682
|
const render = (node) => {
|
|
226
2683
|
const p = node.props;
|
|
227
|
-
let content = "";
|
|
2684
|
+
let content = "", marks = "";
|
|
228
2685
|
switch (node.type) {
|
|
229
2686
|
case "markdown":
|
|
230
2687
|
return cleanMarkdownHtml(p.markdown, report, options);
|
|
231
2688
|
case "metrics":
|
|
232
|
-
content = `<div class="metrics" style="--metric-count:${Math.min(p.items.length, 4)}">${p.items.map((i) => `<div><p class="metric-label">${
|
|
2689
|
+
content = `<div class="metrics" style="--metric-count:${Math.min(p.items.length, 4)}">${p.items.map((i) => `<div${i.tone ? ` class="rpt-metric rpt-${h3(i.tone)}"` : ""}><p class="metric-label">${h3(i.label)}</p><div class="metric-value" style="--metric-size:${Math.min(28, Math.max(12, Math.floor(222 / Math.max(1, i.display.length))))}px">${h3(i.display)}</div>${i.comparison ? `<div class="metric-comparison">${h3(i.comparison)}</div>` : ""}</div>`).join("")}</div>`;
|
|
233
2690
|
break;
|
|
234
2691
|
case "table":
|
|
235
|
-
content = p.rows.length ? tableHtml(p.columns, p.cells) : `<p class="empty">${
|
|
2692
|
+
content = p.rows.length ? tableHtml(p.columns, p.cells, "", { headers: p.headers, rowHeader: p.rowHeader }) : `<p class="empty">${h3(p.empty ?? "No rows to display.")}</p>`;
|
|
236
2693
|
break;
|
|
237
2694
|
case "chart": {
|
|
238
2695
|
if (!p.categories.length) {
|
|
239
|
-
content = `<p class="empty">${
|
|
2696
|
+
content = `<p class="empty">${h3(p.empty ?? "No data to display.")}</p>`;
|
|
240
2697
|
break;
|
|
241
2698
|
}
|
|
242
2699
|
const data = chartTable(node, report);
|
|
243
|
-
|
|
2700
|
+
marks = stamp("kind", p.kind) + stamp("model", { title: p.title, alt: p.alt, x: { label: p.x.label }, categories: p.categories, series: p.series.map((s) => ({ label: s.label, ...s.format ? { format: s.format } : {}, values: s.values })) });
|
|
2701
|
+
content = `<figure class="chart"><h3>${h3(p.title)}</h3><img src="${image(node, chartSvg(node, report, options))}" alt="${h3(p.alt)}"/></figure>${tableHtml(data.columns, data.cells, "chart-data")}`;
|
|
244
2702
|
break;
|
|
245
2703
|
}
|
|
246
2704
|
case "diagram":
|
|
247
|
-
|
|
2705
|
+
marks = stamp("model", { ...p.adapter ? { adapter: p.adapter, model: p.model } : { source: p.source }, alt: p.alt, ...p.caption ? { caption: p.caption } : {} });
|
|
2706
|
+
content = `<figure class="diagram"><img src="${image(node, diagrams.get(node.occurrenceId))}" alt="${h3(p.alt)}"/><figcaption>${h3(p.caption ?? p.alt)}</figcaption></figure>`;
|
|
248
2707
|
break;
|
|
249
2708
|
case "logo":
|
|
250
2709
|
case "image":
|
|
251
|
-
content = `<figure><img src="${
|
|
2710
|
+
content = `<figure><img src="${h3(image(node))}" alt="${h3(p.alt)}"/>${p.caption ? `<figcaption>${h3(p.caption)}</figcaption>` : ""}</figure>`;
|
|
252
2711
|
break;
|
|
253
2712
|
case "narrative":
|
|
254
|
-
content = `${p.heading ? `<h3>${
|
|
2713
|
+
content = `${p.heading ? `<h3>${h3(p.heading)}</h3>` : ""}<p>${h3(p.text).replace(/\n/g, "<br>")}${(p.citations ?? []).map((n) => `<a class="evidence" href="#source-${n}">[${n}]</a>`).join("")}</p>`;
|
|
255
2714
|
break;
|
|
256
|
-
case "list":
|
|
257
|
-
|
|
2715
|
+
case "list": {
|
|
2716
|
+
const lead = (i) => p.leads?.[i] ? `<strong>${h3(p.leads[i])}</strong> ` : "";
|
|
2717
|
+
content = !p.items.length ? `<p class="empty">${h3(p.empty ?? "No items to display.")}</p>` : p.variant === "callout" ? `<aside class="callout rpt-clauses">${p.items.map((s, i) => `<p>${lead(i)}${h3(s)}</p>`).join("")}</aside>` : p.variant === "paragraphs" ? p.items.map((s, i) => `<p>${lead(i)}${h3(s)}</p>`).join("") : `<${p.ordered ? "ol" : "ul"}>${p.items.map((s, i) => `<li>${lead(i)}${h3(s)}</li>`).join("")}</${p.ordered ? "ol" : "ul"}>`;
|
|
258
2718
|
break;
|
|
2719
|
+
}
|
|
259
2720
|
case "sources":
|
|
260
|
-
content = `<ol class="source-list">${p.citations.map((s) => `<li id="source-${s.number}" value="${s.number}">${s.url ? `<a href="${
|
|
2721
|
+
content = `<ol class="source-list">${p.citations.map((s) => `<li id="source-${s.number}" value="${s.number}">${s.url ? `<a href="${h3(s.url)}">${h3(s.label)}</a>` : h3(s.label)}</li>`).join("")}</ol>`;
|
|
261
2722
|
break;
|
|
262
2723
|
case "group":
|
|
263
|
-
content = `${p.heading ? `<h2>${
|
|
2724
|
+
content = `${p.heading ? `<h2>${h3(p.heading)}</h2>` : ""}${(node.children ?? []).map(render).join("")}`;
|
|
264
2725
|
break;
|
|
265
2726
|
case "repeat":
|
|
266
|
-
content = node.children?.length ? node.children.map(render).join("") : `<p class="empty">${
|
|
2727
|
+
content = node.children?.length ? node.children.map(render).join("") : `<p class="empty">${h3(p.empty ?? "No items to display.")}</p>`;
|
|
267
2728
|
break;
|
|
268
2729
|
case "callout":
|
|
269
|
-
content = `<aside class="callout tone-${
|
|
2730
|
+
content = `<aside class="callout tone-${h3(p.tone ?? "info")}">${p.title === "" ? "" : `<strong>${h3(p.title)}</strong>`}<p>${h3(p.text)}</p></aside>`;
|
|
2731
|
+
break;
|
|
2732
|
+
case "masthead":
|
|
2733
|
+
if (p.byline?.length) marks = stamp("model", { byline: p.byline.map((i) => ({ value: i.value, ...i.format ? { format: i.format } : {}, ...i.kind ? { kind: i.kind } : {} })) });
|
|
2734
|
+
content = `<header class="rpt-masthead">${p.marking ? `<div class="rpt-marking">${h3(p.marking)}</div>` : ""}${p.kicker ? `<p class="rpt-kicker">${h3(p.kicker)}</p>` : ""}<h1>${h3(p.title)}</h1>${p.byline?.length ? `<p class="rpt-byline">${p.byline.map((i) => i.kind === "date" || i.kind === "person" ? `<span class="rpt-chip rpt-${i.kind}">${h3(i.display)}</span>` : h3(i.display)).join(" \xB7 ")}</p>` : ""}${p.lead ? `<p class="rpt-lead">${h3(p.lead)}</p>` : ""}</header>`;
|
|
2735
|
+
break;
|
|
2736
|
+
case "footer": {
|
|
2737
|
+
const logo = p.logoImage;
|
|
2738
|
+
const src = logo ? report.assets.find((a) => a.path === logo.src) ? options.html?.assetMode === "bundled" ? logo.src : assetData(report.assets.find((a) => a.path === logo.src)) : logo.src : "";
|
|
2739
|
+
content = `<footer class="rpt-footer">${logo ? `<img src="${h3(src)}" alt="${h3(logo.alt)}"/>` : ""}${h3(p.text)}</footer>`;
|
|
270
2740
|
break;
|
|
2741
|
+
}
|
|
2742
|
+
case "figure": {
|
|
2743
|
+
const svg = figureSvg(node, report, options);
|
|
2744
|
+
marks = stamp("kind", p.figure.kind) + stamp("spec", figureSpec2(p.figure));
|
|
2745
|
+
content = `<figure class="rpt-figure"><div class="rpt-figure-box"><img src="${image(node, svg)}" alt="${h3(p.alt)}"/></div>${p.source ? `<figcaption>${h3(p.source)}</figcaption>` : ""}</figure><div class="rpt-sr-only">${tableHtml(p.table.columns, p.table.cells)}</div>`;
|
|
2746
|
+
break;
|
|
2747
|
+
}
|
|
271
2748
|
case "progress":
|
|
272
|
-
content = p.items.map((i) => `<div class="progress-item"><div class="progress-label"><span>${
|
|
2749
|
+
content = p.items.map((i) => `<div class="progress-item"><div class="progress-label"><span>${h3(i.label)}</span><strong>${formatValue3(i.value, "percent:0", report.locale)}</strong></div><div class="progress-track" role="progressbar" aria-label="${h3(i.label)}" aria-valuenow="${i.value * 100}" aria-valuemin="0" aria-valuemax="100"><span style="width:${i.value * 100}%"></span></div>${i.detail ? `<small>${h3(i.detail)}</small>` : ""}</div>`).join("");
|
|
273
2750
|
break;
|
|
274
2751
|
case "timeline":
|
|
275
|
-
content = p.items.map((i) => `<div class="timeline-item"><div class="timeline-date">${
|
|
2752
|
+
content = p.items.map((i) => `<div class="timeline-item"><div class="timeline-date">${h3(i.date)}</div><strong>${h3(i.title)}</strong>${i.text ? `<p>${h3(i.text)}</p>` : ""}</div>`).join("");
|
|
276
2753
|
break;
|
|
277
2754
|
case "comparison":
|
|
278
2755
|
content = tableHtml([{ label: "", align: "left" }, ...p.labels.map((s) => ({ label: s }))], p.rows.map((r) => [r.label, r.left, r.right]));
|
|
279
2756
|
break;
|
|
280
2757
|
case "checklist":
|
|
281
|
-
content = `<ul class="checklist">${p.items.map((i) => `<li><span class="checkmark">${i.done ? "\u2611" : "\u2610"}</span>${
|
|
2758
|
+
content = `<ul class="checklist">${p.items.map((i) => `<li><span class="checkmark">${i.done ? "\u2611" : "\u2610"}</span>${h3(i.text)}${i.owner ? ` <small>\xB7 ${h3(i.owner)}</small>` : ""}</li>`).join("")}</ul>`;
|
|
282
2759
|
break;
|
|
283
2760
|
case "code":
|
|
284
|
-
content = `${p.language ? `<small>${
|
|
2761
|
+
content = `${p.language ? `<small>${h3(p.language)}</small>` : ""}<pre><code>${h3(p.code)}</code></pre>${p.caption ? `<p>${h3(p.caption)}</p>` : ""}`;
|
|
285
2762
|
break;
|
|
286
2763
|
default:
|
|
287
|
-
|
|
2764
|
+
fail4("RENDERER_UNAVAILABLE", `No HTML representation for semantic type ${node.type}.`, { elementId: node.id, phase: "render" });
|
|
288
2765
|
}
|
|
289
|
-
return `<section data-reportic-type="${
|
|
2766
|
+
return `<section data-reportic-type="${h3(node.type)}" data-reportic-id="${h3(node.id)}" data-reportic-occurrence="${h3(node.occurrenceId)}"${marks}>${content}</section>`;
|
|
290
2767
|
};
|
|
291
|
-
const html = `<!doctype html><html lang="${
|
|
2768
|
+
const html = `<!doctype html><html lang="${h3(report.locale)}"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="generator" content="Reportic 0.2"><title>${h3(report.title)}</title><style>${reportCss(report, options)}</style></head><body><main class="reportic-report">${report.nodes.map(render).join("\n")}</main></body></html>`;
|
|
292
2769
|
return { html, assets: [...report.assets, ...generated] };
|
|
293
2770
|
}
|
|
294
2771
|
async function renderMarkdown(report, options = {}) {
|
|
@@ -344,8 +2821,25 @@ ${md(p.caption)}` : ""}`;
|
|
|
344
2821
|
` : ""}${md(p.text)}${(p.citations ?? []).map((n2) => ` [${n2}]`).join("")}`;
|
|
345
2822
|
case "sources":
|
|
346
2823
|
return p.citations.map((s) => `${s.number}. ${s.url ? `[${md(s.label)}](${s.url})` : md(s.label)}`).join("\n");
|
|
347
|
-
case "list":
|
|
348
|
-
|
|
2824
|
+
case "list": {
|
|
2825
|
+
const lead = (i) => p.leads?.[i] ? `**${md(p.leads[i])}** ` : "";
|
|
2826
|
+
return p.items.length ? p.items.map((s, i) => p.variant === "callout" ? `> ${lead(i)}${md(s)}` : p.variant === "paragraphs" ? `${lead(i)}${md(s)}` : `${p.ordered ? i + 1 + "." : "-"} ${lead(i)}${md(s)}`).join(p.variant === "callout" ? "\n>\n" : p.variant === "paragraphs" ? "\n\n" : "\n") : md(p.empty ?? "No items to display.");
|
|
2827
|
+
}
|
|
2828
|
+
case "masthead":
|
|
2829
|
+
return [p.marking ? `**${md(p.marking)}**` : "", p.kicker ? md(p.kicker) : "", `# ${md(p.title)}`, p.byline?.length ? p.byline.map((i) => md(i.display)).join(" \xB7 ") : "", p.lead ? md(p.lead) : ""].filter(Boolean).join("\n\n");
|
|
2830
|
+
case "footer":
|
|
2831
|
+
return `---
|
|
2832
|
+
|
|
2833
|
+
${md(p.text)}`;
|
|
2834
|
+
case "figure": {
|
|
2835
|
+
const path = `assets/${n.occurrenceId}.svg`;
|
|
2836
|
+
assets.push({ path, mediaType: "image/svg+xml", bytes: Buffer.from(figureSvg(n, report, options)) });
|
|
2837
|
+
return `${p.source ? `
|
|
2838
|
+
|
|
2839
|
+
Source: ${md(p.source)}` : ""}
|
|
2840
|
+
|
|
2841
|
+
${table(p.table.columns, p.table.cells)}`;
|
|
2842
|
+
}
|
|
349
2843
|
case "group":
|
|
350
2844
|
return `${p.heading ? `## ${md(p.heading)}
|
|
351
2845
|
|
|
@@ -357,7 +2851,7 @@ ${md(p.caption)}` : ""}`;
|
|
|
357
2851
|
>
|
|
358
2852
|
> ${md(p.text)}`;
|
|
359
2853
|
case "progress":
|
|
360
|
-
return p.items.map((i) => `- **${md(i.label)}:** ${
|
|
2854
|
+
return p.items.map((i) => `- **${md(i.label)}:** ${formatValue3(i.value, "percent:0", report.locale)}${i.detail ? " \u2014 " + md(i.detail) : ""}`).join("\n");
|
|
361
2855
|
case "timeline":
|
|
362
2856
|
return p.items.map((i) => `- **${md(i.date)} \xB7 ${md(i.title)}**${i.text ? " \u2014 " + md(i.text) : ""}`).join("\n");
|
|
363
2857
|
case "comparison":
|
|
@@ -371,7 +2865,7 @@ ${p.code}
|
|
|
371
2865
|
${ticks}`;
|
|
372
2866
|
}
|
|
373
2867
|
default:
|
|
374
|
-
return
|
|
2868
|
+
return fail4("RENDERER_UNAVAILABLE", `No Markdown representation for ${n.type}.`);
|
|
375
2869
|
}
|
|
376
2870
|
};
|
|
377
2871
|
let markdown = "";
|
|
@@ -386,12 +2880,16 @@ ${ticks}`;
|
|
|
386
2880
|
return { markdown: markdown + (markdown.endsWith("\n") ? "" : "\n"), assets };
|
|
387
2881
|
}
|
|
388
2882
|
export {
|
|
2883
|
+
IMPORT_GUIDE,
|
|
389
2884
|
assetData,
|
|
390
2885
|
chartSvg,
|
|
391
2886
|
chartTable,
|
|
392
2887
|
cleanMarkdownHtml,
|
|
393
2888
|
diagramVisuals,
|
|
2889
|
+
figureSvg,
|
|
394
2890
|
findBrowser,
|
|
2891
|
+
guideFor,
|
|
2892
|
+
importHtml,
|
|
395
2893
|
renderHtml,
|
|
396
2894
|
renderMarkdown,
|
|
397
2895
|
reportCss,
|