@veroxm/react-sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +295 -2
  4. package/dist/cache.d.ts +69 -0
  5. package/dist/cache.js +89 -0
  6. package/dist/client-slots.d.ts +35 -0
  7. package/dist/client-slots.js +169 -0
  8. package/dist/client.d.ts +65 -0
  9. package/dist/client.js +87 -0
  10. package/dist/editor/constants.d.ts +12 -0
  11. package/dist/editor/constants.js +12 -0
  12. package/dist/editor/handler.d.ts +16 -0
  13. package/dist/editor/handler.js +175 -0
  14. package/dist/editor/inline.d.ts +25 -0
  15. package/dist/editor/inline.js +149 -0
  16. package/dist/editor/menu-input.d.ts +26 -0
  17. package/dist/editor/menu-input.js +110 -0
  18. package/dist/editor/overlay.d.ts +31 -0
  19. package/dist/editor/overlay.js +856 -0
  20. package/dist/editor/rich-text.d.ts +21 -0
  21. package/dist/editor/rich-text.js +232 -0
  22. package/dist/editor/server.d.ts +9 -0
  23. package/dist/editor/server.js +43 -0
  24. package/dist/errors.d.ts +20 -0
  25. package/dist/errors.js +26 -0
  26. package/dist/hooks/use-cached-query.d.ts +21 -0
  27. package/dist/hooks/use-cached-query.js +59 -0
  28. package/dist/hooks/use-collection.d.ts +10 -0
  29. package/dist/hooks/use-collection.js +14 -0
  30. package/dist/hooks/use-entries.d.ts +18 -0
  31. package/dist/hooks/use-entries.js +25 -0
  32. package/dist/hooks/use-entry.d.ts +21 -0
  33. package/dist/hooks/use-entry.js +22 -0
  34. package/dist/hooks/use-media.d.ts +9 -0
  35. package/dist/hooks/use-media.js +13 -0
  36. package/dist/hydration-boundary.d.ts +35 -0
  37. package/dist/hydration-boundary.js +38 -0
  38. package/dist/image.d.ts +34 -0
  39. package/dist/image.js +39 -0
  40. package/dist/index.d.ts +46 -0
  41. package/dist/index.js +32 -0
  42. package/dist/next/cache-components.d.ts +15 -0
  43. package/dist/next/cache-components.js +25 -0
  44. package/dist/next/cached.d.ts +9 -0
  45. package/dist/next/cached.js +20 -0
  46. package/dist/next/edge-slot.d.ts +21 -0
  47. package/dist/next/edge-slot.js +29 -0
  48. package/dist/next/editor.d.ts +7 -0
  49. package/dist/next/editor.js +13 -0
  50. package/dist/next/index.d.ts +17 -0
  51. package/dist/next/index.js +21 -0
  52. package/dist/next/llms.d.ts +2 -0
  53. package/dist/next/llms.js +44 -0
  54. package/dist/next/route.d.ts +12 -0
  55. package/dist/next/route.js +16 -0
  56. package/dist/next/slot.d.ts +21 -0
  57. package/dist/next/slot.js +160 -0
  58. package/dist/node.d.ts +43 -0
  59. package/dist/node.js +67 -0
  60. package/dist/preview.d.ts +35 -0
  61. package/dist/preview.js +46 -0
  62. package/dist/provider.d.ts +29 -0
  63. package/dist/provider.js +37 -0
  64. package/dist/query-keys.d.ts +19 -0
  65. package/dist/query-keys.js +49 -0
  66. package/dist/site/chart-view.d.ts +14 -0
  67. package/dist/site/chart-view.js +44 -0
  68. package/dist/site/chart.d.ts +127 -0
  69. package/dist/site/chart.js +639 -0
  70. package/dist/site/map-embed.d.ts +32 -0
  71. package/dist/site/map-embed.js +139 -0
  72. package/dist/site/map-math.d.ts +27 -0
  73. package/dist/site/map-math.js +89 -0
  74. package/dist/site/nav-menu.d.ts +19 -0
  75. package/dist/site/nav-menu.js +76 -0
  76. package/dist/site/site-parts.d.ts +87 -0
  77. package/dist/site/site-parts.js +46 -0
  78. package/dist/site/slider.d.ts +17 -0
  79. package/dist/site/slider.js +78 -0
  80. package/dist/site/styles.d.ts +3 -0
  81. package/dist/site/styles.js +155 -0
  82. package/dist/site/video-embed.d.ts +15 -0
  83. package/dist/site/video-embed.js +27 -0
  84. package/dist/site/video.d.ts +18 -0
  85. package/dist/site/video.js +73 -0
  86. package/dist/slots-core.d.ts +397 -0
  87. package/dist/slots-core.js +367 -0
  88. package/dist/slots.d.ts +13 -0
  89. package/dist/slots.js +30 -0
  90. package/dist/ssr.d.ts +20 -0
  91. package/dist/ssr.js +35 -0
  92. package/dist/structured-data.d.ts +13 -0
  93. package/dist/structured-data.js +36 -0
  94. package/dist/tracking.d.ts +142 -0
  95. package/dist/tracking.js +152 -0
  96. package/dist/types.d.ts +106 -0
  97. package/dist/types.js +6 -0
  98. package/package.json +95 -4
