@aivin-labs/cli 1.0.13 → 1.0.24

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 (73) hide show
  1. package/README.md +325 -304
  2. package/bin/cli.mjs +97 -18
  3. package/bin/lib/localPreview.mjs +437 -0
  4. package/bin/lib/openFile.mjs +235 -0
  5. package/bin/lib/previewCache.mjs +71 -0
  6. package/bin/lib/remote/atomicFile.mjs +32 -0
  7. package/bin/lib/remote/autoStart.mjs +2 -1
  8. package/bin/lib/remote/autoUpdate.mjs +153 -129
  9. package/bin/lib/remote/callLedger.mjs +21 -0
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -2
  11. package/bin/lib/remote/client.mjs +1025 -889
  12. package/bin/lib/remote/codingAgents.mjs +2 -2
  13. package/bin/lib/remote/constants.mjs +263 -251
  14. package/bin/lib/remote/credentials.mjs +81 -4
  15. package/bin/lib/remote/daemonLock.mjs +57 -17
  16. package/bin/lib/remote/desktop/castInput.mjs +98 -0
  17. package/bin/lib/remote/desktop/desktopCast.mjs +337 -198
  18. package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
  19. package/bin/lib/remote/desktop/desktopCastSource.mjs +880 -514
  20. package/bin/lib/remote/desktop/desktopWebRtc.mjs +251 -95
  21. package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
  22. package/bin/lib/remote/desktop/index.mjs +21 -7
  23. package/bin/lib/remote/desktop/linuxTraySource.mjs +1 -8
  24. package/bin/lib/remote/desktop/macTraySource.mjs +0 -2
  25. package/bin/lib/remote/desktop/strings.mjs +28 -2
  26. package/bin/lib/remote/desktop/traySource.mjs +380 -16
  27. package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
  28. package/bin/lib/remote/desktop/webrtcWorker.mjs +183 -0
  29. package/bin/lib/remote/deviceProfile.mjs +2 -4
  30. package/bin/lib/remote/fileIndexer.mjs +30 -14
  31. package/bin/lib/remote/folderRules.mjs +3 -0
  32. package/bin/lib/remote/gitSafe.mjs +31 -0
  33. package/bin/lib/remote/gui/index.mjs +66 -24
  34. package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
  35. package/bin/lib/remote/gui/windowsHost.mjs +3 -1
  36. package/bin/lib/remote/gui/windowsHostSource.mjs +291 -60
  37. package/bin/lib/remote/httpTransfer.mjs +64 -3
  38. package/bin/lib/remote/localPolicy.mjs +73 -7
  39. package/bin/lib/remote/mascot/ask.mjs +956 -768
  40. package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
  41. package/bin/lib/remote/mascot/askHostSource.mjs +658 -530
  42. package/bin/lib/remote/mascot/blocks.mjs +201 -0
  43. package/bin/lib/remote/mascot/bot.mjs +26 -2
  44. package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
  45. package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
  46. package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
  47. package/bin/lib/remote/mascot/fileChips.mjs +62 -0
  48. package/bin/lib/remote/mascot/hostSource.mjs +328 -49
  49. package/bin/lib/remote/mascot/hotkey.mjs +31 -7
  50. package/bin/lib/remote/mascot/images.mjs +111 -0
  51. package/bin/lib/remote/mascot/index.mjs +663 -493
  52. package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
  53. package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
  54. package/bin/lib/remote/mascot/mood.mjs +57 -0
  55. package/bin/lib/remote/mascot/rigSource.mjs +643 -609
  56. package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
  57. package/bin/lib/remote/mascot/strings.mjs +459 -375
  58. package/bin/lib/remote/mascot/ui.mjs +27 -7
  59. package/bin/lib/remote/multiUser.mjs +7 -2
  60. package/bin/lib/remote/notify.mjs +4 -1
  61. package/bin/lib/remote/office/index.mjs +12 -6
  62. package/bin/lib/remote/processes.mjs +5 -2
  63. package/bin/lib/remote/sandbox.mjs +26 -0
  64. package/bin/lib/remote/secretPaths.mjs +21 -0
  65. package/bin/lib/remote/tokenRotation.mjs +28 -0
  66. package/bin/lib/remote/toolHandlers.mjs +79 -15
  67. package/bin/lib/remote/watchBatcher.mjs +56 -0
  68. package/bin/lib/selfUpdate.mjs +12 -2
  69. package/bin/lib/update/binarySwap.mjs +15 -1
  70. package/bin/lib/update/state.mjs +10 -0
  71. package/docs/CLI.md +1545 -1504
  72. package/docs/media/aivin-ecosystem.jpg +0 -0
  73. package/package.json +75 -71
