@icen.ai/ui 0.4.0 → 0.8.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 (155) hide show
  1. package/AGENTS.md +256 -0
  2. package/README.md +47 -13
  3. package/dist/base.css +31 -4
  4. package/dist/behaviors/accordion.d.mts +4 -0
  5. package/dist/behaviors/accordion.mjs +4 -3
  6. package/dist/behaviors/ai-chat.d.mts +57 -0
  7. package/dist/behaviors/ai-chat.mjs +557 -0
  8. package/dist/behaviors/ai-composer.d.mts +112 -0
  9. package/dist/behaviors/ai-composer.mjs +2032 -0
  10. package/dist/behaviors/ai-core.d.mts +151 -0
  11. package/dist/behaviors/ai-core.mjs +491 -0
  12. package/dist/behaviors/ai-diff.d.mts +53 -0
  13. package/dist/behaviors/ai-diff.mjs +282 -0
  14. package/dist/behaviors/ai-panel.d.mts +98 -0
  15. package/dist/behaviors/ai-panel.mjs +1012 -0
  16. package/dist/behaviors/ai-provider.d.mts +198 -0
  17. package/dist/behaviors/ai-provider.mjs +1055 -0
  18. package/dist/behaviors/ai-tool.d.mts +18 -0
  19. package/dist/behaviors/ai-tool.mjs +2125 -0
  20. package/dist/behaviors/ai-tools.d.mts +81 -0
  21. package/dist/behaviors/ai-tools.mjs +1658 -0
  22. package/dist/behaviors/back-top.d.mts +20 -0
  23. package/dist/behaviors/back-top.mjs +101 -0
  24. package/dist/behaviors/carousel.d.mts +4 -0
  25. package/dist/behaviors/carousel.mjs +34 -16
  26. package/dist/behaviors/charts.d.mts +250 -0
  27. package/dist/behaviors/charts.mjs +1301 -448
  28. package/dist/behaviors/command-palette.d.mts +8 -0
  29. package/dist/behaviors/command-palette.mjs +189 -0
  30. package/dist/behaviors/context-menu.d.mts +36 -0
  31. package/dist/behaviors/context-menu.mjs +6 -2
  32. package/dist/behaviors/copy.d.mts +4 -0
  33. package/dist/behaviors/copy.mjs +7 -6
  34. package/dist/behaviors/datatable.d.mts +78 -0
  35. package/dist/behaviors/datatable.mjs +54 -11
  36. package/dist/behaviors/date-picker.d.mts +4 -0
  37. package/dist/behaviors/date-picker.mjs +296 -0
  38. package/dist/behaviors/dropdown.d.mts +4 -0
  39. package/dist/behaviors/dropdown.mjs +7 -3
  40. package/dist/behaviors/input.d.mts +4 -0
  41. package/dist/behaviors/input.mjs +184 -8
  42. package/dist/behaviors/modal.d.mts +11 -0
  43. package/dist/behaviors/modal.mjs +11 -6
  44. package/dist/behaviors/nav.d.mts +7 -0
  45. package/dist/behaviors/nav.mjs +25 -9
  46. package/dist/behaviors/notification.d.mts +172 -0
  47. package/dist/behaviors/notification.mjs +908 -0
  48. package/dist/behaviors/popover.d.mts +46 -0
  49. package/dist/behaviors/popover.mjs +2 -1
  50. package/dist/behaviors/select.d.mts +4 -0
  51. package/dist/behaviors/select.mjs +268 -34
  52. package/dist/behaviors/sidebar.d.mts +4 -0
  53. package/dist/behaviors/sidebar.mjs +4 -3
  54. package/dist/behaviors/slider.d.mts +4 -0
  55. package/dist/behaviors/slider.mjs +4 -3
  56. package/dist/behaviors/split-pane.d.mts +4 -0
  57. package/dist/behaviors/split-pane.mjs +102 -0
  58. package/dist/behaviors/tabs.d.mts +8 -0
  59. package/dist/behaviors/tabs.mjs +44 -19
  60. package/dist/behaviors/tag-input.d.mts +4 -0
  61. package/dist/behaviors/tag-input.mjs +12 -3
  62. package/dist/behaviors/theme.d.mts +25 -0
  63. package/dist/behaviors/theme.mjs +3 -1
  64. package/dist/behaviors/toast.d.mts +26 -0
  65. package/dist/behaviors/toast.mjs +24 -18
  66. package/dist/behaviors/tree.d.mts +4 -0
  67. package/dist/behaviors/tree.mjs +4 -3
  68. package/dist/behaviors/upload.d.mts +4 -0
  69. package/dist/behaviors/upload.mjs +205 -17
  70. package/dist/components/ai-chat.css +1037 -0
  71. package/dist/components/ai-chat.mjs +3 -0
  72. package/dist/components/ai-composer.mjs +3 -0
  73. package/dist/components/ai-context.mjs +2 -0
  74. package/dist/components/ai-diff.css +311 -0
  75. package/dist/components/ai-diff.mjs +3 -0
  76. package/dist/components/ai-files.mjs +3 -0
  77. package/dist/components/ai-message.mjs +3 -0
  78. package/dist/components/ai-panel.css +682 -0
  79. package/dist/components/ai-reasoning.mjs +3 -0
  80. package/dist/components/ai-subagent.mjs +2 -0
  81. package/dist/components/ai-todo.mjs +2 -0
  82. package/dist/components/ai-tool-call.mjs +2 -0
  83. package/dist/components/ai-tool.css +532 -0
  84. package/dist/components/ai-usage.mjs +3 -0
  85. package/dist/components/back-top.css +88 -0
  86. package/dist/components/back-top.mjs +3 -0
  87. package/dist/components/badge.css +127 -0
  88. package/dist/components/badge.mjs +2 -0
  89. package/dist/components/breadcrumb.css +53 -0
  90. package/dist/components/btn.css +4 -7
  91. package/dist/components/card.css +66 -1
  92. package/dist/components/chart-bar.css +10 -0
  93. package/dist/components/chart-calendar.mjs +5 -0
  94. package/dist/components/chart-gauge.css +1 -1
  95. package/dist/components/chart-heatmap.css +40 -0
  96. package/dist/components/chart-scatter.css +24 -0
  97. package/dist/components/chart-scatter.mjs +4 -0
  98. package/dist/components/charts.css +86 -1
  99. package/dist/components/charts.mjs +1 -0
  100. package/dist/components/command-palette.css +246 -0
  101. package/dist/components/command-palette.mjs +3 -0
  102. package/dist/components/content.css +221 -8
  103. package/dist/components/copy.css +93 -0
  104. package/dist/components/copy.mjs +3 -0
  105. package/dist/components/datatable.css +4 -8
  106. package/dist/components/date-picker.css +240 -0
  107. package/dist/components/date-picker.mjs +3 -0
  108. package/dist/components/empty.css +69 -3
  109. package/dist/components/feedback.css +241 -10
  110. package/dist/components/form.css +129 -11
  111. package/dist/components/form.mjs +2 -0
  112. package/dist/components/input.css +25 -2
  113. package/dist/components/layout.css +36 -36
  114. package/dist/components/media.css +153 -6
  115. package/dist/components/menu.css +2 -2
  116. package/dist/components/modal.css +1 -1
  117. package/dist/components/nav.css +106 -2
  118. package/dist/components/notification.css +387 -0
  119. package/dist/components/notification.mjs +3 -0
  120. package/dist/components/pagination.css +1 -1
  121. package/dist/components/panel.css +104 -9
  122. package/dist/components/pill.css +82 -12
  123. package/dist/components/scroll-area.css +112 -0
  124. package/dist/components/scroll-area.mjs +2 -0
  125. package/dist/components/segmented.css +80 -5
  126. package/dist/components/segmented.mjs +1 -0
  127. package/dist/components/select.css +104 -17
  128. package/dist/components/sidebar.css +119 -1
  129. package/dist/components/slider.css +113 -0
  130. package/dist/components/split-pane.css +111 -0
  131. package/dist/components/split-pane.mjs +3 -0
  132. package/dist/components/stat.css +131 -12
  133. package/dist/components/steps.css +98 -1
  134. package/dist/components/switch.css +145 -7
  135. package/dist/components/table.css +111 -29
  136. package/dist/components/tabs.css +132 -22
  137. package/dist/components/tag-input.css +4 -4
  138. package/dist/components/tag.css +164 -0
  139. package/dist/components/tag.mjs +2 -0
  140. package/dist/components/toast.css +122 -5
  141. package/dist/components/toolbar.css +101 -0
  142. package/dist/components/toolbar.mjs +2 -0
  143. package/dist/components/tooltip.css +2 -2
  144. package/dist/components/upload.css +61 -4
  145. package/dist/index.d.mts +37 -0
  146. package/dist/index.mjs +9409 -929
  147. package/dist/registry.json +176 -4
  148. package/dist/retro-effects.css +21 -17
  149. package/dist/tokens/colors.css +4 -1
  150. package/dist/tokens/retro-effects.css +21 -17
  151. package/dist/tokens/style-profiles.css +21 -0
  152. package/dist/tokens.css +25 -1
  153. package/dist/ui.css +9616 -2839
  154. package/docs/spec/ai-native.md +659 -0
  155. package/package.json +15 -5
