dsh-data-window 0.0.0-stage → 0.1.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 (45) hide show
  1. package/AGENTS.md +111 -0
  2. package/CHANGELOG.md +267 -0
  3. package/LICENSE +21 -0
  4. package/README.md +151 -2
  5. package/client.js +8271 -0
  6. package/cordis.patch.yml +4 -0
  7. package/docs/BRIDGE.md +106 -0
  8. package/docs/DESIGN.md +417 -0
  9. package/docs/DETAIL.md +242 -0
  10. package/docs/screenshots/ddl.png +0 -0
  11. package/docs/screenshots/workbench.png +0 -0
  12. package/icon.svg +30 -0
  13. package/index.js +180 -0
  14. package/locale/en.json +304 -0
  15. package/locale/zh.json +304 -0
  16. package/package.json +68 -4
  17. package/src/client/00-css.js +1110 -0
  18. package/src/client/05-icons.js +156 -0
  19. package/src/client/05-theme.js +107 -0
  20. package/src/client/06-shortcuts.js +89 -0
  21. package/src/client/07-bridge.js +202 -0
  22. package/src/client/10-core.js +1320 -0
  23. package/src/client/20-tree.js +293 -0
  24. package/src/client/25-sql.js +631 -0
  25. package/src/client/30-editor.js +742 -0
  26. package/src/client/40-results.js +556 -0
  27. package/src/client/45-export.js +219 -0
  28. package/src/client/50-panel.js +768 -0
  29. package/src/client/60-settings.js +180 -0
  30. package/src/client/63-schema.js +186 -0
  31. package/src/client/64-manual.js +350 -0
  32. package/src/client/65-ai.js +320 -0
  33. package/src/client/66-optimize.js +217 -0
  34. package/src/client/90-apply.js +183 -0
  35. package/src/host/ai.js +721 -0
  36. package/src/host/cache.js +157 -0
  37. package/src/host/catalog.js +161 -0
  38. package/src/host/consoles.js +116 -0
  39. package/src/host/discovery.js +603 -0
  40. package/src/host/manual.js +276 -0
  41. package/src/host/mysql.js +650 -0
  42. package/src/host/remembered.js +225 -0
  43. package/src/host/rpc.js +487 -0
  44. package/src/host/shared.js +180 -0
  45. package/src/host/yaml.js +335 -0
