@innovatorved/code-lab 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/ARCHITECTURE.md +8 -4
  2. package/CHANGELOG.md +45 -0
  3. package/README.md +70 -158
  4. package/dist/apps/web/src/index.d.ts +34 -0
  5. package/dist/code-lab-sql.css +482 -0
  6. package/dist/code-lab-sql.d.ts +179 -0
  7. package/dist/code-lab-sql.esm.js +542 -0
  8. package/dist/code-lab-sql.umd.js +531 -0
  9. package/dist/code-lab.css +298 -2
  10. package/dist/code-lab.d.ts +110 -15
  11. package/dist/code-lab.esm.js +35284 -18253
  12. package/dist/code-lab.js +40434 -23431
  13. package/dist/code-lab.umd.js +65502 -0
  14. package/dist/diagnostics.d.ts +5 -0
  15. package/dist/extensions/cpp.esm.js +19532 -3772
  16. package/dist/extensions/cpp.js +19529 -3769
  17. package/dist/extensions/guided-lab.esm.js +19401 -3725
  18. package/dist/extensions/guided-lab.js +19400 -3724
  19. package/dist/extensions/python.d.ts +1 -0
  20. package/dist/extensions/python.esm.js +19666 -3843
  21. package/dist/extensions/python.js +19668 -3845
  22. package/dist/extensions/umbrella.d.ts +5 -0
  23. package/dist/index.d.ts +1 -1
  24. package/dist/modular-kernel.d.ts +11 -0
  25. package/dist/packages/commands/src/index.d.ts +96 -0
  26. package/dist/packages/core/src/di.d.ts +36 -0
  27. package/dist/packages/core/src/disposable.d.ts +27 -0
  28. package/dist/packages/core/src/errors.d.ts +69 -0
  29. package/dist/packages/core/src/events.d.ts +38 -0
  30. package/dist/packages/core/src/index.d.ts +6 -0
  31. package/dist/packages/core/src/path.d.ts +14 -0
  32. package/dist/packages/core/src/registry.d.ts +23 -0
  33. package/dist/packages/editor/src/index.d.ts +118 -0
  34. package/dist/packages/fs/src/backends.d.ts +37 -0
  35. package/dist/packages/fs/src/index.d.ts +3 -0
  36. package/dist/packages/fs/src/types.d.ts +40 -0
  37. package/dist/packages/fs/src/vfs-service.d.ts +33 -0
  38. package/dist/packages/preview/src/index.d.ts +34 -0
  39. package/dist/packages/runtime/src/index.d.ts +47 -0
  40. package/dist/packages/settings/src/builtin-schemas.d.ts +15 -0
  41. package/dist/packages/settings/src/configuration-service.d.ts +100 -0
  42. package/dist/packages/settings/src/index.d.ts +4 -0
  43. package/dist/packages/settings/src/jsonc.d.ts +20 -0
  44. package/dist/packages/settings/src/schema.d.ts +28 -0
  45. package/dist/packages/sql/src/completions.d.ts +8 -0
  46. package/dist/packages/sql/src/diagnostics.d.ts +2 -0
  47. package/dist/packages/sql/src/formatter.d.ts +2 -0
  48. package/dist/packages/sql/src/index.d.ts +7 -0
  49. package/dist/packages/sql/src/sql-editor.d.ts +2 -0
  50. package/dist/packages/sql/src/styles.d.ts +2 -0
  51. package/dist/packages/sql/src/tokenizer.d.ts +13 -0
  52. package/dist/packages/sql/src/types.d.ts +130 -0
  53. package/dist/packages/terminal/src/index.d.ts +54 -0
  54. package/dist/packages/ui/src/index.d.ts +4 -0
  55. package/dist/packages/ui/src/observability.d.ts +22 -0
  56. package/dist/packages/ui/src/plugin-registry.d.ts +89 -0
  57. package/dist/packages/ui/src/settings-dialog.d.ts +25 -0
  58. package/dist/packages/ui/src/themes.d.ts +35 -0
  59. package/dist/preview-sw.js +82 -24
  60. package/dist/runtime.d.ts +3 -3
  61. package/dist/runtime.esm.js +503 -73
  62. package/dist/runtime.js +501 -73
  63. package/dist/schemas.d.ts +234 -814
  64. package/dist/schemas.esm.js +19401 -3725
  65. package/dist/schemas.js +19404 -3728
  66. package/dist/scm.d.ts +13 -2
  67. package/dist/search.d.ts +5 -1
  68. package/dist/shell.d.ts +1 -1
  69. package/dist/shell.esm.js +435 -54
  70. package/dist/shell.js +435 -54
  71. package/dist/terminal.esm.js +242 -54
  72. package/dist/terminal.js +242 -54
  73. package/dist/workbench/diff-editor.d.ts +1 -0
  74. package/dist/workbench/index.d.ts +1 -1
  75. package/dist/workbench/styles.d.ts +1 -1
  76. package/dist/zip.d.ts +4 -3
  77. package/package.json +37 -8
  78. package/packages/commands/README.md +7 -0
  79. package/packages/commands/package.json +16 -0
  80. package/packages/commands/src/index.ts +467 -0
  81. package/packages/commands/tsconfig.json +22 -0
  82. package/packages/core/README.md +12 -0
  83. package/packages/core/package.json +13 -0
  84. package/packages/core/src/di.ts +147 -0
  85. package/packages/core/src/disposable.ts +112 -0
  86. package/packages/core/src/errors.ts +205 -0
  87. package/packages/core/src/events.ts +157 -0
  88. package/packages/core/src/index.ts +49 -0
  89. package/packages/core/src/path.ts +118 -0
  90. package/packages/core/src/registry.ts +61 -0
  91. package/packages/core/tsconfig.json +19 -0
  92. package/packages/editor/README.md +9 -0
  93. package/packages/editor/package.json +18 -0
  94. package/packages/editor/src/index.ts +344 -0
  95. package/packages/editor/tsconfig.json +24 -0
  96. package/packages/fs/README.md +7 -0
  97. package/packages/fs/package.json +16 -0
  98. package/packages/fs/src/backends.ts +301 -0
  99. package/packages/fs/src/index.ts +18 -0
  100. package/packages/fs/src/types.ts +44 -0
  101. package/packages/fs/src/vfs-service.ts +257 -0
  102. package/packages/fs/tsconfig.json +22 -0
  103. package/packages/preview/README.md +3 -0
  104. package/packages/preview/package.json +16 -0
  105. package/packages/preview/src/index.ts +125 -0
  106. package/packages/preview/tsconfig.json +22 -0
  107. package/packages/runtime/README.md +3 -0
  108. package/packages/runtime/package.json +17 -0
  109. package/packages/runtime/src/index.ts +134 -0
  110. package/packages/runtime/tsconfig.json +23 -0
  111. package/packages/settings/README.md +7 -0
  112. package/packages/settings/package.json +16 -0
  113. package/packages/settings/src/builtin-schemas.ts +235 -0
  114. package/packages/settings/src/configuration-service.ts +543 -0
  115. package/packages/settings/src/index.ts +37 -0
  116. package/packages/settings/src/jsonc.ts +189 -0
  117. package/packages/settings/src/schema.ts +164 -0
  118. package/packages/settings/tsconfig.json +22 -0
  119. package/packages/sql/README.md +12 -0
  120. package/packages/sql/package.json +13 -0
  121. package/packages/sql/src/completions.ts +359 -0
  122. package/packages/sql/src/diagnostics.ts +200 -0
  123. package/packages/sql/src/formatter.ts +271 -0
  124. package/packages/sql/src/index.ts +54 -0
  125. package/packages/sql/src/sql-editor.ts +802 -0
  126. package/packages/sql/src/styles.ts +501 -0
  127. package/packages/sql/src/tokenizer.ts +457 -0
  128. package/packages/sql/src/types.ts +148 -0
  129. package/packages/sql/tsconfig.json +19 -0
  130. package/packages/terminal/README.md +3 -0
  131. package/packages/terminal/package.json +16 -0
  132. package/packages/terminal/src/index.ts +183 -0
  133. package/packages/terminal/tsconfig.json +22 -0
  134. package/packages/ui/README.md +8 -0
  135. package/packages/ui/package.json +18 -0
  136. package/packages/ui/src/index.ts +36 -0
  137. package/packages/ui/src/observability.ts +175 -0
  138. package/packages/ui/src/plugin-registry.ts +274 -0
  139. package/packages/ui/src/settings-dialog.ts +293 -0
  140. package/packages/ui/src/themes.ts +174 -0
  141. package/packages/ui/tsconfig.json +24 -0
  142. package/src/code-lab.css +298 -2
  143. package/src/csp.ts +7 -10
  144. package/src/diagnostics.ts +42 -3
  145. package/src/extensions/cpp.ts +105 -24
  146. package/src/extensions/python.ts +260 -116
  147. package/src/extensions/umbrella.ts +5 -0
  148. package/src/index.ts +1 -1
  149. package/src/modular-kernel.ts +11 -0
  150. package/src/preview-sw.js +73 -12
  151. package/src/runtime.ts +501 -74
  152. package/src/schemas.ts +62 -62
  153. package/src/scm.ts +106 -19
  154. package/src/search.ts +71 -27
  155. package/src/shell.ts +433 -53
  156. package/src/terminal.ts +239 -52
  157. package/src/workbench/diff-editor.ts +106 -18
  158. package/src/workbench/drawer.ts +17 -4
  159. package/src/workbench/guided-pane.ts +12 -2
  160. package/src/workbench/icons.ts +5 -2
  161. package/src/workbench/share.ts +37 -8
  162. package/src/workbench/styles.ts +2 -1
  163. package/src/workbench/toolbar.ts +15 -4
  164. package/src/workbench.ts +2877 -284
  165. package/src/zip.ts +29 -7
  166. package/dist/runtime/index.d.ts +0 -4
  167. package/dist/shell/coreutils/compilers-cli.d.ts +0 -24
  168. package/dist/shell/index.d.ts +0 -4
  169. package/src/runtime/index.ts +0 -5
  170. package/src/shell/coreutils/compilers-cli.ts +0 -103
  171. package/src/shell/index.ts +0 -5
