@adia-ai/web-components 0.4.6 → 0.4.7

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 (284) hide show
  1. package/USAGE.md +29 -9
  2. package/components/accordion/accordion.d.ts +17 -0
  3. package/components/accordion/accordion.js +10 -117
  4. package/components/accordion/class.js +132 -0
  5. package/components/action-list/action-list.d.ts +15 -0
  6. package/components/action-list/action-list.js +9 -140
  7. package/components/action-list/class.js +156 -0
  8. package/components/agent-artifact/agent-artifact.d.ts +25 -0
  9. package/components/agent-artifact/agent-artifact.js +8 -181
  10. package/components/agent-artifact/class.js +200 -0
  11. package/components/agent-feedback-bar/agent-feedback-bar.d.ts +21 -0
  12. package/components/agent-feedback-bar/agent-feedback-bar.js +8 -143
  13. package/components/agent-feedback-bar/class.js +162 -0
  14. package/components/agent-questions/agent-questions.d.ts +23 -0
  15. package/components/agent-questions/agent-questions.js +8 -180
  16. package/components/agent-questions/class.js +199 -0
  17. package/components/agent-reasoning/agent-reasoning.d.ts +23 -0
  18. package/components/agent-reasoning/agent-reasoning.js +8 -494
  19. package/components/agent-reasoning/class.js +513 -0
  20. package/components/agent-suggestions/agent-suggestions.d.ts +21 -0
  21. package/components/agent-suggestions/agent-suggestions.js +8 -78
  22. package/components/agent-suggestions/class.js +97 -0
  23. package/components/agent-trace/agent-trace.d.ts +19 -0
  24. package/components/alert/alert.d.ts +29 -0
  25. package/components/alert/alert.js +8 -175
  26. package/components/alert/class.js +194 -0
  27. package/components/avatar/avatar.d.ts +27 -0
  28. package/components/avatar/avatar.js +9 -159
  29. package/components/avatar/class.js +173 -0
  30. package/components/badge/badge.d.ts +27 -0
  31. package/components/badge/badge.js +9 -75
  32. package/components/badge/class.js +93 -0
  33. package/components/block/block.d.ts +19 -0
  34. package/components/block/block.js +9 -15
  35. package/components/block/class.js +33 -0
  36. package/components/breadcrumb/breadcrumb.d.ts +23 -0
  37. package/components/breadcrumb/breadcrumb.js +8 -113
  38. package/components/breadcrumb/class.js +132 -0
  39. package/components/button/button.d.ts +34 -0
  40. package/components/button/button.js +15 -66
  41. package/components/button/class.js +80 -0
  42. package/components/calendar-picker/calendar-picker.a2ui.json +6 -1
  43. package/components/calendar-picker/calendar-picker.js +8 -332
  44. package/components/calendar-picker/calendar-picker.yaml +51 -177
  45. package/components/calendar-picker/class.js +351 -0
  46. package/components/canvas/canvas.a2ui.json +6 -1
  47. package/components/canvas/canvas.d.ts +17 -0
  48. package/components/canvas/canvas.yaml +19 -36
  49. package/components/card/card.a2ui.json +3 -0
  50. package/components/card/card.d.ts +27 -0
  51. package/components/card/card.js +9 -50
  52. package/components/card/card.yaml +171 -433
  53. package/components/card/class.js +68 -0
  54. package/components/chart/chart.d.ts +41 -0
  55. package/components/chart/chart.js +8 -2131
  56. package/components/chart/class.js +2150 -0
  57. package/components/chart-legend/chart-legend.d.ts +27 -0
  58. package/components/chart-legend/chart-legend.js +8 -197
  59. package/components/chart-legend/class.js +215 -0
  60. package/components/chat-thread/chat-thread.d.ts +17 -0
  61. package/components/chat-thread/chat-thread.js +8 -157
  62. package/components/chat-thread/class.js +176 -0
  63. package/components/check/check.js +11 -52
  64. package/components/check/class.js +68 -0
  65. package/components/code/class.js +501 -0
  66. package/components/code/code.js +8 -482
  67. package/components/col/class.js +30 -0
  68. package/components/col/col.d.ts +23 -0
  69. package/components/col/col.js +10 -13
  70. package/components/color-picker/class.js +550 -0
  71. package/components/color-picker/color-picker.js +8 -531
  72. package/components/command/class.js +364 -0
  73. package/components/command/command.a2ui.json +3 -0
  74. package/components/command/command.d.ts +19 -0
  75. package/components/command/command.js +8 -345
  76. package/components/command/command.yaml +105 -124
  77. package/components/demo-toggle/class.js +153 -0
  78. package/components/demo-toggle/demo-toggle.d.ts +23 -0
  79. package/components/demo-toggle/demo-toggle.js +8 -135
  80. package/components/description-list/class.js +86 -0
  81. package/components/description-list/description-list.d.ts +21 -0
  82. package/components/description-list/description-list.js +8 -67
  83. package/components/divider/class.js +57 -0
  84. package/components/divider/divider.d.ts +19 -0
  85. package/components/divider/divider.js +10 -40
  86. package/components/drawer/class.js +306 -0
  87. package/components/drawer/drawer.d.ts +25 -0
  88. package/components/drawer/drawer.js +8 -287
  89. package/components/embed/class.js +73 -0
  90. package/components/embed/embed.d.ts +23 -0
  91. package/components/embed/embed.js +9 -55
  92. package/components/empty-state/class.js +108 -0
  93. package/components/empty-state/empty-state.d.ts +21 -0
  94. package/components/empty-state/empty-state.js +9 -90
  95. package/components/feed/class.js +381 -0
  96. package/components/feed/feed.d.ts +19 -0
  97. package/components/feed/feed.js +9 -367
  98. package/components/field/class.js +266 -0
  99. package/components/field/field.d.ts +23 -0
  100. package/components/field/field.js +8 -247
  101. package/components/fields/class.js +106 -0
  102. package/components/fields/fields.d.ts +19 -0
  103. package/components/fields/fields.js +8 -87
  104. package/components/grid/class.js +31 -0
  105. package/components/grid/grid.d.ts +23 -0
  106. package/components/grid/grid.js +10 -14
  107. package/components/heatmap/class.js +305 -0
  108. package/components/heatmap/heatmap.d.ts +31 -0
  109. package/components/heatmap/heatmap.js +8 -286
  110. package/components/icon/class.js +54 -0
  111. package/components/icon/icon.d.ts +23 -0
  112. package/components/icon/icon.js +13 -40
  113. package/components/image/class.js +112 -0
  114. package/components/image/image.d.ts +33 -0
  115. package/components/image/image.js +9 -94
  116. package/components/input/class.js +773 -0
  117. package/components/input/input.a2ui.json +3 -0
  118. package/components/input/input.js +8 -755
  119. package/components/input/input.yaml +171 -442
  120. package/components/inspector/class.js +142 -0
  121. package/components/inspector/inspector.a2ui.json +8 -1
  122. package/components/inspector/inspector.d.ts +17 -0
  123. package/components/inspector/inspector.js +8 -124
  124. package/components/inspector/inspector.yaml +15 -30
  125. package/components/kbd/class.js +34 -0
  126. package/components/kbd/kbd.a2ui.json +3 -0
  127. package/components/kbd/kbd.d.ts +17 -0
  128. package/components/kbd/kbd.js +10 -17
  129. package/components/kbd/kbd.yaml +54 -185
  130. package/components/link/class.js +187 -0
  131. package/components/link/link.d.ts +55 -0
  132. package/components/link/link.js +8 -168
  133. package/components/list/class.js +249 -0
  134. package/components/list/list.d.ts +23 -0
  135. package/components/list/list.js +9 -231
  136. package/components/menu/class.js +332 -0
  137. package/components/menu/menu.d.ts +21 -0
  138. package/components/menu/menu.js +11 -316
  139. package/components/modal/class.js +231 -0
  140. package/components/modal/modal.a2ui.json +5 -1
  141. package/components/modal/modal.d.ts +23 -0
  142. package/components/modal/modal.js +8 -212
  143. package/components/modal/modal.yaml +19 -39
  144. package/components/nav/class.js +150 -0
  145. package/components/nav/nav.d.ts +31 -0
  146. package/components/nav/nav.js +8 -131
  147. package/components/nav-group/class.js +152 -0
  148. package/components/nav-group/nav-group.d.ts +35 -0
  149. package/components/nav-group/nav-group.js +9 -134
  150. package/components/nav-item/class.js +86 -0
  151. package/components/nav-item/nav-item.d.ts +37 -0
  152. package/components/nav-item/nav-item.js +10 -69
  153. package/components/noodles/class.js +510 -0
  154. package/components/noodles/noodles.d.ts +33 -0
  155. package/components/noodles/noodles.js +9 -493
  156. package/components/option-card/class.js +167 -0
  157. package/components/option-card/option-card.js +8 -149
  158. package/components/otp-input/class.js +180 -0
  159. package/components/otp-input/otp-input.a2ui.json +5 -1
  160. package/components/otp-input/otp-input.js +9 -162
  161. package/components/otp-input/otp-input.yaml +45 -174
  162. package/components/page/class.js +97 -0
  163. package/components/page/page.d.ts +46 -0
  164. package/components/page/page.js +8 -79
  165. package/components/pagination/class.js +195 -0
  166. package/components/pagination/pagination.d.ts +23 -0
  167. package/components/pagination/pagination.js +9 -177
  168. package/components/pane/class.js +186 -0
  169. package/components/pane/pane.a2ui.json +12 -1
  170. package/components/pane/pane.d.ts +31 -0
  171. package/components/pane/pane.js +8 -167
  172. package/components/pane/pane.yaml +57 -157
  173. package/components/pipeline-status/class.js +189 -0
  174. package/components/pipeline-status/pipeline-status.a2ui.json +7 -1
  175. package/components/pipeline-status/pipeline-status.d.ts +21 -0
  176. package/components/pipeline-status/pipeline-status.js +9 -172
  177. package/components/pipeline-status/pipeline-status.yaml +34 -72
  178. package/components/popover/class.js +194 -0
  179. package/components/popover/popover.d.ts +23 -0
  180. package/components/popover/popover.js +9 -176
  181. package/components/progress/class.js +74 -0
  182. package/components/progress/progress.a2ui.json +3 -0
  183. package/components/progress/progress.d.ts +19 -0
  184. package/components/progress/progress.js +10 -57
  185. package/components/progress/progress.yaml +124 -287
  186. package/components/progress-row/class.js +110 -0
  187. package/components/progress-row/progress-row.d.ts +23 -0
  188. package/components/progress-row/progress-row.js +8 -92
  189. package/components/radio/class.js +83 -0
  190. package/components/radio/radio.js +11 -67
  191. package/components/range/class.js +194 -0
  192. package/components/range/range.js +9 -176
  193. package/components/rating/class.js +148 -0
  194. package/components/rating/rating.js +9 -130
  195. package/components/richtext/class.js +87 -0
  196. package/components/richtext/richtext.a2ui.json +7 -1
  197. package/components/richtext/richtext.d.ts +19 -0
  198. package/components/richtext/richtext.js +8 -68
  199. package/components/richtext/richtext.yaml +30 -65
  200. package/components/row/class.js +50 -0
  201. package/components/row/row.d.ts +27 -0
  202. package/components/row/row.js +10 -33
  203. package/components/search/class.js +134 -0
  204. package/components/search/search.js +10 -117
  205. package/components/segment/class.js +62 -0
  206. package/components/segment/segment.d.ts +25 -0
  207. package/components/segment/segment.js +10 -45
  208. package/components/segmented/class.js +165 -0
  209. package/components/segmented/segmented.a2ui.json +4 -0
  210. package/components/segmented/segmented.js +10 -148
  211. package/components/segmented/segmented.yaml +41 -59
  212. package/components/select/class.js +408 -0
  213. package/components/select/select.js +15 -396
  214. package/components/skeleton/class.js +52 -0
  215. package/components/skeleton/skeleton.d.ts +23 -0
  216. package/components/skeleton/skeleton.js +8 -34
  217. package/components/slider/class.js +184 -0
  218. package/components/slider/slider.js +9 -166
  219. package/components/stack/class.js +28 -0
  220. package/components/stack/stack.d.ts +17 -0
  221. package/components/stack/stack.js +10 -11
  222. package/components/step-progress/class.js +98 -0
  223. package/components/step-progress/step-progress.d.ts +27 -0
  224. package/components/step-progress/step-progress.js +8 -79
  225. package/components/stepper/class.js +126 -0
  226. package/components/stepper/stepper.d.ts +19 -0
  227. package/components/stepper/stepper.js +9 -112
  228. package/components/stream/class.js +109 -0
  229. package/components/stream/stream.d.ts +19 -0
  230. package/components/stream/stream.js +8 -90
  231. package/components/swatch/class.js +131 -0
  232. package/components/swatch/swatch.d.ts +28 -0
  233. package/components/swatch/swatch.js +8 -112
  234. package/components/swiper/class.js +373 -0
  235. package/components/swiper/swiper.a2ui.json +4 -0
  236. package/components/swiper/swiper.d.ts +31 -0
  237. package/components/swiper/swiper.js +8 -354
  238. package/components/swiper/swiper.yaml +68 -212
  239. package/components/switch/class.js +63 -0
  240. package/components/switch/switch.a2ui.json +6 -1
  241. package/components/switch/switch.js +11 -47
  242. package/components/switch/switch.yaml +70 -265
  243. package/components/table/class.js +1453 -0
  244. package/components/table/table.d.ts +37 -0
  245. package/components/table/table.js +8 -1435
  246. package/components/table-toolbar/class.js +680 -0
  247. package/components/table-toolbar/table-toolbar.d.ts +33 -0
  248. package/components/table-toolbar/table-toolbar.js +8 -689
  249. package/components/tabs/class.js +242 -0
  250. package/components/tabs/tabs.d.ts +21 -0
  251. package/components/tabs/tabs.js +8 -223
  252. package/components/tag/class.js +99 -0
  253. package/components/tag/tag.d.ts +27 -0
  254. package/components/tag/tag.js +8 -80
  255. package/components/text/class.js +46 -0
  256. package/components/text/text.d.ts +25 -0
  257. package/components/text/text.js +9 -28
  258. package/components/textarea/class.js +134 -0
  259. package/components/textarea/textarea.js +11 -118
  260. package/components/timeline/class.js +176 -0
  261. package/components/timeline/timeline.d.ts +19 -0
  262. package/components/timeline/timeline.js +9 -162
  263. package/components/toast/class.js +92 -0
  264. package/components/toast/toast.d.ts +23 -0
  265. package/components/toast/toast.js +9 -76
  266. package/components/toggle-group/class.js +154 -0
  267. package/components/toggle-group/toggle-group.d.ts +19 -0
  268. package/components/toggle-group/toggle-group.js +11 -140
  269. package/components/toggle-scheme/class.js +286 -0
  270. package/components/toggle-scheme/toggle-scheme.d.ts +41 -0
  271. package/components/toggle-scheme/toggle-scheme.js +8 -268
  272. package/components/toolbar/class.js +388 -0
  273. package/components/toolbar/toolbar.d.ts +23 -0
  274. package/components/toolbar/toolbar.js +10 -376
  275. package/components/tooltip/class.js +299 -0
  276. package/components/tooltip/tooltip.d.ts +27 -0
  277. package/components/tooltip/tooltip.js +8 -280
  278. package/components/tree/class.js +245 -0
  279. package/components/tree/tree.d.ts +15 -0
  280. package/components/tree/tree.js +9 -244
  281. package/components/upload/class.js +199 -0
  282. package/components/upload/upload.js +11 -183
  283. package/index.d.ts +159 -5
  284. package/package.json +5 -1