@@ -0,0 +1,201 @@
1
+ import { chartLayout } from './chartLayout.mjs';
2
+ import { lucidePath } from './lucideIcons.mjs';
3
+ import { safeWebUrl } from './safeUrl.mjs';
4
+ import { MascotText } from './strings.mjs';
5
+
6
+ /**
7
+ * Rich component của câu trả lời (`blocks` trong `device:chat_event` / `device:notify`) → lệnh cho cửa sổ linh vật (03/11/2026). BE đã giới hạn cỡ; ở đây chặn thêm vì
8
+ * cửa sổ dựng từng phần tử bằng PowerShell, gắn chữ đã dịch, tính độ rộng cột + hình biểu đồ, và gắn tệp ảnh sau khi daemon tải / dựng xong (images.mjs, diagramRender.mjs).
9
+ */
10
+ export const BlockType = Object.freeze({ TABLE: 'table', CARDS: 'cards', IMAGE: 'image', CHART: 'chart', DIAGRAM: 'diagram', WEBVIEW: 'webview', SCREENCAST: 'screencast', LINK_CARD: 'link_card', SOURCES: 'sources' });
11
+ const MAX_BLOCKS = 12;
12
+ const MAX_ROWS = 20;
13
+ const MAX_COLS = 8;
14
+ const MAX_CARDS = 12;
15
+ const MAX_TEXT = 300;
16
+ const MAX_DIAGRAM_CHARS = 20000;
17
+ const MAX_SOURCES = 8;
18
+ /** Bề rộng bảng trong ô đã nới rộng, ước lượng một ký tự chữ cỡ 12 (kể cả đậm) + lề hai bên một ô (askBlocksSource.mjs). */
19
+ const TABLE_WIDTH = 286;
20
+ const CHAR_WIDTH = 6.9;
21
+ const CELL_PADDING = 16;
22
+ /** Từ dài hơn thì chấp nhận xuống dòng giữa từ; chữ dài hơn không đòi thêm chỗ. */
23
+ const MIN_WORD_CHARS = 3;
24
+ const MAX_WORD_CHARS = 14;
25
+ const MAX_LINE_CHARS = 40;
26
+ /** Tên icon lạ: cùng icon dự phòng với thẻ trên web. */
27
+ const DEFAULT_CARD_ICON = 'sparkles';
28
+ const LINK_CARD_ICONS = Object.freeze({ video: 'play', file: 'file-text', link: 'external-link' });
29
+ const HEX_COLOR = /^#[0-9a-f]{6}$/i;
30
+ const ALIGNS = new Set(['left', 'center', 'right']);
31
+ /** Khoá tệp của sơ đồ trong bảng `files` của `withImageFiles` (URL ảnh là khoá của ảnh). */
32
+ const DIAGRAM_KEY = 'diagram:';
33
+
34
+ const str = (v) => (typeof v === 'string' ? v.trim().slice(0, MAX_TEXT) : typeof v === 'number' ? String(v) : '');
35
+
36
+ function normalizeCell(c) {
37
+ if (c?.covered === true) return { text: '', covered: true };
38
+ const span = Number.isInteger(c?.span) && c.span > 1 ? { span: Math.min(c.span, MAX_COLS) } : {};
39
+ const rowspan = Number.isInteger(c?.rowspan) && c.rowspan > 1 ? { rowspan: Math.min(c.rowspan, MAX_ROWS) } : {};
40
+ return {
41
+ text: str(c?.text), ...span, ...rowspan, ...(c?.bold === true ? { bold: true } : {}), ...(c?.italic === true ? { italic: true } : {}), ...(ALIGNS.has(c?.align) ? { align: c.align } : {}),
42
+ ...(HEX_COLOR.test(c?.bg) ? { bg: c.bg } : {}), ...(HEX_COLOR.test(c?.color) ? { color: c.color } : {}),
43
+ };
44
+ }
45
+
46
+ /**
47
+ * Độ rộng từng cột (px trên bề rộng `TABLE_WIDTH`, cửa sổ dùng làm tỉ lệ). Trước hết cột nào cũng đủ chỗ cho từ dài nhất của nó để không bẻ giữa từ / giữa số
48
+ * ("12.50 / 0.000"), chỗ còn lại chia theo độ dài chữ. Hết chỗ thì mới chia theo tỉ lệ phần tối thiểu. Hàng gộp ô không tính.
49
+ */
50
+ export function columnWeights(rows, cols) {
51
+ const plain = rows.filter((r) => !r.some((c) => c.span));
52
+ const measure = (col, read) => Math.max(0, ...plain.map((r) => read(r[col]?.text || '')));
53
+ const least = Array.from({ length: cols }, (_, col) => CELL_PADDING + CHAR_WIDTH * Math.max(MIN_WORD_CHARS, Math.min(MAX_WORD_CHARS, measure(col, (s) => Math.max(0, ...s.split(/[\s-]+/).map((w) => w.length))))));
54
+ const want = Array.from({ length: cols }, (_, col) => CELL_PADDING + CHAR_WIDTH * Math.min(MAX_LINE_CHARS, measure(col, (s) => s.length)));
55
+ const spare = TABLE_WIDTH - least.reduce((a, b) => a + b, 0);
56
+ if (spare <= 0) return least.map(Math.round);
57
+ const extra = want.map((w, i) => Math.max(0, w - least[i]));
58
+ const totalExtra = extra.reduce((a, b) => a + b, 0);
59
+ // Mọi cột đã đủ chỗ cho cả dòng: chia đều phần thừa.
60
+ return least.map((w, i) => Math.round(w + (totalExtra ? (spare * extra[i]) / totalExtra : spare / cols)));
61
+ }
62
+
63
+ function tableBlock(b, { t }) {
64
+ const rows = (Array.isArray(b.rows) ? b.rows : []).slice(0, MAX_ROWS).filter(Array.isArray).map((r) => r.slice(0, MAX_COLS).map(normalizeCell));
65
+ if (!rows.length) return null;
66
+ const cols = Math.min(MAX_COLS, Math.max(...rows.map((r) => r.reduce((n, c) => n + (c.span || 1), 0))));
67
+ const notes = [
68
+ b.more_rows > 0 ? t(MascotText.ASK_MORE_ROWS, { n: b.more_rows }) : '',
69
+ b.more_cols > 0 ? t(MascotText.ASK_MORE_COLS, { n: b.more_cols }) : '',
70
+ ].filter(Boolean);
71
+ return {
72
+ type: BlockType.TABLE, ...(str(b.title) ? { title: str(b.title) } : {}), header: b.header !== false, ...(b.plain === true ? { plain: true } : {}), cols, weights: columnWeights(rows, cols), rows,
73
+ ...(notes.length ? { note: notes.join(', ') } : {}),
74
+ };
75
+ }
76
+
77
+ function cardsBlock(b, { t }) {
78
+ const cards = (Array.isArray(b.cards) ? b.cards : []).slice(0, MAX_CARDS).filter((c) => str(c?.title)).map((c) => {
79
+ const image = safeWebUrl(c.image);
80
+ const tags = Array.isArray(c.tags) ? c.tags.map(str).filter(Boolean).slice(0, 4) : [];
81
+ return {
82
+ title: str(c.title), ...(str(c.text) ? { text: str(c.text) } : {}), ...(tags.length ? { tags } : {}), ...(str(c.footer) ? { footer: str(c.footer) } : {}),
83
+ icon_path: lucidePath(c.icon) || lucidePath(DEFAULT_CARD_ICON), ...(image ? { image } : {}),
84
+ };
85
+ });
86
+ if (!cards.length) return null;
87
+ return {
88
+ type: BlockType.CARDS, ...(str(b.title) ? { title: str(b.title) } : {}), cards,
89
+ ...(b.more > 0 ? { note: t(MascotText.ASK_MORE_CARDS, { n: b.more }) } : {}),
90
+ };
91
+ }
92
+
93
+ function imageBlock(b, { t }) {
94
+ const url = safeWebUrl(b.url);
95
+ if (!url) return null;
96
+ return { type: BlockType.IMAGE, url, ...(str(b.caption) ? { caption: str(b.caption) } : {}), open_text: str(b.caption) || t(MascotText.ASK_OPEN_IMAGE) };
97
+ }
98
+
99
+ function chartBlock(b, { t, lang }) {
100
+ const layout = chartLayout({ kind: b.kind, labels: (Array.isArray(b.labels) ? b.labels : []).map(str), series: Array.isArray(b.series) ? b.series.filter((s) => Array.isArray(s?.data)) : [] }, lang);
101
+ if (!layout) return null;
102
+ return {
103
+ type: BlockType.CHART, ...(str(b.title) ? { title: str(b.title) } : {}), layout,
104
+ ...(b.more > 0 ? { note: t(MascotText.ASK_MORE_POINTS, { n: b.more }) } : {}),
105
+ };
106
+ }
107
+
108
+ /** Sơ đồ: dựng xong thành ảnh, bấm mở phiên trên web để xem lớn (sơ đồ lớn thu vào ô hỏi sẽ khó đọc). Dựng hỏng → nút mở web. */
109
+ function diagramBlock(b, { t, webUrl }) {
110
+ if (typeof b.source !== 'string' || !b.source.trim() || b.source.length > MAX_DIAGRAM_CHARS) return null;
111
+ return { type: BlockType.DIAGRAM, source: b.source, ...(webUrl ? { url: webUrl } : {}), open_text: t(MascotText.ASK_OPEN_DIAGRAM) };
112
+ }
113
+
114
+ function webviewBlock(b, { t, sessionId }) {
115
+ if (typeof b.message_id !== 'string' || !b.message_id || !sessionId) return null;
116
+ return {
117
+ type: BlockType.WEBVIEW, session_id: sessionId, message_id: b.message_id, index: Number.isInteger(b.index) ? b.index : 0,
118
+ title: str(b.title) || t(MascotText.ASK_WEBVIEW_TITLE), action: t(MascotText.ASK_WEBVIEW_OPEN), icon_path: lucidePath('app-window'),
119
+ };
120
+ }
121
+
122
+ function screencastBlock(b, { t, webUrl }) {
123
+ if (!webUrl) return null;
124
+ const site = safeWebUrl(b.url);
125
+ return {
126
+ type: BlockType.LINK_CARD, title: str(b.title) || t(MascotText.ASK_SCREENCAST_TITLE), text: site ? new URL(site).hostname : t(MascotText.ASK_SCREENCAST_HINT),
127
+ url: webUrl, action: t(MascotText.ASK_OPEN_WEB), icon_path: lucidePath('globe'),
128
+ };
129
+ }
130
+
131
+ function linkCardBlock(b) {
132
+ const url = safeWebUrl(b.url);
133
+ if (!url || !str(b.title)) return null;
134
+ return {
135
+ type: BlockType.LINK_CARD, title: str(b.title), ...(str(b.text) ? { text: str(b.text) } : {}), url, ...(str(b.label) ? { action: str(b.label) } : {}),
136
+ icon_path: lucidePath(b.icon) || lucidePath(LINK_CARD_ICONS[b.kind] || LINK_CARD_ICONS.link),
137
+ };
138
+ }
139
+
140
+ function sourcesBlock(b, { t }) {
141
+ const items = (Array.isArray(b.items) ? b.items : []).slice(0, MAX_SOURCES).filter((i) => str(i?.name)).map((i) => {
142
+ const url = safeWebUrl(i.url);
143
+ return { name: str(i.name), ...(url ? { url } : {}) };
144
+ });
145
+ return items.length ? { type: BlockType.SOURCES, label: t(MascotText.ASK_SOURCES), items } : null;
146
+ }
147
+
148
+ const BUILDERS = Object.freeze({
149
+ [BlockType.TABLE]: tableBlock, [BlockType.CARDS]: cardsBlock, [BlockType.IMAGE]: imageBlock, [BlockType.CHART]: chartBlock, [BlockType.DIAGRAM]: diagramBlock,
150
+ [BlockType.WEBVIEW]: webviewBlock, [BlockType.SCREENCAST]: screencastBlock, [BlockType.LINK_CARD]: linkCardBlock, [BlockType.SOURCES]: sourcesBlock,
151
+ });
152
+
153
+ /** Khối BE gửi → khối gửi cửa sổ; loại lạ / rỗng bị bỏ. Không còn gì → null. `ctx`: `{ t, lang, webUrl (phiên trên web), sessionId }`. */
154
+ export function normalizeBlocks(raw, ctx) {
155
+ if (!Array.isArray(raw)) return null;
156
+ const out = raw.slice(0, MAX_BLOCKS).map((b) => {
157
+ const build = typeof b?.type === 'string' && Object.prototype.hasOwnProperty.call(BUILDERS, b.type) ? BUILDERS[b.type] : null;
158
+ return build ? build(b, ctx) : null;
159
+ }).filter(Boolean);
160
+ return out.length ? out : null;
161
+ }
162
+
163
+ /** Mọi tài nguyên cần tải / dựng trong các khối (URL ảnh, thẻ, `diagram:<mã>`), không trùng. */
164
+ export function imageUrlsOf(blocks) {
165
+ const urls = new Set();
166
+ for (const b of blocks || []) {
167
+ if (b.type === BlockType.IMAGE) urls.add(b.url);
168
+ if (b.type === BlockType.DIAGRAM) urls.add(`${DIAGRAM_KEY}${b.source}`);
169
+ if (b.type === BlockType.CARDS) for (const c of b.cards) if (c.image) urls.add(c.image);
170
+ }
171
+ return [...urls];
172
+ }
173
+
174
+ /** Khoá `imageUrlsOf` → mã sơ đồ, không phải sơ đồ → null. */
175
+ export function diagramSourceOf(key) {
176
+ return String(key).startsWith(DIAGRAM_KEY) ? String(key).slice(DIAGRAM_KEY.length) : null;
177
+ }
178
+
179
+ /**
180
+ * Gắn tệp đã tải (`files`: khoá → đường dẫn | null) vào các khối, bỏ cờ chờ. Khối ảnh / sơ đồ hỏng giữ lại không có `file`: cửa sổ vẽ thành nút mở link. Thẻ tải ảnh
181
+ * hỏng về icon. Sơ đồ đã xong thì bỏ mã nguồn, cửa sổ không cần.
182
+ */
183
+ export function withImageFiles(blocks, files) {
184
+ return blocks.map((b) => {
185
+ if (b.type === BlockType.IMAGE) return { ...b, done: true, ...(files.get(b.url) ? { file: files.get(b.url) } : {}) };
186
+ if (b.type === BlockType.DIAGRAM) {
187
+ const { source, ...rest } = b;
188
+ const file = files.get(`${DIAGRAM_KEY}${source}`);
189
+ return { ...rest, done: true, ...(file ? { file } : {}) };
190
+ }
191
+ if (b.type !== BlockType.CARDS) return b;
192
+ return {
193
+ ...b,
194
+ cards: b.cards.map((c) => {
195
+ if (!c.image) return c;
196
+ const { image, ...rest } = c;
197
+ return files.get(image) ? { ...rest, file: files.get(image) } : rest;
198
+ }),
199
+ };
200
+ });
201
+ }
@@ -71,10 +71,15 @@ export const BOT_FACES = Object.freeze({
71
71
  wink: { eyes: 'wink', mouth: 'grin' },
72
72
  curious: { eyes: 'curious', mouth: 'hmm' },
73
73
  star: { eyes: 'star', mouth: 'grin' },
74
+ // Theo emoji của câu trả lời (mood.mjs): xin lỗi / tiếc → mắt cụp, lông mày xếch trong, miệng mếu; ngượng (😅) → cười híp, miệng méo.
75
+ sad: { eyes: 'droop', mouth: 'frown' },
76
+ // Khóc (😭 / 😢): mắt cụp như buồn, miệng mếu há; nước mắt do rig vẽ (BOT_TEARS).
77
+ cry: { eyes: 'droop', mouth: 'wail' },
78
+ sheepish: { eyes: 'happy', mouth: 'hmm' },
74
79
  });