@@ -0,0 +1,802 @@
1
+ import { completeSql } from './completions';
2
+ import { formatSql } from './formatter';
3
+ import { ensureSqlStylesInjected } from './styles';
4
+ import { escapeSqlHtml, highlightSql } from './tokenizer';
5
+ import type {
6
+ SqlCompletionItem,
7
+ SqlDiagnostic,
8
+ SqlDialect,
9
+ SqlEditorInstance,
10
+ SqlEditorMode,
11
+ SqlEditorOptions,
12
+ SqlRunPayload,
13
+ SqlSchema,
14
+ SqlThemeMode
15
+ } from './types';
16
+
17
+ let instanceSeq = 0;
18
+
19
+ const AUTO_INDENT_CLAUSES = /\b(SELECT|FROM|WHERE|JOIN|LEFT\s+JOIN|INNER\s+JOIN|GROUP\s+BY|ORDER\s+BY|HAVING|VALUES|SET|BEGIN)\s*$/i;
20
+ const PAIR_MAP: Readonly<Record<string, string>> = {
21
+ '(': ')',
22
+ '\'': '\'',
23
+ '"': '"'
24
+ };
25
+
26
+ function kindAbbrev(kind: SqlCompletionItem['kind']): string {
27
+ switch (kind) {
28
+ case 'table':
29
+ return 'T';
30
+ case 'column':
31
+ return 'C';
32
+ case 'function':
33
+ return 'ƒ';
34
+ case 'cte':
35
+ return 'W';
36
+ case 'keyword':
37
+ return 'K';
38
+ }
39
+ }
40
+
41
+ export function createSqlEditor(
42
+ containerEl: HTMLElement,
43
+ options: SqlEditorOptions = {}
44
+ ): SqlEditorInstance {
45
+ if (!containerEl) {
46
+ throw new Error('createSqlEditor requires a valid container element');
47
+ }
48
+
49
+ const ownerDoc = containerEl.ownerDocument ?? (typeof document !== 'undefined' ? document : undefined);
50
+ ensureSqlStylesInjected(ownerDoc);
51
+
52
+ const uid = `cl-sql-${++instanceSeq}`;
53
+ const diagId = `${uid}-diagnostics`;
54
+ const listboxId = `${uid}-completions`;
55
+ const statusId = `${uid}-a11y-status`;
56
+
57
+ let currentValue = options.value ?? '';
58
+ let dialect: SqlDialect = options.dialect ?? options.schema?.dialect ?? 'postgres';
59
+ const mode: SqlEditorMode = options.mode ?? 'inline';
60
+ let schema: SqlSchema | null = options.schema ?? null;
61
+ let theme: SqlThemeMode = options.theme ?? 'auto';
62
+ let readOnly = Boolean(options.readOnly);
63
+ let diagnostics: SqlDiagnostic[] = [];
64
+ let completions: SqlCompletionItem[] = [];
65
+ let activeCompletionIdx = 0;
66
+ let tabMovesFocus = false;
67
+ let destroyed = false;
68
+
69
+ const minLines = Math.max(1, options.minLines ?? (mode === 'playground' ? 10 : 3));
70
+ const maxLines = Math.max(minLines, options.maxLines ?? (mode === 'playground' ? 28 : 16));
71
+ const showToolbar = options.showToolbar ?? (mode === 'playground');
72
+
73
+ const docFactory = ownerDoc ?? document;
74
+ const rootEl = docFactory.createElement('div');
75
+ rootEl.className = 'cl-sql-root';
76
+ rootEl.setAttribute('data-cl-sql-mode', mode);
77
+
78
+ // Optional header / toolbar
79
+ let headerSlot: HTMLElement | null = null;
80
+ let dialectPillEl: HTMLElement | null = null;
81
+ if (showToolbar) {
82
+ headerSlot = docFactory.createElement('div');
83
+ headerSlot.className = 'cl-sql-toolbar';
84
+ headerSlot.innerHTML =
85
+ `<div class="cl-sql-toolbar-left">` +
86
+ `<span class="cl-sql-dialect-pill" data-role="dialect-pill">${dialect === 'postgres' ? 'PostgreSQL 18' : 'SQLite 3'}</span>` +
87
+ `</div>` +
88
+ `<div class="cl-sql-toolbar-right">` +
89
+ `<button type="button" class="cl-sql-btn" data-action="format" title="Format SQL (Shift+Alt+F)">Format</button>` +
90
+ (options.onExplain
91
+ ? `<button type="button" class="cl-sql-btn" data-action="explain" title="Explain Query Plan">Explain</button>`
92
+ : '') +
93
+ `<button type="button" class="cl-sql-btn cl-sql-btn-primary" data-action="run" title="Run Query (Cmd/Ctrl+Enter)">Run ↵</button>` +
94
+ `</div>`;
95
+ dialectPillEl = headerSlot.querySelector('[data-role="dialect-pill"]');
96
+ rootEl.appendChild(headerSlot);
97
+ }
98
+
99
+ // Editor surface (gutter + backdrop `<pre>` + `<textarea>`)
100
+ const surfaceEl = docFactory.createElement('div');
101
+ surfaceEl.className = 'cl-sql-surface';
102
+
103
+ const gutterEl = docFactory.createElement('div');
104
+ gutterEl.className = 'cl-sql-gutter';
105
+ gutterEl.setAttribute('aria-hidden', 'true');
106
+
107
+ const editorWrapEl = docFactory.createElement('div');
108
+ editorWrapEl.className = 'cl-sql-editor-wrap';
109
+
110
+ const backdropEl = docFactory.createElement('pre');
111
+ backdropEl.className = 'cl-sql-backdrop';
112
+ backdropEl.setAttribute('aria-hidden', 'true');
113
+
114
+ const textareaEl = docFactory.createElement('textarea');
115
+ textareaEl.className = 'cl-sql-textarea';
116
+ textareaEl.setAttribute('role', 'textbox');
117
+ textareaEl.setAttribute('aria-multiline', 'true');
118
+ textareaEl.setAttribute('aria-label', options.ariaLabel ?? `${dialect.toUpperCase()} SQL Editor`);
119
+ textareaEl.setAttribute('aria-autocomplete', 'list');
120
+ textareaEl.setAttribute('aria-controls', listboxId);
121
+ textareaEl.setAttribute('spellcheck', 'false');
122
+ textareaEl.setAttribute('autocapitalize', 'off');
123
+ textareaEl.setAttribute('autocomplete', 'off');
124
+ textareaEl.setAttribute('autocorrect', 'off');
125
+ if (options.placeholder) {
126
+ textareaEl.setAttribute('placeholder', options.placeholder);
127
+ }
128
+ if (readOnly) {
129
+ textareaEl.readOnly = true;
130
+ textareaEl.setAttribute('aria-readonly', 'true');
131
+ }
132
+ textareaEl.value = currentValue;
133
+
134
+ editorWrapEl.appendChild(backdropEl);
135
+ editorWrapEl.appendChild(textareaEl);
136
+ surfaceEl.appendChild(gutterEl);
137
+ surfaceEl.appendChild(editorWrapEl);
138
+
139
+ // Completion listbox
140
+ const completionListEl = docFactory.createElement('ul');
141
+ completionListEl.id = listboxId;
142
+ completionListEl.className = 'cl-sql-completions';
143
+ completionListEl.setAttribute('role', 'listbox');
144
+ completionListEl.setAttribute('aria-label', 'SQL Completions');
145
+ surfaceEl.appendChild(completionListEl);
146
+
147
+ // Playground split wrapper or direct inline mount
148
+ let resultsSlot: HTMLElement | null = null;
149
+ if (mode === 'playground') {
150
+ const splitEl = docFactory.createElement('div');
151
+ splitEl.className = 'cl-sql-playground-layout';
152
+ splitEl.appendChild(surfaceEl);
153
+ resultsSlot = docFactory.createElement('div');
154
+ resultsSlot.className = 'cl-sql-results-slot';
155
+ resultsSlot.innerHTML = `<div class="cl-sql-ResultsEmpty">Press Cmd/Ctrl+Enter to run query.</div>`;
156
+ splitEl.appendChild(resultsSlot);
157
+ rootEl.appendChild(splitEl);
158
+ } else {
159
+ rootEl.appendChild(surfaceEl);
160
+ }
161
+
162
+ // Diagnostic banner (`aria-describedby` target)
163
+ const diagBannerEl = docFactory.createElement('div');
164
+ diagBannerEl.id = diagId;
165
+ diagBannerEl.className = 'cl-sql-diagnostics';
166
+ diagBannerEl.setAttribute('role', 'status');
167
+ diagBannerEl.setAttribute('aria-live', 'polite');
168
+ rootEl.appendChild(diagBannerEl);
169
+
170
+ // Screen-reader status & optional footer
171
+ const srStatusEl = docFactory.createElement('div');
172
+ srStatusEl.id = statusId;
173
+ srStatusEl.className = 'cl-sql-sr-only';
174
+ srStatusEl.setAttribute('aria-live', 'polite');
175
+ rootEl.appendChild(srStatusEl);
176
+
177
+ let footerSlot: HTMLElement | null = null;
178
+ if (mode === 'playground') {
179
+ footerSlot = docFactory.createElement('div');
180
+ footerSlot.className = 'cl-sql-footer';
181
+ footerSlot.innerHTML =
182
+ `<span data-role="shortcut-hint">Cmd/Ctrl+Enter Run · Shift+Alt+F Format · Esc toggles Tab focus</span>` +
183
+ `<span data-role="tab-mode-indicator"></span>`;
184
+ rootEl.appendChild(footerSlot);
185
+ }
186
+
187
+ containerEl.innerHTML = '';
188
+ containerEl.appendChild(rootEl);
189
+
190
+ const cleanups: Array<() => void> = [];
191
+ const on = <K extends keyof HTMLElementEventMap>(
192
+ el: EventTarget,
193
+ evt: K | string,
194
+ fn: EventListenerOrEventListenerObject
195
+ ): void => {
196
+ el.addEventListener(evt, fn);
197
+ cleanups.push(() => el.removeEventListener(evt, fn));
198
+ };
199
+
200
+ const resolveEffectiveTheme = (): 'dark' | 'light' => {
201
+ if (theme === 'dark' || theme === 'light') return theme;
202
+ const docRoot = ownerDoc?.documentElement;
203
+ if (docRoot) {
204
+ const hostAttr = docRoot.getAttribute('data-theme') || docRoot.getAttribute('data-cl-theme');
205
+ if (hostAttr === 'light') return 'light';
206
+ if (hostAttr === 'dark') return 'dark';
207
+ }
208
+ if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
209
+ const mql = window.matchMedia('(prefers-color-scheme: light)');
210
+ if (mql && mql.matches) return 'light';
211
+ }
212
+ return 'dark';
213
+ };
214
+
215
+ const applyResolvedTheme = (): void => {
216
+ const resolved = resolveEffectiveTheme();
217
+ rootEl.setAttribute('data-cl-sql-theme', resolved);
218
+ rootEl.setAttribute('data-theme', resolved);
219
+ };
220
+
221
+ // Watch host `<html data-theme="...">` and system `prefers-color-scheme`
222
+ if (typeof MutationObserver === 'function' && ownerDoc?.documentElement) {
223
+ const mo = new MutationObserver(() => {
224
+ if (theme === 'auto') applyResolvedTheme();
225
+ });
226
+ mo.observe(ownerDoc.documentElement, {
227
+ attributes: true,
228
+ attributeFilter: ['data-theme', 'data-cl-theme', 'class']
229
+ });
230
+ cleanups.push(() => mo.disconnect());
231
+ }
232
+ if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
233
+ const mql = window.matchMedia('(prefers-color-scheme: dark)');
234
+ if (mql && typeof mql.addEventListener === 'function') {
235
+ const listener = (): void => {
236
+ if (theme === 'auto') applyResolvedTheme();
237
+ };
238
+ mql.addEventListener('change', listener);
239
+ cleanups.push(() => mql.removeEventListener('change', listener));
240
+ }
241
+ }
242
+
243
+ const updateHeightAndGutter = (): void => {
244
+ const lineCount = Math.max(1, currentValue.split('\n').length);
245
+ const clampedLines = Math.max(minLines, Math.min(maxLines, lineCount));
246
+ const lineHeightPx = 21;
247
+ const targetHeight = Math.round(clampedLines * lineHeightPx + 20);
248
+ surfaceEl.style.height = `${targetHeight}px`;
249
+
250
+ // Compute per-line diagnostics for gutter dots
251
+ const lineSeverity = new Map<number, 'error' | 'warning'>();
252
+ for (const d of diagnostics) {
253
+ let line = d.line;
254
+ if (line === undefined && d.fromOffset !== undefined) {
255
+ line = currentValue.slice(0, Math.max(0, d.fromOffset)).split('\n').length;
256
+ }
257
+ if (line !== undefined && line >= 1) {
258
+ const prev = lineSeverity.get(line);
259
+ if (d.severity === 'error' || (!prev && d.severity === 'warning')) {
260
+ lineSeverity.set(line, d.severity === 'error' ? 'error' : 'warning');
261
+ }
262
+ }
263
+ }
264
+
265
+ const gutterHtml: string[] = [];
266
+ for (let ln = 1; ln <= lineCount; ln++) {
267
+ const sev = lineSeverity.get(ln);
268
+ gutterHtml.push(
269
+ `<div class="cl-sql-gutter-line"${sev ? ` data-diag="${sev}"` : ''}>${ln}</div>`
270
+ );
271
+ }
272
+ gutterEl.innerHTML = gutterHtml.join('');
273
+ };
274
+
275
+ const renderDiagnosticsBanner = (): void => {
276
+ if (diagnostics.length === 0) {
277
+ diagBannerEl.setAttribute('data-visible', 'false');
278
+ diagBannerEl.innerHTML = '';
279
+ textareaEl.removeAttribute('aria-describedby');
280
+ textareaEl.removeAttribute('aria-invalid');
281
+ return;
282
+ }
283
+ diagBannerEl.setAttribute('data-visible', 'true');
284
+ const hasError = diagnostics.some((d) => d.severity === 'error');
285
+ if (hasError) {
286
+ textareaEl.setAttribute('aria-invalid', 'true');
287
+ } else {
288
+ textareaEl.removeAttribute('aria-invalid');
289
+ }
290
+ textareaEl.setAttribute('aria-describedby', diagId);
291
+
292
+ diagBannerEl.innerHTML = diagnostics
293
+ .map((d) => {
294
+ const loc = d.line ? ` (line ${d.line}${d.column ? `:${d.column}` : ''})` : '';
295
+ return (
296
+ `<div class="cl-sql-diag-row">` +
297
+ `<span class="cl-sql-diag-badge" data-severity="${escapeSqlHtml(d.severity)}">${escapeSqlHtml(d.severity)}</span>` +
298
+ `<span>${escapeSqlHtml(d.message)}${escapeSqlHtml(loc)}</span>` +
299
+ (d.hint ? `<div class="cl-sql-diag-hint">Hint: ${escapeSqlHtml(d.hint)}</div>` : '') +
300
+ `</div>`
301
+ );
302
+ })
303
+ .join('');
304
+ };
305
+
306
+ const renderHighlight = (): void => {
307
+ backdropEl.innerHTML = highlightSql(currentValue, dialect, diagnostics);
308
+ updateHeightAndGutter();
309
+ };
310
+
311
+ const closeCompletions = (): void => {
312
+ completions = [];
313
+ activeCompletionIdx = 0;
314
+ completionListEl.setAttribute('data-open', 'false');
315
+ completionListEl.innerHTML = '';
316
+ textareaEl.removeAttribute('aria-activedescendant');
317
+ };
318
+
319
+ const applyCompletion = (item: SqlCompletionItem): void => {
320
+ const before = currentValue.slice(0, item.replaceFrom);
321
+ const after = currentValue.slice(item.replaceTo);
322
+ const nextVal = before + item.insertText + after;
323
+ const nextCursor = before.length + item.insertText.length;
324
+ currentValue = nextVal;
325
+ textareaEl.value = nextVal;
326
+ textareaEl.selectionStart = nextCursor;
327
+ textareaEl.selectionEnd = nextCursor;
328
+ closeCompletions();
329
+ renderHighlight();
330
+ options.onChange?.(currentValue);
331
+ textareaEl.focus();
332
+ };
333
+
334
+ const renderCompletions = (): void => {
335
+ if (completions.length === 0 || readOnly) {
336
+ closeCompletions();
337
+ return;
338
+ }
339
+ completionListEl.setAttribute('data-open', 'true');
340
+ const activeId = `${uid}-opt-${activeCompletionIdx}`;
341
+ textareaEl.setAttribute('aria-activedescendant', activeId);
342
+
343
+ completionListEl.innerHTML = completions
344
+ .map((item, idx) => {
345
+ const optId = `${uid}-opt-${idx}`;
346
+ const selected = idx === activeCompletionIdx ? 'true' : 'false';
347
+ const badges: string[] = [];
348
+ if (item.secondaryBadge) {
349
+ badges.push(`<span class="cl-sql-comp-badge">${escapeSqlHtml(item.secondaryBadge)}</span>`);
350
+ }
351
+ if (item.badge) {
352
+ badges.push(`<span class="cl-sql-comp-badge">${escapeSqlHtml(item.badge)}</span>`);
353
+ }
354
+ return (
355
+ `<li id="${optId}" role="option" aria-selected="${selected}" data-comp-idx="${idx}" class="cl-sql-completion-item">` +
356
+ `<span class="cl-sql-comp-main">` +
357
+ `<span class="cl-sql-comp-kind" aria-hidden="true">${kindAbbrev(item.kind)}</span>` +
358
+ `<span class="cl-sql-comp-label">${escapeSqlHtml(item.label)}</span>` +
359
+ `</span>` +
360
+ `<span class="cl-sql-comp-meta">` +
361
+ (item.detail ? `<span>${escapeSqlHtml(item.detail)}</span>` : '') +
362
+ badges.join('') +
363
+ `</span>` +
364
+ `</li>`
365
+ );
366
+ })
367
+ .join('');
368
+ };
369
+
370
+ const updateCompletionsFromCursor = (): void => {
371
+ if (readOnly || !schema) {
372
+ // Still allow dot-less keyword/function completion if schema is absent only when >=2 chars,
373
+ // or full completion when schema is provided
374
+ if (!schema) {
375
+ closeCompletions();
376
+ return;
377
+ }
378
+ }
379
+ const cursor = textareaEl.selectionStart ?? currentValue.length;
380
+ if ((textareaEl.selectionEnd ?? cursor) !== cursor) {
381
+ closeCompletions();
382
+ return;
383
+ }
384
+ const items = completeSql(currentValue, cursor, schema, dialect, 24);
385
+ // Avoid showing single exact match identical to what user already typed
386
+ if (
387
+ items.length === 1 &&
388
+ currentValue.slice(items[0].replaceFrom, items[0].replaceTo) === items[0].insertText
389
+ ) {
390
+ closeCompletions();
391
+ return;
392
+ }
393
+ completions = items;
394
+ activeCompletionIdx = 0;
395
+ renderCompletions();
396
+ };
397
+
398
+ const buildRunPayload = (): SqlRunPayload => {
399
+ const start = textareaEl.selectionStart ?? 0;
400
+ const end = textareaEl.selectionEnd ?? 0;
401
+ const rawSel = end > start ? currentValue.slice(start, end) : '';
402
+ const trimmedSel = rawSel.trim();
403
+ return {
404
+ sql: currentValue,
405
+ selectedSql: rawSel,
406
+ effectiveSql: trimmedSel.length > 0 ? rawSel : currentValue,
407
+ dialect
408
+ };
409
+ };
410
+
411
+ const triggerRun = (): void => {
412
+ closeCompletions();
413
+ options.onRun?.(buildRunPayload());
414
+ };
415
+
416
+ const triggerExplain = (): void => {
417
+ closeCompletions();
418
+ options.onExplain?.(buildRunPayload());
419
+ };
420
+
421
+ const toggleLineComments = (): void => {
422
+ if (readOnly) return;
423
+ const start = textareaEl.selectionStart ?? 0;
424
+ const end = textareaEl.selectionEnd ?? start;
425
+ const lineStart = currentValue.lastIndexOf('\n', Math.max(0, start - 1)) + 1;
426
+ const nextNewline = currentValue.indexOf('\n', end);
427
+ const lineEnd = nextNewline === -1 ? currentValue.length : nextNewline;
428
+ const block = currentValue.slice(lineStart, lineEnd);
429
+ const lines = block.split('\n');
430
+ const allCommented = lines.every((l) => l.trim().length === 0 || /^\s*--/.test(l));
431
+ const updatedLines = lines.map((l) => {
432
+ if (allCommented) {
433
+ return l.replace(/^(\s*)--\s?/, '$1');
434
+ }
435
+ return l.length > 0 ? `-- ${l}` : '--';
436
+ });
437
+ const replacement = updatedLines.join('\n');
438
+ currentValue = currentValue.slice(0, lineStart) + replacement + currentValue.slice(lineEnd);
439
+ textareaEl.value = currentValue;
440
+ textareaEl.selectionStart = lineStart;
441
+ textareaEl.selectionEnd = lineStart + replacement.length;
442
+ renderHighlight();
443
+ options.onChange?.(currentValue);
444
+ };
445
+
446
+ const setTabFocusIndicator = (enabled: boolean): void => {
447
+ tabMovesFocus = enabled;
448
+ rootEl.setAttribute('data-tab-moves-focus', enabled ? 'true' : 'false');
449
+ srStatusEl.textContent = enabled
450
+ ? 'Tab moves focus mode enabled. Press Tab to leave the SQL editor.'
451
+ : 'Tab inserts indentation.';
452
+ const indicator = footerSlot?.querySelector('[data-role="tab-mode-indicator"]');
453
+ if (indicator) {
454
+ indicator.textContent = enabled ? 'Tab moves focus' : '';
455
+ }
456
+ };
457
+
458
+ // Sync scroll between `<textarea>`, `<pre>`, and gutter
459
+ on(textareaEl, 'scroll', () => {
460
+ backdropEl.scrollTop = textareaEl.scrollTop;
461
+ backdropEl.scrollLeft = textareaEl.scrollLeft;
462
+ gutterEl.scrollTop = textareaEl.scrollTop;
463
+ });
464
+
465
+ on(textareaEl, 'input', () => {
466
+ currentValue = textareaEl.value;
467
+ if (tabMovesFocus) setTabFocusIndicator(false);
468
+ renderHighlight();
469
+ updateCompletionsFromCursor();
470
+ options.onChange?.(currentValue);
471
+ });
472
+
473
+ on(textareaEl, 'blur', () => {
474
+ // Delay slightly so touch/mousedown on completion item fires first
475
+ setTimeout(() => {
476
+ if (!destroyed) closeCompletions();
477
+ }, 120);
478
+ });
479
+
480
+ on(completionListEl, 'mousedown', (rawEvt) => {
481
+ const evt = rawEvt as MouseEvent;
482
+ const target = (evt.target as HTMLElement | null)?.closest?.('[data-comp-idx]');
483
+ if (!target) return;
484
+ evt.preventDefault();
485
+ const idx = Number(target.getAttribute('data-comp-idx'));
486
+ if (completions[idx]) {
487
+ applyCompletion(completions[idx]);
488
+ }
489
+ });
490
+
491
+ if (headerSlot) {
492
+ on(headerSlot, 'click', (rawEvt) => {
493
+ const target = (rawEvt.target as HTMLElement | null)?.closest?.('[data-action]');
494
+ if (!target) return;
495
+ const action = target.getAttribute('data-action');
496
+ if (action === 'run') triggerRun();
497
+ else if (action === 'format') instance.format();
498
+ else if (action === 'explain') triggerExplain();
499
+ });
500
+ }
501
+
502
+ on(textareaEl, 'keydown', (rawEvt) => {
503
+ const event = rawEvt as KeyboardEvent;
504
+
505
+ // IME-safe guard: never intercept composition keystrokes (e.g. CJK input Enter/Arrow)
506
+ if (event.isComposing || event.keyCode === 229) {
507
+ return;
508
+ }
509
+
510
+ const mod = event.metaKey || event.ctrlKey;
511
+
512
+ // 1. `Cmd/Ctrl + Enter` -> Run query (selection or full SQL)
513
+ if (mod && event.key === 'Enter') {
514
+ event.preventDefault();
515
+ triggerRun();
516
+ return;
517
+ }
518
+
519
+ // 2. `Shift + Alt + F` or `Cmd/Ctrl + Shift + F` -> Format SQL
520
+ if (
521
+ (event.shiftKey && event.altKey && (event.key === 'F' || event.key === 'f')) ||
522
+ (mod && event.shiftKey && (event.key === 'F' || event.key === 'f'))
523
+ ) {
524
+ event.preventDefault();
525
+ if (!readOnly) instance.format();
526
+ return;
527
+ }
528
+
529
+ // 3. `Cmd/Ctrl + /` -> Toggle `-- ` line comments
530
+ if (mod && event.key === '/') {
531
+ event.preventDefault();
532
+ toggleLineComments();
533
+ return;
534
+ }
535
+
536
+ // 4. Autocomplete navigation when popup is open
537
+ if (completions.length > 0) {
538
+ if (event.key === 'ArrowDown') {
539
+ event.preventDefault();
540
+ activeCompletionIdx = (activeCompletionIdx + 1) % completions.length;
541
+ renderCompletions();
542
+ return;
543
+ }
544
+ if (event.key === 'ArrowUp') {
545
+ event.preventDefault();
546
+ activeCompletionIdx = (activeCompletionIdx - 1 + completions.length) % completions.length;
547
+ renderCompletions();
548
+ return;
549
+ }
550
+ if (event.key === 'Enter' || event.key === 'Tab') {
551
+ event.preventDefault();
552
+ applyCompletion(completions[activeCompletionIdx]);
553
+ return;
554
+ }
555
+ if (event.key === 'Escape') {
556
+ event.preventDefault();
557
+ closeCompletions();
558
+ return;
559
+ }
560
+ }
561
+
562
+ // 5. WCAG 2.1 AA Keyboard Escape: `Esc` enables "Tab moves focus" mode so `Esc` -> `Tab` always leaves editor
563
+ if (event.key === 'Escape') {
564
+ event.preventDefault();
565
+ setTabFocusIndicator(!tabMovesFocus);
566
+ return;
567
+ }
568
+
569
+ if (event.key === 'Tab') {
570
+ if (tabMovesFocus || readOnly) {
571
+ // Do NOT preventDefault — let browser move focus naturally out of the editor!
572
+ return;
573
+ }
574
+ event.preventDefault();
575
+ const start = textareaEl.selectionStart ?? 0;
576
+ const end = textareaEl.selectionEnd ?? start;
577
+ if (event.shiftKey) {
578
+ const lineStart = currentValue.lastIndexOf('\n', Math.max(0, start - 1)) + 1;
579
+ if (currentValue.slice(lineStart, lineStart + 2) === ' ') {
580
+ currentValue = currentValue.slice(0, lineStart) + currentValue.slice(lineStart + 2);
581
+ textareaEl.value = currentValue;
582
+ const nextPos = Math.max(lineStart, start - 2);
583
+ textareaEl.selectionStart = nextPos;
584
+ textareaEl.selectionEnd = Math.max(lineStart, end - 2);
585
+ renderHighlight();
586
+ options.onChange?.(currentValue);
587
+ }
588
+ } else {
589
+ currentValue = currentValue.slice(0, start) + ' ' + currentValue.slice(end);
590
+ textareaEl.value = currentValue;
591
+ textareaEl.selectionStart = start + 2;
592
+ textareaEl.selectionEnd = start + 2;
593
+ renderHighlight();
594
+ options.onChange?.(currentValue);
595
+ }
596
+ return;
597
+ }
598
+
599
+ if (readOnly) return;
600
+
601
+ // 6. Smart auto-indent on `Enter`
602
+ if (event.key === 'Enter' && !mod && !event.shiftKey && !event.altKey) {
603
+ event.preventDefault();
604
+ const start = textareaEl.selectionStart ?? 0;
605
+ const end = textareaEl.selectionEnd ?? start;
606
+ const lineStart = currentValue.lastIndexOf('\n', Math.max(0, start - 1)) + 1;
607
+ const currentLineBefore = currentValue.slice(lineStart, start);
608
+ const leadingSpaces = /^([ \t]*)/.exec(currentLineBefore)?.[1] ?? '';
609
+ const trimmedBefore = currentLineBefore.trim();
610
+ const shouldIndentExtra =
611
+ trimmedBefore.endsWith('(') || AUTO_INDENT_CLAUSES.test(trimmedBefore);
612
+ const nextIndent = leadingSpaces + (shouldIndentExtra ? ' ' : '');
613
+ const insert = '\n' + nextIndent;
614
+ currentValue = currentValue.slice(0, start) + insert + currentValue.slice(end);
615
+ textareaEl.value = currentValue;
616
+ const pos = start + insert.length;
617
+ textareaEl.selectionStart = pos;
618
+ textareaEl.selectionEnd = pos;
619
+ renderHighlight();
620
+ options.onChange?.(currentValue);
621
+ return;
622
+ }
623
+
624
+ // 7. Bracket & quote auto-pairing (`()`, `''`, `""`)
625
+ if (!mod && !event.altKey && event.key in PAIR_MAP) {
626
+ const openChar = event.key;
627
+ const closeChar = PAIR_MAP[openChar];
628
+ const start = textareaEl.selectionStart ?? 0;
629
+ const end = textareaEl.selectionEnd ?? start;
630
+ if (end > start) {
631
+ event.preventDefault();
632
+ const selected = currentValue.slice(start, end);
633
+ currentValue = currentValue.slice(0, start) + openChar + selected + closeChar + currentValue.slice(end);
634
+ textareaEl.value = currentValue;
635
+ textareaEl.selectionStart = start + 1;
636
+ textareaEl.selectionEnd = end + 1;
637
+ renderHighlight();
638
+ options.onChange?.(currentValue);
639
+ return;
640
+ }
641
+ // Skip over closing quote/paren if already right ahead
642
+ if ((openChar === '\'' || openChar === '"') && currentValue[start] === closeChar) {
643
+ event.preventDefault();
644
+ textareaEl.selectionStart = start + 1;
645
+ textareaEl.selectionEnd = start + 1;
646
+ return;
647
+ }
648
+ const nextCh = currentValue[start] ?? '';
649
+ if (!nextCh || /[\s),;]/.test(nextCh)) {
650
+ event.preventDefault();
651
+ currentValue = currentValue.slice(0, start) + openChar + closeChar + currentValue.slice(end);
652
+ textareaEl.value = currentValue;
653
+ textareaEl.selectionStart = start + 1;
654
+ textareaEl.selectionEnd = start + 1;
655
+ renderHighlight();
656
+ options.onChange?.(currentValue);
657
+ return;
658
+ }
659
+ }
660
+
661
+ if (event.key === ')' && !mod && !event.altKey) {
662
+ const start = textareaEl.selectionStart ?? 0;
663
+ const end = textareaEl.selectionEnd ?? start;
664
+ if (start === end && currentValue[start] === ')') {
665
+ event.preventDefault();
666
+ textareaEl.selectionStart = start + 1;
667
+ textareaEl.selectionEnd = start + 1;
668
+ }
669
+ }
670
+ });
671
+
672
+ // Initial render
673
+ applyResolvedTheme();
674
+ renderHighlight();
675
+ renderDiagnosticsBanner();
676
+
677
+ const instance: SqlEditorInstance = {
678
+ getValue(): string {
679
+ return currentValue;
680
+ },
681
+
682
+ setValue(sql: string): void {
683
+ currentValue = String(sql ?? '');
684
+ textareaEl.value = currentValue;
685
+ closeCompletions();
686
+ renderHighlight();
687
+ },
688
+
689
+ getSelection(): string {
690
+ const start = textareaEl.selectionStart ?? 0;
691
+ const end = textareaEl.selectionEnd ?? 0;
692
+ return end > start ? currentValue.slice(start, end) : '';
693
+ },
694
+
695
+ insertAtCursor(text: string): void {
696
+ if (readOnly) return;
697
+ const ins = String(text ?? '');
698
+ const start = textareaEl.selectionStart ?? currentValue.length;
699
+ const end = textareaEl.selectionEnd ?? start;
700
+ currentValue = currentValue.slice(0, start) + ins + currentValue.slice(end);
701
+ textareaEl.value = currentValue;
702
+ const nextPos = start + ins.length;
703
+ textareaEl.selectionStart = nextPos;
704
+ textareaEl.selectionEnd = nextPos;
705
+ renderHighlight();
706
+ options.onChange?.(currentValue);
707
+ textareaEl.focus();
708
+ },
709
+
710
+ format(): string {
711
+ const formatted = formatSql(currentValue, { dialect, indent: 2, keywordCase: 'upper' });
712
+ currentValue = formatted;
713
+ textareaEl.value = formatted;
714
+ closeCompletions();
715
+ renderHighlight();
716
+ options.onFormat?.(formatted);
717
+ options.onChange?.(formatted);
718
+ return formatted;
719
+ },
720
+
721
+ setDialect(nextDialect: SqlDialect): void {
722
+ dialect = nextDialect === 'sqlite' ? 'sqlite' : 'postgres';
723
+ if (dialectPillEl) {
724
+ dialectPillEl.textContent = dialect === 'postgres' ? 'PostgreSQL 18' : 'SQLite 3';
725
+ }
726
+ renderHighlight();
727
+ },
728
+
729
+ getDialect(): SqlDialect {
730
+ return dialect;
731
+ },
732
+
733
+ setSchema(nextSchema: SqlSchema | null): void {
734
+ schema = nextSchema;
735
+ if (nextSchema?.dialect) {
736
+ instance.setDialect(nextSchema.dialect);
737
+ }
738
+ },
739
+
740
+ getSchema(): SqlSchema | null {
741
+ return schema;
742
+ },
743
+
744
+ setDiagnostics(nextDiagnostics: readonly SqlDiagnostic[]): void {
745
+ diagnostics = Array.from(nextDiagnostics);
746
+ renderHighlight();
747
+ renderDiagnosticsBanner();
748
+ },
749
+
750
+ clearDiagnostics(): void {
751
+ diagnostics = [];
752
+ renderHighlight();
753
+ renderDiagnosticsBanner();
754
+ },
755
+
756
+ getDiagnostics(): readonly SqlDiagnostic[] {
757
+ return diagnostics.slice();
758
+ },
759
+
760
+ setTheme(nextTheme: SqlThemeMode): void {
761
+ theme = nextTheme;
762
+ applyResolvedTheme();
763
+ },
764
+
765
+ getTheme(): SqlThemeMode {
766
+ return theme;
767
+ },
768
+
769
+ setReadOnly(nextReadOnly: boolean): void {
770
+ readOnly = Boolean(nextReadOnly);
771
+ textareaEl.readOnly = readOnly;
772
+ if (readOnly) {
773
+ textareaEl.setAttribute('aria-readonly', 'true');
774
+ closeCompletions();
775
+ } else {
776
+ textareaEl.removeAttribute('aria-readonly');
777
+ }
778
+ },
779
+
780
+ focus(): void {
781
+ textareaEl.focus();
782
+ },
783
+
784
+ destroy(): void {
785
+ if (destroyed) return;
786
+ destroyed = true;
787
+ for (const fn of cleanups) {
788
+ fn();
789
+ }
790
+ cleanups.length = 0;
791
+ containerEl.innerHTML = '';
792
+ },
793
+
794
+ slots: {
795
+ header: headerSlot,
796
+ footer: footerSlot,
797
+ results: resultsSlot
798
+ }
799
+ };
800
+
801
+ return instance;
802
+ }