@@ -0,0 +1,501 @@
1
+ /**
2
+ * Non-side-effect class export for `<code-ui>`.
3
+ *
4
+ * Importing this file gives you the class(es) without auto-registering the tag.
5
+ * Useful for test isolation, subclassing with tag-name override, or selective
6
+ * composition.
7
+ *
8
+ * The auto-register path stays at `@adia-ai/web-components/components/code`
9
+ * (which imports this file + calls `defineIfFree()`).
10
+ *
11
+ * @see ../../USAGE.md#registration--auto-vs-explicit
12
+ */
13
+
14
+ /**
15
+ * <code-ui language="js">const x = 42;</code-ui>
16
+ * <code-ui language="css" inline>color: red</code-ui>
17
+ * <code-ui language="json" text='{ "hello": "world" }'></code-ui>
18
+ * <code-ui editable language="json" name="schema" required></code-ui>
19
+ *
20
+ * Inline or block code display with optional language label and copy
21
+ * button. The body comes from (a) declarative children, or (b) the
22
+ * `text` attribute — the `text` path is reactive, so setting
23
+ * `code.setAttribute('text', newText)` updates the rendered code in place.
24
+ *
25
+ * When `[language]` names a supported language (see SUPPORTED_LANGUAGES),
26
+ * CodeMirror 6 is lazy-loaded and mounted in place of `<pre><code>` for
27
+ * syntax-highlighted rendering. Phase 1 shipped read-only; Phase 2 added
28
+ * `[editable]`; Phase 3 added lint + form-association (see
29
+ * `docs/specs/code-editor.md §12`).
30
+ *
31
+ * Form participation — editable instances are Form-Associated Custom
32
+ * Elements (FACE). Set `name`, `required`, `disabled`, `readonly` to
33
+ * opt into standard form behavior; the editor's live document
34
+ * becomes the form value. Non-editable instances declare
35
+ * `formAssociated = true` at the class level (required for FACE) but
36
+ * contribute nothing to form submission when `[editable]` is absent.
37
+ */
38
+
39
+ import { UIElement } from '../../core/element.js';
40
+
41
+ const SUPPORTED_LANGUAGES = new Set([
42
+ 'json', 'html', 'javascript', 'js', 'css', 'markdown', 'md', 'yaml', 'yml',
43
+ ]);
44
+
45
+ // Normalize common language aliases to their canonical pack name.
46
+ const LANGUAGE_ALIAS = {
47
+ js: 'javascript',
48
+ md: 'markdown',
49
+ yml: 'yaml',
50
+ };
51
+
52
+ function canonicalLanguage(name) {
53
+ if (!name) return '';
54
+ const lower = String(name).toLowerCase();
55
+ return LANGUAGE_ALIAS[lower] ?? lower;
56
+ }
57
+
58
+ export class UICode extends UIElement {
59
+ static formAssociated = true;
60
+
61
+ static properties = {
62
+ language: { type: String, default: '', reflect: true },
63
+ inline: { type: Boolean, default: false, reflect: true },
64
+ text: { type: String, default: '', reflect: true },
65
+ textContent: { type: String, default: '' },
66
+ lineNumbers: { type: Boolean, default: false, reflect: true, attribute: 'line-numbers' },
67
+ editable: { type: Boolean, default: false, reflect: true },
68
+ bare: { type: Boolean, default: false, reflect: true },
69
+ placeholder: { type: String, default: '', reflect: true },
70
+
71
+ // Form-association (active only when `editable` is set; non-editable
72
+ // instances are FACE-declared for class consistency but contribute
73
+ // nothing to form submission).
74
+ name: { type: String, default: '', reflect: true },
75
+ required: { type: Boolean, default: false, reflect: true },
76
+ disabled: { type: Boolean, default: false, reflect: true },
77
+ readonly: { type: Boolean, default: false, reflect: true },
78
+ };
79
+
80
+ static template = () => null;
81
+
82
+ #copyBtn = null;
83
+ #copyTimer = null;
84
+ #cmView = null; // EditorView instance when mounted
85
+ #mountGen = 0; // bumps on every connect/disconnect — guards against stale mounts
86
+ #pendingMount = false; // true while bundle/lang pack is loading
87
+ #focusSnapshot = null; // doc text captured on focus; used to diff for `change` event
88
+ #initialDoc = ''; // captured at mount; used by formResetCallback
89
+ #editableCompartment = null; // CM Compartment — reconfigures readonly on disabled/readonly change
90
+
91
+ #onCopyClick = () => this.#copy();
92
+
93
+ connected() {
94
+ this.#mountGen += 1;
95
+
96
+ if (!this.inline && !this.querySelector(':scope > pre')) {
97
+ this.#stampBlock();
98
+ }
99
+ this.#copyBtn = this.querySelector(':scope > header [slot="copy"]');
100
+ if (this.#copyBtn) {
101
+ this.#copyBtn.addEventListener('click', this.#onCopyClick);
102
+ }
103
+
104
+ // Mount CodeMirror when the language is supported OR the element is
105
+ // editable (editable plain-text is still useful). Inline instances
106
+ // stay on the static <code> path. Mount failures leave the static
107
+ // fallback in place — it's already visible. Diff line-state mode
108
+ // (auto via `language="diff"` or explicit `data-line-states`) also
109
+ // stays on the static path — bg tinting lives on the wrapper spans.
110
+ const lang = canonicalLanguage(this.language);
111
+ const useLineState = this.hasAttribute('data-line-states') || lang === 'diff';
112
+ const shouldMount = !this.inline && !useLineState && (SUPPORTED_LANGUAGES.has(lang) || this.editable);
113
+ if (shouldMount) {
114
+ this.#mountEditor();
115
+ }
116
+ }
117
+
118
+ disconnected() {
119
+ this.#mountGen += 1; // invalidate any in-flight mounts
120
+ if (this.#copyTimer != null) {
121
+ clearTimeout(this.#copyTimer);
122
+ this.#copyTimer = null;
123
+ }
124
+ if (this.#copyBtn) {
125
+ this.#copyBtn.removeEventListener('click', this.#onCopyClick);
126
+ this.#copyBtn = null;
127
+ }
128
+ if (this.#cmView) {
129
+ this.#cmView.destroy();
130
+ this.#cmView = null;
131
+ }
132
+ }
133
+
134
+ #stampBlock() {
135
+ // Prefer the `text` attribute when present; otherwise read the authored
136
+ // textContent. Either way, the block is rebuilt from semantic elements
137
+ // so whitespace in source HTML doesn't leak into the rendered <code>.
138
+ const raw = (this.text || this.textContent || '').trim();
139
+ this.textContent = '';
140
+
141
+ // Header — omitted in [bare] mode. Consumers that need zero chrome
142
+ // (the A2UI Editor's Schema + DOM views, an embedded editable surface
143
+ // in a pane, etc.) set [bare] to opt out.
144
+ if (!this.bare) {
145
+ const header = document.createElement('header');
146
+
147
+ const label = document.createElement('span');
148
+ label.setAttribute('slot', 'label');
149
+ label.textContent = this.language || 'code';
150
+ header.appendChild(label);
151
+
152
+ const copyBtn = document.createElement('div');
153
+ copyBtn.setAttribute('role', 'button');
154
+ copyBtn.setAttribute('tabindex', '0');
155
+ copyBtn.setAttribute('slot', 'copy');
156
+ copyBtn.textContent = 'Copy';
157
+ header.appendChild(copyBtn);
158
+
159
+ this.appendChild(header);
160
+ }
161
+
162
+ // Pre > Code — direct semantic elements, no slot attr
163
+ const pre = document.createElement('pre');
164
+ const code = document.createElement('code');
165
+
166
+ // Diff line-state mode — wrap each line so it can carry a state-driven
167
+ // bg tint and (when [line-numbers]) a leading line-number gutter.
168
+ // Triggered by `language="diff"` (auto-parses +/- prefix) or by an
169
+ // explicit `data-line-states` CSV that maps positionally onto lines.
170
+ const lang = canonicalLanguage(this.language);
171
+ const explicit = this.getAttribute('data-line-states');
172
+ const useLineState = explicit != null || lang === 'diff';
173
+ if (useLineState) {
174
+ code.setAttribute('data-line-state-mode', '');
175
+ if (this.lineNumbers) code.setAttribute('data-line-numbers', '');
176
+ const states = explicit?.split(',').map((s) => s.trim()) ?? null;
177
+ const lines = raw.split('\n');
178
+ lines.forEach((line, i) => {
179
+ let state = 'unchanged';
180
+ if (states && states[i]) {
181
+ state = states[i];
182
+ } else if (lang === 'diff') {
183
+ const head = line.charAt(0);
184
+ if (head === '+') state = 'added';
185
+ else if (head === '-') state = 'removed';
186
+ }
187
+ const row = document.createElement('span');
188
+ row.setAttribute('data-line-state', state);
189
+ if (this.lineNumbers) {
190
+ const num = document.createElement('span');
191
+ num.setAttribute('data-line-num', '');
192
+ num.textContent = String(i + 1);
193
+ row.appendChild(num);
194
+ }
195
+ const body = document.createElement('span');
196
+ body.setAttribute('data-line-body', '');
197
+ body.textContent = line;
198
+ row.appendChild(body);
199
+ code.appendChild(row);
200
+ });
201
+ } else {
202
+ code.textContent = raw;
203
+ }
204
+ pre.appendChild(code);
205
+
206
+ this.appendChild(pre);
207
+ }
208
+
209
+ async #mountEditor() {
210
+ if (this.#pendingMount || this.#cmView) return;
211
+ const gen = this.#mountGen;
212
+ const lang = canonicalLanguage(this.language);
213
+ this.#pendingMount = true;
214
+
215
+ try {
216
+ const bundle = await import('./code-editor.js');
217
+
218
+ // Load the language pack with a timeout. If it fails, continue with
219
+ // core-only (editor still renders; no syntax highlight). Emit an
220
+ // event so consumers can observe.
221
+ let extension = null;
222
+ try {
223
+ const mod = await bundle.importWithTimeout(bundle.languages[lang], `lang-${lang}`);
224
+ extension = mod?.extension ?? null;
225
+ } catch (err) {
226
+ this.dispatchEvent(new CustomEvent('language-load-error', {
227
+ bubbles: true, detail: { phase: 'language', language: lang, error: err },
228
+ }));
229
+ }
230
+
231
+ // Stale — component was disconnected (or reconnected elsewhere) while
232
+ // we were loading. Discard.
233
+ if (gen !== this.#mountGen || !this.isConnected) return;
234
+
235
+ this.#attachEditor(bundle, extension, lang);
236
+ } catch (err) {
237
+ this.dispatchEvent(new CustomEvent('language-load-error', {
238
+ bubbles: true, detail: { phase: 'core', error: err },
239
+ }));
240
+ // Fallback <pre><code> stays visible — nothing to revert.
241
+ console.warn('[code-ui] CodeMirror failed to load; staying on static fallback.', err);
242
+ } finally {
243
+ this.#pendingMount = false;
244
+ }
245
+ }
246
+
247
+ #attachEditor(bundle, languageExtension, lang) {
248
+ const {
249
+ EditorState, EditorView,
250
+ Compartment,
251
+ lineNumbers,
252
+ placeholder,
253
+ syntaxHighlighting,
254
+ history, historyKeymap, defaultKeymap, indentWithTab,
255
+ keymap,
256
+ adiaBaseTheme, adiaHighlightStyle,
257
+ lintGutter, jsonLinter,
258
+ } = bundle;
259
+
260
+ // Replace <pre><code> with a mount target. Keep <header> where it is.
261
+ const pre = this.querySelector(':scope > pre');
262
+ const prior = pre ? pre.querySelector('code')?.textContent ?? '' : '';
263
+ const initial = this.text || prior || '';
264
+ this.#initialDoc = initial;
265
+
266
+ const mount = document.createElement('div');
267
+ mount.setAttribute('data-cm-mount', '');
268
+ if (pre) pre.replaceWith(mount);
269
+ else this.appendChild(mount);
270
+
271
+ const extensions = [
272
+ adiaBaseTheme,
273
+ syntaxHighlighting(adiaHighlightStyle),
274
+ ];
275
+
276
+ if (this.editable) {
277
+ extensions.push(
278
+ history(),
279
+ keymap.of([
280
+ { key: 'Mod-s', run: (v) => { this.#emitSave(v); return true; } },
281
+ ...defaultKeymap,
282
+ ...historyKeymap,
283
+ indentWithTab,
284
+ ]),
285
+ EditorView.updateListener.of((update) => {
286
+ if (!update.docChanged) return;
287
+ const value = update.state.doc.toString();
288
+ this.#syncFormValue(value);
289
+ this.dispatchEvent(new CustomEvent('input', {
290
+ bubbles: true,
291
+ detail: { value },
292
+ }));
293
+ }),
294
+ EditorView.domEventHandlers({
295
+ focus: (_, view) => {
296
+ this.#focusSnapshot = view.state.doc.toString();
297
+ return false;
298
+ },
299
+ blur: (_, view) => {
300
+ const current = view.state.doc.toString();
301
+ if (this.#focusSnapshot !== null && current !== this.#focusSnapshot) {
302
+ this.dispatchEvent(new CustomEvent('change', {
303
+ bubbles: true,
304
+ detail: { value: current },
305
+ }));
306
+ }
307
+ this.#focusSnapshot = null;
308
+ return false;
309
+ },
310
+ }),
311
+ );
312
+ }
313
+
314
+ // Editable/readonly compartment — respects editable + disabled + readonly.
315
+ // Dynamic because `disabled` / `readonly` can change at runtime (e.g.
316
+ // `formDisabledCallback` from the owning form). Starts with the
317
+ // correct initial config; `#updateEditableState()` reconfigures on
318
+ // attribute change.
319
+ this.#editableCompartment = new Compartment();
320
+ extensions.push(
321
+ this.#editableCompartment.of(this.#editableExtensions(EditorView, EditorState)),
322
+ );
323
+
324
+ if (languageExtension) extensions.push(languageExtension);
325
+ if (this.lineNumbers) extensions.push(lineNumbers());
326
+ if (this.placeholder) extensions.push(placeholder(this.placeholder));
327
+
328
+ // Lint: editable-only, language-specific. JSON for now; extend per
329
+ // language as need arises. The gutter shows the aggregate marker
330
+ // per line; the diagnostics themselves produce the tooltip + error
331
+ // underline on the offending range.
332
+ if (this.editable && lang === 'json') {
333
+ extensions.push(jsonLinter, lintGutter());
334
+ }
335
+
336
+ this.#cmView = new EditorView({
337
+ parent: mount,
338
+ state: EditorState.create({ doc: initial, extensions }),
339
+ });
340
+
341
+ // Seed form value + constraints now that the editor is live.
342
+ if (this.editable) this.#syncFormValue(initial);
343
+ }
344
+
345
+ /** Returns the CM extensions that enforce editable vs readonly state
346
+ * as a function of (editable && !disabled && !readonly). Called at
347
+ * mount time and on any runtime change via the compartment. */
348
+ #editableExtensions(EditorView, EditorState) {
349
+ const canEdit = this.editable && !this.disabled && !this.readonly;
350
+ if (canEdit) return [];
351
+ return [
352
+ EditorView.editable.of(false),
353
+ EditorState.readOnly.of(true),
354
+ ];
355
+ }
356
+
357
+ /** Re-evaluate the editable/readonly state against current attributes.
358
+ * Called from `render()` on property change. No-op if the editor
359
+ * hasn't mounted yet. */
360
+ async #updateEditableState() {
361
+ if (!this.#cmView || !this.#editableCompartment) return;
362
+ const bundle = await import('./code-editor.js');
363
+ this.#cmView.dispatch({
364
+ effects: this.#editableCompartment.reconfigure(
365
+ this.#editableExtensions(bundle.EditorView, bundle.EditorState),
366
+ ),
367
+ });
368
+ }
369
+
370
+ // ── Form-association (FACE) ───────────────────────────────────────
371
+
372
+ get form() { return this.internals.form; }
373
+ get labels() { return this.internals.labels; }
374
+ get validity() { return this.internals.validity; }
375
+ get validationMessage() { return this.internals.validationMessage; }
376
+ get willValidate() { return this.internals.willValidate; }
377
+
378
+ checkValidity() { return this.internals.checkValidity(); }
379
+ reportValidity() { return this.internals.reportValidity(); }
380
+
381
+ /** Push the current editor value to the form + re-run constraints.
382
+ * No-op when `editable` is false. Called on every CM doc change and
383
+ * from the initial mount + `render()` when `text` is driven externally. */
384
+ #syncFormValue(val) {
385
+ if (!this.editable) return;
386
+ val = val ?? this.value ?? '';
387
+ this.internals.setFormValue(val);
388
+ this.#runConstraints(val);
389
+ }
390
+
391
+ #runConstraints(val) {
392
+ val = val ?? '';
393
+ if (this.required && !val.trim()) {
394
+ this.internals.setValidity(
395
+ { valueMissing: true },
396
+ this.getAttribute('data-msg-required') || 'This field is required.',
397
+ this,
398
+ );
399
+ this.setAttribute('aria-invalid', 'true');
400
+ return false;
401
+ }
402
+ this.internals.setValidity({});
403
+ this.removeAttribute('aria-invalid');
404
+ return true;
405
+ }
406
+
407
+ formResetCallback() {
408
+ if (this.#cmView) {
409
+ this.#cmView.dispatch({
410
+ changes: { from: 0, to: this.#cmView.state.doc.length, insert: this.#initialDoc },
411
+ });
412
+ } else {
413
+ this.text = this.#initialDoc;
414
+ }
415
+ }
416
+
417
+ formDisabledCallback(disabled) {
418
+ this.disabled = disabled;
419
+ // `disabled` is reflected; the render() hook picks up the change
420
+ // and calls #updateEditableState().
421
+ }
422
+
423
+ formStateRestoreCallback(state, _reason) {
424
+ if (typeof state !== 'string') return;
425
+ if (this.#cmView) {
426
+ this.#cmView.dispatch({
427
+ changes: { from: 0, to: this.#cmView.state.doc.length, insert: state },
428
+ });
429
+ } else {
430
+ this.text = state;
431
+ }
432
+ }
433
+
434
+ #emitSave(view) {
435
+ this.dispatchEvent(new CustomEvent('save', {
436
+ bubbles: true, cancelable: true,
437
+ detail: { value: view.state.doc.toString() },
438
+ }));
439
+ }
440
+
441
+ /** Live buffer. Reads from CodeMirror when mounted, else the static <code>. */
442
+ get value() {
443
+ if (this.#cmView) return this.#cmView.state.doc.toString();
444
+ const code = this.querySelector(':scope > pre > code');
445
+ return code?.textContent ?? this.text ?? '';
446
+ }
447
+
448
+ /** Convenience setter — identical to `text` but matches the form-control idiom. */
449
+ set value(v) {
450
+ this.text = String(v ?? '');
451
+ }
452
+
453
+ #copy() {
454
+ const text = this.#cmView
455
+ ? this.#cmView.state.doc.toString()
456
+ : (this.querySelector(':scope > pre > code')?.textContent ?? '');
457
+ if (!text) return;
458
+ navigator.clipboard.writeText(text).then(() => {
459
+ const btn = this.querySelector(':scope > header [slot="copy"]');
460
+ if (!btn) return;
461
+ const prev = btn.textContent;
462
+ btn.textContent = 'Copied!';
463
+ if (this.#copyTimer != null) clearTimeout(this.#copyTimer);
464
+ this.#copyTimer = setTimeout(() => {
465
+ this.#copyTimer = null;
466
+ btn.textContent = prev;
467
+ }, 1500);
468
+ });
469
+ }
470
+
471
+ render() {
472
+ const label = this.querySelector(':scope > header [slot="label"]');
473
+ if (label && this.language) label.textContent = this.language;
474
+
475
+ // React to disabled/readonly toggles on a live editor.
476
+ this.#updateEditableState();
477
+
478
+ // Keep the rendered code in sync with the reactive `text` property so
479
+ // callers can drive updates via setAttribute('text', ...).
480
+ if (!this.inline && this.text !== '') {
481
+ if (this.#cmView) {
482
+ // Don't clobber in-flight edits while the editor has keyboard focus.
483
+ // Callers that want to force-replace can blur the editor first.
484
+ if (this.editable && this.#cmView.hasFocus) return;
485
+ const current = this.#cmView.state.doc.toString();
486
+ if (current !== this.text) {
487
+ this.#cmView.dispatch({
488
+ changes: { from: 0, to: current.length, insert: this.text },
489
+ });
490
+ // CM's updateListener catches the dispatch and re-syncs the
491
+ // form value; nothing extra to do here.
492
+ }
493
+ } else {
494
+ const code = this.querySelector(':scope > pre > code');
495
+ if (code && code.textContent !== this.text) {
496
+ code.textContent = this.text;
497
+ }
498
+ }
499
+ }
500
+ }
501
+ }