@innovatorved/code-lab 0.7.0 → 0.7.2

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 (159) hide show
  1. package/ARCHITECTURE.md +2 -2
  2. package/CHANGELOG.md +30 -0
  3. package/README.md +6 -6
  4. package/dist/code-lab-sql.esm.js +19 -19
  5. package/dist/code-lab-sql.umd.js +20 -20
  6. package/dist/code-lab.css +1 -1
  7. package/dist/code-lab.d.ts +47 -38
  8. package/dist/code-lab.esm.js +1183 -1909
  9. package/dist/code-lab.js +1182 -1906
  10. package/dist/extensions/cpp.esm.js +132 -8760
  11. package/dist/extensions/cpp.js +124 -8770
  12. package/dist/extensions/guided-lab.esm.js +33 -6836
  13. package/dist/extensions/guided-lab.js +33 -6854
  14. package/dist/extensions/javascript.esm.js +1 -36
  15. package/dist/extensions/javascript.js +1 -58
  16. package/dist/extensions/python.esm.js +113 -8122
  17. package/dist/extensions/python.js +113 -8140
  18. package/dist/extensions/typescript.esm.js +1 -55
  19. package/dist/extensions/typescript.js +1 -77
  20. package/dist/index.d.ts +1 -1
  21. package/dist/logger.d.ts +4 -20
  22. package/dist/modular-kernel.d.ts +0 -5
  23. package/dist/packages/core/src/errors.d.ts +5 -1
  24. package/dist/packages/fs/src/backends.d.ts +0 -27
  25. package/dist/packages/fs/src/index.d.ts +1 -1
  26. package/dist/packages/ui/src/html.d.ts +1 -0
  27. package/dist/packages/ui/src/index.d.ts +1 -0
  28. package/dist/{apps/web/src/index.d.ts → packages/ui/src/kernel.d.ts} +3 -11
  29. package/dist/packages/ui/src/observability.d.ts +1 -1
  30. package/dist/packages/ui/src/settings-dialog.d.ts +0 -1
  31. package/dist/preview-sw.js +1 -1
  32. package/dist/runtime.d.ts +3 -0
  33. package/dist/runtime.esm.js +78 -78
  34. package/dist/runtime.js +78 -78
  35. package/dist/schemas.d.ts +10 -1
  36. package/dist/schemas.esm.js +33 -6815
  37. package/dist/schemas.js +33 -6831
  38. package/dist/shell.esm.js +277 -285
  39. package/dist/shell.js +277 -285
  40. package/dist/terminal.esm.js +9 -7
  41. package/dist/terminal.js +7 -7
  42. package/dist/workbench/command-palette.d.ts +0 -4
  43. package/dist/workbench/editor.d.ts +0 -4
  44. package/dist/workbench/index.d.ts +0 -22
  45. package/dist/workbench/intellisense.d.ts +1 -8
  46. package/dist/workbench/xterm-adapter.d.ts +0 -1
  47. package/package.json +4 -13
  48. package/dist/code-lab.umd.js +0 -6117
  49. package/dist/packages/editor/src/index.d.ts +0 -118
  50. package/dist/packages/preview/src/index.d.ts +0 -34
  51. package/dist/packages/runtime/src/index.d.ts +0 -47
  52. package/dist/packages/terminal/src/index.d.ts +0 -54
  53. package/dist/workbench/drawer.d.ts +0 -18
  54. package/dist/workbench/file-tree.d.ts +0 -11
  55. package/dist/workbench/guided-pane.d.ts +0 -11
  56. package/dist/workbench/styles.d.ts +0 -4
  57. package/dist/workbench/toolbar.d.ts +0 -17
  58. package/packages/commands/README.md +0 -7
  59. package/packages/commands/package.json +0 -16
  60. package/packages/commands/src/index.ts +0 -467
  61. package/packages/commands/tsconfig.json +0 -22
  62. package/packages/core/README.md +0 -12
  63. package/packages/core/package.json +0 -13
  64. package/packages/core/src/di.ts +0 -147
  65. package/packages/core/src/disposable.ts +0 -112
  66. package/packages/core/src/errors.ts +0 -205
  67. package/packages/core/src/events.ts +0 -157
  68. package/packages/core/src/index.ts +0 -49
  69. package/packages/core/src/path.ts +0 -118
  70. package/packages/core/src/registry.ts +0 -61
  71. package/packages/core/tsconfig.json +0 -19
  72. package/packages/editor/README.md +0 -9
  73. package/packages/editor/package.json +0 -18
  74. package/packages/editor/src/index.ts +0 -344
  75. package/packages/editor/tsconfig.json +0 -24
  76. package/packages/fs/README.md +0 -7
  77. package/packages/fs/package.json +0 -16
  78. package/packages/fs/src/backends.ts +0 -301
  79. package/packages/fs/src/index.ts +0 -18
  80. package/packages/fs/src/types.ts +0 -44
  81. package/packages/fs/src/vfs-service.ts +0 -257
  82. package/packages/fs/tsconfig.json +0 -22
  83. package/packages/preview/README.md +0 -3
  84. package/packages/preview/package.json +0 -16
  85. package/packages/preview/src/index.ts +0 -125
  86. package/packages/preview/tsconfig.json +0 -22
  87. package/packages/runtime/README.md +0 -3
  88. package/packages/runtime/package.json +0 -17
  89. package/packages/runtime/src/index.ts +0 -134
  90. package/packages/runtime/tsconfig.json +0 -23
  91. package/packages/settings/README.md +0 -7
  92. package/packages/settings/package.json +0 -16
  93. package/packages/settings/src/builtin-schemas.ts +0 -262
  94. package/packages/settings/src/configuration-service.ts +0 -609
  95. package/packages/settings/src/index.ts +0 -38
  96. package/packages/settings/src/jsonc.ts +0 -189
  97. package/packages/settings/src/schema.ts +0 -164
  98. package/packages/settings/tsconfig.json +0 -22
  99. package/packages/sql/README.md +0 -12
  100. package/packages/sql/package.json +0 -13
  101. package/packages/sql/src/completions.ts +0 -359
  102. package/packages/sql/src/diagnostics.ts +0 -200
  103. package/packages/sql/src/formatter.ts +0 -271
  104. package/packages/sql/src/index.ts +0 -54
  105. package/packages/sql/src/sql-editor.ts +0 -802
  106. package/packages/sql/src/styles.ts +0 -524
  107. package/packages/sql/src/tokenizer.ts +0 -457
  108. package/packages/sql/src/types.ts +0 -148
  109. package/packages/sql/tsconfig.json +0 -19
  110. package/packages/terminal/README.md +0 -3
  111. package/packages/terminal/package.json +0 -16
  112. package/packages/terminal/src/index.ts +0 -183
  113. package/packages/terminal/tsconfig.json +0 -22
  114. package/packages/ui/README.md +0 -8
  115. package/packages/ui/package.json +0 -18
  116. package/packages/ui/src/index.ts +0 -40
  117. package/packages/ui/src/observability.ts +0 -173
  118. package/packages/ui/src/plugin-registry.ts +0 -289
  119. package/packages/ui/src/settings-dialog.ts +0 -939
  120. package/packages/ui/src/themes.ts +0 -333
  121. package/packages/ui/tsconfig.json +0 -24
  122. package/src/code-lab.css +0 -8584
  123. package/src/csp.ts +0 -590
  124. package/src/diagnostics.ts +0 -287
  125. package/src/extensions/cpp.ts +0 -2389
  126. package/src/extensions/guided-lab.ts +0 -64
  127. package/src/extensions/javascript.ts +0 -54
  128. package/src/extensions/python.ts +0 -1737
  129. package/src/extensions/typescript.ts +0 -85
  130. package/src/extensions/umbrella.ts +0 -5
  131. package/src/html.ts +0 -88
  132. package/src/index.ts +0 -129
  133. package/src/logger.ts +0 -139
  134. package/src/modular-kernel.ts +0 -11
  135. package/src/preview-sw.js +0 -296
  136. package/src/runtime/test-harness.ts +0 -57
  137. package/src/runtime.ts +0 -10480
  138. package/src/sample.html +0 -304
  139. package/src/schemas.ts +0 -366
  140. package/src/scm.ts +0 -2453
  141. package/src/search.ts +0 -433
  142. package/src/shell.ts +0 -10987
  143. package/src/storage.ts +0 -773
  144. package/src/terminal.ts +0 -1400
  145. package/src/workbench/command-palette.ts +0 -381
  146. package/src/workbench/diff-editor.ts +0 -470
  147. package/src/workbench/drawer.ts +0 -157
  148. package/src/workbench/editor.ts +0 -49
  149. package/src/workbench/file-tree.ts +0 -51
  150. package/src/workbench/guided-pane.ts +0 -43
  151. package/src/workbench/icons.ts +0 -255
  152. package/src/workbench/index.ts +0 -44
  153. package/src/workbench/intellisense.ts +0 -1871
  154. package/src/workbench/share.ts +0 -128
  155. package/src/workbench/styles.ts +0 -211
  156. package/src/workbench/toolbar.ts +0 -182
  157. package/src/workbench/xterm-adapter.ts +0 -1571
  158. package/src/workbench.ts +0 -22132
  159. package/src/zip.ts +0 -348
@@ -1,802 +0,0 @@
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
- }