75
80
 
76
- export const BOT_EYES = Object.freeze(['open', 'focus', 'up', 'wide', 'happy', 'closed', 'sad', 'dizzy', 'wink', 'curious', 'star']);
77
- export const BOT_MOUTHS = Object.freeze(['smile', 'flat', 'hmm', 'open', 'grin', 'wobble', 'talk']);
81
+ export const BOT_EYES = Object.freeze(['open', 'focus', 'up', 'wide', 'happy', 'closed', 'sad', 'dizzy', 'wink', 'curious', 'star', 'droop']);
82
+ export const BOT_MOUTHS = Object.freeze(['smile', 'flat', 'hmm', 'open', 'grin', 'wobble', 'talk', 'frown', 'wail']);
78
83
 
79
84
  /**
80
85
  * Thông số chuyển động theo trạng thái (đơn vị bot / độ / Hz). Giá trị hiện tại luôn trượt dần về đích nên đổi trạng thái không giật.
@@ -126,6 +131,11 @@ const EYE_SHAPES = {
126
131
  wink: [`<Path Data="M-8,3 Q0,-8 8,3" ${glowStroke()} Fill="{x:Null}"/>`, pill(10, 14, 'BlinkWnkR')],
127
132
  curious: [pill(10, 8, 'BlinkCurL'), pill(12.5, 16, 'BlinkCurR')],
128
133
  star: [starEye],
134
+ // Buồn / xin lỗi: mắt thấp hơn, lông mày xếch lên ở phía trong (hai đầu gần nhau cao hơn).
135
+ droop: [
136
+ `<Canvas Canvas.Top="1.5">${pill(10, 11, 'BlinkDrL')}</Canvas><Path Data="M-6.5,-8 L4.5,-11.5" ${glowStroke(2.6)}/>`,
137
+ `<Canvas Canvas.Top="1.5">${pill(10, 11, 'BlinkDrR')}</Canvas><Path Data="M-4.5,-11.5 L6.5,-8" ${glowStroke(2.6)}/>`,
138
+ ],
129
139
  };
130
140
  /** Tên các ScaleTransform chớp mắt (rigSource.mjs đặt ScaleY). */