@@ -0,0 +1,2125 @@
1
+ // src/behaviors/ai-core.ts
2
+ function aiStatusLabel(s) {
3
+ const labels = {
4
+ pending: "\u7B49\u5F85",
5
+ running: "\u6267\u884C\u4E2D",
6
+ streaming: "\u6D41\u5F0F\u4E2D",
7
+ approval: "\u5F85\u786E\u8BA4",
8
+ done: "\u5B8C\u6210",
9
+ error: "\u5931\u8D25",
10
+ cancelled: "\u5DF2\u53D6\u6D88"
11
+ };
12
+ return labels[s] ?? s;
13
+ }
14
+ var svg = (body) => `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${body}</svg>`;
15
+ var ICON_TERMINAL = svg('<path d="m4 17 6-6-6-6"/><path d="M12 19h8"/>');
16
+ var ICON_FILE = svg(
17
+ '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/>'
18
+ );
19
+ var ICON_FILE_PEN = svg(
20
+ '<path d="M12.5 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8l5 5v3.5"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M19 6.5 16.5 4"/><path d="M21.378 16.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z"/>'
21
+ );
22
+ var ICON_FILE_PLUS = svg(
23
+ '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M9 15h6"/><path d="M12 12v6"/>'
24
+ );
25
+ var ICON_TRASH = svg(
26
+ '<path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="M10 11v6"/><path d="M14 11v6"/>'
27
+ );
28
+ var ICON_SEARCH = svg('<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>');
29
+ var ICON_FOLDER_SEARCH = svg(
30
+ '<path d="M11 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v4"/><circle cx="17" cy="17" r="3"/><path d="m21 21-1.9-1.9"/>'
31
+ );
32
+ var ICON_SCAN_SEARCH = svg(
33
+ '<path d="M3 7V5a2 2 0 0 1 2-2h2"/><path d="M17 3h2a2 2 0 0 1 2 2v2"/><path d="M21 17v2a2 2 0 0 1-2 2h-2"/><path d="M7 21H5a2 2 0 0 1-2-2v-2"/><circle cx="12" cy="12" r="3"/><path d="m16 16-1.9-1.9"/>'
34
+ );
35
+ var ICON_GLOBE = svg(
36
+ '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>'
37
+ );
38
+ var ICON_DOWNLOAD = svg(
39
+ '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="m7 10 5 5 5-5"/><path d="M12 15V3"/>'
40
+ );
41
+ var ICON_BLOCKS = svg(
42
+ '<rect width="7" height="7" x="4" y="4" rx="1"/><rect width="7" height="7" x="13" y="4" rx="1"/><rect width="7" height="7" x="4" y="13" rx="1"/><rect width="7" height="7" x="13" y="13" rx="1"/>'
43
+ );
44
+ var ICON_ZAP = svg(
45
+ '<path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/>'
46
+ );
47
+ var ICON_LIST = svg(
48
+ '<path d="M3 12h.01"/><path d="M3 18h.01"/><path d="M3 6h.01"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M8 6h13"/>'
49
+ );
50
+ var ICON_LIST_CHECKS = svg(
51
+ '<path d="m3 17 2 2 4-4"/><path d="m3 7 2 2 4-4"/><path d="M13 6h8"/><path d="M13 12h8"/><path d="M13 18h8"/>'
52
+ );
53
+ var ICON_BOT = svg(
54
+ '<path d="M12 8V4H8"/><rect width="16" height="12" x="4" y="8" rx="2"/><path d="M2 14h2"/><path d="M20 14h2"/><path d="M15 13v2"/><path d="M9 13v2"/>'
55
+ );
56
+ var ICON_CHART = svg(
57
+ '<path d="M3 3v18h18"/><path d="M7 15l4-6 3 4 5-8"/>'
58
+ );
59
+ var ICON_FILE_TEXT = svg(
60
+ '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/>'
61
+ );
62
+ function isObj(v) {
63
+ return typeof v === "object" && v !== null;
64
+ }
65
+ function pickStr(input, keys) {
66
+ if (!isObj(input)) return void 0;
67
+ for (const k of keys) {
68
+ const v = input[k];
69
+ if (typeof v === "string" && v) return v;
70
+ }
71
+ return void 0;
72
+ }
73
+ function pickNum(src, keys) {
74
+ if (!isObj(src)) return void 0;
75
+ for (const k of keys) {
76
+ const v = src[k];
77
+ if (typeof v === "number" && Number.isFinite(v)) return v;
78
+ }
79
+ return void 0;
80
+ }
81
+ function firstLine(s, max = 80) {
82
+ const line = s.split("\n", 1)[0]?.trim() ?? "";
83
+ return line.length > max ? `${line.slice(0, max)}\u2026` : line;
84
+ }
85
+ function filePathOf(input) {
86
+ return pickStr(input, ["file_path", "path", "file", "filename"]);
87
+ }
88
+ var summarizePath = (input) => filePathOf(input);
89
+ function summarizeRead(input) {
90
+ const p = filePathOf(input);
91
+ if (!p) return void 0;
92
+ const offset = pickNum(input, ["offset", "start_line"]);
93
+ if (offset == null) return p;
94
+ const limit = pickNum(input, ["limit", "end_line"]);
95
+ return limit != null ? `${p}:${offset}-${offset + limit}` : `${p}:${offset}`;
96
+ }
97
+ function summarizeShell(input) {
98
+ const cmd = typeof input === "string" ? input : pickStr(input, ["command", "cmd", "script"]);
99
+ return cmd ? firstLine(cmd) : void 0;
100
+ }
101
+ function summarizeGrep(input) {
102
+ const pattern = pickStr(input, ["pattern", "regex", "query"]);
103
+ const p = filePathOf(input);
104
+ if (pattern) return p ? `${firstLine(pattern, 40)} \xB7 ${p}` : firstLine(pattern);
105
+ return p;
106
+ }
107
+ var sum = (fn) => {
108
+ return (input) => fn(input) ?? "";
109
+ };
110
+ var BUILTIN_KINDS = {
111
+ shell: { label: "\u547D\u4EE4", icon: ICON_TERMINAL, tint: "accent", summarize: sum(summarizeShell) },
112
+ read: { label: "\u8BFB\u53D6", icon: ICON_FILE, tint: "info", summarize: sum(summarizeRead) },
113
+ edit: { label: "\u7F16\u8F91", icon: ICON_FILE_PEN, tint: "warning", summarize: sum(summarizePath) },
114
+ write: { label: "\u5199\u5165", icon: ICON_FILE_PLUS, tint: "warning", summarize: sum(summarizePath) },
115
+ rm: { label: "\u5220\u9664", icon: ICON_TRASH, tint: "error", summarize: sum(summarizePath) },
116
+ grep: { label: "\u641C\u7D22", icon: ICON_SEARCH, tint: "info", summarize: sum(summarizeGrep) },
117
+ glob: { label: "\u5339\u914D", icon: ICON_FOLDER_SEARCH, tint: "info", summarize: sum((i) => pickStr(i, ["pattern", "glob", "path"])) },
118
+ browser: { label: "\u6D4F\u89C8", icon: ICON_GLOBE, tint: "accent", summarize: sum((i) => pickStr(i, ["url", "uri", "target"])) },
119
+ search: { label: "\u68C0\u7D22", icon: ICON_SCAN_SEARCH, tint: "accent", summarize: sum((i) => pickStr(i, ["query", "q", "pattern"])) },
120
+ fetch: { label: "\u8BF7\u6C42", icon: ICON_DOWNLOAD, tint: "info", summarize: sum((i) => pickStr(i, ["url", "uri", "endpoint"])) },
121
+ mcp: { label: "MCP", icon: ICON_BLOCKS, tint: "muted", summarize: sum((i) => pickStr(i, ["tool", "method", "name"])) },
122
+ skill: { label: "\u6280\u80FD", icon: ICON_ZAP, tint: "accent", summarize: sum((i) => pickStr(i, ["skill", "name", "command"])) },
123
+ todo: {
124
+ label: "\u5F85\u529E",
125
+ icon: ICON_LIST,
126
+ tint: "info",
127
+ summarize: sum((input) => {
128
+ const items = input && typeof input === "object" && Array.isArray(input.items) ? input.items : Array.isArray(input) ? input : [];
129
+ const done = items.filter((it) => it?.status === "done").length;
130
+ return items.length > 0 ? `${done}/${items.length} \u5B8C\u6210` : "";
131
+ })
132
+ },
133
+ plan: { label: "\u8BA1\u5212", icon: ICON_LIST_CHECKS, tint: "info" },
134
+ subagent: { label: "\u5B50\u4EE3\u7406", icon: ICON_BOT, tint: "accent", summarize: sum((i) => pickStr(i, ["task", "description", "prompt", "message", "subagent_type"])) },
135
+ note: { label: "\u7B14\u8BB0", icon: ICON_FILE_TEXT, tint: "muted" },
136
+ chart: { label: "\u56FE\u8868", icon: ICON_CHART, tint: "info", summarize: sum((i) => pickStr(i, ["title", "name"])) }
137
+ };
138
+ var FALLBACK_KIND = { label: "\u7B14\u8BB0", icon: ICON_FILE_TEXT, tint: "muted" };
139
+ var kindRegistry = new Map(Object.entries(BUILTIN_KINDS));
140
+ function getAiKind(name) {
141
+ return kindRegistry.get(name.trim().toLowerCase()) ?? kindRegistry.get("note") ?? FALLBACK_KIND;
142
+ }
143
+ function str(v) {
144
+ return typeof v === "string" && v ? v : void 0;
145
+ }
146
+ function trim1(v) {
147
+ const s = (Math.round(v * 10) / 10).toFixed(1);
148
+ return s.endsWith(".0") ? s.slice(0, -2) : s;
149
+ }
150
+ function formatDuration(ms) {
151
+ if (!Number.isFinite(ms) || ms <= 0) return "0ms";
152
+ if (ms < 1e3) return `${Math.round(ms)}ms`;
153
+ if (ms < 6e4) return `${trim1(ms / 1e3)}s`;
154
+ const m = Math.floor(ms / 6e4);
155
+ const s = Math.round(ms % 6e4 / 1e3);
156
+ if (ms < 36e5) return s > 0 ? `${m}m${s}s` : `${m}m`;
157
+ const h2 = Math.floor(ms / 36e5);
158
+ const rm = Math.round(ms % 36e5 / 6e4);
159
+ return rm > 0 ? `${h2}h${rm}m` : `${h2}h`;
160
+ }
161
+ var PART_TYPES = /* @__PURE__ */ new Set(["text", "image", "audio", "video", "file", "resource-link"]);
162
+ function isAiContentPart(v) {
163
+ if (!isObj(v)) return false;
164
+ const t = v.type;
165
+ if (typeof t !== "string" || !PART_TYPES.has(t)) return false;
166
+ if (t === "text") return typeof v.text === "string";
167
+ if (t === "resource-link") return typeof v.uri === "string";
168
+ return typeof v.url === "string" || typeof v.data === "string" && typeof v.mimeType === "string";
169
+ }
170
+ function aiContentUrl(part) {
171
+ if (part.type === "text" || part.type === "resource-link") return void 0;
172
+ if (typeof part.url === "string" && part.url) return part.url;
173
+ if (typeof part.data === "string" && part.data && typeof part.mimeType === "string") {
174
+ return `data:${part.mimeType};base64,${part.data}`;
175
+ }
176
+ return void 0;
177
+ }
178
+ function splitDataUri(uri) {
179
+ const m = /^data:([^;,]+);base64,(.*)$/s.exec(uri);
180
+ return m ? { mimeType: m[1] ?? "", data: m[2] ?? "" } : void 0;
181
+ }
182
+ function partFromOpenAi(item) {
183
+ const type = str(item.type) ?? "";
184
+ if (type === "text" && typeof item.text === "string") return { type: "text", text: item.text };
185
+ if (type === "image_url") {
186
+ const iu = isObj(item.image_url) ? item.image_url : void 0;
187
+ const url = iu ? str(iu.url) : void 0;
188
+ if (!url) return void 0;
189
+ const inline = splitDataUri(url);
190
+ return inline ? { type: "image", data: inline.data, mimeType: inline.mimeType } : { type: "image", url };
191
+ }
192
+ if (type === "input_audio") {
193
+ const ia = isObj(item.input_audio) ? item.input_audio : void 0;
194
+ const data = ia ? str(ia.data) : void 0;
195
+ const fmt2 = ia ? str(ia.format) : void 0;
196
+ if (!data) return void 0;
197
+ return { type: "audio", data, mimeType: fmt2 ? `audio/${fmt2}` : "audio/wav" };
198
+ }
199
+ if (type === "file") {
200
+ const f = isObj(item.file) ? item.file : void 0;
201
+ const fileId = f ? str(f.file_id) ?? str(f.filename) : void 0;
202
+ if (!fileId) return void 0;
203
+ return { type: "file", url: fileId, filename: str(f?.filename) };
204
+ }
205
+ return void 0;
206
+ }
207
+ function partFromAnthropicSource(mediaType, src, fallbackMime) {
208
+ if (!isObj(src)) return void 0;
209
+ if (str(src.type) === "url") {
210
+ const url = str(src.url);
211
+ return url ? { type: mediaType, url } : void 0;
212
+ }
213
+ const data = str(src.data);
214
+ const mimeType = str(src.media_type) ?? fallbackMime;
215
+ return data ? { type: mediaType, data, mimeType } : void 0;
216
+ }
217
+ function partFromAnthropic(block) {
218
+ const type = str(block.type) ?? "";
219
+ if (type === "text" && typeof block.text === "string") return { type: "text", text: block.text };
220
+ if (type === "image") return partFromAnthropicSource("image", block.source, "image/png");
221
+ if (type === "audio") return partFromAnthropicSource("audio", block.source, "audio/wav");
222
+ if (type === "document") return partFromAnthropicSource("file", block.source, "application/pdf");
223
+ return void 0;
224
+ }
225
+ function partFromMcp(item) {
226
+ const type = str(item.type) ?? "";
227
+ if (type === "text" && typeof item.text === "string") return { type: "text", text: item.text };
228
+ if (type === "image" || type === "audio") {
229
+ const data = str(item.data);
230
+ const mimeType = str(item.mimeType) ?? (type === "image" ? "image/png" : "audio/wav");
231
+ return data ? { type, data, mimeType } : void 0;
232
+ }
233
+ if (type === "resource_link") {
234
+ const uri = str(item.uri) ?? str(item.url);
235
+ return uri ? { type: "resource-link", uri, name: str(item.name), mimeType: str(item.mimeType) } : void 0;
236
+ }
237
+ if (type === "resource") {
238
+ const res = isObj(item.resource) ? item.resource : void 0;
239
+ if (!res) return void 0;
240
+ const uri = str(res.uri);
241
+ const mimeType = str(res.mimeType) ?? "";
242
+ const text = str(res.text);
243
+ if (text) return { type: "text", text };
244
+ const blob = str(res.blob);
245
+ if (blob) {
246
+ if (mimeType.startsWith("image/")) return { type: "image", data: blob, mimeType };
247
+ if (mimeType.startsWith("audio/")) return { type: "audio", data: blob, mimeType };
248
+ if (mimeType.startsWith("video/")) return { type: "video", data: blob, mimeType };
249
+ return { type: "file", data: blob, mimeType: mimeType || "application/octet-stream", filename: uri?.split("/").pop() };
250
+ }
251
+ return uri ? { type: "resource-link", uri, mimeType: mimeType || void 0 } : void 0;
252
+ }
253
+ return void 0;
254
+ }
255
+ function normalizeContentParts(raw) {
256
+ if (typeof raw === "string") return raw ? [{ type: "text", text: raw }] : [];
257
+ if (!Array.isArray(raw)) return [];
258
+ const out = [];
259
+ for (const item of raw) {
260
+ if (isAiContentPart(item)) {
261
+ out.push(item);
262
+ continue;
263
+ }
264
+ if (!isObj(item)) continue;
265
+ const part = partFromOpenAi(item) ?? partFromAnthropic(item) ?? partFromMcp(item);
266
+ if (part) out.push(part);
267
+ }
268
+ return out;
269
+ }
270
+ function svgIcon(svg2) {
271
+ if (typeof document === "undefined" || typeof DOMParser === "undefined") return null;
272
+ let parsed;
273
+ try {
274
+ parsed = new DOMParser().parseFromString(svg2, "image/svg+xml");
275
+ } catch {
276
+ return null;
277
+ }
278
+ const root = parsed.documentElement;
279
+ if (!root || root.tagName.toLowerCase() !== "svg" || parsed.querySelector("parsererror")) {
280
+ return null;
281
+ }
282
+ const sanitize = (el2) => {
283
+ for (const attr of Array.from(el2.attributes)) {
284
+ const name = attr.name.toLowerCase();
285
+ if (name.startsWith("on")) el2.removeAttribute(attr.name);
286
+ if ((name === "href" || name === "xlink:href") && attr.value.trim().toLowerCase().startsWith("javascript:")) {
287
+ el2.removeAttribute(attr.name);
288
+ }
289
+ }
290
+ for (const child of Array.from(el2.children)) {
291
+ const tag = child.tagName.toLowerCase();
292
+ if (tag === "script" || tag === "foreignobject") {
293
+ child.remove();
294
+ continue;
295
+ }
296
+ sanitize(child);
297
+ }
298
+ };
299
+ sanitize(root);
300
+ return document.importNode(root, true);
301
+ }
302
+
303
+ // src/behaviors/ai-chat.ts
304
+ function safeHref(uri) {
305
+ const s = uri.trim().toLowerCase();
306
+ if (s.startsWith("javascript:") || s.startsWith("data:text/html")) return void 0;
307
+ return uri;
308
+ }
309
+ function el(tag, className, text) {
310
+ const node = document.createElement(tag);
311
+ if (className) node.className = className;
312
+ if (text != null) node.textContent = text;
313
+ return node;
314
+ }
315
+ function renderAiContentPart(part) {
316
+ if (part.type === "text") {
317
+ const span = el("span", "ai-msg-text");
318
+ span.textContent = part.text;
319
+ if (part.state === "streaming") span.classList.add("is-streaming");
320
+ return span;
321
+ }
322
+ if (part.type === "image") {
323
+ const src = aiContentUrl(part);
324
+ if (!src) return void 0;
325
+ const img = document.createElement("img");
326
+ img.className = "ai-msg-media ai-msg-media--image";
327
+ img.alt = part.alt ?? "";
328
+ img.setAttribute("loading", "lazy");
329
+ img.setAttribute("src", src);
330
+ return img;
331
+ }
332
+ if (part.type === "audio") {
333
+ const src = aiContentUrl(part);
334
+ if (!src) return void 0;
335
+ const audio = document.createElement("audio");
336
+ audio.className = "ai-msg-media ai-msg-media--audio";
337
+ audio.controls = true;
338
+ audio.setAttribute("src", src);
339
+ return audio;
340
+ }
341
+ if (part.type === "video") {
342
+ const src = aiContentUrl(part);
343
+ if (!src) return void 0;
344
+ const video = document.createElement("video");
345
+ video.className = "ai-msg-media ai-msg-media--video";
346
+ video.controls = true;
347
+ video.setAttribute("playsinline", "");
348
+ video.setAttribute("src", src);
349
+ return video;
350
+ }
351
+ if (part.type === "file") {
352
+ const chip = el("span", "ai-msg-file");
353
+ chip.appendChild(el("span", "ai-msg-file-name", part.filename ?? "\u6587\u4EF6"));
354
+ const href2 = part.url ? safeHref(part.url) : void 0;
355
+ if (href2 && /^(https?:|data:)/i.test(href2)) {
356
+ const a2 = document.createElement("a");
357
+ a2.className = "ai-msg-file-link";
358
+ a2.href = href2;
359
+ a2.download = part.filename ?? "";
360
+ a2.textContent = "\u4E0B\u8F7D";
361
+ chip.appendChild(a2);
362
+ }
363
+ return chip;
364
+ }
365
+ const a = document.createElement("a");
366
+ a.className = "ai-msg-link";
367
+ const href = safeHref(part.uri);
368
+ if (href) a.href = href;
369
+ a.textContent = part.name ?? part.uri;
370
+ a.title = part.uri;
371
+ return a;
372
+ }
373
+
374
+ // src/behaviors/charts.ts
375
+ var SVG_NS = "http://www.w3.org/2000/svg";
376
+ function toneVar(tone = "accent") {
377
+ switch (tone) {
378
+ case "success":
379
+ return "var(--token-success)";
380
+ case "warning":
381
+ return "var(--token-warning)";
382
+ case "error":
383
+ return "var(--token-error)";
384
+ case "muted":
385
+ return "var(--token-text-faint)";
386
+ case "accent":
387
+ default:
388
+ return "var(--token-accent)";
389
+ }
390
+ }
391
+ function fmt(opts, value) {
392
+ return opts.formatValue ? opts.formatValue(value) : String(value);
393
+ }
394
+ function maxOf(values) {
395
+ let max = 1;
396
+ for (const v of values) if (v > max) max = v;
397
+ return max;
398
+ }
399
+ function sampleLabels(labels, max = 7) {
400
+ if (labels.length <= max) return labels;
401
+ const out = [];
402
+ for (let i = 0; i < max; i++) {
403
+ out.push(labels[Math.round(i * (labels.length - 1) / (max - 1))] ?? "");
404
+ }
405
+ return out;
406
+ }
407
+ function svgEl(tag, attrs) {
408
+ const el2 = document.createElementNS(SVG_NS, tag);
409
+ for (const [k, v] of Object.entries(attrs)) el2.setAttribute(k, v);
410
+ return el2;
411
+ }
412
+ function renderEmpty(el2, label) {
413
+ const box = document.createElement("div");
414
+ box.className = "chart-empty";
415
+ box.textContent = label ?? "\u6682\u65E0\u6570\u636E";
416
+ el2.appendChild(box);
417
+ }
418
+ function legendItem(label, valueText, tone) {
419
+ const row = document.createElement("div");
420
+ row.className = "chart-legend-item";
421
+ const dot = document.createElement("span");
422
+ dot.className = "chart-legend-dot";
423
+ if (tone) dot.style.setProperty("--chart-tone", toneVar(tone));
424
+ const name = document.createElement("span");
425
+ name.className = "chart-legend-label";
426
+ name.textContent = label;
427
+ const val = document.createElement("span");
428
+ val.className = "chart-legend-value";
429
+ val.textContent = valueText;
430
+ row.append(dot, name, val);
431
+ return row;
432
+ }
433
+ function labelsRow(labels) {
434
+ const row = document.createElement("div");
435
+ row.className = "chart-labels";
436
+ for (const label of labels) {
437
+ const span = document.createElement("span");
438
+ span.textContent = label;
439
+ row.appendChild(span);
440
+ }
441
+ return row;
442
+ }
443
+ function normalizeSeriesInput(opts) {
444
+ if (opts.series && opts.series.length > 0) return opts.series;
445
+ return [{ name: "", values: opts.values ?? [], tone: opts.tone }];
446
+ }
447
+ function toneOf(tone, seriesIndex) {
448
+ if (typeof tone === "string") return toneVar(tone);
449
+ if (typeof tone === "number") return paletteVar(tone);
450
+ return seriesIndex > 0 ? paletteVar((seriesIndex - 1) % 6 + 1) : void 0;
451
+ }
452
+ var PALETTE_VARS = [
453
+ "var(--token-accent)",
454
+ "var(--token-accent-cold)",
455
+ "var(--token-success)",
456
+ "var(--token-warning)",
457
+ "var(--token-info)",
458
+ "color-mix(in srgb, var(--token-text) 50%, transparent)"
459
+ ];
460
+ function paletteVar(index) {
461
+ const i = ((Math.floor(index) - 1) % 6 + 6) % 6;
462
+ return PALETTE_VARS[i];
463
+ }
464
+ function setMarkData(node, data) {
465
+ node.setAttribute("data-chart-mark", "1");
466
+ if (data.index != null) node.setAttribute("data-chart-index", String(data.index));
467
+ if (data.seriesIndex != null) node.setAttribute("data-chart-series", String(data.seriesIndex));
468
+ if (data.seriesName != null) node.setAttribute("data-chart-series-name", String(data.seriesName));
469
+ if (data.label != null) node.setAttribute("data-chart-label", String(data.label));
470
+ if (data.value != null) node.setAttribute("data-chart-value", String(data.value));
471
+ }
472
+ function copyMarkData(target, source) {
473
+ for (const attr of Array.from(source.attributes)) {
474
+ if (attr.name.startsWith("data-chart-")) target.setAttribute(attr.name, attr.value);
475
+ }
476
+ }
477
+ var CHART_EYE_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2.06 12.35a1 1 0 0 1 0-.7 10.75 10.75 0 0 1 19.88 0 1 1 0 0 1 0 .7 10.75 10.75 0 0 1-19.88 0"/><circle cx="12" cy="12" r="3"/></svg>';
478
+ var CHART_EYE_OFF_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.73 5.08A10.4 10.4 0 0 1 12 5c7 0 10 7 10 7a13.2 13.2 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.5 13.5 0 0 0 2 12s3 7 10 7a9.7 9.7 0 0 0 5.39-1.61"/><path d="M2 2l20 20"/><path d="M9.9 9.9a3 3 0 0 0 4.2 4.2"/></svg>';
479
+ function parseChartSvg(svg2) {
480
+ try {
481
+ const doc = new DOMParser().parseFromString(svg2, "image/svg+xml");
482
+ const el2 = doc.documentElement;
483
+ return el2 && el2.tagName.toLowerCase() === "svg" && !doc.querySelector("parsererror") ? document.importNode(el2, true) : null;
484
+ } catch {
485
+ return null;
486
+ }
487
+ }
488
+ function withChrome(el2, opts, hasLegend, paint, state) {
489
+ if (el2.dataset.chartBody != null) {
490
+ el2.textContent = "";
491
+ paint(el2);
492
+ return;
493
+ }
494
+ el2.textContent = "";
495
+ const body = document.createElement("div");
496
+ body.className = "chart-body";
497
+ body.dataset.chartBody = "";
498
+ if (!opts.title && !hasLegend) {
499
+ el2.appendChild(body);
500
+ paint(body);
501
+ return;
502
+ }
503
+ let hidden = state && state.hidden != null ? state.hidden : opts.legend === false;
504
+ if (state) state.hidden = hidden;
505
+ el2.setAttribute("data-legend-hidden", String(hidden));
506
+ const head = document.createElement("div");
507
+ head.className = "chart-head";
508
+ const title = document.createElement("div");
509
+ title.className = "chart-title";
510
+ title.textContent = opts.title ?? "";
511
+ if (!opts.title) title.setAttribute("aria-hidden", "true");
512
+ const eye = document.createElement("button");
513
+ eye.type = "button";
514
+ eye.className = "chart-legend-eye";
515
+ eye.dataset.chartLegendEye = "";
516
+ const syncEye = () => {
517
+ const nowHidden = el2.getAttribute("data-legend-hidden") === "true";
518
+ eye.setAttribute("aria-pressed", String(!nowHidden));
519
+ eye.setAttribute("aria-label", nowHidden ? "\u663E\u793A\u56FE\u4F8B" : "\u9690\u85CF\u56FE\u4F8B");
520
+ eye.setAttribute("title", nowHidden ? "\u663E\u793A\u56FE\u4F8B" : "\u9690\u85CF\u56FE\u4F8B");
521
+ const icon = parseChartSvg(nowHidden ? CHART_EYE_OFF_SVG : CHART_EYE_SVG);
522
+ if (icon) eye.replaceChildren(icon);
523
+ };
524
+ eye.addEventListener("click", () => {
525
+ const nowHidden = el2.getAttribute("data-legend-hidden") === "true";
526
+ hidden = !nowHidden;
527
+ if (state) state.hidden = hidden;
528
+ el2.setAttribute("data-legend-hidden", String(hidden));
529
+ syncEye();
530
+ el2.dispatchEvent(new CustomEvent("icen:chart-legend-visibility", {
531
+ bubbles: true,
532
+ detail: { visible: hidden ? false : true }
533
+ }));
534
+ });
535
+ syncEye();
536
+ head.append(title, eye);
537
+ el2.append(head, body);
538
+ paint(body);
539
+ }
540
+ function toggleLegend(items, scope, _opts) {
541
+ const legend = document.createElement("div");
542
+ legend.className = "chart-legend chart-legend--toggle";
543
+ for (const item of items) {
544
+ const row = legendItem(item.label, "", item.tone);
545
+ row.classList.add("chart-legend-toggle-item");
546
+ row.setAttribute("role", "button");
547
+ row.tabIndex = 0;
548
+ row.setAttribute("aria-pressed", "true");
549
+ row.dataset.chartKey = item.key;
550
+ const dot = row.querySelector(".chart-legend-dot");
551
+ const toneColor = toneOf(item.tone, item.si + 1);
552
+ if (dot && toneColor) dot.style.setProperty("--chart-tone", toneColor);
553
+ const toggle = () => {
554
+ const off = row.classList.toggle("is-off");
555
+ row.setAttribute("aria-pressed", String(!off));
556
+ scope.querySelectorAll(`[data-chart-key="${CSS.escape(item.key)}"]`).forEach((m) => {
557
+ m.classList.toggle("is-off", off);
558
+ });
559
+ legend.dispatchEvent(new CustomEvent("icen:chart-legend-toggle", {
560
+ bubbles: true,
561
+ detail: { key: item.key, seriesIndex: item.si, hidden: off }
562
+ }));
563
+ };
564
+ row.addEventListener("click", toggle);
565
+ row.addEventListener("keydown", (e) => {
566
+ if (e.key === "Enter" || e.key === " ") {
567
+ e.preventDefault();
568
+ toggle();
569
+ }
570
+ });
571
+ legend.appendChild(row);
572
+ }
573
+ for (const item of items) {
574
+ scope.querySelectorAll(`[data-chart-series="${item.si}"]`).forEach((m) => {
575
+ if (!m.hasAttribute("data-chart-key")) m.setAttribute("data-chart-key", item.key);
576
+ });
577
+ }
578
+ return legend;
579
+ }
580
+ function renderVBar(el2, opts) {
581
+ if (typeof document === "undefined") return;
582
+ const seriesList = normalizeSeriesInput(opts);
583
+ const labels = opts.labels ?? [];
584
+ const n = Math.min(labels.length, ...seriesList.map((s) => s.values.length));
585
+ withChrome(el2, opts, seriesList.length > 1, (body) => {
586
+ if (n === 0 || seriesList.length === 0) {
587
+ renderEmpty(body, opts.emptyLabel);
588
+ return;
589
+ }
590
+ const labelsUsed = labels.slice(0, n);
591
+ let max = 1;
592
+ if (opts.stacked && seriesList.length > 1) {
593
+ for (let i = 0; i < n; i++) {
594
+ let sum2 = 0;
595
+ for (const s of seriesList) sum2 += Math.max(0, s.values[i] ?? 0);
596
+ if (sum2 > max) max = sum2;
597
+ }
598
+ } else {
599
+ for (const s of seriesList) max = Math.max(max, maxOf(s.values.slice(0, n)));
600
+ }
601
+ const wrap = document.createElement("div");
602
+ wrap.className = "chart-vbar";
603
+ if (opts.tone) wrap.style.setProperty("--chart-tone", toneVar(opts.tone));
604
+ for (let i = 0; i < n; i++) {
605
+ const track = document.createElement("div");
606
+ track.className = "chart-vbar-track";
607
+ if (seriesList.length > 1) {
608
+ track.classList.add("chart-vbar-track--multi");
609
+ if (opts.stacked) track.classList.add("chart-vbar-track--stacked");
610
+ }
611
+ seriesList.forEach((s, si) => {
612
+ const value = s.values[i] ?? 0;
613
+ const bar = document.createElement("div");
614
+ bar.className = "chart-vbar-bar";
615
+ const height = value > 0 ? Math.max(6, value / max * 100) : 0;
616
+ bar.style.height = `${height}%`;
617
+ const toneColor = toneOf(s.tone, si);
618
+ if (toneColor) bar.style.setProperty("--chart-tone", toneColor);
619
+ bar.setAttribute("title", seriesList.length > 1 ? `${labelsUsed[i]} \xB7 ${s.name}: ${fmt(opts, value)}` : `${labelsUsed[i]}: ${fmt(opts, value)}`);
620
+ setMarkData(bar, {
621
+ index: i,
622
+ seriesIndex: seriesList.length > 1 ? si : void 0,
623
+ seriesName: seriesList.length > 1 ? s.name : void 0,
624
+ label: labelsUsed[i] ?? "",
625
+ value
626
+ });
627
+ track.appendChild(bar);
628
+ });
629
+ wrap.appendChild(track);
630
+ }
631
+ body.append(wrap, labelsRow(labelsUsed));
632
+ if (seriesList.length > 1) body.appendChild(toggleLegend(seriesList.map((s, si) => ({ key: s.name, label: s.name, tone: s.tone, si })), wrap, opts));
633
+ });
634
+ }
635
+ function renderHBar(el2, opts) {
636
+ if (typeof document === "undefined") return;
637
+ withChrome(el2, opts, false, (body) => {
638
+ const n = Math.min(opts.labels.length, opts.values.length);
639
+ if (n === 0) {
640
+ renderEmpty(body, opts.emptyLabel);
641
+ return;
642
+ }
643
+ const labels = opts.labels.slice(0, n);
644
+ const values = opts.values.slice(0, n);
645
+ const max = maxOf(values);
646
+ const wrap = document.createElement("div");
647
+ wrap.className = "chart-hbar";
648
+ if (opts.tone) wrap.style.setProperty("--chart-tone", toneVar(opts.tone));
649
+ values.forEach((value, i) => {
650
+ const row = document.createElement("div");
651
+ row.className = "chart-hbar-row";
652
+ const label = document.createElement("span");
653
+ label.className = "chart-hbar-label";
654
+ label.textContent = labels[i] ?? "";
655
+ const track = document.createElement("div");
656
+ track.className = "chart-hbar-track";
657
+ const bar = document.createElement("div");
658
+ bar.className = "chart-hbar-bar";
659
+ bar.style.width = value > 0 ? `${Math.max(2, value / max * 100)}%` : "0%";
660
+ setMarkData(bar, { index: i, label: labels[i] ?? "", value });
661
+ const val = document.createElement("span");
662
+ val.className = "chart-hbar-value";
663
+ val.textContent = fmt(opts, value);
664
+ track.appendChild(bar);
665
+ row.append(label, track, val);
666
+ wrap.appendChild(row);
667
+ });
668
+ body.appendChild(wrap);
669
+ });
670
+ }
671
+ function renderStack(el2, opts) {
672
+ if (typeof document === "undefined") return;
673
+ withChrome(el2, opts, opts.segments.length > 0, (body) => {
674
+ const total = opts.segments.reduce((sum2, s) => sum2 + s.value, 0);
675
+ if (opts.segments.length === 0 || total <= 0) {
676
+ renderEmpty(body, opts.emptyLabel);
677
+ return;
678
+ }
679
+ const bar = document.createElement("div");
680
+ bar.className = "chart-stack";
681
+ for (const seg of opts.segments) {
682
+ const s = document.createElement("div");
683
+ s.className = "chart-stack-seg";
684
+ s.style.width = `${seg.value / total * 100}%`;
685
+ if (seg.tone) s.style.setProperty("--chart-tone", toneVar(seg.tone));
686
+ s.setAttribute("title", `${seg.label}: ${fmt(opts, seg.value)}`);
687
+ setMarkData(s, { index: opts.segments.indexOf(seg), label: seg.label, value: seg.value });
688
+ bar.appendChild(s);
689
+ }
690
+ const legend = document.createElement("div");
691
+ legend.className = "chart-legend";
692
+ for (const seg of opts.segments) {
693
+ legend.appendChild(legendItem(seg.label, fmt(opts, seg.value), seg.tone));
694
+ }
695
+ body.append(bar, legend);
696
+ });
697
+ }
698
+ function renderDonut(el2, opts) {
699
+ if (typeof document === "undefined") return;
700
+ withChrome(el2, opts, opts.segments.length > 0, (body) => {
701
+ const total = opts.segments.reduce((sum2, s) => sum2 + s.value, 0);
702
+ if (opts.segments.length === 0 || total <= 0) {
703
+ renderEmpty(body, opts.emptyLabel);
704
+ return;
705
+ }
706
+ const radius = 42;
707
+ const circumference = 2 * Math.PI * radius;
708
+ const wrap = document.createElement("div");
709
+ wrap.className = "chart-donut";
710
+ const svg2 = svgEl("svg", { viewBox: "0 0 120 120", role: "img" });
711
+ svg2.style.transform = "rotate(-90deg)";
712
+ svg2.appendChild(svgEl("circle", {
713
+ cx: "60",
714
+ cy: "60",
715
+ r: String(radius),
716
+ fill: "none",
717
+ stroke: "var(--token-line-soft)",
718
+ "stroke-width": "14"
719
+ }));
720
+ let offset = 0;
721
+ opts.segments.forEach((seg, segIndex) => {
722
+ const dash = seg.value / total * circumference;
723
+ const arc = svgEl("circle", {
724
+ cx: "60",
725
+ cy: "60",
726
+ r: String(radius),
727
+ fill: "none",
728
+ stroke: toneVar(seg.tone),
729
+ "stroke-width": "14",
730
+ "stroke-dasharray": `${dash} ${circumference - dash}`,
731
+ "stroke-dashoffset": String(-offset),
732
+ "stroke-linecap": "butt"
733
+ });
734
+ setMarkData(arc, { index: segIndex, label: seg.label, value: seg.value });
735
+ svg2.appendChild(arc);
736
+ offset += dash;
737
+ });
738
+ const legend = document.createElement("div");
739
+ legend.className = "chart-legend";
740
+ for (const seg of opts.segments) {
741
+ legend.appendChild(legendItem(seg.label, `${Math.round(seg.value / total * 100)}%`, seg.tone));
742
+ }
743
+ wrap.append(svg2, legend);
744
+ body.appendChild(wrap);
745
+ });
746
+ }
747
+ var lineGradientSeq = 0;
748
+ function renderLine(el2, opts) {
749
+ if (typeof document === "undefined") return;
750
+ const seriesList = normalizeSeriesInput(opts);
751
+ const labels = opts.labels ?? [];
752
+ const n = Math.min(labels.length, ...seriesList.map((s) => s.values.length));
753
+ withChrome(el2, opts, seriesList.length > 1, (body) => {
754
+ if (n === 0 || seriesList.length === 0) {
755
+ renderEmpty(body, opts.emptyLabel);
756
+ return;
757
+ }
758
+ const labelsUsed = labels.slice(0, n);
759
+ const width = 360;
760
+ const height = 150;
761
+ const pad = 14;
762
+ let max = 1;
763
+ for (const s of seriesList) max = Math.max(max, maxOf(s.values.slice(0, n)));
764
+ const wrap = document.createElement("div");
765
+ wrap.className = "chart-line";
766
+ const svg2 = svgEl("svg", { viewBox: `0 0 ${width} ${height}`, role: "img" });
767
+ const defs = svgEl("defs", {});
768
+ for (let i = 0; i < 4; i++) {
769
+ const y = pad + i * (height - pad * 2) / 3;
770
+ svg2.appendChild(svgEl("line", {
771
+ x1: String(pad),
772
+ x2: String(width - pad),
773
+ y1: String(y),
774
+ y2: String(y),
775
+ stroke: "var(--token-line-soft)",
776
+ "stroke-width": "1"
777
+ }));
778
+ }
779
+ seriesList.forEach((s, si) => {
780
+ const tone = toneOf(s.tone, si) ?? toneVar(opts.tone);
781
+ const values = s.values.slice(0, n);
782
+ const points = values.map((value, i) => ({
783
+ i,
784
+ x: n <= 1 ? width / 2 : pad + i / (n - 1) * (width - pad * 2),
785
+ y: height - pad - Math.max(0, value) / max * (height - pad * 2),
786
+ value,
787
+ label: labelsUsed[i] ?? ""
788
+ }));
789
+ const line = points.map((p, i) => `${i === 0 ? "M" : "L"}${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(" ");
790
+ const last = points[points.length - 1];
791
+ const first = points[0];
792
+ const fillArea = seriesList.length === 1 || opts.fill;
793
+ if (fillArea) {
794
+ const area = `${line} L${last.x.toFixed(1)},${height - pad} L${first.x.toFixed(1)},${height - pad} Z`;
795
+ const gradientId = `icen-chart-line-${++lineGradientSeq}`;
796
+ const gradient = svgEl("linearGradient", { id: gradientId, x1: "0", x2: "0", y1: "0", y2: "1" });
797
+ const strong = seriesList.length > 1 ? "0.20" : "0.32";
798
+ gradient.appendChild(svgEl("stop", { offset: "0%", "stop-color": tone, "stop-opacity": strong }));
799
+ gradient.appendChild(svgEl("stop", { offset: "100%", "stop-color": tone, "stop-opacity": "0.02" }));
800
+ defs.appendChild(gradient);
801
+ const areaPath = svgEl("path", { d: area, fill: `url(#${gradientId})` });
802
+ if (seriesList.length > 1) {
803
+ setMarkData(areaPath, { seriesIndex: si, seriesName: s.name, label: s.name, value: values.reduce((a, b) => a + b, 0) });
804
+ }
805
+ svg2.appendChild(areaPath);
806
+ }
807
+ const linePath = svgEl("path", {
808
+ d: line,
809
+ fill: "none",
810
+ stroke: tone,
811
+ "stroke-width": seriesList.length > 1 ? "2" : "2.5",
812
+ "stroke-linecap": "round",
813
+ "stroke-linejoin": "round"
814
+ });
815
+ const lineTitle = svgEl("title", {});
816
+ lineTitle.textContent = s.name || "\u6570\u503C";
817
+ linePath.appendChild(lineTitle);
818
+ setMarkData(linePath, { seriesIndex: si, seriesName: s.name, label: s.name, value: values[values.length - 1] ?? 0 });
819
+ svg2.appendChild(linePath);
820
+ for (const p of points) {
821
+ const dot = svgEl("circle", {
822
+ cx: p.x.toFixed(1),
823
+ cy: p.y.toFixed(1),
824
+ r: "3",
825
+ fill: "var(--token-card)",
826
+ stroke: tone,
827
+ "stroke-width": "2"
828
+ });
829
+ const title = svgEl("title", {});
830
+ title.textContent = seriesList.length > 1 ? `${p.label} \xB7 ${s.name}: ${fmt(opts, p.value)}` : `${p.label}: ${fmt(opts, p.value)}`;
831
+ dot.appendChild(title);
832
+ setMarkData(dot, {
833
+ index: p.i,
834
+ seriesIndex: seriesList.length > 1 ? si : void 0,
835
+ seriesName: seriesList.length > 1 ? s.name : void 0,
836
+ label: p.label,
837
+ value: p.value
838
+ });
839
+ svg2.appendChild(dot);
840
+ const hit = svgEl("circle", {
841
+ cx: p.x.toFixed(1),
842
+ cy: p.y.toFixed(1),
843
+ r: "8",
844
+ fill: "transparent",
845
+ "data-chart-hit": "1"
846
+ });
847
+ copyMarkData(hit, dot);
848
+ svg2.appendChild(hit);
849
+ }
850
+ });
851
+ if (defs.firstChild) svg2.insertBefore(defs, svg2.firstChild);
852
+ wrap.append(svg2, labelsRow(sampleLabels(labelsUsed)));
853
+ body.appendChild(wrap);
854
+ if (seriesList.length > 1) body.appendChild(toggleLegend(seriesList.map((s, si) => ({ key: s.name, label: s.name, tone: s.tone, si })), wrap, opts));
855
+ });
856
+ }
857
+ function renderRadar(el2, opts) {
858
+ if (typeof document === "undefined") return;
859
+ withChrome(el2, opts, opts.series.length > 1, (body) => {
860
+ const axes = opts.axes;
861
+ const n = axes.length;
862
+ if (n < 3 || opts.series.length === 0) {
863
+ renderEmpty(body, opts.emptyLabel);
864
+ return;
865
+ }
866
+ let maxVal = opts.max ?? 0;
867
+ if (opts.max == null) {
868
+ for (const s of opts.series) {
869
+ for (let i = 0; i < n; i++) maxVal = Math.max(maxVal, s.values[i] ?? 0);
870
+ }
871
+ maxVal = niceCeil(maxVal);
872
+ }
873
+ if (maxVal <= 0) maxVal = 1;
874
+ const size = 200;
875
+ const cx = size / 2;
876
+ const cy = size / 2;
877
+ const radius = 78;
878
+ const levels = Math.max(2, opts.levels ?? 4);
879
+ const angleOf = (i) => -Math.PI / 2 + i * 2 * Math.PI / n;
880
+ const pointAt = (i, r) => ({
881
+ x: cx + r * Math.cos(angleOf(i)),
882
+ y: cy + r * Math.sin(angleOf(i))
883
+ });
884
+ const wrap = document.createElement("div");
885
+ wrap.className = "chart-radar";
886
+ const svg2 = svgEl("svg", { viewBox: `0 0 ${size} ${size}`, role: "img" });
887
+ for (let lv = 1; lv <= levels; lv++) {
888
+ const r = radius * lv / levels;
889
+ const pts = Array.from({ length: n }, (_, i) => {
890
+ const p = pointAt(i, r);
891
+ return `${p.x.toFixed(1)},${p.y.toFixed(1)}`;
892
+ }).join(" ");
893
+ svg2.appendChild(svgEl("polygon", {
894
+ points: pts,
895
+ fill: "none",
896
+ stroke: "var(--token-line-soft)",
897
+ "stroke-width": "1",
898
+ "stroke-dasharray": lv === levels ? "0" : "3 2"
899
+ }));
900
+ }
901
+ for (let i = 0; i < n; i++) {
902
+ const edge = pointAt(i, radius);
903
+ svg2.appendChild(svgEl("line", {
904
+ x1: String(cx),
905
+ y1: String(cy),
906
+ x2: edge.x.toFixed(1),
907
+ y2: edge.y.toFixed(1),
908
+ stroke: "var(--token-line-soft)",
909
+ "stroke-width": "1"
910
+ }));
911
+ const labelP = pointAt(i, radius + 14);
912
+ const txt = svgEl("text", {
913
+ x: labelP.x.toFixed(1),
914
+ y: labelP.y.toFixed(1),
915
+ "text-anchor": "middle",
916
+ "dominant-baseline": "middle",
917
+ "font-size": "9",
918
+ fill: "var(--token-text-muted)"
919
+ });
920
+ txt.textContent = axes[i] ?? "";
921
+ svg2.appendChild(txt);
922
+ }
923
+ const legendItems = [];
924
+ opts.series.forEach((s, si) => {
925
+ const tone = toneVar(s.tone);
926
+ const pts = Array.from({ length: n }, (_, i) => {
927
+ const v = Math.max(0, Math.min(maxVal, s.values[i] ?? 0));
928
+ const p = pointAt(i, v / maxVal * radius);
929
+ return `${p.x.toFixed(1)},${p.y.toFixed(1)}`;
930
+ }).join(" ");
931
+ const polyFill = svgEl("polygon", {
932
+ points: pts,
933
+ fill: tone,
934
+ "fill-opacity": "0.16",
935
+ stroke: tone,
936
+ "stroke-width": "2",
937
+ "stroke-linejoin": "round"
938
+ });
939
+ const title = svgEl("title", {});
940
+ title.textContent = `${s.name}: ${s.values.map((v) => fmt(opts, v)).join(" / ")}`;
941
+ polyFill.appendChild(title);
942
+ setMarkData(polyFill, { seriesIndex: si, seriesName: s.name || void 0, label: s.name, value: s.values.reduce((a, b) => a + (b || 0), 0) });
943
+ svg2.appendChild(polyFill);
944
+ for (let i = 0; i < n; i++) {
945
+ const v = Math.max(0, Math.min(maxVal, s.values[i] ?? 0));
946
+ const p = pointAt(i, v / maxVal * radius);
947
+ const dot = svgEl("circle", {
948
+ cx: p.x.toFixed(1),
949
+ cy: p.y.toFixed(1),
950
+ r: "2.5",
951
+ fill: "var(--token-card)",
952
+ stroke: tone,
953
+ "stroke-width": "1.5"
954
+ });
955
+ setMarkData(dot, { index: i, seriesIndex: si, seriesName: s.name || void 0, label: axes[i] ?? "", value: s.values[i] ?? 0 });
956
+ svg2.appendChild(dot);
957
+ }
958
+ legendItems.push({ key: s.name || `\u7CFB\u5217${si + 1}`, label: s.name || `\u7CFB\u5217${si + 1}`, tone: s.tone, si });
959
+ });
960
+ wrap.append(svg2, opts.series.length > 1 ? toggleLegend(legendItems, wrap, opts) : (() => {
961
+ const l = document.createElement("div");
962
+ l.className = "chart-legend";
963
+ return l;
964
+ })());
965
+ body.appendChild(wrap);
966
+ });
967
+ }
968
+ function niceCeil(v) {
969
+ if (v <= 0) return 1;
970
+ const exp = Math.floor(Math.log10(v));
971
+ const base = Math.pow(10, exp);
972
+ const frac = v / base;
973
+ let nice;
974
+ if (frac <= 1) nice = 1;
975
+ else if (frac <= 2) nice = 2;
976
+ else if (frac <= 5) nice = 5;
977
+ else nice = 10;
978
+ return nice * base;
979
+ }
980
+ function isoDate(d) {
981
+ const m = String(d.getMonth() + 1).padStart(2, "0");
982
+ const day = String(d.getDate()).padStart(2, "0");
983
+ return `${d.getFullYear()}-${m}-${day}`;
984
+ }
985
+ function renderHeatmap(el2, opts) {
986
+ if (typeof document === "undefined") return;
987
+ withChrome(el2, opts, true, (body) => {
988
+ let entries;
989
+ if (opts.data && opts.data.length > 0) {
990
+ entries = opts.data;
991
+ } else if (opts.values && opts.values.length > 0) {
992
+ const today = /* @__PURE__ */ new Date();
993
+ entries = opts.values.map((value, i) => {
994
+ const d = new Date(today);
995
+ d.setDate(d.getDate() - (opts.values.length - 1 - i));
996
+ return { date: isoDate(d), value };
997
+ });
998
+ } else {
999
+ renderEmpty(body, opts.emptyLabel);
1000
+ return;
1001
+ }
1002
+ const weeks = opts.weeks ?? Math.ceil(entries.length / 7);
1003
+ if (entries.length > weeks * 7) entries = entries.slice(entries.length - weeks * 7);
1004
+ const max = maxOf(entries.map((e) => e.value));
1005
+ const levelOf = (v) => v <= 0 ? 0 : Math.min(4, Math.ceil(v / max * 4));
1006
+ const wrap = document.createElement("div");
1007
+ wrap.className = "chart-heatmap";
1008
+ if (opts.tone) wrap.style.setProperty("--chart-tone", toneVar(opts.tone));
1009
+ const grid = document.createElement("div");
1010
+ grid.className = "chart-heatmap-grid";
1011
+ grid.setAttribute("role", "img");
1012
+ const first = /* @__PURE__ */ new Date(`${entries[0].date}T00:00:00`);
1013
+ const pad = (first.getDay() + 6) % 7;
1014
+ for (let i = 0; i < pad; i++) {
1015
+ const blank = document.createElement("span");
1016
+ blank.className = "chart-heatmap-cell is-blank";
1017
+ grid.appendChild(blank);
1018
+ }
1019
+ for (const entry of entries) {
1020
+ const cell = document.createElement("span");
1021
+ cell.className = "chart-heatmap-cell";
1022
+ cell.dataset.level = String(levelOf(entry.value));
1023
+ cell.setAttribute("title", `${entry.date}\uFF1A${fmt(opts, entry.value)}`);
1024
+ setMarkData(cell, { index: entries.indexOf(entry), label: entry.date, value: entry.value });
1025
+ grid.appendChild(cell);
1026
+ }
1027
+ const legend = document.createElement("div");
1028
+ legend.className = "chart-heatmap-legend";
1029
+ const less = document.createElement("span");
1030
+ less.textContent = "\u5C11";
1031
+ const more = document.createElement("span");
1032
+ more.textContent = "\u591A";
1033
+ legend.appendChild(less);
1034
+ for (let lv = 0; lv <= 4; lv++) {
1035
+ const cell = document.createElement("span");
1036
+ cell.className = "chart-heatmap-cell";
1037
+ cell.dataset.level = String(lv);
1038
+ legend.appendChild(cell);
1039
+ }
1040
+ legend.appendChild(more);
1041
+ wrap.append(grid, legend);
1042
+ body.appendChild(wrap);
1043
+ });
1044
+ }
1045
+ function renderSparkline(el2, opts) {
1046
+ if (typeof document === "undefined") return;
1047
+ withChrome(el2, opts, false, (body) => {
1048
+ const values = opts.values;
1049
+ if (values.length === 0) {
1050
+ renderEmpty(body, opts.emptyLabel);
1051
+ return;
1052
+ }
1053
+ const width = 96;
1054
+ const height = 28;
1055
+ const pad = 3;
1056
+ const max = maxOf(values);
1057
+ const tone = toneVar(opts.tone);
1058
+ const points = values.map((value, i) => ({
1059
+ x: values.length <= 1 ? width / 2 : pad + i / (values.length - 1) * (width - pad * 2),
1060
+ y: height - pad - value / max * (height - pad * 2),
1061
+ value
1062
+ }));
1063
+ const line = points.map((p, i) => `${i === 0 ? "M" : "L"}${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(" ");
1064
+ const last = points[points.length - 1];
1065
+ const first = points[0];
1066
+ const area = `${line} L${last.x.toFixed(1)},${height - pad} L${first.x.toFixed(1)},${height - pad} Z`;
1067
+ const gradientId = `icen-chart-line-${++lineGradientSeq}`;
1068
+ const wrap = document.createElement("div");
1069
+ wrap.className = "chart-sparkline";
1070
+ const svg2 = svgEl("svg", { viewBox: `0 0 ${width} ${height}`, role: "img" });
1071
+ const defs = svgEl("defs", {});
1072
+ const gradient = svgEl("linearGradient", { id: gradientId, x1: "0", x2: "0", y1: "0", y2: "1" });
1073
+ gradient.appendChild(svgEl("stop", { offset: "0%", "stop-color": tone, "stop-opacity": "0.28" }));
1074
+ gradient.appendChild(svgEl("stop", { offset: "100%", "stop-color": tone, "stop-opacity": "0.02" }));
1075
+ defs.appendChild(gradient);
1076
+ svg2.appendChild(defs);
1077
+ svg2.appendChild(svgEl("path", { d: area, fill: `url(#${gradientId})` }));
1078
+ svg2.appendChild(svgEl("path", {
1079
+ d: line,
1080
+ fill: "none",
1081
+ stroke: tone,
1082
+ "stroke-width": "1.8",
1083
+ "stroke-linecap": "round",
1084
+ "stroke-linejoin": "round"
1085
+ }));
1086
+ const dot = svgEl("circle", {
1087
+ cx: last.x.toFixed(1),
1088
+ cy: last.y.toFixed(1),
1089
+ r: "2.4",
1090
+ fill: "var(--token-card)",
1091
+ stroke: tone,
1092
+ "stroke-width": "1.6"
1093
+ });
1094
+ const title = svgEl("title", {});
1095
+ title.textContent = fmt(opts, last.value);
1096
+ dot.appendChild(title);
1097
+ svg2.appendChild(dot);
1098
+ wrap.appendChild(svg2);
1099
+ body.appendChild(wrap);
1100
+ });
1101
+ }
1102
+ function renderGauge(el2, opts) {
1103
+ if (typeof document === "undefined") return;
1104
+ el2.textContent = "";
1105
+ const max = opts.max ?? 100;
1106
+ const ratio = max > 0 ? Math.min(1, Math.max(0, opts.value / max)) : 0;
1107
+ const radius = 42;
1108
+ const circumference = 2 * Math.PI * radius;
1109
+ const wrap = document.createElement("div");
1110
+ wrap.className = "chart-gauge";
1111
+ if (opts.tone) wrap.style.setProperty("--chart-tone", toneVar(opts.tone));
1112
+ const svg2 = svgEl("svg", { viewBox: "0 0 120 120", role: "img" });
1113
+ svg2.style.transform = "rotate(-90deg)";
1114
+ svg2.appendChild(svgEl("circle", {
1115
+ cx: "60",
1116
+ cy: "60",
1117
+ r: String(radius),
1118
+ fill: "none",
1119
+ stroke: "var(--token-line-soft)",
1120
+ "stroke-width": "10"
1121
+ }));
1122
+ const dash = ratio * circumference;
1123
+ svg2.appendChild(svgEl("circle", {
1124
+ cx: "60",
1125
+ cy: "60",
1126
+ r: String(radius),
1127
+ fill: "none",
1128
+ stroke: toneVar(opts.tone),
1129
+ "stroke-width": "10",
1130
+ "stroke-dasharray": `${dash} ${circumference - dash}`,
1131
+ "stroke-linecap": "round"
1132
+ }));
1133
+ const center = document.createElement("div");
1134
+ center.className = "chart-gauge-center";
1135
+ const val = document.createElement("span");
1136
+ val.className = "chart-gauge-value";
1137
+ val.textContent = opts.formatValue ? opts.formatValue(opts.value) : `${Math.round(ratio * 100)}%`;
1138
+ center.appendChild(val);
1139
+ if (opts.label) {
1140
+ const lab = document.createElement("span");
1141
+ lab.className = "chart-gauge-label";
1142
+ lab.textContent = opts.label;
1143
+ center.appendChild(lab);
1144
+ }
1145
+ wrap.append(svg2, center);
1146
+ el2.appendChild(wrap);
1147
+ }
1148
+ function renderCalendar(el2, opts) {
1149
+ if (typeof document === "undefined") return;
1150
+ withChrome(el2, opts, true, (body) => {
1151
+ let entries;
1152
+ if (opts.data && opts.data.length > 0) {
1153
+ entries = opts.data;
1154
+ } else if (opts.dates && opts.dates.length > 0 && opts.values) {
1155
+ entries = opts.dates.slice(0, opts.values.length).map((date, i) => ({ date, value: opts.values[i] ?? 0 }));
1156
+ } else {
1157
+ renderEmpty(body, opts.emptyLabel);
1158
+ return;
1159
+ }
1160
+ const wrap = document.createElement("div");
1161
+ wrap.className = "chart-calendar";
1162
+ if (opts.tone) wrap.style.setProperty("--chart-tone", toneVar(opts.tone));
1163
+ const grid = document.createElement("div");
1164
+ grid.className = "chart-heatmap-grid";
1165
+ grid.setAttribute("role", "img");
1166
+ const months = document.createElement("div");
1167
+ months.className = "chart-calendar-months";
1168
+ const weekdayRow = document.createElement("div");
1169
+ weekdayRow.className = "chart-calendar-weekdays";
1170
+ ["\u4E00", "", "\u4E09", "", "\u4E94", "", "\u65E5"].forEach((w) => {
1171
+ const s = document.createElement("span");
1172
+ s.textContent = w;
1173
+ weekdayRow.appendChild(s);
1174
+ });
1175
+ const max = maxOf(entries.map((e) => e.value));
1176
+ const levelOf = (v) => v <= 0 ? 0 : Math.min(4, Math.ceil(v / max * 4));
1177
+ const first = /* @__PURE__ */ new Date(`${entries[0].date}T00:00:00`);
1178
+ const pad = (first.getDay() + 6) % 7;
1179
+ for (let i = 0; i < pad; i++) {
1180
+ const blank = document.createElement("span");
1181
+ blank.className = "chart-heatmap-cell is-blank";
1182
+ grid.appendChild(blank);
1183
+ }
1184
+ let lastMonth = -1;
1185
+ entries.forEach((entry, i) => {
1186
+ const d = /* @__PURE__ */ new Date(`${entry.date}T00:00:00`);
1187
+ const col = Math.floor((pad + i) / 7);
1188
+ if (d.getMonth() !== lastMonth) {
1189
+ lastMonth = d.getMonth();
1190
+ const label = document.createElement("span");
1191
+ label.className = "chart-calendar-month";
1192
+ label.textContent = `${d.getMonth() + 1}\u6708`;
1193
+ label.style.setProperty("--col", String(col));
1194
+ months.appendChild(label);
1195
+ }
1196
+ const cell = document.createElement("span");
1197
+ cell.className = "chart-heatmap-cell";
1198
+ cell.dataset.level = String(levelOf(entry.value));
1199
+ cell.setAttribute("title", `${entry.date}\uFF1A${fmt(opts, entry.value)}`);
1200
+ setMarkData(cell, { index: i, label: entry.date, value: entry.value });
1201
+ grid.appendChild(cell);
1202
+ });
1203
+ const legend = document.createElement("div");
1204
+ legend.className = "chart-heatmap-legend";
1205
+ const less = document.createElement("span");
1206
+ less.textContent = "\u5C11";
1207
+ const more = document.createElement("span");
1208
+ more.textContent = "\u591A";
1209
+ legend.appendChild(less);
1210
+ for (let lv = 0; lv <= 4; lv++) {
1211
+ const cell = document.createElement("span");
1212
+ cell.className = "chart-heatmap-cell";
1213
+ cell.dataset.level = String(lv);
1214
+ legend.appendChild(cell);
1215
+ }
1216
+ legend.appendChild(more);
1217
+ const columns = Math.max(1, Math.ceil((pad + entries.length) / 7));
1218
+ months.style.setProperty("--columns", String(columns));
1219
+ wrap.append(months, weekdayRow, grid, legend);
1220
+ body.appendChild(wrap);
1221
+ });
1222
+ }
1223
+ function renderScatter(el2, opts) {
1224
+ if (typeof document === "undefined") return;
1225
+ withChrome(el2, opts, false, (body) => {
1226
+ const pts = opts.points.filter((p) => Number.isFinite(p.x) && Number.isFinite(p.y));
1227
+ if (pts.length === 0) {
1228
+ renderEmpty(body, opts.emptyLabel);
1229
+ return;
1230
+ }
1231
+ const width = 360;
1232
+ const height = 220;
1233
+ const pad = 30;
1234
+ let xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, sMax = 0;
1235
+ for (const p of pts) {
1236
+ if (p.x < xMin) xMin = p.x;
1237
+ if (p.x > xMax) xMax = p.x;
1238
+ if (p.y < yMin) yMin = p.y;
1239
+ if (p.y > yMax) yMax = p.y;
1240
+ if ((p.size ?? 0) > sMax) sMax = p.size ?? 0;
1241
+ }
1242
+ if (xMax === xMin) xMax = xMin + 1;
1243
+ if (yMax === yMin) yMax = yMin + 1;
1244
+ const rOf = (size) => size && sMax > 0 ? 3 + size / sMax * 7 : 4;
1245
+ const wrap = document.createElement("div");
1246
+ wrap.className = "chart-scatter";
1247
+ const tone = toneVar(opts.tone);
1248
+ const svg2 = svgEl("svg", { viewBox: `0 0 ${width} ${height}`, role: "img" });
1249
+ const xAt = (x) => pad + (x - xMin) / (xMax - xMin) * (width - pad * 2);
1250
+ const yAt = (y) => height - pad - (y - yMin) / (yMax - yMin) * (height - pad * 2);
1251
+ for (let i = 0; i <= 3; i++) {
1252
+ const y = pad + i * (height - pad * 2) / 3;
1253
+ svg2.appendChild(svgEl("line", {
1254
+ x1: String(pad),
1255
+ x2: String(width - pad),
1256
+ y1: String(y),
1257
+ y2: String(y),
1258
+ stroke: "var(--token-line-soft)",
1259
+ "stroke-width": "1"
1260
+ }));
1261
+ const tv = yMin + (yMax - yMin) * (3 - i) / 3;
1262
+ const txt = svgEl("text", {
1263
+ x: String(pad - 4),
1264
+ y: String(y + 3),
1265
+ "text-anchor": "end",
1266
+ "font-size": "8",
1267
+ fill: "var(--token-text-faint)"
1268
+ });
1269
+ txt.textContent = String(Math.round(tv * 10) / 10);
1270
+ svg2.appendChild(txt);
1271
+ }
1272
+ for (let i = 0; i <= 4; i++) {
1273
+ const x = pad + i * (width - pad * 2) / 4;
1274
+ svg2.appendChild(svgEl("line", {
1275
+ x1: String(x),
1276
+ x2: String(x),
1277
+ y1: String(pad),
1278
+ y2: String(height - pad),
1279
+ stroke: "var(--token-line-soft)",
1280
+ "stroke-width": "1",
1281
+ "stroke-dasharray": "2 3"
1282
+ }));
1283
+ const tv = xMin + (xMax - xMin) * i / 4;
1284
+ const txt = svgEl("text", {
1285
+ x: String(x),
1286
+ y: String(height - pad + 12),
1287
+ "text-anchor": "middle",
1288
+ "font-size": "8",
1289
+ fill: "var(--token-text-faint)"
1290
+ });
1291
+ txt.textContent = String(Math.round(tv * 10) / 10);
1292
+ svg2.appendChild(txt);
1293
+ }
1294
+ if (opts.yLabel) {
1295
+ const t = svgEl("text", { x: "10", y: String(pad - 10), "font-size": "8", fill: "var(--token-text-faint)" });
1296
+ t.textContent = opts.yLabel;
1297
+ svg2.appendChild(t);
1298
+ }
1299
+ if (opts.xLabel) {
1300
+ const t = svgEl("text", { x: String(width - pad), y: String(pad - 10), "text-anchor": "end", "font-size": "8", fill: "var(--token-text-faint)" });
1301
+ t.textContent = opts.xLabel;
1302
+ svg2.appendChild(t);
1303
+ }
1304
+ pts.forEach((p, i) => {
1305
+ const c = svgEl("circle", {
1306
+ cx: xAt(p.x).toFixed(1),
1307
+ cy: yAt(p.y).toFixed(1),
1308
+ r: rOf(p.size).toFixed(1),
1309
+ fill: tone,
1310
+ "fill-opacity": "0.55",
1311
+ stroke: tone,
1312
+ "stroke-width": "1"
1313
+ });
1314
+ const title = svgEl("title", {});
1315
+ title.textContent = `${p.label ?? `#${i + 1}`}: (${p.x}, ${p.y}${p.size != null ? `, size ${p.size}` : ""})`;
1316
+ c.appendChild(title);
1317
+ setMarkData(c, { index: i, label: p.label ?? `#${i + 1}`, value: p.y });
1318
+ c.dataset.chartX = String(p.x);
1319
+ svg2.appendChild(c);
1320
+ });
1321
+ wrap.appendChild(svg2);
1322
+ body.appendChild(wrap);
1323
+ });
1324
+ }
1325
+ function chartFormatValue(format) {
1326
+ if (!format) return (v) => String(v);
1327
+ const notation = format.notation ?? "raw";
1328
+ return (v) => {
1329
+ let text;
1330
+ if (notation === "compact") {
1331
+ const abs = Math.abs(v);
1332
+ text = abs >= 1e6 ? `${Math.round(v / 1e5) / 10}M` : abs >= 1e3 ? `${Math.round(v / 100) / 10}k` : String(v);
1333
+ } else if (notation === "percent") {
1334
+ text = `${Math.round(v * 10) / 10}%`;
1335
+ } else if (notation === "ms") {
1336
+ if (v <= 0) text = "0ms";
1337
+ else if (v < 1e3) text = `${Math.round(v)}ms`;
1338
+ else if (v < 6e4) text = `${Math.round(v / 100) / 10}s`;
1339
+ else text = `${Math.floor(v / 6e4)}m`;
1340
+ } else {
1341
+ text = String(Math.round(v * 100) / 100);
1342
+ }
1343
+ return format.unit ? `${text} ${format.unit}` : text;
1344
+ };
1345
+ }
1346
+ function pivotData(spec) {
1347
+ const data = spec.data;
1348
+ if (!Array.isArray(data) || data.length === 0) return {};
1349
+ const d = spec.dims ?? {};
1350
+ const labelField = d.label ?? "label";
1351
+ const seriesField = d.series ?? "series";
1352
+ const valueField = d.value ?? "value";
1353
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : Number(v) || 0;
1354
+ const str2 = (v) => typeof v === "string" ? v : v == null ? "" : String(v);
1355
+ if (d.x || data.some((r) => typeof r.x === "number")) {
1356
+ const xf = d.x ?? "x";
1357
+ const yf = d.y ?? "y";
1358
+ const sf = d.size ?? "size";
1359
+ const lf = d.label ?? "label";
1360
+ const points = data.filter((r) => r[xf] != null && r[yf] != null).map((r) => ({
1361
+ x: num(r[xf]),
1362
+ y: num(r[yf]),
1363
+ size: r[sf] != null ? num(r[sf]) : void 0,
1364
+ label: r[lf] != null ? str2(r[lf]) : void 0
1365
+ }));
1366
+ return { points };
1367
+ }
1368
+ const labels = [];
1369
+ const seenLabel = /* @__PURE__ */ new Set();
1370
+ const hasSeries = data.some((r) => r[seriesField] != null && r[seriesField] !== "");
1371
+ const seriesNames = [];
1372
+ const seenSeries = /* @__PURE__ */ new Set();
1373
+ for (const r of data) {
1374
+ const l = str2(r[labelField]);
1375
+ if (!seenLabel.has(l)) {
1376
+ seenLabel.add(l);
1377
+ labels.push(l);
1378
+ }
1379
+ if (hasSeries) {
1380
+ const sn = str2(r[seriesField]);
1381
+ if (!seenSeries.has(sn)) {
1382
+ seenSeries.add(sn);
1383
+ seriesNames.push(sn);
1384
+ }
1385
+ }
1386
+ }
1387
+ const labelIndex = new Map(labels.map((l, i) => [l, i]));
1388
+ const seriesIndex = new Map(seriesNames.map((s, i) => [s, i]));
1389
+ const matrix = seriesNames.map(() => labels.map(() => NaN));
1390
+ for (const r of data) {
1391
+ const li = labelIndex.get(str2(r[labelField])) ?? 0;
1392
+ const si = hasSeries ? seriesIndex.get(str2(r[seriesField])) ?? 0 : 0;
1393
+ (matrix[si] ?? [])[li] = num(r[valueField]);
1394
+ }
1395
+ for (const row of matrix) for (let i = 0; i < row.length; i++) if (Number.isNaN(row[i])) row[i] = 0;
1396
+ if (hasSeries) {
1397
+ return {
1398
+ labels,
1399
+ series: seriesNames.map((name, si) => ({ name, values: matrix[si] ?? [] }))
1400
+ };
1401
+ }
1402
+ return { labels, values: matrix[0] ?? [] };
1403
+ }
1404
+ var CHART_TYPE_ALIASES = {
1405
+ bar: "vbar",
1406
+ column: "vbar",
1407
+ "vertical-bar": "vbar",
1408
+ "bar-vertical": "vbar",
1409
+ "horizontal-bar": "hbar",
1410
+ "bar-horizontal": "hbar",
1411
+ ranking: "hbar",
1412
+ pie: "donut",
1413
+ ring: "donut",
1414
+ "pie-chart": "donut",
1415
+ "stacked-bar": "stack",
1416
+ "stacked-bar-100": "stack",
1417
+ ratio: "stack",
1418
+ time: "line",
1419
+ timeline: "line",
1420
+ trend: "line",
1421
+ "trend-line": "line",
1422
+ contribution: "calendar",
1423
+ "contribution-graph": "calendar",
1424
+ "calendar-heatmap": "calendar",
1425
+ heat: "heatmap",
1426
+ matrix: "heatmap",
1427
+ bubble: "scatter",
1428
+ "scatter-plot": "scatter",
1429
+ dial: "gauge",
1430
+ progress: "gauge",
1431
+ mini: "sparkline",
1432
+ "trend-sparkline": "sparkline",
1433
+ spider: "radar",
1434
+ "radar-chart": "radar"
1435
+ };
1436
+ function toNum(v) {
1437
+ if (typeof v === "number" && Number.isFinite(v)) return v;
1438
+ if (typeof v === "string" && v.trim() !== "") {
1439
+ const n = Number(v.replace(/[,\s%]/g, ""));
1440
+ if (Number.isFinite(n)) return n;
1441
+ }
1442
+ return void 0;
1443
+ }
1444
+ function normalizeChartSpec(raw) {
1445
+ let src = raw;
1446
+ if (typeof src === "string") {
1447
+ try {
1448
+ src = JSON.parse(src);
1449
+ } catch {
1450
+ return {};
1451
+ }
1452
+ }
1453
+ if (!src || typeof src !== "object" || Array.isArray(src)) {
1454
+ if (Array.isArray(raw)) src = { data: raw };
1455
+ else return {};
1456
+ }
1457
+ const s = src;
1458
+ const spec = {};
1459
+ if (typeof s.type === "string") {
1460
+ const t = s.type.trim().toLowerCase();
1461
+ spec.type = CHART_TYPE_ALIASES[t] ?? t;
1462
+ }
1463
+ for (const k of ["title", "tone", "emptyLabel"]) {
1464
+ if (typeof s[k] === "string") spec[k] = s[k];
1465
+ }
1466
+ for (const k of ["stacked", "fill", "tooltip", "legend"]) {
1467
+ if (typeof s[k] === "boolean") spec[k] = s[k];
1468
+ }
1469
+ for (const k of ["weeks", "max", "levels"]) {
1470
+ const n = toNum(s[k]);
1471
+ if (n != null) spec[k] = n;
1472
+ }
1473
+ if (Array.isArray(s.labels)) spec.labels = s.labels.map((v) => String(v ?? ""));
1474
+ if (Array.isArray(s.values)) {
1475
+ const values = s.values.map(toNum).filter((v) => v != null);
1476
+ if (values.length > 0) spec.values = values;
1477
+ }
1478
+ if (Array.isArray(s.dates)) spec.dates = s.dates.map((v) => String(v ?? ""));
1479
+ if (Array.isArray(s.axes)) spec.axes = s.axes.map((v) => String(v ?? ""));
1480
+ if (Array.isArray(s.series)) {
1481
+ const series = s.series.filter((v) => !!v && typeof v === "object").map((v, i) => {
1482
+ const values = Array.isArray(v.values) ? v.values.map(toNum).filter((n) => n != null) : [];
1483
+ const sv = { name: String(v.name ?? `\u7CFB\u5217${i + 1}`), values };
1484
+ const tone = v.tone;
1485
+ if (typeof tone === "string" || typeof tone === "number") sv.tone = tone;
1486
+ return sv;
1487
+ }).filter((v) => v.values.length > 0);
1488
+ if (series.length > 0) spec.series = series;
1489
+ }
1490
+ if (Array.isArray(s.segments)) {
1491
+ const segments = s.segments.filter((v) => !!v && typeof v === "object").map((v) => {
1492
+ const seg = { label: String(v.label ?? v.name ?? ""), value: toNum(v.value) ?? 0 };
1493
+ if (typeof v.tone === "string") seg.tone = v.tone;
1494
+ return seg;
1495
+ }).filter((v) => v.label !== "" || v.value !== 0);
1496
+ if (segments.length > 0) spec.segments = segments;
1497
+ }
1498
+ if (Array.isArray(s.points)) {
1499
+ const points = s.points.filter((v) => !!v && typeof v === "object").map((v) => ({
1500
+ x: toNum(v.x) ?? 0,
1501
+ y: toNum(v.y) ?? 0,
1502
+ size: toNum(v.size),
1503
+ label: typeof v.label === "string" ? v.label : void 0
1504
+ }));
1505
+ if (points.length > 0) spec.points = points;
1506
+ }
1507
+ if (Array.isArray(s.data)) spec.data = s.data.filter((v) => !!v && typeof v === "object");
1508
+ if (s.dims && typeof s.dims === "object" && !Array.isArray(s.dims)) spec.dims = s.dims;
1509
+ if (s.format && typeof s.format === "object") {
1510
+ const f = s.format;
1511
+ const format = {};
1512
+ if (typeof f.unit === "string") format.unit = f.unit;
1513
+ if (typeof f.notation === "string" && ["compact", "percent", "ms", "raw"].includes(f.notation)) {
1514
+ format.notation = f.notation;
1515
+ }
1516
+ spec.format = format;
1517
+ }
1518
+ const isDateRecords = spec.data?.length && spec.data[0] && "date" in spec.data[0];
1519
+ if (spec.data && spec.data.length > 0 && !isDateRecords && !spec.series && !spec.points && !spec.values && !spec.segments) {
1520
+ Object.assign(spec, pivotData(spec));
1521
+ }
1522
+ return spec;
1523
+ }
1524
+ function looksTemporal(labels) {
1525
+ if (labels.length === 0) return false;
1526
+ let hits = 0;
1527
+ for (const l of labels) {
1528
+ if (/^\d{4}-\d{2}(-\d{2})?$/.test(l)) hits++;
1529
+ else if (/^\d{4}\/\d{1,2}(\/\d{1,2})?$/.test(l)) hits++;
1530
+ else if (/^\d{4}年/.test(l)) hits++;
1531
+ else if (/^[Qq][1-4]$/.test(l)) hits++;
1532
+ else if (/^(周一|周二|周三|周四|周五|周六|周日|Mon|Tue|Wed|Thu|Fri|Sat|Sun)/i.test(l)) hits++;
1533
+ else if (/^第?\d+[日时周月]/.test(l)) hits++;
1534
+ else if (/^(v|ver\.?|version[ .]?)?\d+(\.\d+)+$/i.test(l)) hits++;
1535
+ else if (/^\d{4}$/.test(l)) hits++;
1536
+ }
1537
+ return hits / labels.length >= 0.6;
1538
+ }
1539
+ function inferChartType(spec) {
1540
+ if (spec.points && spec.points.length > 0) return "scatter";
1541
+ if (spec.dates && spec.dates.length > 0) return "calendar";
1542
+ if (spec.segments && spec.segments.length > 0) return "donut";
1543
+ if (spec.axes && spec.axes.length >= 3) return "radar";
1544
+ const labels = spec.labels ?? [];
1545
+ const multiSeries = (spec.series?.length ?? 0) > 1;
1546
+ if (labels.length > 0) {
1547
+ if (looksTemporal(labels)) return "line";
1548
+ if (multiSeries) return "vbar";
1549
+ return labels.length > 8 ? "hbar" : "vbar";
1550
+ }
1551
+ if (multiSeries) return "line";
1552
+ if (spec.values && spec.values.length > 1) return "line";
1553
+ if (typeof spec.max === "number" && spec.values && spec.values.length === 1) return "gauge";
1554
+ return "vbar";
1555
+ }
1556
+ function dispatchChartEvent(root, type, mark, chart, phase, pointer) {
1557
+ const read = (name) => mark.getAttribute(name) ?? void 0;
1558
+ const numOr = (v) => v == null ? void 0 : Number(v);
1559
+ const detail = {
1560
+ type,
1561
+ phase,
1562
+ chart,
1563
+ index: numOr(read("data-chart-index")),
1564
+ seriesIndex: numOr(read("data-chart-series")),
1565
+ seriesName: read("data-chart-series-name"),
1566
+ label: read("data-chart-label"),
1567
+ value: numOr(read("data-chart-value")),
1568
+ target: mark,
1569
+ pointerX: pointer?.x,
1570
+ pointerY: pointer?.y
1571
+ };
1572
+ root.dispatchEvent(new CustomEvent(`icen:chart-${type}`, { detail, bubbles: true }));
1573
+ }
1574
+ var tooltipEl = null;
1575
+ function chartTooltip() {
1576
+ if (!tooltipEl) {
1577
+ tooltipEl = document.createElement("div");
1578
+ tooltipEl.className = "chart-tooltip";
1579
+ tooltipEl.setAttribute("role", "tooltip");
1580
+ tooltipEl.hidden = true;
1581
+ document.body.appendChild(tooltipEl);
1582
+ }
1583
+ return tooltipEl;
1584
+ }
1585
+ function tooltipText(mark) {
1586
+ const label = mark.getAttribute("data-chart-label") ?? "";
1587
+ const series = mark.getAttribute("data-chart-series-name");
1588
+ const value = mark.getAttribute("data-chart-value");
1589
+ const head = series ? label ? `${series} \xB7 ${label}` : series : label;
1590
+ return value != null ? `${head}\uFF1A${value}` : head;
1591
+ }
1592
+ function moveTooltip(x, y) {
1593
+ const tip = chartTooltip();
1594
+ const pad = 12;
1595
+ const w = tip.offsetWidth || 120;
1596
+ const h2 = tip.offsetHeight || 28;
1597
+ let left = x + pad;
1598
+ let top = y - h2 - pad;
1599
+ if (left + w > window.innerWidth - 8) left = x - w - pad;
1600
+ if (top < 8) top = y + pad;
1601
+ tip.style.left = `${Math.round(left)}px`;
1602
+ tip.style.top = `${Math.round(top)}px`;
1603
+ }
1604
+ function hasLegendOf(spec) {
1605
+ switch (spec.type) {
1606
+ case "donut":
1607
+ case "stack":
1608
+ return (spec.segments?.length ?? 0) > 0;
1609
+ case "heatmap":
1610
+ case "calendar":
1611
+ return true;
1612
+ case "line":
1613
+ case "vbar":
1614
+ case "radar":
1615
+ return (spec.series?.length ?? 0) > 1;
1616
+ default:
1617
+ return false;
1618
+ }
1619
+ }
1620
+ function renderChart(el2, raw) {
1621
+ const noop = () => void 0;
1622
+ if (typeof document === "undefined") {
1623
+ return { el: el2, spec: {}, update: noop, on: () => noop, destroy: noop };
1624
+ }
1625
+ const root = el2;
1626
+ const attached = root;
1627
+ const wasBound = attached.__icenChartBound === true;
1628
+ attached.__icenChartBound = true;
1629
+ let current = normalizeChartSpec(raw);
1630
+ const typeOf = () => current.type ?? "vbar";
1631
+ const legendState = { hidden: null };
1632
+ const render = () => {
1633
+ if (!current.type) current = { ...current, type: inferChartType(current) };
1634
+ const spec = current;
1635
+ const formatValue = chartFormatValue(spec.format);
1636
+ if (spec.legend !== void 0) legendState.hidden = spec.legend === false;
1637
+ withChrome(root, spec, hasLegendOf(spec), (body) => {
1638
+ switch (spec.type) {
1639
+ case "line":
1640
+ renderLine(body, { labels: spec.labels ?? [], values: spec.values ?? [], series: spec.series, tone: spec.tone, fill: spec.fill, formatValue, emptyLabel: spec.emptyLabel, title: spec.title, legend: spec.legend });
1641
+ break;
1642
+ case "area":
1643
+ renderLine(body, { labels: spec.labels ?? [], values: spec.values ?? [], series: spec.series, tone: spec.tone, fill: true, formatValue, emptyLabel: spec.emptyLabel, title: spec.title, legend: spec.legend });
1644
+ break;
1645
+ case "vbar":
1646
+ renderVBar(body, { labels: spec.labels ?? [], values: spec.values ?? [], series: spec.series, stacked: spec.stacked, tone: spec.tone, formatValue, emptyLabel: spec.emptyLabel, title: spec.title, legend: spec.legend });
1647
+ break;
1648
+ case "hbar":
1649
+ renderHBar(body, { labels: spec.labels ?? [], values: spec.values ?? [], tone: spec.tone, formatValue, emptyLabel: spec.emptyLabel, title: spec.title, legend: spec.legend });
1650
+ break;
1651
+ case "stack":
1652
+ renderStack(body, { segments: spec.segments ?? [], formatValue, emptyLabel: spec.emptyLabel, title: spec.title, legend: spec.legend });
1653
+ break;
1654
+ case "donut":
1655
+ renderDonut(body, { segments: spec.segments ?? [], formatValue, emptyLabel: spec.emptyLabel, title: spec.title, legend: spec.legend });
1656
+ break;
1657
+ case "radar": {
1658
+ const series = spec.series ? spec.series.map((s) => ({ name: s.name, values: s.values, tone: typeof s.tone === "string" ? s.tone : void 0 })) : spec.values ? [{ name: "", values: spec.values }] : [];
1659
+ renderRadar(body, { axes: spec.axes ?? spec.labels ?? [], series, max: spec.max, levels: spec.levels, formatValue, emptyLabel: spec.emptyLabel, title: spec.title, legend: spec.legend });
1660
+ break;
1661
+ }
1662
+ case "heatmap":
1663
+ renderHeatmap(body, { values: spec.values, data: spec.data, weeks: spec.weeks, tone: spec.tone, formatValue, emptyLabel: spec.emptyLabel, title: spec.title, legend: spec.legend });
1664
+ break;
1665
+ case "calendar":
1666
+ renderCalendar(body, { dates: spec.dates, values: spec.values, data: spec.data, tone: spec.tone, formatValue, emptyLabel: spec.emptyLabel, title: spec.title, legend: spec.legend });
1667
+ break;
1668
+ case "sparkline":
1669
+ renderSparkline(body, { labels: spec.labels ?? [], values: spec.values ?? [], tone: spec.tone, formatValue, emptyLabel: spec.emptyLabel, title: spec.title, legend: spec.legend });
1670
+ break;
1671
+ case "gauge":
1672
+ renderGauge(body, { value: spec.values?.[0] ?? 0, max: spec.max, tone: spec.tone, label: spec.labels?.[0], formatValue });
1673
+ break;
1674
+ case "scatter":
1675
+ renderScatter(body, { points: spec.points ?? [], tone: spec.tone, formatValue, emptyLabel: spec.emptyLabel, title: spec.title, legend: spec.legend });
1676
+ break;
1677
+ default:
1678
+ renderEmpty(body, spec.emptyLabel);
1679
+ }
1680
+ });
1681
+ };
1682
+ if (!wasBound) {
1683
+ const markOf = (e) => {
1684
+ const t = e.target;
1685
+ return t instanceof Element ? t.closest("[data-chart-mark]") : null;
1686
+ };
1687
+ const tipEnabled = () => current.tooltip !== false;
1688
+ let hoverMark = null;
1689
+ const enterMark = (mark, x, y) => {
1690
+ hoverMark = mark;
1691
+ mark.classList.add("is-hover");
1692
+ dispatchChartEvent(root, "hover", mark, typeOf(), "enter", { x, y });
1693
+ if (tipEnabled()) {
1694
+ const tip = chartTooltip();
1695
+ tip.textContent = tooltipText(mark);
1696
+ tip.hidden = false;
1697
+ moveTooltip(x, y);
1698
+ }
1699
+ };
1700
+ const leaveMark = (pointer) => {
1701
+ if (!hoverMark) return;
1702
+ hoverMark.classList.remove("is-hover");
1703
+ dispatchChartEvent(root, "hover", hoverMark, typeOf(), "leave", pointer);
1704
+ hoverMark = null;
1705
+ chartTooltip().hidden = true;
1706
+ };
1707
+ root.addEventListener("pointerover", (e) => {
1708
+ const mark = markOf(e);
1709
+ if (!mark || mark === hoverMark) return;
1710
+ leaveMark({ x: e.clientX, y: e.clientY });
1711
+ enterMark(mark, e.clientX, e.clientY);
1712
+ });
1713
+ root.addEventListener("pointermove", (e) => {
1714
+ if (hoverMark && tipEnabled()) {
1715
+ dispatchChartEvent(root, "hover", hoverMark, typeOf(), "move", { x: e.clientX, y: e.clientY });
1716
+ moveTooltip(e.clientX, e.clientY);
1717
+ }
1718
+ });
1719
+ root.addEventListener("pointerout", (e) => {
1720
+ const mark = markOf(e);
1721
+ if (mark && mark === hoverMark) leaveMark({ x: e.clientX, y: e.clientY });
1722
+ });
1723
+ root.addEventListener("pointerleave", () => leaveMark());
1724
+ root.addEventListener("click", (e) => {
1725
+ const mark = markOf(e);
1726
+ if (mark) dispatchChartEvent(root, "click", mark, typeOf(), void 0, { x: e.clientX, y: e.clientY });
1727
+ });
1728
+ root.addEventListener("dblclick", (e) => {
1729
+ const mark = markOf(e);
1730
+ if (mark) dispatchChartEvent(root, "dblclick", mark, typeOf(), void 0, { x: e.clientX, y: e.clientY });
1731
+ });
1732
+ root.addEventListener("contextmenu", (e) => {
1733
+ const mark = markOf(e);
1734
+ if (!mark) return;
1735
+ e.preventDefault();
1736
+ dispatchChartEvent(root, "contextmenu", mark, typeOf(), void 0, { x: e.clientX, y: e.clientY });
1737
+ });
1738
+ }
1739
+ render();
1740
+ return {
1741
+ el: root,
1742
+ spec: current,
1743
+ update(next) {
1744
+ current = normalizeChartSpec(next);
1745
+ render();
1746
+ },
1747
+ on(name, listener) {
1748
+ const handler = (event) => {
1749
+ listener(event.detail, event);
1750
+ };
1751
+ root.addEventListener(`icen:chart-${name}`, handler);
1752
+ return () => root.removeEventListener(`icen:chart-${name}`, handler);
1753
+ },
1754
+ destroy() {
1755
+ root.textContent = "";
1756
+ attached.__icenChartBound = false;
1757
+ chartTooltip().hidden = true;
1758
+ }
1759
+ };
1760
+ }
1761
+
1762
+ // src/behaviors/ai-tool.ts
1763
+ var AI_STATUSES = [
1764
+ "pending",
1765
+ "running",
1766
+ "streaming",
1767
+ "approval",
1768
+ "done",
1769
+ "error",
1770
+ "cancelled"
1771
+ ];
1772
+ function h(tag, className, text) {
1773
+ const node = document.createElement(tag);
1774
+ if (className) node.className = className;
1775
+ if (text != null) node.textContent = text;
1776
+ return node;
1777
+ }
1778
+ function setStatusClass(item, status) {
1779
+ for (const s of AI_STATUSES) item.classList.toggle(`is-${s}`, s === status);
1780
+ }
1781
+ function prettyValue(value) {
1782
+ if (value == null) return "";
1783
+ if (typeof value === "string") return value;
1784
+ try {
1785
+ return JSON.stringify(value, null, 2) ?? "";
1786
+ } catch {
1787
+ return String(value);
1788
+ }
1789
+ }
1790
+ function compactValue(value, max = 160) {
1791
+ if (value == null) return "";
1792
+ let text;
1793
+ if (typeof value === "string") {
1794
+ text = value.replace(/\s+/g, " ").trim();
1795
+ } else {
1796
+ try {
1797
+ text = JSON.stringify(value) ?? "";
1798
+ } catch {
1799
+ text = String(value);
1800
+ }
1801
+ }
1802
+ return text.length > max ? `${text.slice(0, max)}\u2026` : text;
1803
+ }
1804
+ function summarizeInput(model) {
1805
+ const kind = getAiKind(model.kind);
1806
+ if (typeof kind.summarize === "function") {
1807
+ try {
1808
+ const text = kind.summarize(model.input);
1809
+ if (text) return text;
1810
+ } catch {
1811
+ }
1812
+ }
1813
+ return compactValue(model.input);
1814
+ }
1815
+ function buildHead(headClass) {
1816
+ const head = h("button", headClass);
1817
+ head.type = "button";
1818
+ head.setAttribute("aria-expanded", "false");
1819
+ const iconEl = h("span", "ai-item-icon");
1820
+ iconEl.setAttribute("aria-hidden", "true");
1821
+ const main = h("span", "ai-item-main");
1822
+ const titleEl = h("span", "ai-item-title");
1823
+ const subEl = h("span", "ai-item-sub");
1824
+ const statusEl = h("span", "ai-item-status");
1825
+ statusEl.setAttribute("role", "img");
1826
+ const metaEl = h("span", "ai-item-meta");
1827
+ main.append(titleEl, subEl);
1828
+ head.append(iconEl, main, statusEl, metaEl);
1829
+ return { head, iconEl, titleEl, subEl, statusEl, metaEl };
1830
+ }
1831
+ function buildIo(label) {
1832
+ const root = h("div", "ai-tool-io");
1833
+ root.append(h("div", "ai-tool-io-label", label));
1834
+ const pre = h("pre", "ai-tool-io-content");
1835
+ const media = h("div", "ai-tool-io-media");
1836
+ media.hidden = true;
1837
+ root.append(pre, media);
1838
+ return { root, pre, media };
1839
+ }
1840
+ function chartSpecOf(value) {
1841
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
1842
+ const v = value;
1843
+ if (v.type === "chart" && v.spec && typeof v.spec === "object") return v.spec;
1844
+ const t = typeof v.type === "string" ? v.type : void 0;
1845
+ const looksChart = Array.isArray(v.series) || Array.isArray(v.segments) || Array.isArray(v.points) || Array.isArray(v.dates) || Array.isArray(v.labels) && Array.isArray(v.values);
1846
+ if (looksChart && (t === void 0 || typeof t === "string")) return v;
1847
+ return null;
1848
+ }
1849
+ function setIo(io, value, allowChart = true) {
1850
+ const chartSpec = allowChart ? chartSpecOf(value) : null;
1851
+ if (chartSpec) {
1852
+ io.pre.textContent = "";
1853
+ io.pre.hidden = true;
1854
+ io.media.replaceChildren();
1855
+ const holder = document.createElement("div");
1856
+ holder.className = "ai-tool-io-chart";
1857
+ io.media.appendChild(holder);
1858
+ renderChart(holder, chartSpec);
1859
+ io.media.hidden = false;
1860
+ io.root.hidden = false;
1861
+ return;
1862
+ }
1863
+ const parts = Array.isArray(value) ? normalizeContentParts(value) : [];
1864
+ if (parts.length > 0) {
1865
+ io.pre.textContent = "";
1866
+ io.pre.hidden = true;
1867
+ io.media.replaceChildren();
1868
+ for (const part of parts) {
1869
+ const node = renderAiContentPart(part);
1870
+ if (node) io.media.appendChild(node);
1871
+ }
1872
+ io.media.hidden = io.media.childElementCount === 0;
1873
+ io.root.hidden = io.media.hidden;
1874
+ return;
1875
+ }
1876
+ io.media.replaceChildren();
1877
+ io.media.hidden = true;
1878
+ const text = prettyValue(value).trim();
1879
+ io.pre.textContent = text;
1880
+ io.pre.hidden = false;
1881
+ io.root.hidden = !text;
1882
+ }
1883
+ function defaultExpanded(m) {
1884
+ if (m.kind === "chart" || m.status === "error" || m.status === "approval") return true;
1885
+ if (Array.isArray(m.output)) {
1886
+ const parts = normalizeContentParts(m.output);
1887
+ if (parts.some((p) => p.type === "image" || p.type === "video" || p.type === "audio")) return true;
1888
+ }
1889
+ return false;
1890
+ }
1891
+ function buildApproval() {
1892
+ const root = h("div", "ai-tool-approval");
1893
+ const reason = h("div", "ai-tool-approval-reason");
1894
+ reason.hidden = true;
1895
+ const allow = h("button", "btn btn-sm btn-primary", "\u5141\u8BB8");
1896
+ allow.type = "button";
1897
+ allow.setAttribute("data-ai-approve", "");
1898
+ const deny = h("button", "btn btn-sm", "\u62D2\u7EDD");
1899
+ deny.type = "button";
1900
+ deny.setAttribute("data-ai-reject", "");
1901
+ root.append(reason, allow, deny);
1902
+ return { root, reason };
1903
+ }
1904
+ function applyTint(item, model) {
1905
+ const tint = getAiKind(model.kind).tint;
1906
+ if (tint) item.style.setProperty("--ai-item-tint", `var(--token-${tint})`);
1907
+ else item.style.removeProperty("--ai-item-tint");
1908
+ }
1909
+ function applyKindVisual(parts, model) {
1910
+ const kind = getAiKind(model.kind);
1911
+ parts.titleEl.textContent = kind.label || model.name;
1912
+ parts.iconEl.replaceChildren();
1913
+ const svg2 = svgIcon(kind.icon);
1914
+ if (svg2) parts.iconEl.append(svg2);
1915
+ const sub = summarizeInput(model);
1916
+ parts.subEl.textContent = sub;
1917
+ parts.subEl.hidden = !sub;
1918
+ }
1919
+ function applyStatusMeta(parts, status, meta) {
1920
+ parts.statusEl.setAttribute("aria-label", aiStatusLabel(status));
1921
+ parts.metaEl.textContent = meta;
1922
+ parts.metaEl.hidden = !meta;
1923
+ }
1924
+ function renderAiToolCall(el2, model) {
1925
+ if (typeof document === "undefined") {
1926
+ return { el: el2, update: () => void 0 };
1927
+ }
1928
+ const item = el2;
1929
+ let current = model;
1930
+ item.className = `ai-tool ai-tool--${model.kind}`;
1931
+ item.dataset.aiId = model.id;
1932
+ item.dataset.aiKind = model.kind;
1933
+ const parts = buildHead("ai-tool-head");
1934
+ const body = h("div", "ai-tool-body");
1935
+ body.hidden = true;
1936
+ const inputIo = buildIo("\u8F93\u5165");
1937
+ const outputIo = buildIo("\u8F93\u51FA");
1938
+ const approval = buildApproval();
1939
+ body.append(inputIo.root, outputIo.root, approval.root);
1940
+ item.append(parts.head, body);
1941
+ const setOpen = (open, fire = true) => {
1942
+ parts.head.setAttribute("aria-expanded", String(open));
1943
+ body.hidden = !open;
1944
+ if (fire) {
1945
+ item.dispatchEvent(
1946
+ new CustomEvent("icen:ai-toggle", { detail: { el: item, open }, bubbles: true })
1947
+ );
1948
+ }
1949
+ };
1950
+ let prevStatus = null;
1951
+ const apply = (m) => {
1952
+ setStatusClass(item, m.status);
1953
+ applyTint(item, m);
1954
+ applyKindVisual(parts, m);
1955
+ const meta = m.durationMs != null ? formatDuration(m.durationMs) : "";
1956
+ applyStatusMeta(parts, m.status, meta);
1957
+ setIo(inputIo, m.input, false);
1958
+ setIo(outputIo, m.errorText ?? m.output);
1959
+ const reason = m.approval?.reason ? compactValue(m.approval.reason, 300) : "";
1960
+ approval.reason.textContent = reason;
1961
+ approval.reason.hidden = !reason;
1962
+ if (!item.dataset.aiUserToggled && defaultExpanded(m)) setOpen(true);
1963
+ prevStatus = m.status;
1964
+ };
1965
+ apply(current);
1966
+ return {
1967
+ el: item,
1968
+ update(patch) {
1969
+ current = { ...current, ...patch };
1970
+ apply(current);
1971
+ }
1972
+ };
1973
+ }
1974
+ function renderAiSubagent(el2, model) {
1975
+ if (typeof document === "undefined") {
1976
+ return { el: el2, update: () => void 0 };
1977
+ }
1978
+ const item = el2;
1979
+ let current = model;
1980
+ item.className = "ai-subagent";
1981
+ item.dataset.aiId = model.id;
1982
+ item.dataset.aiKind = model.kind;
1983
+ const parts = buildHead("ai-subagent-head");
1984
+ const body = h("div", "ai-subagent-body");
1985
+ body.hidden = true;
1986
+ const stream = h("div", "ai-subagent-stream");
1987
+ const result = h("div", "ai-subagent-result");
1988
+ result.hidden = true;
1989
+ body.append(stream, result);
1990
+ item.append(parts.head, body);
1991
+ const setOpen = (open, fire = true) => {
1992
+ parts.head.setAttribute("aria-expanded", String(open));
1993
+ body.hidden = !open;
1994
+ if (fire) {
1995
+ item.dispatchEvent(
1996
+ new CustomEvent("icen:ai-toggle", { detail: { el: item, open }, bubbles: true })
1997
+ );
1998
+ }
1999
+ };
2000
+ const activityHandles = /* @__PURE__ */ new Map();
2001
+ const renderActivities = (activities) => {
2002
+ const list = activities ?? [];
2003
+ const seen = /* @__PURE__ */ new Set();
2004
+ list.forEach((act, index) => {
2005
+ seen.add(act.id);
2006
+ const existing = activityHandles.get(act.id);
2007
+ if (existing) {
2008
+ existing.update(act);
2009
+ } else {
2010
+ const host = document.createElement("div");
2011
+ const handle = act.kind === "subagent" ? renderAiSubagent(host, act) : renderAiToolCall(host, act);
2012
+ handle.el.style.setProperty("--ai-activity-index", String(index));
2013
+ activityHandles.set(act.id, handle);
2014
+ stream.append(handle.el);
2015
+ }
2016
+ });
2017
+ for (const [id, handle] of activityHandles) {
2018
+ if (!seen.has(id)) {
2019
+ handle.el.remove();
2020
+ activityHandles.delete(id);
2021
+ }
2022
+ }
2023
+ };
2024
+ let prevStatus = null;
2025
+ const apply = (m) => {
2026
+ setStatusClass(item, m.status);
2027
+ applyTint(item, m);
2028
+ applyKindVisual(parts, m);
2029
+ const steps = m.activities?.length ?? 0;
2030
+ const meta = [m.durationMs != null ? formatDuration(m.durationMs) : "", steps > 0 ? `${steps} \u6B65` : ""].filter(Boolean).join(" \xB7 ");
2031
+ applyStatusMeta(parts, m.status, meta);
2032
+ renderActivities(m.activities);
2033
+ const receipt = compactValue(m.output);
2034
+ result.textContent = receipt;
2035
+ result.hidden = !receipt;
2036
+ if (!item.dataset.aiUserToggled && defaultExpanded(m)) setOpen(true);
2037
+ prevStatus = m.status;
2038
+ };
2039
+ apply(current);
2040
+ return {
2041
+ el: item,
2042
+ update(patch) {
2043
+ current = { ...current, ...patch };
2044
+ apply(current);
2045
+ }
2046
+ };
2047
+ }
2048
+ function setupItem(item, kind) {
2049
+ const marked = item;
2050
+ const flag = kind === "tool" ? "__icenAiToolInit" : "__icenAiSubagentInit";
2051
+ if (marked[flag]) return;
2052
+ marked[flag] = true;
2053
+ const headClass = kind === "tool" ? ".ai-tool-head" : ".ai-subagent-head";
2054
+ const bodyClass = kind === "tool" ? ".ai-tool-body" : ".ai-subagent-body";
2055
+ const head = item.querySelector(`:scope > ${headClass}`);
2056
+ const body = item.querySelector(`:scope > ${bodyClass}`);
2057
+ const setOpen = (open, fire = true) => {
2058
+ head?.setAttribute("aria-expanded", String(open));
2059
+ if (body) body.hidden = !open;
2060
+ if (fire) {
2061
+ item.dispatchEvent(
2062
+ new CustomEvent("icen:ai-toggle", { detail: { el: item, open }, bubbles: true })
2063
+ );
2064
+ }
2065
+ };
2066
+ item.addEventListener("click", (ev) => {
2067
+ const target = ev.target;
2068
+ if (!(target instanceof Element)) return;
2069
+ const ownerOf = (node) => node.closest(".ai-tool, .ai-subagent");
2070
+ const approveBtn = target.closest("[data-ai-approve]");
2071
+ if (approveBtn && ownerOf(approveBtn) === item) {
2072
+ item.dispatchEvent(
2073
+ new CustomEvent("icen:ai-approve", {
2074
+ detail: { id: item.dataset.aiId ?? "", kind: item.dataset.aiKind ?? "" },
2075
+ bubbles: true
2076
+ })
2077
+ );
2078
+ return;
2079
+ }
2080
+ const rejectBtn = target.closest("[data-ai-reject]");
2081
+ if (rejectBtn && ownerOf(rejectBtn) === item) {
2082
+ item.dispatchEvent(
2083
+ new CustomEvent("icen:ai-reject", {
2084
+ detail: { id: item.dataset.aiId ?? "", kind: item.dataset.aiKind ?? "" },
2085
+ bubbles: true
2086
+ })
2087
+ );
2088
+ return;
2089
+ }
2090
+ const headEl = target.closest(".ai-tool-head, .ai-subagent-head");
2091
+ if (!headEl || ownerOf(headEl) !== item || !head) return;
2092
+ item.dataset.aiUserToggled = "1";
2093
+ setOpen(head.getAttribute("aria-expanded") !== "true");
2094
+ });
2095
+ if (body?.hidden) {
2096
+ const kindName = item.dataset.aiKind ?? "";
2097
+ const isErr = item.classList.contains("is-error");
2098
+ const isApproval = item.classList.contains("is-approval");
2099
+ if (isErr || isApproval || kindName === "chart") {
2100
+ item.dataset.aiUserToggled = "";
2101
+ setOpen(true, false);
2102
+ delete item.dataset.aiUserToggled;
2103
+ }
2104
+ }
2105
+ }
2106
+ function initItems(root, selector, kind) {
2107
+ if (typeof document === "undefined") return;
2108
+ const scope = root ?? document;
2109
+ const items = [];
2110
+ if (scope instanceof Element && scope.matches(selector)) items.push(scope);
2111
+ items.push(...Array.from(scope.querySelectorAll(selector)));
2112
+ for (const item of items) setupItem(item, kind);
2113
+ }
2114
+ function initAiTool(root) {
2115
+ initItems(root, ".ai-tool", "tool");
2116
+ }
2117
+ function initAiSubagent(root) {
2118
+ initItems(root, ".ai-subagent", "subagent");
2119
+ }
2120
+ export {
2121
+ initAiSubagent,
2122
+ initAiTool,
2123
+ renderAiSubagent,
2124
+ renderAiToolCall
2125
+ };