@@ -0,0 +1,742 @@
1
+ /**
2
+ * Workbench tabs, the SQL editor and the DDL document.
3
+ *
4
+ * One tab per database is what requirement 4 asks for, so the tab id is the
5
+ * database target id: asking for the same database twice focuses the console that
6
+ * already exists instead of opening a second one. A tab that needs a second
7
+ * statement gets its own id from the store, never a rewrite of the first.
8
+ */
9
+
10
+ /** The reference a tab copies: `schema.table`, or the schema alone. */
11
+ function dwTabReference(tab) {
12
+ const database = String(tab?.database ?? '').trim()
13
+ // Table consoles keep the table in their id (`sql:<dbId>:tbl:<table>`).
14
+ const id = String(tab?.id ?? '')
15
+ const table = String(tab?.table ?? '').trim()
16
+ || (id.includes(':tbl:') ? id.split(':tbl:').slice(1).join(':tbl:') : '')
17
+ if (database !== '' && table !== '') return `${database}.${table}`
18
+ if (database !== '') return database
19
+ return String(tab?.title ?? '')
20
+ }
21
+
22
+ /** Insert text into the chat composer when it is open; false when it is not. */
23
+ function dwInsertComposerText(text) {
24
+ const doc = globalThis.document
25
+ if (doc === undefined || typeof doc.querySelector !== 'function') return false
26
+ const seat = doc.querySelector('[data-composer-seat]')
27
+ if (seat === null) return false
28
+ const editor = seat.querySelector('[contenteditable="true"], textarea')
29
+ if (editor === null) return false
30
+ try {
31
+ editor.focus()
32
+ if (editor.tagName === 'TEXTAREA') {
33
+ const setter = Object.getOwnPropertyDescriptor(globalThis.HTMLTextAreaElement.prototype, 'value')?.set
34
+ const start = editor.selectionStart ?? editor.value.length
35
+ const end = editor.selectionEnd ?? start
36
+ if (typeof setter === 'function') setter.call(editor, `${editor.value.slice(0, start)}${text}${editor.value.slice(end)}`)
37
+ editor.setSelectionRange(start + text.length, start + text.length)
38
+ editor.dispatchEvent(new Event('input', { bubbles: true }))
39
+ return true
40
+ }
41
+ const before = editor.textContent
42
+ const selection = typeof globalThis.getSelection === 'function' ? globalThis.getSelection() : null
43
+ if (selection === null || selection === undefined) return false
44
+ const range = doc.createRange()
45
+ range.selectNodeContents(editor)
46
+ range.collapse(false)
47
+ selection.removeAllRanges()
48
+ selection.addRange(range)
49
+ doc.execCommand('insertText', false, text)
50
+ return editor.textContent !== before
51
+ } catch (error) {
52
+ void error
53
+ return false
54
+ }
55
+ }
56
+
57
+ function DwTabs({ store, state, tr }) {
58
+ const [menu, setMenu] = useState(null)
59
+ if ((state.tabs ?? []).length === 0) return null
60
+
61
+ const copyReference = (tab) => {
62
+ const reference = dwTabReference(tab)
63
+ const write = globalThis.navigator?.clipboard?.writeText?.(reference)
64
+ if (write === undefined) {
65
+ store.pushLog('warn', tr('copyUpdateFailed'))
66
+ return
67
+ }
68
+ write
69
+ .then(() => store.pushLog('info', tr('log.copiedReference', { reference })))
70
+ .catch(() => store.pushLog('warn', tr('copyUpdateFailed')))
71
+ }
72
+
73
+ const copyReferenceToChat = (tab) => {
74
+ const reference = dwTabReference(tab)
75
+ const inserted = dwInsertComposerText(`${reference} `)
76
+ const write = globalThis.navigator?.clipboard?.writeText?.(reference)
77
+ if (write !== undefined) write.catch(() => undefined)
78
+ store.pushLog('info', tr(inserted ? 'log.copiedReferenceToChat' : 'log.copiedReferenceOnly', { reference }))
79
+ }
80
+
81
+ const menuItem = (key, icon, label, disabled, run) => h('button', {
82
+ key,
83
+ type: 'button',
84
+ role: 'menuitem',
85
+ className: 'dw-tabmenu-item',
86
+ disabled,
87
+ onClick: () => {
88
+ setMenu(null)
89
+ run()
90
+ },
91
+ }, [
92
+ h('span', { key: 'ic', className: 'dw-tabmenu-icon' }, h(DwIcon, { name: icon, size: 13 })),
93
+ h('span', { key: 'lb', className: 'dw-tabmenu-label' }, label),
94
+ ])
95
+
96
+ const index = menu === null ? -1 : (state.tabs ?? []).findIndex((tab) => tab.id === menu.tab.id)
97
+ const menuLayer = menu === null ? null : h('div', {
98
+ key: 'backdrop',
99
+ className: 'dw-tabmenu-backdrop',
100
+ onPointerDown: () => setMenu(null),
101
+ onContextMenu: (event) => {
102
+ event.preventDefault()
103
+ setMenu(null)
104
+ },
105
+ }, h('div', {
106
+ key: 'menu',
107
+ className: 'dw-tabmenu',
108
+ role: 'menu',
109
+ 'aria-label': tr('tabMenuLabel'),
110
+ style: { left: menu.x, top: menu.y },
111
+ onPointerDown: (event) => event.stopPropagation(),
112
+ }, [
113
+ menuItem('close', 'close', tr('tabClose'), false, () => store.closeTab(menu.tab.id)),
114
+ menuItem('close-others', 'layers', tr('tabCloseOthers'), (state.tabs ?? []).length <= 1, () => store.closeOtherTabs(menu.tab.id)),
115
+ menuItem('close-all', 'stack', tr('tabCloseAll'), false, () => store.closeAllTabs()),
116
+ menuItem('close-left', 'arrow-left', tr('tabCloseLeft'), index <= 0, () => store.closeTabsToLeft(menu.tab.id)),
117
+ menuItem('close-right', 'arrow-right', tr('tabCloseRight'), index < 0 || index >= (state.tabs ?? []).length - 1, () => store.closeTabsToRight(menu.tab.id)),
118
+ h('div', { key: 'sep', className: 'dw-tabmenu-sep' }),
119
+ menuItem('copy-reference', 'copy', tr('copyReference'), false, () => copyReference(menu.tab)),
120
+ menuItem('copy-reference-chat', 'at', tr('copyReferenceToChat'), false, () => copyReferenceToChat(menu.tab)),
121
+ ]))
122
+
123
+ return h(React.Fragment, null, [
124
+ h('div', { key: 'tabs', className: 'dw-tabs', role: 'tablist' }, state.tabs.map((tab) => {
125
+ const active = tab.id === state.activeTab
126
+ return h('div', {
127
+ key: tab.id,
128
+ role: 'tab',
129
+ 'aria-selected': active,
130
+ className: `dw-tab${active ? ' dw-tab-active' : ''}`,
131
+ title: tab.subtitle ?? tab.title,
132
+ onClick: () => store.setActiveTab(tab.id),
133
+ onContextMenu: (event) => {
134
+ event.preventDefault()
135
+ // Keep the menu inside the panel, like the code workspace's menu does.
136
+ const rect = typeof document === 'undefined' ? null : document.querySelector('.dw-root')?.getBoundingClientRect()
137
+ const left = rect === null || rect === undefined ? 8 : Math.max(8, rect.left + 8)
138
+ const top = rect === null || rect === undefined ? 8 : Math.max(8, rect.top + 8)
139
+ const right = (rect === null || rect === undefined ? (globalThis.innerWidth ?? 1200) : rect.right) - 248
140
+ const bottom = (rect === null || rect === undefined ? (globalThis.innerHeight ?? 800) : rect.bottom) - 238
141
+ setMenu({
142
+ x: Math.max(left, Math.min(event.clientX, Math.max(left, right))),
143
+ y: Math.max(top, Math.min(event.clientY, Math.max(top, bottom))),
144
+ tab,
145
+ })
146
+ },
147
+ onAuxClick: (event) => {
148
+ if (event.button === 1) {
149
+ event.preventDefault()
150
+ store.closeTab(tab.id)
151
+ }
152
+ },
153
+ }, [
154
+ h(DwIcon, { key: 'ic', name: 'database', size: 12 }),
155
+ h('span', { key: 'lb', className: 'dw-tab-label' }, tab.title),
156
+ // Several environments can hold a schema of the same name, so the tab says
157
+ // which one it is; the full text stays in the tooltip.
158
+ tab.env !== '' ? h('span', { key: 'env', className: 'dw-badge', style: { marginLeft: 2 } }, tab.env) : null,
159
+ h('button', {
160
+ key: 'cl',
161
+ type: 'button',
162
+ className: 'dw-tab-close',
163
+ title: tr('closeTab'),
164
+ 'aria-label': tr('closeTab'),
165
+ onClick: (event) => {
166
+ event.stopPropagation()
167
+ store.closeTab(tab.id)
168
+ },
169
+ }, h(DwIcon, { name: 'close', size: 10 })),
170
+ ])
171
+ })),
172
+ menuLayer,
173
+ ])
174
+ }
175
+
176
+ /** A draggable horizontal divider that resizes the editor. */
177
+ function DwDragHandle({ value, onChange, min, max }) {
178
+ return h('div', {
179
+ className: 'dw-drag',
180
+ role: 'separator',
181
+ 'aria-orientation': 'horizontal',
182
+ title: '↕',
183
+ onPointerDown: (event) => {
184
+ event.preventDefault()
185
+ const startY = event.clientY
186
+ const startValue = value
187
+ const onMove = (moveEvent) => {
188
+ const next = Math.min(max, Math.max(min, startValue + (moveEvent.clientY - startY)))
189
+ onChange(next)
190
+ }
191
+ const onUp = () => {
192
+ globalThis.removeEventListener('pointermove', onMove)
193
+ globalThis.removeEventListener('pointerup', onUp)
194
+ }
195
+ globalThis.addEventListener('pointermove', onMove)
196
+ globalThis.addEventListener('pointerup', onUp)
197
+ },
198
+ })
199
+ }
200
+
201
+ /** Caret position inside the textarea, measured with an in-place mirror. */
202
+ function dwCaretPoint(area, text, caret) {
203
+ const wrap = area?.parentElement
204
+ if (area === null || area === undefined || wrap === null || wrap === undefined) return { left: 0, top: 0 }
205
+ const style = globalThis.getComputedStyle(area)
206
+ const mirror = document.createElement('div')
207
+ mirror.style.position = 'absolute'
208
+ mirror.style.visibility = 'hidden'
209
+ mirror.style.pointerEvents = 'none'
210
+ mirror.style.top = '0'
211
+ mirror.style.left = '0'
212
+ mirror.style.width = `${area.offsetWidth}px`
213
+ mirror.style.padding = style.padding
214
+ mirror.style.border = style.border
215
+ mirror.style.fontFamily = style.fontFamily
216
+ mirror.style.fontSize = style.fontSize
217
+ mirror.style.fontWeight = style.fontWeight
218
+ mirror.style.letterSpacing = style.letterSpacing
219
+ mirror.style.lineHeight = style.lineHeight
220
+ mirror.style.tabSize = style.tabSize
221
+ mirror.style.whiteSpace = 'pre'
222
+ mirror.style.overflow = 'hidden'
223
+ mirror.textContent = text.slice(0, caret)
224
+ const marker = document.createElement('span')
225
+ marker.textContent = '|'
226
+ mirror.append(marker)
227
+ wrap.append(mirror)
228
+ const left = marker.offsetLeft - area.scrollLeft
229
+ const top = marker.offsetTop - area.scrollTop
230
+ mirror.remove()
231
+ return { left, top }
232
+ }
233
+
234
+ /** The SQL editor: highlighted text, completion and one-keystroke formatting. */
235
+ function DwEditor({ store, tab, tr, onRun, height, schema }) {
236
+ const value = tab.sql ?? ''
237
+ const tokens = useMemo(() => dwSqlLex(value), [value])
238
+ const lines = useMemo(() => value.split('\n').length, [value])
239
+ const gutterRef = useRef(null)
240
+ const areaRef = useRef(null)
241
+ const highlightRef = useRef(null)
242
+ const completionRef = useRef(null)
243
+ const [completion, setCompletion] = useState(null)
244
+ const [editorMenu, setEditorMenu] = useState(null)
245
+ const [optimize, setOptimize] = useState(null)
246
+
247
+ useEffect(() => {
248
+ const area = areaRef.current
249
+ if (area === null) return
250
+ // Focusing on tab activation is the behaviour of every SQL console: the caret
251
+ // lands where the user is about to type.
252
+ area.focus()
253
+ area.setSelectionRange(area.value.length, area.value.length)
254
+ }, [tab.id])
255
+
256
+ // The completion list needs the schema of this database; one round trip, cached
257
+ // by the store. A failure only degrades the list to keywords.
258
+ useEffect(() => {
259
+ void store.loadSchema(tab.dbId)
260
+ }, [tab.dbId, store])
261
+
262
+ const syncScroll = (area) => {
263
+ const gutter = gutterRef.current
264
+ if (gutter !== null) {
265
+ gutter.scrollTop = area.scrollTop
266
+ gutter.scrollLeft = area.scrollLeft
267
+ }
268
+ const highlight = highlightRef.current
269
+ if (highlight !== null) {
270
+ highlight.scrollTop = area.scrollTop
271
+ highlight.scrollLeft = area.scrollLeft
272
+ }
273
+ }
274
+
275
+ const refreshCompletion = (text, caret) => {
276
+ const area = areaRef.current
277
+ if (area === null) return
278
+ const result = dwSqlCompletion(text, caret, schema)
279
+ const afterDot = /[A-Za-z0-9_$`]\.$/.test(text.slice(0, caret))
280
+ if (result.items.length === 0 || (result.prefix === '' && !afterDot)) {
281
+ setCompletion(null)
282
+ return
283
+ }
284
+ const point = dwCaretPoint(area, text, caret)
285
+ setCompletion({ ...result, index: 0, left: point.left, top: point.top + 20 })
286
+ }
287
+
288
+ // The schema map starts loading when the tab opens; a fast typist can type a whole
289
+ // word before it lands, which used to leave the list closed until the next key.
290
+ // Re-evaluate the caret once the map arrives so the popup appears on its own.
291
+ useEffect(() => {
292
+ if (schema === undefined) return
293
+ const area = areaRef.current
294
+ if (area === null || document.activeElement !== area) return
295
+ refreshCompletion(value, area.selectionStart)
296
+ }, [schema])
297
+
298
+ // Arrow keys move the highlight through a list that can be taller than its box;
299
+ // scroll just the popup so the selected row never disappears below the fold.
300
+ useEffect(() => {
301
+ const popup = completionRef.current
302
+ if (popup === null || completion === null) return
303
+ const active = popup.querySelector('.dw-complete-row.active')
304
+ if (active === null) return
305
+ const top = active.offsetTop
306
+ const bottom = top + active.offsetHeight
307
+ if (top < popup.scrollTop) popup.scrollTop = top
308
+ else if (bottom > popup.scrollTop + popup.clientHeight) popup.scrollTop = bottom - popup.clientHeight
309
+ }, [completion])
310
+
311
+ const applyCompletion = (item) => {
312
+ const current = completion
313
+ if (current === null || item === undefined) return
314
+ const next = `${value.slice(0, current.from)}${item.label}${value.slice(current.to)}`
315
+ const position = current.from + item.label.length
316
+ store.setTabSql(tab.id, next)
317
+ setCompletion(null)
318
+ requestAnimationFrame(() => {
319
+ const area = areaRef.current
320
+ if (area === null) return
321
+ area.focus()
322
+ area.setSelectionRange(position, position)
323
+ })
324
+ }
325
+
326
+ const runStatement = () => {
327
+ const area = areaRef.current
328
+ const selected = area !== null && area.selectionEnd > area.selectionStart
329
+ ? value.slice(area.selectionStart, area.selectionEnd)
330
+ : ''
331
+ onRun(selected.trim() === '' ? undefined : selected)
332
+ }
333
+
334
+ // The right-click menu replaces the browser's own so it can offer the same
335
+ // editing commands plus the model. Clipboard writes/reads go through the async
336
+ // API; undo/redo keep using the textarea's native history.
337
+ const editorMenuAction = (run) => () => {
338
+ setEditorMenu(null)
339
+ run()
340
+ }
341
+
342
+ const editorCommand = (command) => {
343
+ const area = areaRef.current
344
+ if (area === null) return
345
+ area.focus()
346
+ try {
347
+ document.execCommand(command)
348
+ } catch (error) {
349
+ void error
350
+ }
351
+ }
352
+
353
+ const editorCopy = () => {
354
+ const area = areaRef.current
355
+ if (area === null) return
356
+ const selected = area.selectionEnd > area.selectionStart ? value.slice(area.selectionStart, area.selectionEnd) : value
357
+ const write = globalThis.navigator?.clipboard?.writeText?.(selected)
358
+ if (write !== undefined) write.catch(() => undefined)
359
+ }
360
+
361
+ const editorCut = () => {
362
+ const area = areaRef.current
363
+ if (area === null) return
364
+ const start = area.selectionStart
365
+ const end = area.selectionEnd
366
+ if (end <= start) return
367
+ editorCopy()
368
+ store.setTabSql(tab.id, `${value.slice(0, start)}${value.slice(end)}`)
369
+ requestAnimationFrame(() => {
370
+ const next = areaRef.current
371
+ if (next === null) return
372
+ next.focus()
373
+ next.setSelectionRange(start, start)
374
+ })
375
+ }
376
+
377
+ const editorPaste = async () => {
378
+ const area = areaRef.current
379
+ if (area === null) return
380
+ const read = globalThis.navigator?.clipboard?.readText
381
+ if (typeof read !== 'function') {
382
+ store.pushLog('warn', tr('editorPasteBlocked'))
383
+ return
384
+ }
385
+ try {
386
+ const text = await read.call(globalThis.navigator.clipboard)
387
+ if (typeof text !== 'string' || text === '') return
388
+ const start = area.selectionStart
389
+ const end = area.selectionEnd
390
+ store.setTabSql(tab.id, `${value.slice(0, start)}${text}${value.slice(end)}`)
391
+ requestAnimationFrame(() => {
392
+ const next = areaRef.current
393
+ if (next === null) return
394
+ next.focus()
395
+ next.setSelectionRange(start + text.length, start + text.length)
396
+ })
397
+ } catch (error) {
398
+ void error
399
+ store.pushLog('warn', tr('editorPasteBlocked'))
400
+ }
401
+ }
402
+
403
+ const editorSelectAll = () => {
404
+ const area = areaRef.current
405
+ if (area === null) return
406
+ area.focus()
407
+ area.select()
408
+ }
409
+
410
+ const openOptimize = () => {
411
+ const area = areaRef.current
412
+ const selected = area !== null && area.selectionEnd > area.selectionStart
413
+ ? value.slice(area.selectionStart, area.selectionEnd)
414
+ : ''
415
+ const text = selected.trim() === '' ? value.trim() : selected.trim()
416
+ if (text === '') {
417
+ store.pushLog('warn', tr('log.noStatement'))
418
+ return
419
+ }
420
+ setOptimize({ sql: text, database: tab.database })
421
+ }
422
+
423
+ const menuItem = (key, label, shortcut, run) => h('button', {
424
+ key,
425
+ type: 'button',
426
+ className: 'dw-menu-item',
427
+ onClick: editorMenuAction(run),
428
+ }, [
429
+ h('span', { key: 'l' }, label),
430
+ shortcut === '' ? null : h('span', { key: 's', className: 'dw-menu-shortcut' }, shortcut),
431
+ ])
432
+
433
+ const format = () => {
434
+ const formatted = dwFormatSql(value)
435
+ if (formatted === value) return
436
+ store.setTabSql(tab.id, formatted)
437
+ requestAnimationFrame(() => areaRef.current?.focus())
438
+ }
439
+
440
+ const gutter = []
441
+ for (let index = 1; index <= Math.max(lines, 1); index += 1) gutter.push(`${index}\n`)
442
+
443
+ const bar = h('div', { key: 'bar', className: 'dw-editor-bar' }, [
444
+ h('span', { key: 'db', style: { color: 'var(--dsw-alias-label-primary)', fontWeight: 600 } }, tab.database),
445
+ h('span', { key: 'env' }, tab.subtitle ?? ''),
446
+ h('span', { key: 'sp', className: 'dw-spacer' }),
447
+ h('button', {
448
+ key: 'format',
449
+ type: 'button',
450
+ className: 'dw-btn',
451
+ title: tr('formatSqlHint'),
452
+ onClick: format,
453
+ }, [h(DwIcon, { key: 'i', name: 'format', size: 11 }), h('span', { key: 't' }, tr('formatSql'))]),
454
+ h('span', { key: 'hint', style: { fontSize: 11 } }, tr('runHint')),
455
+ h('button', {
456
+ key: 'run',
457
+ type: 'button',
458
+ className: 'dw-btn dw-btn-accent',
459
+ disabled: tab.running === true,
460
+ title: tr('runHint'),
461
+ onClick: runStatement,
462
+ }, [
463
+ h(DwIcon, { key: 'i', name: tab.running === true ? 'spinner' : 'play', size: 11 }),
464
+ h('span', { key: 't' }, tab.running === true ? tr('running') : tr('run')),
465
+ ]),
466
+ ])
467
+
468
+ const editorMenuLayer = editorMenu === null ? null : h(React.Fragment, null, [
469
+ h('div', {
470
+ key: 'backdrop',
471
+ className: 'dw-backdrop',
472
+ onClick: () => setEditorMenu(null),
473
+ onContextMenu: (event) => {
474
+ event.preventDefault()
475
+ setEditorMenu(null)
476
+ },
477
+ }),
478
+ h('div', { key: 'menu', className: 'dw-menu', style: { left: editorMenu.x, top: editorMenu.y } }, [
479
+ menuItem('undo', tr('editorUndo'), '⌘Z', () => editorCommand('undo')),
480
+ menuItem('redo', tr('editorRedo'), '⇧⌘Z', () => editorCommand('redo')),
481
+ h('div', { key: 'sep1', className: 'dw-project-sep' }),
482
+ menuItem('cut', tr('editorCut'), '⌘X', editorCut),
483
+ menuItem('copy', tr('editorCopy'), '⌘C', editorCopy),
484
+ menuItem('paste', tr('editorPaste'), '⌘V', () => void editorPaste()),
485
+ menuItem('select-all', tr('editorSelectAll'), '⌘A', editorSelectAll),
486
+ h('div', { key: 'sep2', className: 'dw-project-sep' }),
487
+ menuItem('optimize', tr('sqlOptimize'), '', openOptimize),
488
+ ]),
489
+ ])
490
+
491
+ return h('div', { className: 'dw-editor-wrap', style: { height } }, [
492
+ bar,
493
+ h('div', { key: 'editor', className: 'dw-editor' }, [
494
+ h('div', {
495
+ key: 'gutter',
496
+ className: 'dw-gutter',
497
+ ref: gutterRef,
498
+ 'aria-hidden': true,
499
+ }, gutter.join('')),
500
+ h('div', { key: 'wrap', className: 'dw-code-wrap' }, [
501
+ h('pre', { key: 'hl', className: 'dw-code-highlight', ref: highlightRef, 'aria-hidden': true },
502
+ tokens.map((token, index) => (token.type === 'space'
503
+ ? token.value
504
+ : h('span', { key: index, className: `dw-tok-${token.type}` }, token.value)))),
505
+ h('textarea', {
506
+ key: 'area',
507
+ ref: areaRef,
508
+ className: 'dw-code',
509
+ value,
510
+ spellCheck: false,
511
+ placeholder: tr('sqlPlaceholder'),
512
+ onChange: (event) => {
513
+ const text = event.target.value
514
+ const caret = event.target.selectionStart
515
+ store.setTabSql(tab.id, text)
516
+ refreshCompletion(text, caret)
517
+ },
518
+ onClick: (event) => refreshCompletion(event.target.value, event.target.selectionStart),
519
+ onContextMenu: (event) => {
520
+ event.preventDefault()
521
+ const width = 210
522
+ const height = 268
523
+ const maxX = (globalThis.innerWidth ?? 1200) - width
524
+ const maxY = (globalThis.innerHeight ?? 800) - height
525
+ setEditorMenu({
526
+ x: Math.max(8, Math.min(event.clientX, maxX)),
527
+ y: Math.max(8, Math.min(event.clientY, maxY)),
528
+ })
529
+ },
530
+ onBlur: () => setCompletion(null),
531
+ onScroll: (event) => syncScroll(event.target),
532
+ onKeyDown: (event) => {
533
+ const modifier = event.metaKey || event.ctrlKey
534
+ if (completion !== null) {
535
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
536
+ event.preventDefault()
537
+ const size = completion.items.length
538
+ const delta = event.key === 'ArrowDown' ? 1 : -1
539
+ setCompletion({ ...completion, index: (completion.index + delta + size) % size })
540
+ return
541
+ }
542
+ if ((event.key === 'Enter' && !modifier) || event.key === 'Tab') {
543
+ event.preventDefault()
544
+ applyCompletion(completion.items[completion.index])
545
+ return
546
+ }
547
+ if (event.key === 'Escape') {
548
+ event.preventDefault()
549
+ setCompletion(null)
550
+ return
551
+ }
552
+ }
553
+ if (modifier && event.key === 'Enter') {
554
+ event.preventDefault()
555
+ runStatement()
556
+ return
557
+ }
558
+ if (modifier && event.key === ' ') {
559
+ event.preventDefault()
560
+ refreshCompletion(value, event.target.selectionStart)
561
+ return
562
+ }
563
+ if (event.key === 'Tab' && !event.shiftKey && !modifier) {
564
+ event.preventDefault()
565
+ const area = event.target
566
+ const start = area.selectionStart
567
+ const end = area.selectionEnd
568
+ const next = `${value.slice(0, start)} ${value.slice(end)}`
569
+ store.setTabSql(tab.id, next)
570
+ requestAnimationFrame(() => {
571
+ area.setSelectionRange(start + 2, start + 2)
572
+ })
573
+ }
574
+ },
575
+ }),
576
+ completion === null
577
+ ? null
578
+ : h('div', {
579
+ key: 'ac',
580
+ ref: completionRef,
581
+ className: 'dw-complete',
582
+ style: { left: completion.left, top: completion.top },
583
+ role: 'listbox',
584
+ }, completion.items.map((item, index) => h('div', {
585
+ key: `${item.kind}:${item.label}`,
586
+ role: 'option',
587
+ 'aria-selected': index === completion.index,
588
+ className: index === completion.index ? 'dw-complete-row active' : 'dw-complete-row',
589
+ onMouseDown: (event) => event.preventDefault(),
590
+ onClick: () => applyCompletion(item),
591
+ }, [
592
+ h('span', { key: 'l', className: 'dw-complete-label' }, item.label),
593
+ h('span', { key: 'd', className: 'dw-complete-detail' }, item.detail ?? ''),
594
+ h('span', { key: 'k', className: 'dw-complete-kind' }, item.kind === 'column' ? tr('suggestColumn') : item.kind === 'table' ? tr('suggestTable') : tr('suggestKeyword')),
595
+ ]))),
596
+ ]),
597
+ ]),
598
+ editorMenuLayer,
599
+ optimize === null ? null : h(DwSqlOptimizeDialog, {
600
+ key: 'optimize',
601
+ store,
602
+ tr,
603
+ sql: optimize.sql,
604
+ database: optimize.database,
605
+ onClose: () => setOptimize(null),
606
+ }),
607
+ ])
608
+ }
609
+
610
+ /** The create statement as a dialog: copy it and close, no work tab involved. */
611
+ function DwDdlDialog({ node, tr, store, onClose }) {
612
+ const allTables = node.kind === 'database'
613
+ const [phase, setPhase] = useState('loading')
614
+ const [ddl, setDdl] = useState('')
615
+ const [error, setError] = useState('')
616
+ const [progress, setProgress] = useState({ done: 0, total: 0 })
617
+ const [failureCount, setFailureCount] = useState(0)
618
+ const [count, setCount] = useState(0)
619
+
620
+ useEffect(() => {
621
+ let alive = true
622
+ const fail = (failure, name) => {
623
+ if (!alive) return
624
+ const message = dwExplainFailure(tr, failure)
625
+ setError(message)
626
+ setPhase('error')
627
+ store.pushLog('error', tr('log.loadFailed', { name, message }))
628
+ }
629
+
630
+ const loadTable = async () => {
631
+ try {
632
+ const value = await dwRpc('ddl', { id: node.dbId, table: node.table })
633
+ if (!alive) return
634
+ setDdl(String(value?.ddl ?? ''))
635
+ setCount(1)
636
+ setPhase('done')
637
+ store.pushLog('info', tr('log.ddl', { table: node.table, ms: dwDuration(value?.statementTime ?? 0) }))
638
+ } catch (failure) {
639
+ fail(failure, node.table)
640
+ }
641
+ }
642
+
643
+ // A whole database: list the tables, then read each statement in turn so the
644
+ // dialog can show progress and a closed dialog stops issuing round trips.
645
+ const loadDatabase = async () => {
646
+ const startedAt = Date.now()
647
+ try {
648
+ const listed = await dwRpc('tables', { id: node.dbId })
649
+ if (!alive) return
650
+ const names = (Array.isArray(listed?.tables) ? listed.tables : [])
651
+ .map((table) => String(table?.name ?? ''))
652
+ .filter((name) => name !== '')
653
+ setProgress({ done: 0, total: names.length })
654
+ const parts = []
655
+ const failures = []
656
+ for (let index = 0; index < names.length; index += 1) {
657
+ if (!alive) return
658
+ try {
659
+ const value = await dwRpc('ddl', { id: node.dbId, table: names[index] })
660
+ const text = String(value?.ddl ?? '').trim().replace(/;+$/, '')
661
+ if (text !== '') parts.push(`-- ${names[index]}\n${text};`)
662
+ } catch (failure) {
663
+ failures.push(`${names[index]}: ${dwExplainFailure(tr, failure).replace(/\s+/g, ' ')}`)
664
+ }
665
+ if (alive) setProgress({ done: index + 1, total: names.length })
666
+ }
667
+ if (!alive) return
668
+ const failedBlock = failures.length === 0 ? '' : failures.map((line) => `-- ${line}`).join('\n')
669
+ setDdl([...parts, failedBlock].filter((part) => part !== '').join('\n\n'))
670
+ setCount(parts.length)
671
+ setFailureCount(failures.length)
672
+ setPhase('done')
673
+ store.pushLog('info', tr('log.ddlAll', { database: node.database, count: parts.length, ms: Date.now() - startedAt }))
674
+ } catch (failure) {
675
+ fail(failure, node.database)
676
+ }
677
+ }
678
+
679
+ if (allTables) void loadDatabase()
680
+ else void loadTable()
681
+ return () => { alive = false }
682
+ }, [])
683
+
684
+ const loadingHint = allTables && progress.total > 0
685
+ ? `${tr('ddlLoading')} ${progress.done}/${progress.total}`
686
+ : tr('ddlLoading')
687
+ const body = phase === 'loading'
688
+ ? h('div', { key: 'loading', className: 'dw-empty', style: { minHeight: 120 } }, [
689
+ h(DwIcon, { key: 'i', name: 'spinner', size: 18 }),
690
+ h('div', { key: 't', className: 'dw-empty-hint' }, loadingHint),
691
+ ])
692
+ : phase === 'error'
693
+ ? h('div', { key: 'error' }, [
694
+ h('div', { key: 't', className: 'dw-empty-title', style: { color: 'var(--dsw-alias-state-error-primary)', fontSize: 12 } }, tr('ddlFailed')),
695
+ h('div', { key: 'm', className: 'dw-error-text' }, error),
696
+ ])
697
+ : h('div', { key: 'done', className: 'dw-ddl-result' }, [
698
+ failureCount > 0
699
+ ? h('div', { key: 'warn', className: 'dw-log-warn' }, tr('ddlAllPartial', { count: failureCount }))
700
+ : null,
701
+ h('pre', { key: 'ddl', className: 'dw-cell-view dw-ddl-code' },
702
+ ddl === '' ? tr(allTables ? 'ddlAllEmpty' : 'ddlEmpty') : ddl),
703
+ ])
704
+
705
+ return h('div', { className: 'dw-modal', onClick: onClose }, h('div', {
706
+ key: 'card',
707
+ className: 'dw-modal-card dw-ddl-dialog',
708
+ onClick: (event) => event.stopPropagation(),
709
+ }, [
710
+ h('div', { key: 'title', className: 'dw-modal-title' }, [
711
+ h(DwIcon, { key: 'i', name: 'ddl', size: 13 }),
712
+ h('span', { key: 't' }, tr(allTables ? 'menuDdlAll' : 'menuDdl')),
713
+ h('span', { key: 'p', style: { color: 'var(--dsw-alias-label-secondary)', fontWeight: 400, fontSize: 11 } },
714
+ [node.env, node.database, node.table].filter((part) => typeof part === 'string' && part !== '').join(' / ')),
715
+ ]),
716
+ h('div', { key: 'body', className: 'dw-modal-body' }, body),
717
+ h('div', { key: 'foot', className: 'dw-modal-foot' }, [
718
+ phase === 'done' && ddl !== ''
719
+ ? h('button', {
720
+ key: 'copy',
721
+ type: 'button',
722
+ className: 'dw-btn',
723
+ onClick: () => {
724
+ const write = globalThis.navigator?.clipboard?.writeText?.(ddl)
725
+ if (write === undefined) {
726
+ store.pushLog('warn', tr('copyUpdateFailed'))
727
+ return
728
+ }
729
+ write
730
+ .then(() => store.pushLog('info', allTables
731
+ ? tr('log.copiedDdlAll', { database: node.database, count })
732
+ : tr('log.copiedDdl', { table: node.table })))
733
+ .catch(() => store.pushLog('warn', tr('copyUpdateFailed')))
734
+ },
735
+ }, [h(DwIcon, { key: 'i', name: 'copy', size: 11 }), h('span', { key: 't' }, tr('copyDdl'))])
736
+ : null,
737
+ h('button', { key: 'close', type: 'button', className: 'dw-btn dw-btn-accent', onClick: onClose }, tr('close')),
738
+ ]),
739
+ ]))
740
+ }
741
+
742
+ export { DwTabs, DwEditor, DwDdlDialog, DwDragHandle }