@icen.ai/ui 0.5.0 → 0.8.1

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