131
141
  export const BOT_BLINKS = Object.freeze([
@@ -135,6 +145,7 @@ export const BOT_BLINKS = Object.freeze([
135
145
  'BlinkWL', 'BlinkWR',
136
146
  'BlinkWnkR',
137
147
  'BlinkCurL', 'BlinkCurR',
148
+ 'BlinkDrL', 'BlinkDrR',
138
149
  ]);
139
150
 
140
151
  const eyeSide = (side) => BOT_EYES.map((n) => {
@@ -150,8 +161,20 @@ const MOUTH_SHAPES = {
150
161
  grin: `<Path Data="M-8,-2.5 C-4,-3.6 4,-3.6 8,-2.5 C7.4,4.6 3.8,7.6 0,7.6 C-3.8,7.6 -7.4,4.6 -8,-2.5 Z" Fill="${GLOW}" Stroke="${GLOW}" StrokeThickness="2.2" StrokeLineJoin="Round"/>`,
151
162
  wobble: `<Path Data="M-6.5,2 C-4.5,-0.8 -2,-0.8 0,1.4 C2,3.6 4.5,3.6 6.5,0.8" ${glowStroke(3.6)} Fill="{x:Null}"/>`,
152
163
  talk: `<Ellipse Canvas.Left="-5" Canvas.Top="-4" Width="10" Height="8" Fill="${GLOW}" RenderTransformOrigin="0.5,0.5"><Ellipse.RenderTransform><ScaleTransform x:Name="MouthTalkScale"/></Ellipse.RenderTransform></Ellipse>`,
164
+ frown: `<Path Data="M-5.5,2.4 C-3.5,-1.6 3.5,-1.6 5.5,2.4" ${glowStroke(4)} Fill="{x:Null}"/>`,
165
+ // Khóc: miệng mếu há (đáy phẳng, đỉnh cong lên).
166
+ wail: `<Path Data="M-5.5,3 C-4.5,-3 4.5,-3 5.5,3 Z" Fill="${GLOW}" Stroke="${GLOW}" StrokeThickness="2" StrokeLineJoin="Round"/>`,
153
167
  };
154
168
 
169
+ /**
170
+ * Nước mắt (khóc): mỗi mắt 2 giọt so le, rơi từ dưới mắt xuống ngang miệng rồi tan; rig dời `TearMove*` + chỉnh độ mờ từng giọt, cả cụm
171
+ * `Tears` ẩn khi không khóc. Nằm trong `EyeLook` nên đi theo hướng nhìn của mắt.
172
+ */
173
+ export const BOT_TEARS = Object.freeze(['L0', 'L1', 'R0', 'R1']);
174
+ const TEAR = { x: 17, y: 5, color: '#E6FBFF' };
175
+ const tearDrop = (id) => `<Path x:Name="Tear${id}" Canvas.Left="${id[0] === 'L' ? -TEAR.x : TEAR.x}" Canvas.Top="${TEAR.y}" Data="M0,-4.6 Q3.7,1.1 0,4 Q-3.7,1.1 0,-4.6 Z" Fill="${TEAR.color}" Opacity="0"><Path.RenderTransform><TranslateTransform x:Name="TearMove${id}"/></Path.RenderTransform></Path>`;
176
+ const TEARS_XAML = `<Canvas x:Name="Tears" Visibility="Collapsed">${BOT_TEARS.map(tearDrop).join('')}</Canvas>`;
177
+
155
178
  const R = BOT_RIG;
156
179
  const V = R.visor;
157
180
  const F = R.face;
@@ -367,6 +390,7 @@ export const BOT_XAML = `<Canvas x:Name="Stage" Width="${S}" Height="${S}">
367
390
  <Canvas x:Name="EyeR" Canvas.Left="${F.eyeDx}" Canvas.Top="${F.eyeY}"><Canvas.RenderTransform><ScaleTransform x:Name="EyeMorphR"/></Canvas.RenderTransform>
368
391
  ${eyeSide('R')}
369
392
  </Canvas>
393
+ ${TEARS_XAML}
370
394
  </Canvas>
371
395
  <Canvas x:Name="Mouth" Canvas.Top="${F.mouthY}"><Canvas.RenderTransform><ScaleTransform x:Name="MouthMorph"/></Canvas.RenderTransform>
372
396
  ${BOT_MOUTHS.map((n) => `<Canvas x:Name="Mouth_${n}" Visibility="Collapsed">${MOUTH_SHAPES[n]}</Canvas>`).join('\n ')}
@@ -0,0 +1,382 @@
1
+ /**
2
+ * Tính hình của biểu đồ cho ô hỏi linh vật (03/11/2026): khối `chart` → danh sách hình (chữ nhật, nét, chấm, chữ) theo toạ độ; cửa sổ chỉ vẽ lại đúng danh sách đó
3
+ * (askChartSource.mjs). Tính ở daemon để PowerShell không phải chạy vòng lặp toán, và test được không cần cửa sổ. Đủ 12 kiểu như `ChartComponent.txt`.
4
+ * Hình: `{ k: 'r', x, y, w, h, f, rx? }`, `{ k: 'p', d, s?, f?, sw?, dash? }`, `{ k: 'c', x, y, r, f, s? }`, `{ k: 't', x, y, w, t, a?, c?, z?, b? }`.
5
+ */
6
+ const WIDTH = 288;
7
+ const CHART_HEIGHT = 150;
8
+ const ROUND_HEIGHT = 150;
9
+ const RADAR_HEIGHT = 180;
10
+ /** Nền cột nhạt, nét đường đậm cùng tông: giống bảng màu biểu đồ trên web. */
11
+ const FILLS = ['#93C5FD', '#6EE7B7', '#FCD34D', '#FCA5A5', '#C4B5FD', '#67E8F9'];
12
+ const INKS = ['#2563EB', '#059669', '#D97706', '#DC2626', '#7C3AED', '#0891B2'];
13
+ const POSITIVE = '#34D399';
14
+ const NEGATIVE = '#F87171';
15
+ const POSITIVE_INK = '#059669';
16
+ const NEGATIVE_INK = '#DC2626';
17
+ const GRID = '#EEF0F4';
18
+ const TICK_INK = '#86909C';
19
+ const TEXT_INK = '#4E5969';
20
+ const TICK_SIZE = 10.5;
21
+ const CHAR_PX = 5.6;
22
+ /** Chữ số rộng hơn chữ thường một chút: nhãn trục mà tính thiếu thì bị cắt mất số. */
23
+ const TICK_CHAR_PX = 6.4;
24
+ const LABEL_GAP = 4;
25
+
26
+ const BAR_KINDS = new Set(['bar', 'stackedBar']);
27
+ const HORIZONTAL_KINDS = new Set(['horizontalBar', 'stackedHorizontalBar']);
28
+ const STACKED_KINDS = new Set(['stackedBar', 'stackedHorizontalBar']);
29
+
30
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
31
+ const fix = (v) => Math.round(v * 100) / 100;
32
+ const point = (x, y) => `${fix(x)} ${fix(y)}`;
33
+
34
+ function formatter(lang) {
35
+ try {
36
+ return new Intl.NumberFormat(lang || 'en', { notation: 'compact', maximumFractionDigits: 1 });
37
+ } catch {
38
+ return new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 });
39
+ }
40
+ }
41
+
42
+ /** Mốc trục tròn số bao trọn [min, max]. */
43
+ export function niceTicks(min, max, count = 4) {
44
+ if (min === max) { max = min === 0 ? 1 : min + Math.abs(min) / 2; min = min > 0 ? 0 : min - (min < 0 ? Math.abs(min) / 2 : 0); }
45
+ const raw = (max - min) / count;
46
+ const mag = 10 ** Math.floor(Math.log10(raw));
47
+ const norm = raw / mag;
48
+ const step = (norm <= 1 ? 1 : norm <= 2 ? 2 : norm <= 5 ? 5 : 10) * mag;
49
+ const low = Math.floor(min / step) * step;
50
+ const high = Math.ceil(max / step) * step;
51
+ const ticks = [];
52
+ for (let v = low; v <= high + step / 2; v += step) ticks.push(fix(v * 1e6) / 1e6);
53
+ return { min: low, max: high, ticks };
54
+ }
55
+
56
+ const text = (x, y, w, t, extra = {}) => ({ k: 't', x: fix(x), y: fix(y), w: fix(w), t, ...extra });
57
+ const hline = (x1, x2, y, s = GRID) => ({ k: 'p', d: `M${point(x1, y)}L${point(x2, y)}`, s, sw: 1 });
58
+ const vline = (x, y1, y2, s = GRID) => ({ k: 'p', d: `M${point(x, y1)}L${point(x, y2)}`, s, sw: 1 });
59
+
60
+ const seriesFill = (s, i) => s.color || (s.semantic === 'positive' ? POSITIVE : s.semantic === 'negative' ? NEGATIVE : FILLS[i % FILLS.length]);
61
+ const seriesInk = (s, i) => s.color || (s.semantic === 'positive' ? POSITIVE_INK : s.semantic === 'negative' ? NEGATIVE_INK : INKS[i % INKS.length]);
62
+
63
+ /** Một dãy duy nhất có cả số dương lẫn âm: tăng xanh, giảm đỏ, như web. */
64
+ const mixedSigns = (series) => series.length === 1 && series[0].data.some((v) => num(v) > 0) && series[0].data.some((v) => num(v) < 0);
65
+
66
+ function barColor(series, seriesIndex, value, pointIndex, all) {
67
+ const s = series;
68
+ if (mixedSigns(all) && !s.color) return value < 0 ? NEGATIVE : POSITIVE;
69
+ // Nhấn vài cột: cột thường nhạt đi, cột nhấn dùng màu đậm.
70
+ if (s.highlight?.length) return s.highlight.includes(pointIndex) ? seriesInk(s, seriesIndex) : seriesFill(s, seriesIndex);
71
+ return seriesFill(s, seriesIndex);
72
+ }
73
+
74
+ function stackedRange(series, n) {
75
+ let low = 0;
76
+ let high = 0;
77
+ for (let p = 0; p < n; p++) {
78
+ let up = 0;
79
+ let down = 0;
80
+ for (const s of series) {
81
+ const v = num(s.data[p]) ?? 0;
82
+ if (v >= 0) up += v; else down += v;
83
+ }
84
+ high = Math.max(high, up);
85
+ low = Math.min(low, down);
86
+ }
87
+ return [low, high];
88
+ }
89
+
90
+ function plainRange(series, includeZero) {
91
+ const values = series.flatMap((s) => s.data.map(num)).filter((v) => v !== null);
92
+ if (!values.length) return null;
93
+ return [includeZero ? Math.min(0, ...values) : Math.min(...values), includeZero ? Math.max(0, ...values) : Math.max(...values)];
94
+ }
95
+
96
+ /** Nhãn danh mục dọc trục ngang: nhãn dày thì cách quãng để không đè nhau. */
97
+ function categoryLabels(shapes, labels, n, left, slot, y) {
98
+ const every = Math.max(1, Math.ceil((CHAR_PX * 6) / slot));
99
+ for (let i = 0; i < n; i += every) {
100
+ if (!labels[i]) continue;
101
+ const w = slot * every - 2;
102
+ shapes.push(text(left + slot * i + slot / 2 - w / 2, y, w, labels[i], { a: 'c', c: TICK_INK, z: TICK_SIZE }));
103
+ }
104
+ }
105
+
106
+ function pointCount(chart) {
107
+ return Math.max(chart.labels.length, ...chart.series.map((s) => s.data.length));
108
+ }
109
+
110
+ /** Cột dọc gom nhóm / chồng + đường, gồm cả `combo` (đường theo trục phải). */
111
+ function verticalChart(chart, lang) {
112
+ const { series, labels, kind } = chart;
113
+ const n = pointCount(chart);
114
+ const fmt = formatter(lang);
115
+ const isLine = (s) => kind === 'line' || (kind === 'combo' && s.type === 'line');
116
+ const leftSeries = series.filter((s) => s.axis !== 'right');
117
+ const rightSeries = series.filter((s) => s.axis === 'right');
118
+ const stacked = STACKED_KINDS.has(kind);
119
+ const includeZero = kind !== 'line';
120
+ const leftRange = stacked ? stackedRange(leftSeries, n) : plainRange(leftSeries, includeZero);
121
+ if (!leftRange) return null;
122
+ const left = niceTicks(leftRange[0], leftRange[1]);
123
+ const rightRange = rightSeries.length ? plainRange(rightSeries, false) : null;
124
+ const right = rightRange ? niceTicks(rightRange[0], rightRange[1]) : null;
125
+ const tickWidth = (ticks) => Math.max(...ticks.map((v) => fmt.format(v).length)) * TICK_CHAR_PX + LABEL_GAP;
126
+ const x0 = tickWidth(left.ticks);
127
+ const x1 = WIDTH - (right ? tickWidth(right.ticks) + LABEL_GAP : 4);
128
+ const y0 = 6;
129
+ const y1 = CHART_HEIGHT - 20;
130
+ const yOf = (scale, v) => y1 - ((v - scale.min) / (scale.max - scale.min || 1)) * (y1 - y0);
131
+ const shapes = [];
132
+ for (const v of left.ticks) {
133
+ const y = yOf(left, v);
134
+ shapes.push(hline(x0, x1, y, v === 0 ? '#C9CDD4' : GRID));
135
+ shapes.push(text(0, y - 7, x0 - LABEL_GAP, fmt.format(v), { a: 'r', c: TICK_INK, z: TICK_SIZE }));
136
+ }
137
+ if (right) {
138
+ for (const v of right.ticks) shapes.push(text(x1 + LABEL_GAP, yOf(right, v) - 7, WIDTH - x1 - LABEL_GAP, fmt.format(v), { a: 'l', c: TICK_INK, z: TICK_SIZE }));
139
+ }
140
+ const slot = (x1 - x0) / Math.max(n, 1);
141
+ const barSeries = series.filter((s) => !isLine(s));
142
+ const groupWidth = slot * 0.72;
143
+ const barWidth = stacked ? Math.min(groupWidth, 32) : Math.min(groupWidth / Math.max(barSeries.length, 1), 24);
144
+ for (let p = 0; p < n; p++) {
145
+ let up = 0;
146
+ let down = 0;
147
+ let at = 0;
148
+ const groupStart = x0 + slot * p + slot / 2 - (stacked ? barWidth : barWidth * barSeries.length) / 2;
149
+ series.forEach((s, si) => {
150
+ if (isLine(s)) return;
151
+ const v = num(s.data[p]);
152
+ const index = at++;
153
+ if (v === null) return;
154
+ const scale = s.axis === 'right' && right ? right : left;
155
+ let from = 0;
156
+ if (stacked) { from = v >= 0 ? up : down; if (v >= 0) up += v; else down += v; }
157
+ const a = yOf(scale, from);
158
+ const b = yOf(scale, from + v);
159
+ shapes.push({
160
+ k: 'r', x: fix(stacked ? groupStart : groupStart + index * barWidth + 0.5), y: fix(Math.min(a, b)), w: fix(Math.max(1, barWidth - (stacked ? 0 : 1))), h: fix(Math.max(1, Math.abs(a - b))),
161
+ f: barColor(s, si, v, p, series), rx: stacked ? 0 : 2,
162
+ });
163
+ });
164
+ }
165
+ series.forEach((s, si) => {
166
+ if (!isLine(s)) return;
167
+ const scale = s.axis === 'right' && right ? right : left;
168
+ const ink = seriesInk(s, si);
169
+ let d = '';
170
+ let pen = false;
171
+ for (let p = 0; p < n; p++) {
172
+ const v = num(s.data[p]);
173
+ if (v === null) { pen = false; continue; }
174
+ d += `${pen ? 'L' : 'M'}${point(x0 + slot * p + slot / 2, yOf(scale, v))}`;
175
+ pen = true;
176
+ }
177
+ if (d) shapes.push({ k: 'p', d, s: ink, sw: 2 });
178
+ if (n <= 16) {
179
+ for (let p = 0; p < n; p++) {
180
+ const v = num(s.data[p]);
181
+ if (v !== null) shapes.push({ k: 'c', x: fix(x0 + slot * p + slot / 2), y: fix(yOf(scale, v)), r: 2.5, f: '#FFFFFF', s: ink });
182
+ }
183
+ }
184
+ });
185
+ categoryLabels(shapes, labels, n, x0, slot, y1 + 4);
186
+ return { w: WIDTH, h: CHART_HEIGHT, shapes };
187
+ }
188
+
189
+ function horizontalChart(chart, lang) {
190
+ const { series, labels, kind } = chart;
191
+ const n = pointCount(chart);
192
+ const fmt = formatter(lang);
193
+ const stacked = STACKED_KINDS.has(kind);
194
+ const range = stacked ? stackedRange(series, n) : plainRange(series, true);
195
+ if (!range) return null;
196
+ const scale = niceTicks(range[0], range[1], 3);
197
+ const labelWidth = Math.min(96, Math.max(24, Math.max(0, ...labels.map((l) => (l || '').length)) * CHAR_PX + LABEL_GAP));
198
+ const x0 = labelWidth + LABEL_GAP;
199
+ const x1 = WIDTH - 8;
200
+ const groupHeight = stacked ? 16 : Math.max(10, Math.min(8 * series.length + 4, 24));
201
+ const rowHeight = groupHeight + 6;
202
+ const h = n * rowHeight + 20;
203
+ const xOf = (v) => x0 + ((v - scale.min) / (scale.max - scale.min || 1)) * (x1 - x0);
204
+ const shapes = [];
205
+ for (const v of scale.ticks) {
206
+ const x = xOf(v);
207
+ shapes.push(vline(x, 2, h - 18, v === 0 ? '#C9CDD4' : GRID));
208
+ shapes.push(text(x - 24, h - 15, 48, fmt.format(v), { a: 'c', c: TICK_INK, z: TICK_SIZE }));
209
+ }
210
+ for (let p = 0; p < n; p++) {
211
+ const top = 3 + p * rowHeight;
212
+ if (labels[p]) shapes.push(text(0, top + groupHeight / 2 - 7, labelWidth, labels[p], { a: 'r', c: TEXT_INK, z: TICK_SIZE }));
213
+ let up = 0;
214
+ let down = 0;
215
+ series.forEach((s, si) => {
216
+ const v = num(s.data[p]);
217
+ if (v === null) return;
218
+ let from = 0;
219
+ if (stacked) { from = v >= 0 ? up : down; if (v >= 0) up += v; else down += v; }
220
+ const a = xOf(from);
221
+ const b = xOf(from + v);
222
+ const barHeight = stacked ? groupHeight : groupHeight / series.length;
223
+ shapes.push({
224
+ k: 'r', x: fix(Math.min(a, b)), y: fix(stacked ? top : top + si * barHeight), w: fix(Math.max(1, Math.abs(a - b))), h: fix(Math.max(1, barHeight - (stacked ? 0 : 1))),
225
+ f: barColor(s, si, v, p, series), rx: stacked ? 0 : 2,
226
+ });
227
+ });
228
+ }
229
+ return { w: WIDTH, h, shapes };
230
+ }
231
+
232
+ function sector(cx, cy, r, inner, start, end) {
233
+ const sweep = end - start;
234
+ // Một lát trọn vòng: vẽ hai nửa, cung trùng điểm đầu cuối thì không ra hình.
235
+ if (sweep >= Math.PI * 2 - 1e-4) return `${sector(cx, cy, r, inner, start, start + Math.PI)}${sector(cx, cy, r, inner, start + Math.PI, start + Math.PI * 2)}`;
236
+ const at = (radius, angle) => point(cx + radius * Math.cos(angle), cy + radius * Math.sin(angle));
237
+ const large = sweep > Math.PI ? 1 : 0;
238
+ if (!inner) return `M${point(cx, cy)}L${at(r, start)}A${fix(r)} ${fix(r)} 0 ${large} 1 ${at(r, end)}Z`;
239
+ return `M${at(r, start)}A${fix(r)} ${fix(r)} 0 ${large} 1 ${at(r, end)}L${at(inner, end)}A${fix(inner)} ${fix(inner)} 0 ${large} 0 ${at(inner, start)}Z`;
240
+ }
241
+
242
+ function pieChart(chart) {
243
+ const values = chart.series[0].data.map((v) => Math.max(0, num(v) ?? 0));
244
+ const total = values.reduce((a, b) => a + b, 0);
245
+ if (!total) return null;
246
+ const cy = ROUND_HEIGHT / 2;
247
+ const cx = WIDTH / 2;
248
+ const r = cy - 4;
249
+ const inner = chart.kind === 'doughnut' ? r * 0.58 : 0;
250
+ const shapes = [];
251
+ const legend = [];
252
+ let angle = -Math.PI / 2;
253
+ values.forEach((v, i) => {
254
+ const color = chart.series[0].highlight?.includes(i) ? INKS[i % INKS.length] : FILLS[i % FILLS.length];
255
+ const pct = Math.round((v / total) * 100);
256
+ if (chart.labels[i]) legend.push({ label: `${chart.labels[i]} ${pct}%`, color });
257
+ if (!v) return;
258
+ const end = angle + (v / total) * Math.PI * 2;
259
+ shapes.push({ k: 'p', d: sector(cx, cy, r, inner, angle, end), f: color, s: '#FFFFFF', sw: 1.5 });
260
+ if (pct >= 8) {
261
+ const mid = (angle + end) / 2;
262
+ const rr = inner ? (r + inner) / 2 : r * 0.62;
263
+ shapes.push(text(cx + rr * Math.cos(mid) - 18, cy + rr * Math.sin(mid) - 7, 36, `${pct}%`, { a: 'c', c: TEXT_INK, z: TICK_SIZE, b: true }));
264
+ }
265
+ angle = end;
266
+ });
267
+ return { w: WIDTH, h: ROUND_HEIGHT, shapes, legend };
268
+ }
269
+
270
+ function polarChart(chart) {
271
+ const values = chart.series[0].data.map((v) => Math.max(0, num(v) ?? 0));
272
+ const max = Math.max(...values);
273
+ if (!max) return null;
274
+ const cy = ROUND_HEIGHT / 2;
275
+ const cx = WIDTH / 2;
276
+ const r = cy - 4;
277
+ const shapes = [];
278
+ const legend = [];
279
+ for (const k of [1, 0.66, 0.33]) shapes.push({ k: 'c', x: cx, y: cy, r: fix(r * k), f: null, s: GRID });
280
+ const slice = (Math.PI * 2) / values.length;
281
+ values.forEach((v, i) => {
282
+ const start = -Math.PI / 2 + i * slice;
283
+ const color = FILLS[i % FILLS.length];
284
+ if (chart.labels[i]) legend.push({ label: chart.labels[i], color });
285
+ if (v) shapes.push({ k: 'p', d: sector(cx, cy, r * (v / max), 0, start, start + slice), f: `#CC${color.slice(1)}`, s: '#FFFFFF', sw: 1 });
286
+ });
287
+ return { w: WIDTH, h: ROUND_HEIGHT, shapes, legend };
288
+ }
289
+
290
+ function radarChart(chart) {
291
+ const n = pointCount(chart);
292
+ const range = plainRange(chart.series, true);
293
+ if (!range || n < 3) return null;
294
+ const scale = niceTicks(0, Math.max(range[1], 1), 4);
295
+ const cx = WIDTH / 2;
296
+ const cy = RADAR_HEIGHT / 2;
297
+ const r = cy - 20;
298
+ const at = (i, k) => {
299
+ const a = -Math.PI / 2 + (i / n) * Math.PI * 2;
300
+ return [cx + r * k * Math.cos(a), cy + r * k * Math.sin(a)];
301
+ };
302
+ const shapes = [];
303
+ for (const v of scale.ticks.slice(1)) {
304
+ const k = v / scale.max;
305
+ shapes.push({ k: 'p', d: `${Array.from({ length: n }, (_, i) => `${i ? 'L' : 'M'}${point(...at(i, k))}`).join('')}Z`, s: GRID, sw: 1 });
306
+ }
307
+ for (let i = 0; i < n; i++) {
308
+ const [x, y] = at(i, 1);
309
+ shapes.push({ k: 'p', d: `M${point(cx, cy)}L${point(x, y)}`, s: GRID, sw: 1 });
310
+ if (chart.labels[i]) {
311
+ const [lx, ly] = at(i, 1.1);
312
+ const onLeft = lx < cx - 4;
313
+ const onRight = lx > cx + 4;
314
+ const w = 76;
315
+ shapes.push(text(onLeft ? lx - w : onRight ? lx : lx - w / 2, ly - 7, w, chart.labels[i], { a: onLeft ? 'r' : onRight ? 'l' : 'c', c: TICK_INK, z: TICK_SIZE }));
316
+ }
317
+ }
318
+ chart.series.forEach((s, si) => {
319
+ const ink = seriesInk(s, si);
320
+ const pts = Array.from({ length: n }, (_, i) => at(i, Math.max(0, num(s.data[i]) ?? 0) / scale.max));
321
+ shapes.push({ k: 'p', d: `${pts.map((p, i) => `${i ? 'L' : 'M'}${point(...p)}`).join('')}Z`, s: ink, sw: 1.6, f: `#33${ink.slice(1)}` });
322
+ for (const p of pts) shapes.push({ k: 'c', x: fix(p[0]), y: fix(p[1]), r: 2, f: ink });
323
+ });
324
+ return { w: WIDTH, h: RADAR_HEIGHT, shapes };
325
+ }
326
+
327
+ function scatterChart(chart, lang) {
328
+ const pts = chart.series.flatMap((s) => s.data).filter((v) => v && typeof v === 'object');
329
+ if (!pts.length) return null;
330
+ const fmt = formatter(lang);
331
+ const xs = niceTicks(Math.min(...pts.map((p) => p.x)), Math.max(...pts.map((p) => p.x)));
332
+ const ys = niceTicks(Math.min(...pts.map((p) => p.y)), Math.max(...pts.map((p) => p.y)));
333
+ const x0 = Math.max(...ys.ticks.map((v) => fmt.format(v).length)) * TICK_CHAR_PX + LABEL_GAP;
334
+ const x1 = WIDTH - 8;
335
+ const y0 = 6;
336
+ const y1 = CHART_HEIGHT - 20;
337
+ const px = (v) => x0 + ((v - xs.min) / (xs.max - xs.min || 1)) * (x1 - x0);
338
+ const py = (v) => y1 - ((v - ys.min) / (ys.max - ys.min || 1)) * (y1 - y0);
339
+ const shapes = [];
340
+ for (const v of ys.ticks) {
341
+ shapes.push(hline(x0, x1, py(v)));
342
+ shapes.push(text(0, py(v) - 7, x0 - LABEL_GAP, fmt.format(v), { a: 'r', c: TICK_INK, z: TICK_SIZE }));
343
+ }
344
+ for (const v of xs.ticks) {
345
+ shapes.push(vline(px(v), y0, y1));
346
+ shapes.push(text(px(v) - 22, y1 + 4, 44, fmt.format(v), { a: 'c', c: TICK_INK, z: TICK_SIZE }));
347
+ }
348
+ const maxR = Math.max(1, ...pts.map((p) => num(p.r) ?? 0));
349
+ chart.series.forEach((s, si) => {
350
+ const ink = seriesInk(s, si);
351
+ for (const p of s.data) {
352
+ if (!p || typeof p !== 'object') continue;
353
+ const r = chart.kind === 'bubble' ? Math.max(3, Math.sqrt((num(p.r) ?? 0) / maxR) * 14) : 3;
354
+ shapes.push({ k: 'c', x: fix(px(p.x)), y: fix(py(p.y)), r: fix(r), f: `#66${ink.slice(1)}`, s: ink });
355
+ }
356
+ });
357
+ return { w: WIDTH, h: CHART_HEIGHT, shapes };
358
+ }
359
+
360
+ function seriesLegend(chart) {
361
+ if (chart.series.length < 2 && !chart.series[0]?.label) return [];
362
+ return chart.series.filter((s) => s.label).map((s) => {
363
+ const si = chart.series.indexOf(s);
364
+ const line = chart.kind === 'line' || chart.kind === 'radar' || chart.kind === 'scatter' || chart.kind === 'bubble' || (chart.kind === 'combo' && s.type === 'line');
365
+ return { label: s.label, color: line ? seriesInk(s, si) : seriesFill(s, si) };
366
+ });
367
+ }
368
+
369
+ /** Khối biểu đồ → `{ w, h, shapes, legend }`; không có số để vẽ → null (nơi gọi đổi thành nhãn + nút xem trên web). */
370
+ export function chartLayout(chart, lang) {
371
+ if (!chart?.series?.length) return null;
372
+ const { kind } = chart;
373
+ let out = null;
374
+ if (kind === 'pie' || kind === 'doughnut') out = pieChart(chart);
375
+ else if (kind === 'polarArea') out = polarChart(chart);
376
+ else if (kind === 'radar') out = radarChart(chart);
377
+ else if (kind === 'scatter' || kind === 'bubble') out = scatterChart(chart, lang);
378
+ else if (HORIZONTAL_KINDS.has(kind)) out = horizontalChart(chart, lang);
379
+ else if (BAR_KINDS.has(kind) || kind === 'line' || kind === 'combo') out = verticalChart(chart, lang);
380
+ if (!out) return null;
381
+ return { ...out, legend: out.legend || seriesLegend(chart) };
382
+ }