@@ -0,0 +1,639 @@
1
+ // A copy of the chart section of @mycms/shared-types (this package cannot
2
+ // depend on it); keep the two in step.
3
+ // ---------------------------------------------------------------- charts
4
+ // A chart a marketer edits: its kind, its numbers (typed in, read from the
5
+ // customer's own systems, or from VeroXM's analytics), and how numbers are
6
+ // written. chartSvg() draws it as SVG markup with no library, used by the
7
+ // React SDK's <Chart>, the dashboard's preview and the docs. Kept in step
8
+ // with @veroxm/react-sdk's copy (packages/sdk-react/src/site/chart.ts).
9
+ export const CHART_KINDS = ["bar", "hbar", "line", "area", "pie", "donut", "kpi"];
10
+ export const ANALYTICS_METRICS = ["visitors", "pageviews", "event", "top_pages"];
11
+ export const ANALYTICS_DAYS = [7, 30, 90];
12
+ export const ROW_OPS = ["value", "sum", "count", "average"];
13
+ export const MAX_CHART_LABELS = 60;
14
+ export const MAX_CHART_SERIES = 6;
15
+ export const MAX_PIE_SLICES = 6;
16
+ const DATA_KEY = /^[a-z0-9][a-z0-9_.-]{0,63}$/;
17
+ const isNum = (v) => typeof v === "number" && Number.isFinite(v);
18
+ const str = (v, max) => (typeof v === "string" ? v.trim().slice(0, max) : "");
19
+ const FIELD_PATH = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,79}$/;
20
+ function checkRowsSpec(src, problems) {
21
+ const label = str(src.label, 80);
22
+ if (!FIELD_PATH.test(label))
23
+ problems.push("choose the field that holds each label");
24
+ const list = Array.isArray(src.series) ? src.series : [];
25
+ if (!list.length)
26
+ problems.push("choose at least one field to chart");
27
+ if (list.length > MAX_CHART_SERIES)
28
+ problems.push(`${MAX_CHART_SERIES} series at most`);
29
+ const groupBy = src.groupBy === true;
30
+ const series = list.slice(0, MAX_CHART_SERIES).map((s, i) => {
31
+ const e = (s ?? {});
32
+ const op = ROW_OPS.includes(e.op) ? e.op : groupBy ? "sum" : "value";
33
+ const field = str(e.field, 80);
34
+ if (op !== "count" && !FIELD_PATH.test(field))
35
+ problems.push(`series ${i + 1} needs a field with numbers`);
36
+ if (!groupBy && op !== "value")
37
+ problems.push(`series ${i + 1}: sum, count and average need "group by label"`);
38
+ return { name: str(e.name, 40) || field || `Series ${i + 1}`, field, ...(op !== "value" ? { op } : {}) };
39
+ });
40
+ const limit = src.limit === undefined || src.limit === null || src.limit === "" ? undefined : Number(src.limit);
41
+ if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > MAX_CHART_LABELS))
42
+ problems.push(`keep 1 to ${MAX_CHART_LABELS} rows`);
43
+ return { label, series, ...(groupBy ? { groupBy } : {}), ...(limit !== undefined ? { limit } : {}) };
44
+ }
45
+ /** A value inside a row by dot path ("price.amount"). */
46
+ function fieldAt(row, path) {
47
+ let cur = row;
48
+ for (const part of path.split(".")) {
49
+ if (cur === null || typeof cur !== "object")
50
+ return undefined;
51
+ cur = cur[part];
52
+ }
53
+ return cur;
54
+ }
55
+ /** A number from a row's value: numbers, numeric text, a currency value ({ amount }) or true/false. */
56
+ function rowNumber(v) {
57
+ if (typeof v === "number")
58
+ return Number.isFinite(v) ? v : null;
59
+ if (typeof v === "string" && v.trim() !== "") {
60
+ const n = Number(v.replace(/[,\s]/g, ""));
61
+ return Number.isFinite(n) ? n : null;
62
+ }
63
+ if (typeof v === "boolean")
64
+ return v ? 1 : 0;
65
+ if (v && typeof v === "object" && "amount" in v)
66
+ return rowNumber(v.amount);
67
+ return null;
68
+ }
69
+ /** Labels and series from rows: collection entries, objects from an API, or anything a developer fetched. */
70
+ export function chartDataFromRows(rows, spec) {
71
+ const max = Math.min(spec.limit ?? MAX_CHART_LABELS, MAX_CHART_LABELS);
72
+ const labelOf = (r) => {
73
+ const v = fieldAt(r, spec.label);
74
+ return v === null || v === undefined ? "" : String(typeof v === "object" ? JSON.stringify(v) : v).slice(0, 40);
75
+ };
76
+ if (!spec.groupBy) {
77
+ const kept = rows.slice(0, max);
78
+ return { labels: kept.map(labelOf), series: spec.series.map((s) => ({ name: s.name, values: kept.map((r) => rowNumber(fieldAt(r, s.field))) })) };
79
+ }
80
+ const groups = new Map();
81
+ for (const r of rows) {
82
+ const l = labelOf(r);
83
+ groups.set(l, [...(groups.get(l) ?? []), r]);
84
+ }
85
+ const labels = [...groups.keys()].slice(0, max);
86
+ const series = spec.series.map((s) => ({
87
+ name: s.name,
88
+ values: labels.map((l) => {
89
+ const members = groups.get(l);
90
+ if (s.op === "count")
91
+ return members.length;
92
+ const nums = members.map((r) => rowNumber(fieldAt(r, s.field))).filter(isNum);
93
+ if (!nums.length)
94
+ return null;
95
+ const sum = nums.reduce((a, b) => a + b, 0);
96
+ return s.op === "average" ? sum / nums.length : sum;
97
+ }),
98
+ }));
99
+ return { labels, series };
100
+ }
101
+ /** A chart from rows a developer already has (from any API): `chartFromRows(orders, { kind: "bar", label: "month", series: [{ name: "Revenue", field: "total" }] })`. */
102
+ export function chartFromRows(rows, spec) {
103
+ const { labels, series } = chartDataFromRows(rows, spec);
104
+ return { kind: spec.kind, ...(spec.title ? { title: spec.title } : {}), ...(spec.caption ? { caption: spec.caption } : {}), ...(spec.format ? { format: spec.format } : {}), ...(spec.target !== undefined ? { target: spec.target } : {}), labels, series, source: { type: "manual" } };
105
+ }
106
+ /** A chart's value checked and cleaned; problems say what to fix. `forPublish` also refuses sample numbers and empty manual charts. */
107
+ export function checkChart(raw, forPublish = true) {
108
+ const o = (raw ?? {});
109
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
110
+ return { value: null, problems: ["must be a chart"] };
111
+ const problems = [];
112
+ const kind = o.kind;
113
+ if (!CHART_KINDS.includes(kind))
114
+ problems.push(`the kind must be one of ${CHART_KINDS.join(", ")}`);
115
+ if (typeof o.title === "string" && o.title.trim().length > 120)
116
+ problems.push("the title is longer than 120 characters");
117
+ if (typeof o.caption === "string" && o.caption.trim().length > 300)
118
+ problems.push("the caption is longer than 300 characters");
119
+ const src = (o.source ?? { type: "manual" });
120
+ let source = { type: "manual" };
121
+ if (src.type === "connected") {
122
+ const list = Array.isArray(src.series) ? src.series : [];
123
+ if (!list.length)
124
+ problems.push("choose at least one value from your systems");
125
+ if (list.length > MAX_CHART_SERIES)
126
+ problems.push(`${MAX_CHART_SERIES} series at most`);
127
+ const series = list.slice(0, MAX_CHART_SERIES).map((s, i) => {
128
+ const e = (s ?? {});
129
+ const key = str(e.key, 64).replace(/^data\./, "");
130
+ if (!DATA_KEY.test(key))
131
+ problems.push(`series ${i + 1} needs a value key from Connected APIs (such as sales.monthly)`);
132
+ return { name: str(e.name, 40) || key, key };
133
+ });
134
+ const labelsKey = str(src.labelsKey, 64).replace(/^data\./, "");
135
+ if (labelsKey && !DATA_KEY.test(labelsKey))
136
+ problems.push("the labels key isn't a value key from Connected APIs");
137
+ source = { type: "connected", series, ...(labelsKey ? { labelsKey } : {}) };
138
+ }
139
+ else if (src.type === "analytics") {
140
+ const metric = src.metric;
141
+ const days = Number(src.days);
142
+ if (!ANALYTICS_METRICS.includes(metric))
143
+ problems.push(`the analytics measure must be one of ${ANALYTICS_METRICS.join(", ")}`);
144
+ if (!ANALYTICS_DAYS.includes(days))
145
+ problems.push("the period must be 7, 30 or 90 days");
146
+ const event = str(src.event, 100);
147
+ if (metric === "event" && !event)
148
+ problems.push("name the event to count (such as signup)");
149
+ source = { type: "analytics", metric, days, ...(metric === "event" ? { event } : {}) };
150
+ }
151
+ else if (src.type === "content" || src.type === "api") {
152
+ const rows = checkRowsSpec(src, problems);
153
+ if (src.type === "content") {
154
+ const collection = str(src.collection, 120);
155
+ if (!/^[a-z0-9][a-z0-9_-]{0,119}$/i.test(collection))
156
+ problems.push("choose a collection");
157
+ const sort = str(src.sort, 80);
158
+ if (sort && !/^[A-Za-z0-9_.]+:(asc|desc)$/.test(sort))
159
+ problems.push('the sort must look like "field:asc" or "field:desc"');
160
+ source = { type: "content", collection, ...(sort ? { sort } : {}), ...rows };
161
+ }
162
+ else {
163
+ const key = str(src.key, 64).replace(/^data\./, "");
164
+ if (!DATA_KEY.test(key))
165
+ problems.push("choose a value from Connected APIs that returns a list of rows");
166
+ source = { type: "api", key, ...rows };
167
+ }
168
+ }
169
+ else if (src.type !== undefined && src.type !== "manual")
170
+ problems.push("the source must be manual, content, api, connected or analytics");
171
+ let labels = (Array.isArray(o.labels) ? o.labels : []).map((l) => (typeof l === "string" || typeof l === "number" ? String(l).trim().slice(0, 40) : ""));
172
+ let series = [];
173
+ if (source.type === "manual") {
174
+ if (labels.length > MAX_CHART_LABELS)
175
+ problems.push(`${MAX_CHART_LABELS} labels at most`);
176
+ labels = labels.slice(0, MAX_CHART_LABELS);
177
+ const rawSeries = Array.isArray(o.series) ? o.series : [];
178
+ if (rawSeries.length > MAX_CHART_SERIES)
179
+ problems.push(`${MAX_CHART_SERIES} series at most`);
180
+ series = rawSeries.slice(0, MAX_CHART_SERIES).map((s, i) => {
181
+ const e = (s ?? {});
182
+ const values = (Array.isArray(e.values) ? e.values : []).slice(0, labels.length).map((v) => {
183
+ if (v === null || v === undefined || v === "")
184
+ return null;
185
+ const n = typeof v === "number" ? v : Number(String(v).replace(/[,\s]/g, ""));
186
+ if (!Number.isFinite(n)) {
187
+ problems.push(`series ${i + 1}: "${String(v).slice(0, 20)}" isn't a number`);
188
+ return null;
189
+ }
190
+ return n;
191
+ });
192
+ while (values.length < labels.length)
193
+ values.push(null);
194
+ return { name: str(e.name, 40) || `Series ${i + 1}`, values };
195
+ });
196
+ if ((kind === "pie" || kind === "donut") && series.some((s) => s.values.some((v) => isNum(v) && v < 0)))
197
+ problems.push("a pie can't show negative numbers");
198
+ if (forPublish && !series.some((s) => s.values.some(isNum)))
199
+ problems.push("type at least one number");
200
+ }
201
+ const f = (o.format ?? {});
202
+ const decimals = f.decimals === undefined || f.decimals === "" || f.decimals === null ? undefined : Number(f.decimals);
203
+ if (decimals !== undefined && (!Number.isInteger(decimals) || decimals < 0 || decimals > 4))
204
+ problems.push("decimals must be 0 to 4");
205
+ // Prefix and suffix keep their spaces ("SAR " or " SAR").
206
+ const affix = (v, max) => (typeof v === "string" && v.trim() ? v.slice(0, max) : "");
207
+ const format = { ...(affix(f.prefix, 8) ? { prefix: affix(f.prefix, 8) } : {}), ...(affix(f.suffix, 12) ? { suffix: affix(f.suffix, 12) } : {}), ...(decimals !== undefined ? { decimals } : {}) };
208
+ let target;
209
+ if (o.target !== undefined && o.target !== null && o.target !== "") {
210
+ target = Number(o.target);
211
+ if (!Number.isFinite(target))
212
+ problems.push("the target must be a number");
213
+ }
214
+ const sample = o.sample === true;
215
+ if (forPublish && sample)
216
+ problems.push("still shows the template's sample numbers: put in your own before publishing");
217
+ const value = {
218
+ kind: CHART_KINDS.includes(kind) ? kind : "bar",
219
+ ...(str(o.title, 120) ? { title: str(o.title, 120) } : {}),
220
+ ...(str(o.caption, 300) ? { caption: str(o.caption, 300) } : {}),
221
+ labels: source.type === "manual" ? labels : source.type === "connected" && !source.labelsKey ? labels.slice(0, MAX_CHART_LABELS) : [],
222
+ series,
223
+ ...(Object.keys(format).length ? { format } : {}),
224
+ ...(target !== undefined && Number.isFinite(target) ? { target } : {}),
225
+ source,
226
+ ...(str(o.template, 40) ? { template: str(o.template, 40) } : {}),
227
+ ...(sample ? { sample: true } : {}),
228
+ };
229
+ return { value, problems };
230
+ }
231
+ /** A number as the chart writes it: the chart's prefix, suffix and decimals, in the reader's locale. */
232
+ export function formatChartNumber(v, format = {}, opts = {}) {
233
+ if (!isNum(v))
234
+ return "–";
235
+ const nf = new Intl.NumberFormat(opts.locale, {
236
+ maximumFractionDigits: format.decimals ?? (opts.compact ? 1 : Math.abs(v) < 10 ? 2 : 0),
237
+ minimumFractionDigits: opts.compact ? 0 : (format.decimals ?? 0),
238
+ ...(opts.compact && Math.abs(v) >= 10000 ? { notation: "compact" } : {}),
239
+ });
240
+ return `${format.prefix ?? ""}${nf.format(v)}${format.suffix ?? ""}`;
241
+ }
242
+ /** One sentence describing the chart, for screen readers. */
243
+ export function chartSummary(c, locale) {
244
+ const kind = { bar: "Column chart", hbar: "Bar chart", line: "Line chart", area: "Area chart", pie: "Pie chart", donut: "Donut chart", kpi: "Key figure" }[c.kind];
245
+ const s = c.series[0];
246
+ const nums = (s?.values ?? []).map((v, i) => ({ v, l: c.labels[i] ?? "" })).filter((x) => isNum(x.v));
247
+ if (!s || !nums.length)
248
+ return `${kind}${c.title ? `, ${c.title}` : ""}: no numbers yet.`;
249
+ const fmt = (v) => formatChartNumber(v, c.format, { locale });
250
+ if (c.kind === "kpi") {
251
+ const last = nums[nums.length - 1];
252
+ return `${c.title || s.name}: ${fmt(last.v)}${last.l ? ` (${last.l})` : ""}${isNum(c.target) ? `, target ${fmt(c.target)}` : ""}.`;
253
+ }
254
+ const hi = nums.reduce((a, b) => (b.v > a.v ? b : a));
255
+ const lo = nums.reduce((a, b) => (b.v < a.v ? b : a));
256
+ const span = c.labels.length > 1 ? ` from ${c.labels[0]} to ${c.labels[c.labels.length - 1]}` : "";
257
+ const more = c.series.length > 1 ? `, ${c.series.length} series (${c.series.map((x) => x.name).join(", ")})` : "";
258
+ return `${kind}${c.title ? `, ${c.title}` : ""}: ${c.labels.length} points${span}${more}. ${s.name} is highest at ${hi.l} (${fmt(hi.v)}) and lowest at ${lo.l} (${fmt(lo.v)}).`;
259
+ }
260
+ // ------------------------------------------------------------ drawing
261
+ const PALETTE = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300"];
262
+ const INK = { ink: "#0b0b0b", ink2: "#52514e", muted: "#898781", grid: "#e1e0d9", axis: "#c3c2b7", surface: "#fcfcfb", good: "#006300", bad: "#d03b3b" };
263
+ const fill = (i) => `fill:var(--vxc-${i + 1},${PALETTE[i % PALETTE.length]})`;
264
+ const stroke = (i) => `stroke:var(--vxc-${i + 1},${PALETTE[i % PALETTE.length]})`;
265
+ const ink = (k) => `var(--vxc-${k},${INK[k]})`;
266
+ const esc = (s) => s.replace(/[&<>"']/g, (ch) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[ch]);
267
+ const r1 = (v) => Math.round(v * 10) / 10;
268
+ const textW = (s, size = 12) => s.length * size * 0.56;
269
+ const lastOf = (a) => a[a.length - 1];
270
+ const clip = (s, max) => (s.length > max ? `${s.slice(0, max - 1)}…` : s);
271
+ function niceTicks(min, max, count = 4) {
272
+ if (min === max)
273
+ max = min + 1;
274
+ const raw = (max - min) / count;
275
+ const mag = 10 ** Math.floor(Math.log10(raw));
276
+ const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? raw;
277
+ const out = [];
278
+ for (let v = Math.floor(min / step) * step; v <= max + step * 0.001; v += step)
279
+ out.push(Math.round(v / step) * step);
280
+ if (out[out.length - 1] < max)
281
+ out.push(out[out.length - 1] + step);
282
+ return out;
283
+ }
284
+ /** A bar with a 4px rounded data end and a square end at the baseline. */
285
+ function barPath(x, y0, w, y1, horizontal = false) {
286
+ if (horizontal) {
287
+ const [a, b] = [y0, y1]; // x positions along the bar
288
+ const len = Math.abs(b - a);
289
+ const r = Math.min(4, len, w / 2);
290
+ const dir = b >= a ? 1 : -1;
291
+ const end = b;
292
+ return `M${r1(a)},${r1(x)}H${r1(end - dir * r)}Q${r1(end)},${r1(x)} ${r1(end)},${r1(x + r)}V${r1(x + w - r)}Q${r1(end)},${r1(x + w)} ${r1(end - dir * r)},${r1(x + w)}H${r1(a)}Z`;
293
+ }
294
+ const h = Math.abs(y1 - y0);
295
+ const r = Math.min(4, h, w / 2);
296
+ const up = y1 <= y0;
297
+ const d = up ? 1 : -1;
298
+ return `M${r1(x)},${r1(y0)}V${r1(y1 + d * r)}Q${r1(x)},${r1(y1)} ${r1(x + r)},${r1(y1)}H${r1(x + w - r)}Q${r1(x + w)},${r1(y1)} ${r1(x + w)},${r1(y1 + d * r)}V${r1(y0)}Z`;
299
+ }
300
+ function legend(series, x, y, width) {
301
+ if (series.length < 2)
302
+ return { svg: "", height: 0 };
303
+ let cx = x;
304
+ let cy = y;
305
+ const parts = [];
306
+ series.forEach((s, i) => {
307
+ const w = 14 + textW(s.name) + 16;
308
+ if (cx + w > x + width && cx > x) {
309
+ cx = x;
310
+ cy += 18;
311
+ }
312
+ parts.push(`<rect x="${r1(cx)}" y="${r1(cy - 8)}" width="10" height="10" rx="2" style="${fill(i)}"/><text x="${r1(cx + 14)}" y="${r1(cy + 1)}" style="fill:${ink("ink2")}">${esc(s.name)}</text>`);
313
+ cx += w;
314
+ });
315
+ return { svg: `<g class="vxc-legend">${parts.join("")}</g>`, height: cy - y + 22 };
316
+ }
317
+ /** The chart as SVG markup (empty when there is nothing to draw). Marks carry data-x so a page can show a tooltip on hover. */
318
+ export function chartSvg(c, { width, height, locale }) {
319
+ const series = c.series.filter((s) => s.values.some(isNum));
320
+ if (!series.length || width < 120 || height < 80)
321
+ return "";
322
+ const fmt = (v, compact = false) => formatChartNumber(v, c.format, { compact, locale });
323
+ const open = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}" font-family="system-ui,-apple-system,'Segoe UI',sans-serif" font-size="12" class="vxc-svg vxc-${c.kind}">`;
324
+ if (c.kind === "kpi")
325
+ return open + kpiBody(c, series[0], width, height, fmt) + "</svg>";
326
+ if (c.kind === "pie" || c.kind === "donut")
327
+ return open + pieBody(c, series[0], width, height, fmt) + "</svg>";
328
+ const leg = legend(series, 8, 14, width - 16);
329
+ const top = 12 + leg.height;
330
+ const all = series.flatMap((s) => s.values.filter(isNum));
331
+ if (isNum(c.target))
332
+ all.push(c.target);
333
+ // Bars and areas start at zero; a line whose numbers sit far from zero may zoom in on them.
334
+ const dataMin = Math.min(...all);
335
+ const dataMax = Math.max(...all);
336
+ const zoomIn = c.kind === "line" && dataMin > 0 && dataMin > dataMax * 0.5;
337
+ const ticks = zoomIn ? niceTicks(dataMin - (dataMax - dataMin) * 0.25, dataMax) : niceTicks(Math.min(0, dataMin), Math.max(0, dataMax));
338
+ const lo = ticks[0];
339
+ const hi = ticks[ticks.length - 1];
340
+ const n = c.labels.length || Math.max(...series.map((s) => s.values.length));
341
+ const label = (i) => c.labels[i] ?? String(i + 1);
342
+ if (c.kind === "hbar") {
343
+ const labelW = Math.min(width * 0.38, Math.max(...Array.from({ length: n }, (_, i) => textW(clip(label(i), 24)))) + 12);
344
+ const left = labelW + 8;
345
+ const right = width - 16 - textW(fmt(Math.max(...all))) - 6;
346
+ const bottom = height - 8;
347
+ const band = (bottom - top) / n;
348
+ const k = series.length;
349
+ const bw = Math.min(24, (band * 0.72 - (k - 1) * 2) / k);
350
+ const xs = (v) => left + ((v - lo) / (hi - lo || 1)) * (right - left);
351
+ const parts = [];
352
+ for (const t of ticks)
353
+ parts.push(`<line x1="${r1(xs(t))}" x2="${r1(xs(t))}" y1="${top}" y2="${bottom}" style="stroke:${t === 0 ? ink("axis") : ink("grid")}" stroke-width="1"/>`);
354
+ for (let i = 0; i < n; i++) {
355
+ const y = top + i * band;
356
+ const gy = y + (band - (bw * k + (k - 1) * 2)) / 2;
357
+ parts.push(`<text x="${r1(labelW)}" y="${r1(y + band / 2 + 4)}" text-anchor="end" style="fill:${ink("ink2")}">${esc(clip(label(i), 24))}</text>`);
358
+ series.forEach((s, j) => {
359
+ const v = s.values[i];
360
+ if (!isNum(v))
361
+ return;
362
+ const by = gy + j * (bw + 2);
363
+ parts.push(`<path d="${barPath(by, xs(0), bw, xs(v), true)}" style="${fill(j)}"/>`);
364
+ if (k === 1)
365
+ parts.push(`<text x="${r1(xs(v) + (v >= 0 ? 6 : -6))}" y="${r1(by + bw / 2 + 4)}" text-anchor="${v >= 0 ? "start" : "end"}" style="fill:${ink("ink2")}">${esc(fmt(v))}</text>`);
366
+ });
367
+ parts.push(`<rect class="vxc-hit" data-x="${i}" x="0" y="${r1(y)}" width="${width}" height="${r1(band)}" fill="transparent"/>`);
368
+ }
369
+ return open + leg.svg + parts.join("") + "</svg>";
370
+ }
371
+ const tickW = Math.max(...ticks.map((t) => textW(fmt(t, true), 11)));
372
+ const left = Math.ceil(tickW + 14);
373
+ const right = width - (c.kind === "bar" ? 12 : 16 + Math.min(80, textW(fmt(lastOf(series[0].values.filter(isNum)) ?? 0)) + 4));
374
+ const bottom = height - 26;
375
+ const ys = (v) => bottom - ((v - lo) / (hi - lo || 1)) * (bottom - top);
376
+ const parts = [];
377
+ for (const t of ticks) {
378
+ parts.push(`<line x1="${left}" x2="${r1(right)}" y1="${r1(ys(t))}" y2="${r1(ys(t))}" style="stroke:${t === 0 ? ink("axis") : ink("grid")}" stroke-width="1"/>`);
379
+ parts.push(`<text x="${left - 8}" y="${r1(ys(t) + 4)}" text-anchor="end" font-size="11" style="fill:${ink("muted")}">${esc(fmt(t, true))}</text>`);
380
+ }
381
+ const plotW = right - left;
382
+ const band = plotW / n;
383
+ const xAt = (i) => (c.kind === "bar" ? left + band * (i + 0.5) : left + (n === 1 ? plotW / 2 : (i * plotW) / (n - 1)));
384
+ // x labels: as many as fit.
385
+ const widest = Math.max(...Array.from({ length: n }, (_, i) => textW(clip(label(i), 14), 11))) + 10;
386
+ const every = Math.max(1, Math.ceil(widest / (c.kind === "bar" ? band : plotW / Math.max(1, n - 1))));
387
+ for (let i = 0; i < n; i += every)
388
+ parts.push(`<text x="${r1(xAt(i))}" y="${bottom + 18}" text-anchor="middle" font-size="11" style="fill:${ink("muted")}">${esc(clip(label(i), 14))}</text>`);
389
+ if (c.kind === "bar") {
390
+ const k = series.length;
391
+ const bw = Math.min(24, (band * 0.72 - (k - 1) * 2) / k);
392
+ for (let i = 0; i < n; i++) {
393
+ const gx = xAt(i) - (bw * k + (k - 1) * 2) / 2;
394
+ series.forEach((s, j) => {
395
+ const v = s.values[i];
396
+ if (!isNum(v))
397
+ return;
398
+ const x = gx + j * (bw + 2);
399
+ parts.push(`<path d="${barPath(x, ys(0), bw, ys(v))}" style="${fill(j)}"/>`);
400
+ // Values on the caps, sparingly: all of them for a few bars, else the highest and the last.
401
+ const nums = s.values.filter(isNum);
402
+ const pick = n <= 6 || v === Math.max(...nums) || i === lastOf(s.values.map((x, q) => (isNum(x) ? q : -1)).filter((q) => q >= 0));
403
+ if (k === 1 && pick && textW(fmt(v, true), 11) < band * 2 - 8) {
404
+ parts.push(`<text x="${r1(x + bw / 2)}" y="${r1(v >= 0 ? ys(v) - 6 : ys(v) + 14)}" text-anchor="middle" font-size="11" style="fill:${ink("ink2")}">${esc(fmt(v, true))}</text>`);
405
+ }
406
+ });
407
+ parts.push(`<rect class="vxc-hit" data-x="${i}" x="${r1(left + band * i)}" y="${top}" width="${r1(band)}" height="${r1(bottom - top)}" fill="transparent"/>`);
408
+ }
409
+ }
410
+ else {
411
+ series.forEach((s, j) => {
412
+ const pts = s.values.map((v, i) => (isNum(v) ? [xAt(i), ys(v)] : null));
413
+ const runs = [[]];
414
+ // A missing value breaks the line into separate runs.
415
+ for (const p of pts) {
416
+ if (p)
417
+ runs[runs.length - 1].push(p);
418
+ else if (runs[runs.length - 1].length)
419
+ runs.push([]);
420
+ }
421
+ for (const run of runs.filter((r) => r.length)) {
422
+ const d = run.map((p, i) => `${i ? "L" : "M"}${r1(p[0])},${r1(p[1])}`).join("");
423
+ if (c.kind === "area")
424
+ parts.push(`<path d="${d}L${r1(run[run.length - 1][0])},${r1(ys(Math.max(lo, 0)))}L${r1(run[0][0])},${r1(ys(Math.max(lo, 0)))}Z" style="${fill(j)};fill-opacity:.12"/>`);
425
+ parts.push(`<path d="${d}" fill="none" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" style="${stroke(j)}"/>`);
426
+ if (run.length === 1)
427
+ parts.push(`<circle cx="${r1(run[0][0])}" cy="${r1(run[0][1])}" r="4" style="${fill(j)}"/>`);
428
+ }
429
+ // End dot and value for the last point of each series (up to 4).
430
+ const lastIdx = s.values.map((v, i) => (isNum(v) ? i : -1)).filter((i) => i >= 0);
431
+ const lastI = lastOf(lastIdx);
432
+ if (lastI !== undefined && series.length <= 4) {
433
+ const v = s.values[lastI];
434
+ parts.push(`<circle cx="${r1(xAt(lastI))}" cy="${r1(ys(v))}" r="4" stroke-width="2" style="${fill(j)};stroke:${ink("surface")}"/>`);
435
+ parts.push(`<text x="${r1(xAt(lastI) + 8)}" y="${r1(ys(v) + 4)}" style="fill:${ink("ink")}" font-weight="600">${esc(fmt(v, true))}</text>`);
436
+ }
437
+ });
438
+ for (let i = 0; i < n; i++) {
439
+ const x0 = n === 1 ? left : Math.max(left, xAt(i) - plotW / (n - 1) / 2);
440
+ const x1 = n === 1 ? right : Math.min(right, xAt(i) + plotW / (n - 1) / 2);
441
+ parts.push(`<rect class="vxc-hit" data-x="${i}" data-cx="${r1(xAt(i))}" x="${r1(x0)}" y="${top}" width="${r1(x1 - x0)}" height="${r1(bottom - top)}" fill="transparent"/>`);
442
+ }
443
+ }
444
+ if (isNum(c.target)) {
445
+ const y = ys(c.target);
446
+ parts.push(`<line x1="${left}" x2="${r1(right)}" y1="${r1(y)}" y2="${r1(y)}" stroke-width="1.5" stroke-dasharray="4 3" style="stroke:${ink("ink2")}"/>`);
447
+ parts.push(`<text x="${left + 6}" y="${r1(y - 6)}" font-size="11" style="fill:${ink("ink2")}">Target ${esc(fmt(c.target, true))}</text>`);
448
+ }
449
+ return open + leg.svg + parts.join("") + "</svg>";
450
+ }
451
+ function pieBody(c, s, width, height, fmt) {
452
+ let slices = s.values.map((v, i) => ({ v: isNum(v) && v > 0 ? v : 0, label: c.labels[i] ?? `Slice ${i + 1}`, i })).filter((x) => x.v > 0);
453
+ if (slices.length > MAX_PIE_SLICES) {
454
+ const sorted = [...slices].sort((a, b) => b.v - a.v);
455
+ const rest = sorted.slice(MAX_PIE_SLICES - 1);
456
+ slices = [...sorted.slice(0, MAX_PIE_SLICES - 1), { v: rest.reduce((a, b) => a + b.v, 0), label: "Other", i: -1 }];
457
+ }
458
+ const total = slices.reduce((a, b) => a + b.v, 0);
459
+ if (!total)
460
+ return "";
461
+ const legendRight = width >= 360;
462
+ const size = legendRight ? Math.min(height - 16, width * 0.5) : Math.min(width - 16, height - 24 - slices.length * 20);
463
+ const r = size / 2;
464
+ const cx = legendRight ? 8 + r : width / 2;
465
+ const cy = legendRight ? height / 2 : 8 + r;
466
+ const inner = c.kind === "donut" ? r * 0.6 : 0;
467
+ const parts = [];
468
+ let a0 = -Math.PI / 2;
469
+ slices.forEach((sl, k) => {
470
+ const a1 = a0 + (sl.v / total) * Math.PI * 2;
471
+ const large = a1 - a0 > Math.PI ? 1 : 0;
472
+ const p = (rad, a) => `${r1(cx + rad * Math.cos(a))},${r1(cy + rad * Math.sin(a))}`;
473
+ const full = slices.length === 1;
474
+ const d = full
475
+ ? `M${r1(cx - r)},${r1(cy)}a${r1(r)},${r1(r)} 0 1,0 ${r1(2 * r)},0a${r1(r)},${r1(r)} 0 1,0 ${r1(-2 * r)},0${inner ? `M${r1(cx - inner)},${r1(cy)}a${r1(inner)},${r1(inner)} 0 1,1 ${r1(2 * inner)},0a${r1(inner)},${r1(inner)} 0 1,1 ${r1(-2 * inner)},0` : ""}Z`
476
+ : inner
477
+ ? `M${p(r, a0)}A${r1(r)},${r1(r)} 0 ${large},1 ${p(r, a1)}L${p(inner, a1)}A${r1(inner)},${r1(inner)} 0 ${large},0 ${p(inner, a0)}Z`
478
+ : `M${r1(cx)},${r1(cy)}L${p(r, a0)}A${r1(r)},${r1(r)} 0 ${large},1 ${p(r, a1)}Z`;
479
+ parts.push(`<path class="vxc-hit" data-x="${sl.i}" d="${d}" fill-rule="evenodd" stroke-width="2" style="${fill(k)};stroke:${ink("surface")}"/>`);
480
+ a0 = a1;
481
+ });
482
+ // Shares already in percent need no total, and no second percentage.
483
+ const asPercent = c.format?.suffix?.trim() === "%";
484
+ if (inner && !asPercent) {
485
+ parts.push(`<text x="${r1(cx)}" y="${r1(cy + 2)}" text-anchor="middle" font-size="${Math.max(14, Math.round(inner / 2.6))}" font-weight="600" style="fill:${ink("ink")}">${esc(fmt(total))}</text>`);
486
+ parts.push(`<text x="${r1(cx)}" y="${r1(cy + 20)}" text-anchor="middle" font-size="11" style="fill:${ink("muted")}">Total</text>`);
487
+ }
488
+ const lx = legendRight ? cx + r + 24 : 12;
489
+ let ly = legendRight ? cy - (slices.length * 22) / 2 + 12 : cy + r + 22;
490
+ slices.forEach((sl, k) => {
491
+ const pct = Math.round((sl.v / total) * 1000) / 10;
492
+ parts.push(`<rect x="${r1(lx)}" y="${r1(ly - 9)}" width="10" height="10" rx="2" style="${fill(k)}"/>`);
493
+ parts.push(`<text x="${r1(lx + 16)}" y="${r1(ly)}" style="fill:${ink("ink")}">${esc(clip(sl.label, 22))}</text>`);
494
+ parts.push(`<text x="${r1(width - 8)}" y="${r1(ly)}" text-anchor="end" style="fill:${ink("ink2")}">${asPercent ? esc(fmt(sl.v)) : `${pct}% · ${esc(fmt(sl.v))}`}</text>`);
495
+ ly += 22;
496
+ });
497
+ return parts.join("");
498
+ }
499
+ function kpiBody(c, s, width, height, fmt) {
500
+ const idx = s.values.map((v, i) => (isNum(v) ? i : -1)).filter((i) => i >= 0);
501
+ const li = idx[idx.length - 1];
502
+ const pi = idx.length > 1 ? idx[idx.length - 2] : undefined;
503
+ const v = s.values[li];
504
+ const parts = [];
505
+ const pad = 16;
506
+ parts.push(`<text x="${pad}" y="28" font-size="14" style="fill:${ink("ink2")}">${esc(clip(s.name, 60))}${c.labels[li] ? ` · ${esc(c.labels[li])}` : ""}</text>`);
507
+ const big = Math.min(52, Math.max(28, (width - pad * 2) / Math.max(4, fmt(v, true).length) * 1.4));
508
+ parts.push(`<text x="${pad}" y="${r1(36 + big)}" font-size="${r1(big)}" font-weight="600" style="fill:${ink("ink")}">${esc(fmt(v, true))}</text>`);
509
+ let y = 36 + big + 26;
510
+ if (pi !== undefined) {
511
+ const prev = s.values[pi];
512
+ const change = prev === 0 ? null : ((v - prev) / Math.abs(prev)) * 100;
513
+ if (change !== null) {
514
+ const up = change >= 0;
515
+ parts.push(`<text x="${pad}" y="${r1(y)}" font-size="13" style="fill:${up ? ink("good") : ink("bad")}">${up ? "▲" : "▼"} ${Math.abs(Math.round(change * 10) / 10)}%<tspan style="fill:${ink("muted")}"> vs ${esc(c.labels[pi] || "before")}</tspan></text>`);
516
+ y += 24;
517
+ }
518
+ }
519
+ if (isNum(c.target) && c.target > 0) {
520
+ const share = Math.max(0, v / c.target);
521
+ const w = width - pad * 2;
522
+ parts.push(`<rect x="${pad}" y="${r1(y - 4)}" width="${r1(w)}" height="8" rx="4" style="${fill(0)};fill-opacity:.18"/>`);
523
+ parts.push(`<rect x="${pad}" y="${r1(y - 4)}" width="${r1(Math.max(8, Math.min(1, share) * w))}" height="8" rx="4" style="${fill(0)}"/>`);
524
+ parts.push(`<text x="${pad}" y="${r1(y + 22)}" font-size="12" style="fill:${ink("ink2")}">${Math.round(share * 100)}% of the ${esc(fmt(c.target, true))} target</text>`);
525
+ y += 34;
526
+ }
527
+ // Sparkline of the history, when there is one and room for it.
528
+ if (idx.length >= 3 && height - y > 30) {
529
+ const vals = idx.map((i) => s.values[i]);
530
+ const mn = Math.min(...vals);
531
+ const mx = Math.max(...vals);
532
+ const sw = width - pad * 2;
533
+ const sh = Math.min(48, height - y - 10);
534
+ const pts = vals.map((x, k) => [pad + (k * sw) / (vals.length - 1), y + sh - ((x - mn) / (mx - mn || 1)) * sh]);
535
+ parts.push(`<path d="${pts.map((p, k) => `${k ? "L" : "M"}${r1(p[0])},${r1(p[1])}`).join("")}" fill="none" stroke-width="2" stroke-linejoin="round" style="stroke:${ink("axis")}"/>`);
536
+ const last = pts[pts.length - 1];
537
+ parts.push(`<circle cx="${r1(last[0])}" cy="${r1(last[1])}" r="4" stroke-width="2" style="${fill(0)};stroke:${ink("surface")}"/>`);
538
+ }
539
+ return parts.join("");
540
+ }
541
+ /** Series values for analytics and connected charts, filled into a chart (labels and series replaced). */
542
+ export function withChartData(c, labels, series) {
543
+ return { ...c, labels: labels.slice(0, MAX_CHART_LABELS), series: series.slice(0, MAX_CHART_SERIES).map((s) => ({ name: s.name, values: s.values.slice(0, MAX_CHART_LABELS) })) };
544
+ }
545
+ // ------------------------------------------------------------ as a table
546
+ // Typed or pasted numbers, as a spreadsheet would copy them: a header row
547
+ // (anything, then one name per series), then a row per label. Tabs,
548
+ // semicolons or commas between cells; "1,200" with a tab or semicolon
549
+ // between cells is read as 1200.
550
+ /** The chart's typed-in numbers as text, a row per label (tabs between cells). */
551
+ export function chartTableText(c) {
552
+ const head = ["Label", ...c.series.map((s) => s.name)].join("\t");
553
+ const rows = c.labels.map((l, i) => [l, ...c.series.map((s) => (isNum(s.values[i]) ? String(s.values[i]) : ""))].join("\t"));
554
+ return [head, ...rows].join("\n");
555
+ }
556
+ /** Labels and series from pasted or typed rows, or what's wrong with them. */
557
+ export function parseChartTable(text) {
558
+ const lines = text.split(/\r?\n/).map((l) => l.trimEnd()).filter((l) => l.trim());
559
+ if (lines.length < 2)
560
+ return { error: "Put a header row (Label, then a name per series) and at least one row of numbers." };
561
+ const sep = lines[0].includes("\t") ? "\t" : lines[0].includes(";") ? ";" : ",";
562
+ const cells = (l) => l.split(sep).map((c) => c.trim());
563
+ const names = cells(lines[0]).slice(1);
564
+ if (!names.length)
565
+ return { error: "The header row needs a name for each series after the first column." };
566
+ if (names.length > MAX_CHART_SERIES)
567
+ return { error: `${MAX_CHART_SERIES} series at most.` };
568
+ if (lines.length - 1 > MAX_CHART_LABELS)
569
+ return { error: `${MAX_CHART_LABELS} rows at most.` };
570
+ const labels = [];
571
+ const series = names.map((name, k) => ({ name: name || `Series ${k + 1}`, values: [] }));
572
+ for (const [r, line] of lines.slice(1).entries()) {
573
+ const row = cells(line);
574
+ labels.push((row[0] ?? "").slice(0, 40));
575
+ for (let k = 0; k < names.length; k++) {
576
+ const raw = (row[k + 1] ?? "").replace(sep === "," ? /\s/g : /[\s,]/g, "");
577
+ if (raw === "") {
578
+ series[k].values.push(null);
579
+ continue;
580
+ }
581
+ const n = Number(raw.replace(/[^\d.eE+-]/g, ""));
582
+ if (!Number.isFinite(n) || !/\d/.test(raw))
583
+ return { error: `Row ${r + 2}: "${row[k + 1]}" isn't a number.` };
584
+ series[k].values.push(n);
585
+ }
586
+ }
587
+ return { labels, series };
588
+ }
589
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
590
+ export const CHART_TEMPLATES = [
591
+ {
592
+ id: "monthly-sales",
593
+ name: "Monthly sales",
594
+ why: "Which months sell best, so stock, staff and campaigns can be planned around them.",
595
+ value: { kind: "bar", title: "Monthly sales", labels: MONTHS, series: [{ name: "Sales", values: [96, 88, 104, 118, 131, 127, 122, 140, 152, 149, 171, 188].map((v) => v * 1000) }], format: { suffix: " SAR" }, source: { type: "manual" }, template: "monthly-sales", sample: true },
596
+ },
597
+ {
598
+ id: "revenue-target",
599
+ name: "Revenue against target",
600
+ why: "The one number leadership checks first: are we on track this quarter, and is it better than last?",
601
+ value: { kind: "kpi", title: "Quarterly revenue", labels: ["Q1", "Q2", "Q3", "Q4"], series: [{ name: "Revenue", values: [1120000, 1240000, 1310000, 1460000] }], format: { suffix: " SAR" }, target: 1600000, source: { type: "manual" }, template: "revenue-target", sample: true },
602
+ },
603
+ {
604
+ id: "visitors",
605
+ name: "Website visitors",
606
+ why: "Is the site reaching more people? A line that rises after a campaign shows it worked. Real numbers from VeroXM's analytics.",
607
+ value: { kind: "area", title: "Visitors a day", labels: [], series: [], source: { type: "analytics", metric: "visitors", days: 30 }, template: "visitors" },
608
+ },
609
+ {
610
+ id: "satisfaction",
611
+ name: "Customer satisfaction",
612
+ why: "Whether customers are getting happier, quarter by quarter, against the score you aim for.",
613
+ value: { kind: "line", title: "Customer satisfaction (CSAT)", labels: ["Q1 25", "Q2 25", "Q3 25", "Q4 25", "Q1 26", "Q2 26"], series: [{ name: "CSAT", values: [78, 80, 79, 83, 85, 87] }], format: { suffix: "%" }, target: 85, source: { type: "manual" }, template: "satisfaction", sample: true },
614
+ },
615
+ {
616
+ id: "sales-by-region",
617
+ name: "Sales by region",
618
+ why: "Where the business comes from, to see which regions to invest in and which to look into.",
619
+ value: { kind: "donut", title: "Sales by region", labels: ["Riyadh", "Jeddah", "Dammam", "Makkah", "Other"], series: [{ name: "Share", values: [38, 24, 17, 12, 9] }], format: { suffix: "%" }, source: { type: "manual" }, template: "sales-by-region", sample: true },
620
+ },
621
+ {
622
+ id: "tickets",
623
+ name: "Support tickets opened and solved",
624
+ why: "If opened keeps outgrowing solved, the backlog grows: time to add people or fix the top cause.",
625
+ value: { kind: "bar", title: "Support tickets", labels: ["Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6"], series: [{ name: "Opened", values: [320, 344, 362, 351, 388, 402] }, { name: "Solved", values: [310, 338, 341, 349, 360, 371] }], source: { type: "manual" }, template: "tickets", sample: true },
626
+ },
627
+ {
628
+ id: "top-pages",
629
+ name: "Most visited pages",
630
+ why: "The pages people actually read: keep them up to date and put your offers there. Real numbers from VeroXM's analytics.",
631
+ value: { kind: "hbar", title: "Most visited pages", labels: [], series: [], source: { type: "analytics", metric: "top_pages", days: 30 }, template: "top-pages" },
632
+ },
633
+ {
634
+ id: "signups",
635
+ name: "Sign-ups a day",
636
+ why: "How many people do the thing that matters most (here an event named signup), day by day. Real numbers from VeroXM's analytics.",
637
+ value: { kind: "line", title: "Sign-ups a day", labels: [], series: [], source: { type: "analytics", metric: "event", days: 30, event: "signup" }, template: "signups" },
638
+ },
639
+ ];