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,768 @@
1
+ /**
2
+ * Panel and workspace binding.
3
+ *
4
+ * Requirement 1 is "opening a workspace loads its own configuration". A global main
5
+ * panel is not a conversation, so the panel cannot read the Session on screen at
6
+ * paint time; a headless tracker in the frame's overlay layer remembers the Session
7
+ * — and therefore the Workspace — while the Conversation still holds the column,
8
+ * and the store follows whatever that tracker last saw.
9
+ */
10
+
11
+ /** Bounds for the editor/document split, in pixels. */
12
+ const DW_EDITOR_MIN = 88
13
+ const DW_EDITOR_MAX = 620
14
+
15
+ /** Bounds for the explorer column, in pixels. */
16
+ const DW_SIDE_MIN = 200
17
+ const DW_SIDE_MAX = 720
18
+ const DW_SIDE_DEFAULT = 268
19
+ const DW_SIDE_KEY = 'dsh-data-window:side-width'
20
+
21
+ /** Wide layouts collapse the navigation column; below this the toggle is a drawer. */
22
+ const DW_WIDE_LAYOUT = 1024
23
+
24
+ /** Last path segment, used when a Workspace has no title. */
25
+ function dwBasename(path) {
26
+ const parts = String(path ?? '').split('/').filter((part) => part !== '')
27
+ return parts.length === 0 ? String(path ?? '') : parts[parts.length - 1]
28
+ }
29
+
30
+ /** `~/Documents/x` instead of an absolute home path. */
31
+ function dwShortPath(path) {
32
+ return String(path ?? '').replace(/^\/(?:Users|home)\/[^/]+\//, '~/')
33
+ }
34
+
35
+ /** Stored explorer width, clamped so a bad value cannot hide the tree. */
36
+ function dwReadSideWidth() {
37
+ const raw = Number(globalThis.localStorage?.getItem(DW_SIDE_KEY))
38
+ if (!Number.isFinite(raw) || raw <= 0) return DW_SIDE_DEFAULT
39
+ return Math.min(DW_SIDE_MAX, Math.max(DW_SIDE_MIN, raw))
40
+ }
41
+
42
+ /**
43
+ * Whether the shell's navigation column is collapsed.
44
+ *
45
+ * `layout.toggleSidebar()` is a bare toggle with no readable state, so the frame's
46
+ * own marker is the only way to avoid flipping a column the user had already
47
+ * folded.
48
+ */
49
+ function dwSidebarCollapsed() {
50
+ try {
51
+ const layer = document.querySelector('[data-shell-overlay]')
52
+ const frame = layer === null ? null : layer.parentElement
53
+ return frame === null ? false : frame.hasAttribute('data-sidebar-collapsed')
54
+ } catch (error) {
55
+ void error
56
+ return false
57
+ }
58
+ }
59
+
60
+ /** Fold the navigation column; false when it was already folded or unavailable. */
61
+ function dwHideSidebar(store) {
62
+ const layout = store.layout?.()
63
+ if (layout === undefined || typeof layout.toggleSidebar !== 'function') return false
64
+ if ((Number(globalThis.innerWidth) || 0) < DW_WIDE_LAYOUT) return false
65
+ if (dwSidebarCollapsed()) return false
66
+ layout.toggleSidebar()
67
+ return true
68
+ }
69
+
70
+ /** Unfold the navigation column, but only when it is still folded. */
71
+ function dwShowSidebar(store) {
72
+ const layout = store.layout?.()
73
+ if (layout === undefined || typeof layout.toggleSidebar !== 'function') return
74
+ if (!dwSidebarCollapsed()) return
75
+ layout.toggleSidebar()
76
+ try {
77
+ globalThis.dispatchEvent(new Event('resize'))
78
+ } catch (error) {
79
+ void error
80
+ }
81
+ }
82
+
83
+ /** The workspace a Session belongs to, tolerating both snapshot spellings. */
84
+ function dwResolveRoot(sessionsState, workspacesState) {
85
+ const byId = sessionsState?.byId ?? {}
86
+ const ids = Array.isArray(sessionsState?.ids) ? sessionsState.ids : []
87
+ const workspaceItems = Array.isArray(workspacesState?.items) ? workspacesState.items : []
88
+
89
+ const candidates = []
90
+ for (const id of ids) {
91
+ const row = byId[id]
92
+ if (row === undefined) continue
93
+ const retained = Number(row.retainedBy?.mainView ?? 0)
94
+ const cwd = typeof row.cwd === 'string' ? row.cwd : ''
95
+ candidates.push({ id, retained: Number.isFinite(retained) ? retained : 0, cwd })
96
+ }
97
+ candidates.sort((left, right) => right.retained - left.retained)
98
+
99
+ for (const candidate of candidates) {
100
+ const workspace = workspaceItems.find((item) => {
101
+ const sessionIds = Array.isArray(item?.sessionIds) ? item.sessionIds : []
102
+ return sessionIds.includes(candidate.id)
103
+ })
104
+ const fromWorkspace = typeof workspace?.path === 'string' ? workspace.path : ''
105
+ if (fromWorkspace !== '') return fromWorkspace
106
+ if (candidate.cwd !== '') return candidate.cwd
107
+ }
108
+ // No Session yet (a fresh window): the first Workspace is the best answer.
109
+ const first = workspaceItems.find((item) => typeof item?.path === 'string' && item.path !== '')
110
+ return typeof first?.path === 'string' ? first.path : ''
111
+ }
112
+
113
+ /** Headless entry that keeps the resolved workspace in the store. */
114
+ function DwTracker({ store, useSessions, useWorkspaces }) {
115
+ const selectSessions = typeof useSessions === 'function' ? useSessions : () => undefined
116
+ const selectWorkspaces = typeof useWorkspaces === 'function' ? useWorkspaces : () => undefined
117
+ const sessions = selectSessions((snapshot) => snapshot)
118
+ const workspaces = selectWorkspaces((snapshot) => snapshot)
119
+ const root = dwResolveRoot(sessions, workspaces)
120
+ useEffect(() => {
121
+ if (root === '') return
122
+ store.setDetectedRoot(root)
123
+ }, [root, store])
124
+ return null
125
+ }
126
+
127
+ /** The workspace chip and its menu: switching here re-roots the window in place. */
128
+ function DwProjectMenu({ state, projects, tr, onSelect, onFollow }) {
129
+ const [open, setOpen] = useState(false)
130
+ const root = state.root === '' ? '' : state.root.replace(/\/+$/, '')
131
+ const current = projects.find((item) => item.path === root)
132
+ const label = current === undefined
133
+ ? (state.root === '' ? tr('noWorkspace') : dwBasename(state.root))
134
+ : current.title
135
+
136
+ useEffect(() => {
137
+ if (!open) return undefined
138
+ const onDown = (event) => {
139
+ const element = event.target
140
+ if (element instanceof Element && element.closest('.dw-project') !== null) return
141
+ setOpen(false)
142
+ }
143
+ globalThis.addEventListener('pointerdown', onDown, true)
144
+ return () => globalThis.removeEventListener('pointerdown', onDown, true)
145
+ }, [open])
146
+
147
+ return h('div', { className: 'dw-project' }, [
148
+ h('button', {
149
+ key: 'btn',
150
+ type: 'button',
151
+ className: 'dw-project-btn',
152
+ title: tr('projectSwitch'),
153
+ 'aria-label': tr('projectSwitch'),
154
+ onClick: () => setOpen(!open),
155
+ }, [
156
+ h('span', { key: 'nm', className: 'dw-project-name' }, label),
157
+ h('span', { key: 'c', className: 'dw-project-caret' }, '\u25be'),
158
+ ]),
159
+ open
160
+ ? h('div', { key: 'menu', className: 'dw-project-menu', role: 'menu' }, [
161
+ h('button', {
162
+ key: '__follow',
163
+ type: 'button',
164
+ role: 'menuitem',
165
+ className: state.manual === true ? 'dw-project-row' : 'dw-project-row active',
166
+ onClick: () => {
167
+ setOpen(false)
168
+ if (state.manual === true) onFollow()
169
+ },
170
+ }, tr('followWorkspace')),
171
+ h('div', { key: '__sep', className: 'dw-project-sep' }),
172
+ ...projects.map((item) => h('button', {
173
+ key: item.path,
174
+ type: 'button',
175
+ role: 'menuitem',
176
+ className: item.path === root ? 'dw-project-row active' : 'dw-project-row',
177
+ title: item.path,
178
+ onClick: () => {
179
+ setOpen(false)
180
+ if (item.path !== root) onSelect(item.path)
181
+ },
182
+ }, [
183
+ h('span', { key: 't', className: 'dw-project-row-title' }, item.title),
184
+ h('span', { key: 'p', className: 'dw-project-row-path' }, dwShortPath(item.path)),
185
+ ])),
186
+ ])
187
+ : null,
188
+ ])
189
+ }
190
+
191
+ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }) {
192
+ const tr = typeof translate === 'function' ? translate : (key) => key
193
+ const state = useSyncExternalStore(store.subscribe, store.getState, store.getState)
194
+ const [menu, setMenu] = useState(null)
195
+ const [editorHeight, setEditorHeight] = useState(168)
196
+ const [sideWidth, setSideWidth] = useState(() => dwReadSideWidth())
197
+ const [sidebarHidden, setSidebarHidden] = useState(false)
198
+ const [aiOpen, setAiOpen] = useState(false)
199
+ const [manualOpen, setManualOpen] = useState(false)
200
+ const [schemaTarget, setSchemaTarget] = useState(null)
201
+ const [ddlTarget, setDdlTarget] = useState(null)
202
+ const [renameTarget, setRenameTarget] = useState(null)
203
+ const [removeEnvTarget, setRemoveEnvTarget] = useState(null)
204
+ const aiPrompted = useRef(false)
205
+ const panelRef = useRef(null)
206
+ const logRef = useRef(null)
207
+ const sideWidthRef = useRef(sideWidth)
208
+ const sidebarHiddenRef = useRef(false)
209
+
210
+ // The tracker in the overlay reports first; these hooks read the same data, so
211
+ // whichever mounted first decides, and a Workspace switch updates both.
212
+ const selectSessions = typeof useSessions === 'function' ? useSessions : () => undefined
213
+ const selectWorkspaces = typeof useWorkspaces === 'function' ? useWorkspaces : () => undefined
214
+ const sessions = selectSessions((snapshot) => snapshot)
215
+ const workspaces = selectWorkspaces((snapshot) => snapshot)
216
+ const detected = dwResolveRoot(sessions, workspaces)
217
+
218
+ useEffect(() => {
219
+ if (detected !== '') store.setDetectedRoot(detected)
220
+ }, [detected, store])
221
+
222
+ // First open of a workspace the rule-based scan cannot read: offer the model
223
+ // picker instead of leaving the user with an empty tree and no next step. It
224
+ // asks once per mount and only while no model has been chosen yet.
225
+ useEffect(() => {
226
+ if (aiPrompted.current) return
227
+ if (state.root === '' || state.phase !== 'empty') return
228
+ if (dwAiModel() !== null) return
229
+ aiPrompted.current = true
230
+ setAiOpen(true)
231
+ }, [state.phase, state.root])
232
+
233
+ // Requirement: entering the window folds the shell's navigation column, so the
234
+ // explorer and the workbench get the whole frame. Leaving unfolds it again, but
235
+ // only if it is still folded.
236
+ useEffect(() => {
237
+ // The settings page can keep the shell's navigation column where it is; the
238
+ // toolbar button still folds it on demand.
239
+ if (dwReadPrefs().autoHideSidebar === false) return undefined
240
+ if (dwHideSidebar(store)) {
241
+ sidebarHiddenRef.current = true
242
+ setSidebarHidden(true)
243
+ }
244
+ return () => {
245
+ if (!sidebarHiddenRef.current) return
246
+ sidebarHiddenRef.current = false
247
+ dwShowSidebar(store)
248
+ }
249
+ }, [store])
250
+
251
+ const toggleSidebar = () => {
252
+ if (sidebarHiddenRef.current || dwSidebarCollapsed()) {
253
+ sidebarHiddenRef.current = false
254
+ setSidebarHidden(false)
255
+ dwShowSidebar(store)
256
+ return
257
+ }
258
+ if (dwHideSidebar(store)) {
259
+ sidebarHiddenRef.current = true
260
+ setSidebarHidden(true)
261
+ }
262
+ }
263
+
264
+ // Drag the divider between the explorer and the workbench; the width is stored
265
+ // per browser because it is a reading preference, not a per-project fact.
266
+ const startSideResize = (event) => {
267
+ if (event.button !== 0) return
268
+ event.preventDefault()
269
+ const startX = event.clientX
270
+ const startWidth = sideWidthRef.current
271
+ const panelWidth = panelRef.current?.getBoundingClientRect?.().width ?? globalThis.innerWidth
272
+ const max = Math.max(DW_SIDE_MIN + 40, Math.min(DW_SIDE_MAX, panelWidth - 360))
273
+ const previousSelect = document.body.style.userSelect
274
+ document.body.style.userSelect = 'none'
275
+ const move = (moveEvent) => {
276
+ const width = Math.min(max, Math.max(DW_SIDE_MIN, startWidth + moveEvent.clientX - startX))
277
+ sideWidthRef.current = width
278
+ setSideWidth(width)
279
+ }
280
+ const stop = () => {
281
+ globalThis.removeEventListener('pointermove', move)
282
+ globalThis.removeEventListener('pointerup', stop)
283
+ document.body.style.userSelect = previousSelect
284
+ globalThis.localStorage?.setItem(DW_SIDE_KEY, String(sideWidthRef.current))
285
+ }
286
+ globalThis.addEventListener('pointermove', move)
287
+ globalThis.addEventListener('pointerup', stop)
288
+ }
289
+
290
+ const resetSideWidth = () => {
291
+ sideWidthRef.current = DW_SIDE_DEFAULT
292
+ setSideWidth(DW_SIDE_DEFAULT)
293
+ globalThis.localStorage?.setItem(DW_SIDE_KEY, String(DW_SIDE_DEFAULT))
294
+ }
295
+
296
+ // Requirement 3: one keystroke from the selected table to its create statement.
297
+ useEffect(() => {
298
+ const onKey = (event) => {
299
+ const modifier = event.metaKey || event.ctrlKey
300
+ const isDdl = event.key === 'F4' || (modifier && event.shiftKey && (event.key === 'd' || event.key === 'D'))
301
+ if (!isDdl) return
302
+ const selected = store.getState().selectedNode
303
+ if (selected === null || selected === undefined) return
304
+ if (selected.kind !== 'table' && selected.kind !== 'view' && selected.kind !== 'database') return
305
+ event.preventDefault()
306
+ event.stopPropagation()
307
+ setDdlTarget(selected)
308
+ }
309
+ globalThis.addEventListener('keydown', onKey, true)
310
+ return () => globalThis.removeEventListener('keydown', onKey, true)
311
+ }, [store])
312
+
313
+ // Escape closes the context menu, the same way the shipped menus behave.
314
+ useEffect(() => {
315
+ if (menu === null) return
316
+ const onKey = (event) => {
317
+ if (event.key === 'Escape') setMenu(null)
318
+ }
319
+ globalThis.addEventListener('keydown', onKey)
320
+ return () => globalThis.removeEventListener('keydown', onKey)
321
+ }, [menu])
322
+
323
+ // The log follows the newest line while it is open; a user who scrolled up is
324
+ // left where they are, because the next line would otherwise yank them away.
325
+ useEffect(() => {
326
+ const node = logRef.current
327
+ if (node === null || state.logOpen !== true) return
328
+ node.scrollTop = node.scrollHeight
329
+ }, [state.log, state.logOpen])
330
+
331
+ const activeTab = (state.tabs ?? []).find((tab) => tab.id === state.activeTab)
332
+ const environments = state.environments ?? []
333
+ // The palette is owned by the code workspace; watch it so switching there
334
+ // recolours this panel without a reload.
335
+ const themeId = useSyncExternalStore(dwSubscribeTheme, dwSharedTheme, dwSharedTheme)
336
+ useEffect(() => { dwWatchTheme() }, [])
337
+
338
+ // Every Workspace the shell knows, plus the current root when it is not a
339
+ // registered Workspace yet (a directory picked by hand).
340
+ const projectItems = []
341
+ const seenProjectPaths = new Set()
342
+ for (const item of Array.isArray(workspaces?.items) ? workspaces.items : []) {
343
+ const path = typeof item?.path === 'string' ? item.path.replace(/\/+$/, '') : ''
344
+ if (path === '' || seenProjectPaths.has(path)) continue
345
+ seenProjectPaths.add(path)
346
+ const title = typeof item?.title === 'string' && item.title.trim() !== '' ? item.title.trim() : dwBasename(path)
347
+ projectItems.push({ path, title })
348
+ }
349
+ const currentRoot = state.root === '' ? '' : state.root.replace(/\/+$/, '')
350
+ if (currentRoot !== '' && !seenProjectPaths.has(currentRoot)) {
351
+ projectItems.unshift({ path: currentRoot, title: dwBasename(currentRoot) })
352
+ }
353
+
354
+ const pickWorkspace = async () => {
355
+ if (typeof pickDirectory !== 'function') return
356
+ try {
357
+ const picked = await pickDirectory()
358
+ if (typeof picked !== 'string' || picked === '') return
359
+ store.setManualRoot(picked)
360
+ } catch (error) {
361
+ store.pushLog('error', tr('log.pickFailed', { message: error?.message ?? error }))
362
+ }
363
+ }
364
+
365
+ const toolbar = h('div', { key: 'toolbar', className: 'dw-toolbar' }, [
366
+ h('span', { key: 'ic', className: 'dw-node-icon' }, h(DwIcon, { name: 'database-play', size: 15 })),
367
+ h('div', { key: 'title', className: 'dw-toolbar-title' }, [
368
+ h(DwProjectMenu, {
369
+ key: 'ws',
370
+ state,
371
+ projects: projectItems,
372
+ tr,
373
+ onSelect: (path) => store.setManualRoot(path),
374
+ onFollow: () => store.followDetected(),
375
+ }),
376
+ h('span', { key: 'path', className: 'dw-toolbar-path', title: state.root }, state.root),
377
+ ]),
378
+ environments.length > 0 ? h('span', { key: 'envs', className: 'dw-badge', style: { marginLeft: 0 } }, `${environments.length} ${tr('environments')}`) : null,
379
+ state.manual === true
380
+ ? h('span', { key: 'manual', className: 'dw-badge', style: { marginLeft: 0 }, title: state.detected }, tr('manualWorkspace'))
381
+ : null,
382
+ h('span', { key: 'sp', className: 'dw-spacer' }),
383
+ h('button', {
384
+ key: 'sidebar',
385
+ type: 'button',
386
+ className: 'dw-btn dw-btn-icon',
387
+ onClick: toggleSidebar,
388
+ title: sidebarHidden ? tr('showSidebar') : tr('hideSidebar'),
389
+ 'aria-label': sidebarHidden ? tr('showSidebar') : tr('hideSidebar'),
390
+ }, h(DwIcon, { name: 'panel', size: 13 })),
391
+ h('button', {
392
+ key: 'refresh',
393
+ type: 'button',
394
+ className: 'dw-btn',
395
+ disabled: state.root === '' || state.refreshing === true || state.phase === 'loading',
396
+ onClick: () => void store.loadDiscovery({ refresh: true }),
397
+ title: tr('refreshHint'),
398
+ }, [
399
+ h(DwIcon, { key: 'i', name: state.refreshing === true || state.phase === 'loading' ? 'spinner' : 'refresh', size: 12 }),
400
+ h('span', { key: 't' }, tr('refresh')),
401
+ ]),
402
+ ])
403
+
404
+ const selectedTable = state.selectedNode !== null
405
+ && state.selectedNode !== undefined
406
+ && (state.selectedNode.kind === 'table' || state.selectedNode.kind === 'view' || state.selectedNode.kind === 'database')
407
+
408
+ const side = h('aside', { key: 'side', className: 'dw-side', style: { width: sideWidth } }, [
409
+ h('div', { key: 'head', className: 'dw-side-head' }, [
410
+ h('span', { key: 't' }, tr('treeTitle')),
411
+ h('span', { key: 'sp', className: 'dw-spacer' }),
412
+ selectedTable === true ? h('span', { key: 'n' }, tr('ddlShortcutHint')) : null,
413
+ // These two belong to the tree, so they live in the tree's own header.
414
+ h('button', {
415
+ key: 'ai',
416
+ type: 'button',
417
+ className: 'dw-btn dw-btn-icon',
418
+ disabled: state.root === '' || state.aiRunning === true,
419
+ onClick: () => setAiOpen(true),
420
+ title: tr('aiOpenHint'),
421
+ 'aria-label': tr('aiOpen'),
422
+ }, h(DwIcon, { key: 'i', name: state.aiRunning === true ? 'spinner' : 'ai', size: 12 })),
423
+ h('button', {
424
+ // A distinct key: the manual-workspace badge in the toolbar already owns
425
+ // 'manual', and duplicate keys make React reuse one node for both.
426
+ key: 'add-manual',
427
+ type: 'button',
428
+ className: 'dw-btn dw-btn-icon',
429
+ disabled: state.root === '',
430
+ onClick: () => setManualOpen(true),
431
+ title: tr('manualOpenHint'),
432
+ 'aria-label': tr('manualOpen'),
433
+ }, h(DwIcon, { key: 'i', name: 'plus', size: 12 })),
434
+ ]),
435
+ h('div', { key: 'filter', style: { padding: '5px 8px', borderBottom: '1px solid var(--dsw-alias-border-l1)' } }, [
436
+ h('input', {
437
+ key: 'i',
438
+ type: 'search',
439
+ value: state.filter ?? '',
440
+ placeholder: tr('filterPlaceholder'),
441
+ onChange: (event) => store.patch({ filter: event.target.value }),
442
+ style: {
443
+ width: '100%',
444
+ height: 24,
445
+ padding: '0 8px',
446
+ borderRadius: 6,
447
+ border: '1px solid var(--dsw-alias-border-l1, #31353d)',
448
+ background: 'var(--dsw-alias-bg-layer-2, #262930)',
449
+ color: 'inherit',
450
+ font: 'inherit',
451
+ fontSize: 12,
452
+ outline: 'none',
453
+ },
454
+ }),
455
+ ]),
456
+ h(DwTree, {
457
+ key: 'tree',
458
+ store,
459
+ state,
460
+ tr,
461
+ onContextMenu: (event, node) => setMenu({ x: event.clientX, y: event.clientY, node }),
462
+ onChooseDatabases: (node) => setSchemaTarget(node),
463
+ }),
464
+ ])
465
+
466
+ let main
467
+ if (state.root === '') {
468
+ main = h('div', { key: 'main', className: 'dw-main' }, h(DwEmpty, {
469
+ tr,
470
+ state,
471
+ onPick: pickWorkspace,
472
+ onOpenAi: () => setAiOpen(true),
473
+ onOpenManual: () => setManualOpen(true),
474
+ }))
475
+ } else if (state.phase === 'loading' && environments.length === 0) {
476
+ main = h('div', { key: 'main', className: 'dw-main' }, h('div', { className: 'dw-empty' }, [
477
+ h(DwIcon, { key: 'i', name: 'spinner', size: 20 }),
478
+ h('div', { key: 't', className: 'dw-empty-title' }, tr('discovering')),
479
+ h('div', { key: 'h', className: 'dw-empty-hint' }, tr('discoveringHint')),
480
+ ]))
481
+ } else {
482
+ main = h('div', { key: 'main', className: 'dw-main' }, [
483
+ h(DwTabs, { key: 'tabs', store, state, tr }),
484
+ activeTab === undefined
485
+ ? h(DwEmpty, { key: 'empty', tr, state, onPick: pickWorkspace, onOpenAi: () => setAiOpen(true), onOpenManual: () => setManualOpen(true) })
486
+ : h(React.Fragment, { key: activeTab.id }, [
487
+ h(DwEditor, {
488
+ key: 'editor',
489
+ store,
490
+ tab: activeTab,
491
+ tr,
492
+ height: editorHeight,
493
+ schema: state.schemas?.get(activeTab.dbId),
494
+ onRun: (statement) => void store.runActiveTab(statement),
495
+ }),
496
+ h(DwDragHandle, {
497
+ key: 'drag',
498
+ value: editorHeight,
499
+ min: DW_EDITOR_MIN,
500
+ max: DW_EDITOR_MAX,
501
+ onChange: setEditorHeight,
502
+ }),
503
+ h(DwResults, { key: 'results', store, state, tab: activeTab, tr }),
504
+ ]),
505
+ ])
506
+ }
507
+
508
+ const log = h('div', { key: 'log', className: `dw-log${state.logOpen === true ? '' : ' dw-log-collapsed'}` }, [
509
+ h('div', { key: 'bar', className: 'dw-log-bar' }, [
510
+ h('button', {
511
+ key: 'toggle',
512
+ type: 'button',
513
+ className: 'dw-log-toggle',
514
+ title: tr('logTitle'),
515
+ onClick: () => store.setLogOpen(state.logOpen !== true),
516
+ }, [
517
+ h(DwIcon, { key: 'i', name: 'chevron', size: 10, className: state.logOpen === true ? 'dw-rot-down' : '' }),
518
+ h('span', { key: 't' }, tr('logTitle')),
519
+ h('span', { key: 'c' }, `${state.log.length}`),
520
+ ]),
521
+ state.log.some((entry) => entry.level === 'error')
522
+ ? h('span', { key: 'err', className: 'dw-log-error' }, tr('logHasError'))
523
+ : null,
524
+ h('span', { key: 'sp', className: 'dw-spacer' }),
525
+ h('button', {
526
+ key: 'clear',
527
+ type: 'button',
528
+ className: 'dw-btn',
529
+ style: { height: 20, fontSize: 11 },
530
+ onClick: () => store.patch({ log: [] }),
531
+ }, tr('clear')),
532
+ ]),
533
+ h('div', { key: 'body', className: 'dw-log-body', ref: logRef }, state.log.map((entry) => h('div', {
534
+ key: entry.id,
535
+ className: `dw-log-line ${entry.level === 'error' ? 'dw-log-error' : entry.level === 'warn' ? 'dw-log-warn' : entry.level === 'ok' ? 'dw-log-ok' : entry.level === 'sql' ? 'dw-log-sql' : ''}`,
536
+ }, [
537
+ h('b', { key: 't' }, `[${dwClock(entry.at)}] `),
538
+ entry.level === 'sql' ? h('span', { key: 'tag', className: 'dw-log-tag' }, 'SQL') : null,
539
+ entry.text,
540
+ ]))),
541
+ ])
542
+
543
+ // The menu is fixed-positioned inside a clipped panel, so it is clamped to the
544
+ // panel's own rectangle instead of the viewport: otherwise a menu opened near the
545
+ // bottom edge would be cut in half.
546
+ let menuLayer = null
547
+ if (menu !== null) {
548
+ const rect = panelRef.current?.getBoundingClientRect?.()
549
+ const width = 210
550
+ const height = 230
551
+ const left = rect === undefined ? menu.x : Math.min(menu.x, rect.right - width)
552
+ const top = rect === undefined ? menu.y : Math.min(menu.y, rect.bottom - height)
553
+ menuLayer = h(React.Fragment, null, [
554
+ h('div', { key: 'backdrop', className: 'dw-backdrop', onClick: () => setMenu(null), onContextMenu: (event) => { event.preventDefault(); setMenu(null) } }),
555
+ h('div', {
556
+ key: 'menu',
557
+ className: 'dw-menu',
558
+ style: {
559
+ left: Math.max(rect === undefined ? 0 : rect.left, left),
560
+ top: Math.max(rect === undefined ? 0 : rect.top, top),
561
+ },
562
+ }, dwMenuItems(menu.node, store, tr, () => setMenu(null), (node) => setSchemaTarget(node), (node) => setRenameTarget(node), (node) => setRemoveEnvTarget(node), (node) => setDdlTarget(node))),
563
+ ])
564
+ }
565
+
566
+ return h('div', { className: 'dw-root', ref: panelRef, 'data-dsh-theme': themeId === '' ? undefined : themeId }, [
567
+ h(DwStyles, { key: 'style' }),
568
+ toolbar,
569
+ h('div', { key: 'body', className: 'dw-body' }, [
570
+ side,
571
+ h('div', {
572
+ key: 'resizer',
573
+ className: 'dw-resizer',
574
+ role: 'separator',
575
+ 'aria-orientation': 'vertical',
576
+ title: tr('resizeTree'),
577
+ onPointerDown: startSideResize,
578
+ onDoubleClick: resetSideWidth,
579
+ }),
580
+ main,
581
+ ]),
582
+ log,
583
+ menuLayer,
584
+ aiOpen ? h(DwAiDialog, {
585
+ key: 'ai-dialog',
586
+ store,
587
+ tr,
588
+ onClose: () => setAiOpen(false),
589
+ onManual: () => {
590
+ setAiOpen(false)
591
+ setManualOpen(true)
592
+ },
593
+ }) : null,
594
+ manualOpen ? h(DwManualDialog, {
595
+ key: 'manual-dialog',
596
+ store,
597
+ tr,
598
+ onClose: () => setManualOpen(false),
599
+ onSaved: () => void store.loadDiscovery({ quiet: true }),
600
+ }) : null,
601
+ ddlTarget === null ? null : h(DwDdlDialog, {
602
+ key: 'ddl-dialog',
603
+ store,
604
+ tr,
605
+ node: ddlTarget,
606
+ onClose: () => setDdlTarget(null),
607
+ }),
608
+ removeEnvTarget === null ? null : h(DwConfirmDialog, {
609
+ key: 'remove-env-dialog',
610
+ tr,
611
+ title: tr('removeEnvironmentTitle'),
612
+ message: tr('removeEnvironmentHint', { name: removeEnvTarget.label }),
613
+ confirmLabel: tr('removeEnvironmentConfirm'),
614
+ onClose: () => setRemoveEnvTarget(null),
615
+ onConfirm: async () => {
616
+ await store.removeManualEnvironment(removeEnvTarget.label)
617
+ setRemoveEnvTarget(null)
618
+ },
619
+ }),
620
+ renameTarget === null ? null : h(DwRenameEnvDialog, {
621
+ key: 'rename-dialog',
622
+ store,
623
+ tr,
624
+ label: renameTarget.label,
625
+ onClose: () => setRenameTarget(null),
626
+ onRenamed: () => void store.loadDiscovery({ quiet: true }),
627
+ }),
628
+ schemaTarget === null ? null : h(DwSchemaDialog, {
629
+ key: 'schema-dialog',
630
+ store,
631
+ tr,
632
+ instance: schemaTarget,
633
+ onClose: () => setSchemaTarget(null),
634
+ }),
635
+ ])
636
+ }
637
+
638
+ /** Local wall-clock time for one log line. */
639
+ function dwClock(date) {
640
+ const value = date instanceof Date ? date : new Date()
641
+ const pad = (number) => String(number).padStart(2, '0')
642
+ return `${pad(value.getHours())}:${pad(value.getMinutes())}:${pad(value.getSeconds())}`
643
+ }
644
+
645
+ /** The context menu of one node. */
646
+ function dwMenuItems(node, store, tr, close, openSchemaDialog, openRenameEnv, openRemoveEnv, openDdlDialog) {
647
+ const items = []
648
+ const add = (key, label, shortcut, run, tone) => items.push(h('button', {
649
+ key,
650
+ type: 'button',
651
+ className: tone === undefined ? 'dw-menu-item' : `dw-menu-item ${tone}`,
652
+ onClick: () => {
653
+ close()
654
+ run()
655
+ },
656
+ }, [h('span', { key: 'l' }, label), shortcut === '' ? null : h('span', { key: 's', className: 'dw-menu-shortcut' }, shortcut)]))
657
+
658
+ if (node.kind === 'table' || node.kind === 'view') {
659
+ add('ddl', tr('menuDdl'), 'F4', () => openDdlDialog(node))
660
+ add('data', tr('menuOpenData'), '', () => {
661
+ const statement = `SELECT *\nFROM \`${node.database}\`.\`${node.table}\`\nLIMIT 100`
662
+ store.seedStatement(node, statement)
663
+ void store.runActiveTab(statement)
664
+ })
665
+ add('refresh', tr('refreshStructure'), '', () => void store.refreshNode(node))
666
+ add('name', tr('menuCopyName'), '', () => {
667
+ const write = globalThis.navigator?.clipboard?.writeText?.(node.table)
668
+ if (write !== undefined) write.then(() => store.pushLog('info', tr('log.copiedName', { name: node.table }))).catch(() => undefined)
669
+ })
670
+ } else if (node.kind === 'database') {
671
+ add('open', tr('menuOpenConsole'), '', () => store.openDatabase(node))
672
+ add('ddl', tr('menuDdlAll'), 'F4', () => openDdlDialog(node))
673
+ add('refresh', tr('refreshStructure'), '', () => void store.refreshNode(node))
674
+ if (node.remembered === true) {
675
+ add('forget-database', tr('forgetDatabase'), '', () => void store.forgetDatabase(node), 'dw-menu-danger')
676
+ }
677
+ } else if (node.kind === 'instance') {
678
+ add('pick', tr('chooseDatabases'), '', () => openSchemaDialog(node))
679
+ add('refresh', tr('refreshStructure'), '', () => void store.refreshNode(node))
680
+ if (node.manual === true && typeof node.entryId === 'string') {
681
+ add('remove-manual', tr('removeConnection'), '', () => void store.removeManual(node.entryId), 'dw-menu-danger')
682
+ }
683
+ } else if (node.kind === 'env') {
684
+ add('expand', tr('menuExpand'), '', () => void store.toggleNode(node))
685
+ if (node.manual === true) {
686
+ add('rename', tr('renameEnvironment'), '', () => openRenameEnv(node))
687
+ add('remove-env', tr('removeEnvironment'), '', () => openRemoveEnv(node), 'dw-menu-danger')
688
+ }
689
+ } else if (node.kind === 'column') {
690
+ add('name', tr('menuCopyName'), '', () => {
691
+ const write = globalThis.navigator?.clipboard?.writeText?.(node.label)
692
+ if (write !== undefined) write.then(() => store.pushLog('info', tr('log.copiedName', { name: node.label }))).catch(() => undefined)
693
+ })
694
+ }
695
+ if (items.length === 0) items.push(h('div', { key: 'none', className: 'dw-menu-item', style: { opacity: .5 } }, tr('menuEmpty')))
696
+ return items
697
+ }
698
+
699
+ /**
700
+ * The panel's empty state.
701
+ *
702
+ * Three different situations used to share one misleading sentence: no workspace,
703
+ * a workspace whose configuration resolved no database, and a workspace whose
704
+ * configuration failed. Each one now says what happened and what to do next.
705
+ */
706
+ function DwEmpty({ tr, state, onPick, onOpenAi, onOpenManual }) {
707
+ const warnings = state.warnings ?? []
708
+ const canUseAi = state.root !== '' && (state.environments ?? []).length === 0
709
+ const states = []
710
+ if (state.root === '') {
711
+ states.push({ title: tr('emptyTitle'), hint: tr('emptyHint') })
712
+ } else if (state.phase === 'error') {
713
+ states.push({ title: tr('stateError'), hint: state.discoveryError })
714
+ } else if ((state.environments ?? []).length === 0) {
715
+ states.push({ title: tr('emptyNoEnvTitle'), hint: tr('emptyNoEnvHint') })
716
+ } else {
717
+ states.push({ title: tr('emptyReadyTitle'), hint: tr('emptyReadyHint') })
718
+ }
719
+ const current = states[0]
720
+
721
+ return h('div', { className: 'dw-empty' }, [
722
+ h('div', { key: 't', className: 'dw-empty-title' }, current.title),
723
+ h('div', { key: 'h', className: 'dw-empty-hint' }, current.hint),
724
+ h('div', { key: 'k', className: 'dw-empty-hint', style: { fontSize: 11.5, opacity: .8 } }, tr('shortcutSummary')),
725
+ h('button', { key: 'b', type: 'button', className: 'dw-btn', onClick: onPick }, tr('pickWorkspace')),
726
+ canUseAi === true
727
+ ? h('button', {
728
+ key: 'ai',
729
+ type: 'button',
730
+ className: 'dw-btn dw-btn-accent',
731
+ disabled: state.aiRunning === true,
732
+ onClick: onOpenAi,
733
+ }, [
734
+ h(DwIcon, { key: 'i', name: 'ai', size: 12 }),
735
+ h('span', { key: 't' }, state.aiRunning === true ? tr('aiRunningShort') : tr('aiOpen')),
736
+ ])
737
+ : null,
738
+ canUseAi === true
739
+ ? h('button', {
740
+ key: 'manual',
741
+ type: 'button',
742
+ className: 'dw-btn',
743
+ onClick: onOpenManual,
744
+ }, [
745
+ h(DwIcon, { key: 'i', name: 'plus', size: 12 }),
746
+ h('span', { key: 't' }, tr('manualOpen')),
747
+ ])
748
+ : null,
749
+ canUseAi === true
750
+ ? h('div', { key: 'aihint', className: 'dw-empty-hint', style: { fontSize: 11.5, opacity: .8 } }, tr('aiEmptyHint'))
751
+ : null,
752
+ warnings.length > 0
753
+ ? h('div', { key: 'w', className: 'dw-code-block' }, warnings.map((warning) => dwWarningText(warning, tr)).join('\n'))
754
+ : null,
755
+ ])
756
+ }
757
+
758
+ /** Turn one discovery warning code into a sentence. */
759
+ function dwWarningText(code, tr) {
760
+ // A code may carry a detail after a colon (`unparsed-jdbc-url:spring.datasource`);
761
+ // the dictionary is keyed by the code alone.
762
+ const base = String(code).split(':')[0]
763
+ const key = `warning.${base}`
764
+ const text = tr(key)
765
+ return text === key ? `· ${code}` : `· ${text}`
766
+ }
767
+
768
+ export { DwPanel, DwTracker, dwResolveRoot, DwEmpty, dwWarningText }