dsh-data-window 0.1.1 → 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.
package/client.js CHANGED
@@ -288,6 +288,24 @@ window.__ModuleLoader__.load({
288
288
  "optimizeNotes": "Notes",
289
289
  "optimizeCopy": "Copy SQL",
290
290
  "log.optimizeCopied": "Optimized SQL copied",
291
+ "tabClose": "Close",
292
+ "tabCloseOthers": "Close other tabs",
293
+ "tabCloseAll": "Close all tabs",
294
+ "tabCloseLeft": "Close tabs to the left",
295
+ "tabCloseRight": "Close tabs to the right",
296
+ "copyReference": "Copy reference",
297
+ "copyReferenceToChat": "Copy reference to chat",
298
+ "log.copiedReference": "Reference copied: {reference}",
299
+ "log.copiedReferenceToChat": "Reference inserted into the chat: {reference}",
300
+ "log.copiedReferenceOnly": "Chat input is closed; reference copied: {reference}",
301
+ "tabMenuLabel": "Tab menu",
302
+ "optimizeOriginal": "Original SQL",
303
+ "optimizeOptimized": "Optimized SQL",
304
+ "menuDdlAll": "Show all create statements",
305
+ "ddlAllEmpty": "This database has no tables",
306
+ "ddlAllPartial": "{count} table(s) could not be read; noted at the end of the script",
307
+ "log.ddlAll": "Read all create statements of {database}: {count} tables · {ms}",
308
+ "log.copiedDdlAll": "Copied all create statements of {database} ({count} tables)",
291
309
  }
292
310
  const DW_TEXT_ZH = {
293
311
  "openPanel": "数据窗口",
@@ -569,6 +587,24 @@ window.__ModuleLoader__.load({
569
587
  "optimizeNotes": "优化说明",
570
588
  "optimizeCopy": "复制 SQL",
571
589
  "log.optimizeCopied": "优化后的 SQL 已复制",
590
+ "tabClose": "关闭",
591
+ "tabCloseOthers": "关闭其他标签页",
592
+ "tabCloseAll": "关闭所有标签页",
593
+ "tabCloseLeft": "关闭左侧标签页",
594
+ "tabCloseRight": "关闭右侧标签页",
595
+ "copyReference": "复制引用",
596
+ "copyReferenceToChat": "复制引用到对话",
597
+ "log.copiedReference": "已复制引用:{reference}",
598
+ "log.copiedReferenceToChat": "已把引用插入对话:{reference}",
599
+ "log.copiedReferenceOnly": "对话输入框未打开,已复制引用:{reference}",
600
+ "tabMenuLabel": "标签页菜单",
601
+ "optimizeOriginal": "原始 SQL",
602
+ "optimizeOptimized": "优化后 SQL",
603
+ "menuDdlAll": "查看全部建表语句",
604
+ "ddlAllEmpty": "这个库还没有表",
605
+ "ddlAllPartial": "{count} 张表读取失败,已在脚本末尾用注释标出",
606
+ "log.ddlAll": "读取 {database} 的全部建表语句:{count} 张表 · {ms}",
607
+ "log.copiedDdlAll": "已复制 {database} 的全部建表语句({count} 张表)",
572
608
  }
573
609
 
574
610
  // ---- 00-css.js -----------------------------------------------------------
@@ -1205,6 +1241,63 @@ const DW_CSS = `
1205
1241
  background: var(--dsw-alias-bg-overlay, #23262d);
1206
1242
  box-shadow: 0 10px 26px rgba(0,0,0,.42);
1207
1243
  }
1244
+ .dw-tabmenu-backdrop {
1245
+ position: fixed;
1246
+ inset: 0;
1247
+ z-index: 70;
1248
+ background: transparent;
1249
+ }
1250
+ /* The tab menu mirrors the code workspace's menu (icons + labels, IDEA-like). */
1251
+ .dw-tabmenu {
1252
+ position: fixed;
1253
+ overflow-y: auto;
1254
+ overscroll-behavior: contain;
1255
+ min-width: 232px;
1256
+ padding: 5px;
1257
+ border: 0.5px solid var(--dsw-alias-border-l2, rgba(255, 255, 255, .1));
1258
+ border-radius: var(--dsw-radius-md, 10px);
1259
+ background: var(--dsw-specific-menu, var(--dsw-alias-bg-layer-2, #23262b));
1260
+ backdrop-filter: var(--dsw-menu-backdrop-filter, none);
1261
+ box-shadow: var(--dsw-elevation-prominent, 0 12px 32px rgba(0, 0, 0, .35));
1262
+ color: var(--dsw-alias-label-primary, inherit);
1263
+ }
1264
+ .dw-tabmenu-item {
1265
+ display: flex;
1266
+ align-items: center;
1267
+ gap: 9px;
1268
+ width: 100%;
1269
+ height: 27px;
1270
+ padding: 0 9px;
1271
+ border: 0;
1272
+ border-radius: var(--dsw-radius-sm, 6px);
1273
+ background: transparent;
1274
+ color: inherit;
1275
+ font: inherit;
1276
+ font-size: 12.5px;
1277
+ line-height: 27px;
1278
+ text-align: left;
1279
+ cursor: default;
1280
+ }
1281
+ .dw-tabmenu-item:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover, rgba(255, 255, 255, .08)); }
1282
+ .dw-tabmenu-item:disabled { opacity: .45; }
1283
+ .dw-tabmenu-item:focus-visible {
1284
+ outline: none;
1285
+ box-shadow: inset 0 0 0 2px var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary, #4a7dff));
1286
+ }
1287
+ .dw-tabmenu-icon {
1288
+ display: inline-flex;
1289
+ flex: none;
1290
+ align-items: center;
1291
+ justify-content: center;
1292
+ width: 14px;
1293
+ color: var(--dsw-alias-label-secondary, inherit);
1294
+ }
1295
+ .dw-tabmenu-label { flex: 1 1 auto; }
1296
+ .dw-tabmenu-sep {
1297
+ height: 0.5px;
1298
+ margin: 5px 8px;
1299
+ background: var(--dsw-alias-border-l1, rgba(255, 255, 255, .08));
1300
+ }
1208
1301
  .dw-menu-note {
1209
1302
  padding: 4px 8px 5px;
1210
1303
  color: var(--dsw-alias-label-secondary, #8b919d);
@@ -1482,7 +1575,67 @@ const DW_CSS = `
1482
1575
  word-break: break-all;
1483
1576
  }
1484
1577
  .dw-cell-dialog { width: min(720px, 100%); }
1485
- .dw-optimize-dialog { width: min(760px, 100%); }
1578
+ .dw-optimize-dialog { width: min(1100px, 100%); }
1579
+ .dw-ddl-dialog { width: min(900px, 100%); }
1580
+ /*
1581
+ * The DDL is the only scroll container in this dialog: one scrollbar pair, at the
1582
+ * code box, instead of the modal body plus the pre each growing their own.
1583
+ */
1584
+ .dw-ddl-dialog .dw-modal-body {
1585
+ display: flex;
1586
+ flex-direction: column;
1587
+ min-height: 0;
1588
+ overflow: hidden;
1589
+ }
1590
+ .dw-ddl-result {
1591
+ display: flex;
1592
+ flex: 1 1 auto;
1593
+ flex-direction: column;
1594
+ min-height: 0;
1595
+ }
1596
+ .dw-ddl-result .dw-log-warn { margin-bottom: 6px; }
1597
+ .dw-ddl-code {
1598
+ flex: 1 1 auto;
1599
+ min-height: 0;
1600
+ max-height: none;
1601
+ overflow: auto;
1602
+ /* Keep the server's line breaks: long COMMENTs scroll sideways, never wrap. */
1603
+ white-space: pre;
1604
+ word-break: normal;
1605
+ }
1606
+ .dw-diff { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
1607
+ .dw-diff-col { display: flex; flex-direction: column; min-width: 0; }
1608
+ .dw-diff-head {
1609
+ padding-bottom: 5px;
1610
+ color: var(--dsw-alias-label-secondary, #8b919d);
1611
+ font-size: 11px;
1612
+ }
1613
+ .dw-diff-pane {
1614
+ margin: 0;
1615
+ padding: 10px 12px;
1616
+ max-height: 320px;
1617
+ overflow: auto;
1618
+ border: 1px solid var(--dsw-alias-border-l1, #31353d);
1619
+ border-radius: 8px;
1620
+ background: var(--dsw-alias-bg-layer-2, #262930);
1621
+ color: var(--dsw-alias-label-primary, #e6e8ec);
1622
+ font-family: var(--dsw-font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
1623
+ font-size: 12px;
1624
+ line-height: 1.55;
1625
+ white-space: pre-wrap;
1626
+ word-break: break-word;
1627
+ }
1628
+ .dw-diff-del {
1629
+ border-radius: 2px;
1630
+ background: color-mix(in srgb, var(--dsw-alias-state-error-primary, #e5534b) 26%, transparent);
1631
+ }
1632
+ .dw-diff-add {
1633
+ border-radius: 2px;
1634
+ background: color-mix(in srgb, var(--dsw-alias-state-success-primary, #3fb950) 26%, transparent);
1635
+ }
1636
+ @media (max-width: 720px) {
1637
+ .dw-diff { grid-template-columns: 1fr; }
1638
+ }
1486
1639
  .dw-optimize-model { padding-bottom: 8px; color: var(--dsw-alias-label-secondary, #8b919d); font-size: 11px; }
1487
1640
  .dw-optimize-notes {
1488
1641
  max-height: 120px;
@@ -1634,6 +1787,25 @@ function DwIcon({ name, size = 14, className }) {
1634
1787
  return h('svg', { ...common, fill: 'currentColor', stroke: 'none' }, [h('path', { d: 'M4.6 2.9l8 5.1-8 5.1z' })])
1635
1788
  case 'stop':
1636
1789
  return h('svg', { ...common, fill: 'currentColor', stroke: 'none' }, [h('rect', { x: 4, y: 4, width: 8, height: 8, rx: 1.4 })])
1790
+ case 'layers':
1791
+ return h('svg', common, [
1792
+ h('rect', { key: 'a', x: 2.4, y: 2.4, width: 7, height: 7, rx: 1.4 }),
1793
+ h('rect', { key: 'b', x: 6.6, y: 6.6, width: 7, height: 7, rx: 1.4 }),
1794
+ ])
1795
+ case 'stack':
1796
+ return h('svg', common, [
1797
+ h('path', { key: 'a', d: 'M2 6 8 3.2 14 6 8 8.8Z' }),
1798
+ h('path', { key: 'b', d: 'M2 10.4 8 13.2 14 10.4' }),
1799
+ ])
1800
+ case 'arrow-left':
1801
+ return h('svg', common, [h('path', { key: 'a', d: 'M12.5 8H3.5M7 4.5 3.5 8 7 11.5' })])
1802
+ case 'arrow-right':
1803
+ return h('svg', common, [h('path', { key: 'a', d: 'M3.5 8h9M9 4.5 12.5 8 9 11.5' })])
1804
+ case 'at':
1805
+ return h('svg', common, [
1806
+ h('circle', { key: 'a', cx: 8, cy: 8, r: 2.4 }),
1807
+ h('path', { key: 'b', d: 'M10.4 8v1.4a2.1 2.1 0 0 0 4.2 0V8A6.4 6.4 0 1 0 8 14.4c1.2 0 2.2-.2 3-.7' }),
1808
+ ])
1637
1809
  case 'close':
1638
1810
  return h('svg', common, [h('path', { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' })])
1639
1811
  case 'download':
@@ -1951,6 +2123,9 @@ function dwBridgeDatabases(state) {
1951
2123
  env: environment.env,
1952
2124
  envLabel: environment.label ?? environment.env,
1953
2125
  instanceLabel: instance.label ?? '',
2126
+ // 资源树是全机共享的,同一个实例下会挂着别的项目的库;只有本项目发现出来的
2127
+ // 库才带这个标记,`openSql` 靠它选库。
2128
+ inWorkspace: database.inWorkspace === true,
1954
2129
  })
1955
2130
  }
1956
2131
  }
@@ -2062,7 +2237,13 @@ async function dwBridgeHandle(detail, deps) {
2062
2237
  return
2063
2238
  }
2064
2239
  const schema = typeof detail.schema === 'string' ? detail.schema.trim() : ''
2065
- const target = databases.find((entry) => schema !== '' && entry.database === schema) ?? databases[0]
2240
+ // 库的定位:显式 schema 优先;没有就只在本项目发现出来的库里挑。
2241
+ // 以前直接取 databases[0],共享资源树里第一个常常是别的项目的库
2242
+ // (bluewhale-order-service 的 Mapper 被打开在 tiangong_tk_order 下)。
2243
+ const own = databases.filter((entry) => entry.inWorkspace === true)
2244
+ const pool = own.length > 0 ? own : databases
2245
+ const target = (schema === '' ? null : databases.find((entry) => entry.database === schema))
2246
+ ?? pool[0]
2066
2247
  layout()?.selectPanel?.(DW_PANEL_ID)
2067
2248
  // Paste only: Mapper SQL usually carries #{...} parameters and dynamic
2068
2249
  // fragments, so running it automatically would just produce an error.
@@ -2925,10 +3106,6 @@ function dwCreateStore(translate) {
2925
3106
  void store.loadSchema(node.dbId)
2926
3107
  await store.ensureChildren(node)
2927
3108
  if (state.loadState.get(node.key) === 'error') return
2928
- if (node.kind === 'table' || node.kind === 'view') {
2929
- const tab = state.tabs.find((entry) => entry.kind === 'ddl' && entry.dbId === node.dbId && entry.table === node.table)
2930
- if (tab !== undefined) await store.refreshDdl(tab.id)
2931
- }
2932
3109
  pushLog('info', t('log.refreshedStructure', { name: node.label }))
2933
3110
  },
2934
3111
 
@@ -3163,73 +3340,45 @@ function dwCreateStore(translate) {
3163
3340
  return tab
3164
3341
  },
3165
3342
 
3166
- /**
3167
- * Open the DDL of one table.
3168
- *
3169
- * Requirement: the create statement is one keystroke away. The tab is keyed by
3170
- * table, so asking twice focuses the same document instead of stacking copies.
3171
- */
3172
- async openDdl(node) {
3173
- if (node === null || node === undefined || node.table === undefined) return
3174
- const id = `ddl:${node.dbId}:${node.table}`
3175
- const existing = state.tabs.find((tab) => tab.id === id)
3176
- if (existing !== undefined) {
3177
- patch({ activeTab: id })
3178
- if (existing.loading !== true && existing.ddl !== '') return
3179
- await store.refreshDdl(id)
3180
- return
3181
- }
3182
- const tab = {
3183
- id,
3184
- kind: 'ddl',
3185
- title: node.table,
3186
- env: node.env ?? '',
3187
- subtitle: [node.env, node.database].filter((part) => typeof part === 'string' && part !== '').join(' · '),
3188
- dbId: node.dbId,
3189
- database: node.database,
3190
- instanceLabel: node.instanceLabel ?? '',
3191
- table: node.table,
3192
- ddl: '',
3193
- columns: [],
3194
- loading: true,
3195
- error: '',
3343
+ /** Close one or more tabs and keep the active selection on a neighbour. */
3344
+ closeTabs(ids) {
3345
+ const removing = new Set(Array.isArray(ids) ? ids : [])
3346
+ if (removing.size === 0) return
3347
+ const tabs = state.tabs.filter((tab) => !removing.has(tab.id))
3348
+ let activeTab = state.activeTab
3349
+ if (removing.has(activeTab)) {
3350
+ const index = state.tabs.findIndex((tab) => tab.id === activeTab)
3351
+ const neighbour = state.tabs.slice(index + 1).find((tab) => !removing.has(tab.id))
3352
+ ?? state.tabs.slice(0, index).reverse().find((tab) => !removing.has(tab.id))
3353
+ activeTab = neighbour?.id ?? ''
3196
3354
  }
3197
- patch({ tabs: [...state.tabs, tab], activeTab: id })
3198
- await store.refreshDdl(id)
3355
+ patch({ tabs, activeTab })
3356
+ // Closing a console is deliberate: drop it from storage now, not later.
3357
+ flushConsoles()
3199
3358
  },
3200
3359
 
3201
- /** Re-read one DDL tab (a schema change is exactly why the tab exists). */
3202
- async refreshDdl(id) {
3203
- const tab = state.tabs.find((entry) => entry.id === id)
3204
- if (tab === undefined || tab.kind !== 'ddl') return
3205
- patch({ tabs: state.tabs.map((entry) => (entry.id === id ? { ...entry, loading: true, error: '' } : entry)) })
3206
- try {
3207
- const value = await call('ddl', { id: tab.dbId, table: tab.table })
3208
- patch({
3209
- tabs: state.tabs.map((entry) => (entry.id === id
3210
- ? { ...entry, ddl: value.ddl ?? '', columns: value.columns ?? [], loading: false, error: '' }
3211
- : entry)),
3212
- })
3213
- pushLog('info', t('log.ddl', { table: tab.table, ms: dwDuration(value.statementTime) }))
3214
- } catch (error) {
3215
- patch({ tabs: state.tabs.map((entry) => (entry.id === id ? { ...entry, loading: false, error: dwExplainFailure(t, error) } : entry)) })
3216
- pushLog('error', t('log.loadFailed', { name: tab.table, message: dwExplainFailure(t, error) }))
3217
- }
3360
+ closeTab(id) {
3361
+ store.closeTabs([id])
3218
3362
  },
3219
3363
 
3220
- /** Close one tab and pick a neighbour. */
3221
- closeTab(id) {
3364
+ closeOtherTabs(id) {
3365
+ store.closeTabs(state.tabs.filter((tab) => tab.id !== id).map((tab) => tab.id))
3366
+ },
3367
+
3368
+ closeAllTabs() {
3369
+ store.closeTabs(state.tabs.map((tab) => tab.id))
3370
+ },
3371
+
3372
+ closeTabsToLeft(id) {
3373
+ const index = state.tabs.findIndex((tab) => tab.id === id)
3374
+ if (index <= 0) return
3375
+ store.closeTabs(state.tabs.slice(0, index).map((tab) => tab.id))
3376
+ },
3377
+
3378
+ closeTabsToRight(id) {
3222
3379
  const index = state.tabs.findIndex((tab) => tab.id === id)
3223
3380
  if (index < 0) return
3224
- const tabs = state.tabs.filter((tab) => tab.id !== id)
3225
- let activeTab = state.activeTab
3226
- if (activeTab === id) {
3227
- const neighbour = tabs[index] ?? tabs[index - 1]
3228
- activeTab = neighbour?.id ?? ''
3229
- }
3230
- patch({ tabs, activeTab })
3231
- // Closing a console is deliberate: drop it from storage now, not later.
3232
- flushConsoles()
3381
+ store.closeTabs(state.tabs.slice(index + 1).map((tab) => tab.id))
3233
3382
  },
3234
3383
 
3235
3384
  setActiveTab(id) {
@@ -3611,6 +3760,8 @@ function DwTree({ store, state, tr, onContextMenu, onChooseDatabases }) {
3611
3760
  [state.environments, state.expanded, state.children, state.loadState, state.filter],
3612
3761
  )
3613
3762
 
3763
+ // A row click only selects: expanding belongs to the twisty (and to double-click
3764
+ // for the kinds whose whole purpose is to be opened).
3614
3765
  const activate = (row) => {
3615
3766
  const node = row.node
3616
3767
  if (node.kind === 'retry') {
@@ -3618,13 +3769,24 @@ function DwTree({ store, state, tr, onContextMenu, onChooseDatabases }) {
3618
3769
  return
3619
3770
  }
3620
3771
  store.select(node)
3772
+ }
3773
+
3774
+ const openRow = (row) => {
3775
+ const node = row.node
3776
+ if (node.kind === 'retry') {
3777
+ store.retryNode(node.retryOf)
3778
+ return
3779
+ }
3780
+ store.select(node)
3621
3781
  if (node.kind === 'database') {
3622
3782
  store.openDatabase(node)
3623
- // Opening the workbench also reveals its tables: that is the list the user
3624
- // came for, and one click is better than two.
3625
3783
  if (row.open !== true) void store.toggleNode(node)
3626
3784
  return
3627
3785
  }
3786
+ if (node.kind === 'table' || node.kind === 'view') {
3787
+ openTableData(row)
3788
+ return
3789
+ }
3628
3790
  if (node.kind === 'instance' && (node.databases ?? []).length === 0) {
3629
3791
  onChooseDatabases(node)
3630
3792
  return
@@ -3670,10 +3832,9 @@ function DwTree({ store, state, tr, onContextMenu, onChooseDatabases }) {
3670
3832
  className: 'dw-node-twisty',
3671
3833
  style: { transform: row.open === true ? 'rotate(90deg)' : 'none', transition: 'transform 110ms ease', cursor: 'pointer' },
3672
3834
  onClick: (event) => {
3673
- // The twisty is the only control that collapses a node: clicking the row
3674
- // of a database opens its workbench and never closes the list.
3835
+ // The twisty is the only control that expands or collapses a node;
3836
+ // clicking the row never changes the expansion.
3675
3837
  event.stopPropagation()
3676
- store.select(node)
3677
3838
  void store.toggleNode(node)
3678
3839
  },
3679
3840
  }, row.loading === true ? h(DwIcon, { name: 'spinner', size: 11 }) : h(DwIcon, { name: 'chevron', size: 11 }))
@@ -3700,7 +3861,7 @@ function DwTree({ store, state, tr, onContextMenu, onChooseDatabases }) {
3700
3861
  ].filter((part) => part !== '').join(' · ')
3701
3862
  : `${node.title ?? `${node.label}${node.detail ? ` ${node.detail}` : ''}`}`,
3702
3863
  onClick: () => activate(row),
3703
- onDoubleClick: () => (node.kind === 'table' || node.kind === 'view' ? openTableData(row) : undefined),
3864
+ onDoubleClick: () => openRow(row),
3704
3865
  onContextMenu: (event) => {
3705
3866
  event.preventDefault()
3706
3867
  store.select(node)
@@ -4377,42 +4538,170 @@ function dwFormatSql(text) {
4377
4538
  * statement gets its own id from the store, never a rewrite of the first.
4378
4539
  */
4379
4540
 
4541
+ /** The reference a tab copies: `schema.table`, or the schema alone. */
4542
+ function dwTabReference(tab) {
4543
+ const database = String(tab?.database ?? '').trim()
4544
+ // Table consoles keep the table in their id (`sql:<dbId>:tbl:<table>`).
4545
+ const id = String(tab?.id ?? '')
4546
+ const table = String(tab?.table ?? '').trim()
4547
+ || (id.includes(':tbl:') ? id.split(':tbl:').slice(1).join(':tbl:') : '')
4548
+ if (database !== '' && table !== '') return `${database}.${table}`
4549
+ if (database !== '') return database
4550
+ return String(tab?.title ?? '')
4551
+ }
4552
+
4553
+ /** Insert text into the chat composer when it is open; false when it is not. */
4554
+ function dwInsertComposerText(text) {
4555
+ const doc = globalThis.document
4556
+ if (doc === undefined || typeof doc.querySelector !== 'function') return false
4557
+ const seat = doc.querySelector('[data-composer-seat]')
4558
+ if (seat === null) return false
4559
+ const editor = seat.querySelector('[contenteditable="true"], textarea')
4560
+ if (editor === null) return false
4561
+ try {
4562
+ editor.focus()
4563
+ if (editor.tagName === 'TEXTAREA') {
4564
+ const setter = Object.getOwnPropertyDescriptor(globalThis.HTMLTextAreaElement.prototype, 'value')?.set
4565
+ const start = editor.selectionStart ?? editor.value.length
4566
+ const end = editor.selectionEnd ?? start
4567
+ if (typeof setter === 'function') setter.call(editor, `${editor.value.slice(0, start)}${text}${editor.value.slice(end)}`)
4568
+ editor.setSelectionRange(start + text.length, start + text.length)
4569
+ editor.dispatchEvent(new Event('input', { bubbles: true }))
4570
+ return true
4571
+ }
4572
+ const before = editor.textContent
4573
+ const selection = typeof globalThis.getSelection === 'function' ? globalThis.getSelection() : null
4574
+ if (selection === null || selection === undefined) return false
4575
+ const range = doc.createRange()
4576
+ range.selectNodeContents(editor)
4577
+ range.collapse(false)
4578
+ selection.removeAllRanges()
4579
+ selection.addRange(range)
4580
+ doc.execCommand('insertText', false, text)
4581
+ return editor.textContent !== before
4582
+ } catch (error) {
4583
+ void error
4584
+ return false
4585
+ }
4586
+ }
4587
+
4380
4588
  function DwTabs({ store, state, tr }) {
4589
+ const [menu, setMenu] = useState(null)
4381
4590
  if ((state.tabs ?? []).length === 0) return null
4382
- return h('div', { className: 'dw-tabs', role: 'tablist' }, state.tabs.map((tab) => {
4383
- const active = tab.id === state.activeTab
4384
- return h('div', {
4385
- key: tab.id,
4386
- role: 'tab',
4387
- 'aria-selected': active,
4388
- className: `dw-tab${active ? ' dw-tab-active' : ''}`,
4389
- title: tab.subtitle ?? tab.title,
4390
- onClick: () => store.setActiveTab(tab.id),
4391
- onAuxClick: (event) => {
4392
- if (event.button === 1) {
4591
+
4592
+ const copyReference = (tab) => {
4593
+ const reference = dwTabReference(tab)
4594
+ const write = globalThis.navigator?.clipboard?.writeText?.(reference)
4595
+ if (write === undefined) {
4596
+ store.pushLog('warn', tr('copyUpdateFailed'))
4597
+ return
4598
+ }
4599
+ write
4600
+ .then(() => store.pushLog('info', tr('log.copiedReference', { reference })))
4601
+ .catch(() => store.pushLog('warn', tr('copyUpdateFailed')))
4602
+ }
4603
+
4604
+ const copyReferenceToChat = (tab) => {
4605
+ const reference = dwTabReference(tab)
4606
+ const inserted = dwInsertComposerText(`${reference} `)
4607
+ const write = globalThis.navigator?.clipboard?.writeText?.(reference)
4608
+ if (write !== undefined) write.catch(() => undefined)
4609
+ store.pushLog('info', tr(inserted ? 'log.copiedReferenceToChat' : 'log.copiedReferenceOnly', { reference }))
4610
+ }
4611
+
4612
+ const menuItem = (key, icon, label, disabled, run) => h('button', {
4613
+ key,
4614
+ type: 'button',
4615
+ role: 'menuitem',
4616
+ className: 'dw-tabmenu-item',
4617
+ disabled,
4618
+ onClick: () => {
4619
+ setMenu(null)
4620
+ run()
4621
+ },
4622
+ }, [
4623
+ h('span', { key: 'ic', className: 'dw-tabmenu-icon' }, h(DwIcon, { name: icon, size: 13 })),
4624
+ h('span', { key: 'lb', className: 'dw-tabmenu-label' }, label),
4625
+ ])
4626
+
4627
+ const index = menu === null ? -1 : (state.tabs ?? []).findIndex((tab) => tab.id === menu.tab.id)
4628
+ const menuLayer = menu === null ? null : h('div', {
4629
+ key: 'backdrop',
4630
+ className: 'dw-tabmenu-backdrop',
4631
+ onPointerDown: () => setMenu(null),
4632
+ onContextMenu: (event) => {
4633
+ event.preventDefault()
4634
+ setMenu(null)
4635
+ },
4636
+ }, h('div', {
4637
+ key: 'menu',
4638
+ className: 'dw-tabmenu',
4639
+ role: 'menu',
4640
+ 'aria-label': tr('tabMenuLabel'),
4641
+ style: { left: menu.x, top: menu.y },
4642
+ onPointerDown: (event) => event.stopPropagation(),
4643
+ }, [
4644
+ menuItem('close', 'close', tr('tabClose'), false, () => store.closeTab(menu.tab.id)),
4645
+ menuItem('close-others', 'layers', tr('tabCloseOthers'), (state.tabs ?? []).length <= 1, () => store.closeOtherTabs(menu.tab.id)),
4646
+ menuItem('close-all', 'stack', tr('tabCloseAll'), false, () => store.closeAllTabs()),
4647
+ menuItem('close-left', 'arrow-left', tr('tabCloseLeft'), index <= 0, () => store.closeTabsToLeft(menu.tab.id)),
4648
+ menuItem('close-right', 'arrow-right', tr('tabCloseRight'), index < 0 || index >= (state.tabs ?? []).length - 1, () => store.closeTabsToRight(menu.tab.id)),
4649
+ h('div', { key: 'sep', className: 'dw-tabmenu-sep' }),
4650
+ menuItem('copy-reference', 'copy', tr('copyReference'), false, () => copyReference(menu.tab)),
4651
+ menuItem('copy-reference-chat', 'at', tr('copyReferenceToChat'), false, () => copyReferenceToChat(menu.tab)),
4652
+ ]))
4653
+
4654
+ return h(React.Fragment, null, [
4655
+ h('div', { key: 'tabs', className: 'dw-tabs', role: 'tablist' }, state.tabs.map((tab) => {
4656
+ const active = tab.id === state.activeTab
4657
+ return h('div', {
4658
+ key: tab.id,
4659
+ role: 'tab',
4660
+ 'aria-selected': active,
4661
+ className: `dw-tab${active ? ' dw-tab-active' : ''}`,
4662
+ title: tab.subtitle ?? tab.title,
4663
+ onClick: () => store.setActiveTab(tab.id),
4664
+ onContextMenu: (event) => {
4393
4665
  event.preventDefault()
4394
- store.closeTab(tab.id)
4395
- }
4396
- },
4397
- }, [
4398
- h(DwIcon, { key: 'ic', name: tab.kind === 'ddl' ? 'ddl' : 'database', size: 12 }),
4399
- h('span', { key: 'lb', className: 'dw-tab-label' }, tab.title),
4400
- // Several environments can hold a schema of the same name, so the tab says
4401
- // which one it is; the full text stays in the tooltip.
4402
- tab.env !== '' ? h('span', { key: 'env', className: 'dw-badge', style: { marginLeft: 2 } }, tab.env) : null,
4403
- h('button', {
4404
- key: 'cl',
4405
- type: 'button',
4406
- className: 'dw-tab-close',
4407
- title: tr('closeTab'),
4408
- 'aria-label': tr('closeTab'),
4409
- onClick: (event) => {
4410
- event.stopPropagation()
4411
- store.closeTab(tab.id)
4666
+ // Keep the menu inside the panel, like the code workspace's menu does.
4667
+ const rect = typeof document === 'undefined' ? null : document.querySelector('.dw-root')?.getBoundingClientRect()
4668
+ const left = rect === null || rect === undefined ? 8 : Math.max(8, rect.left + 8)
4669
+ const top = rect === null || rect === undefined ? 8 : Math.max(8, rect.top + 8)
4670
+ const right = (rect === null || rect === undefined ? (globalThis.innerWidth ?? 1200) : rect.right) - 248
4671
+ const bottom = (rect === null || rect === undefined ? (globalThis.innerHeight ?? 800) : rect.bottom) - 238
4672
+ setMenu({
4673
+ x: Math.max(left, Math.min(event.clientX, Math.max(left, right))),
4674
+ y: Math.max(top, Math.min(event.clientY, Math.max(top, bottom))),
4675
+ tab,
4676
+ })
4412
4677
  },
4413
- }, h(DwIcon, { name: 'close', size: 10 })),
4414
- ])
4415
- }))
4678
+ onAuxClick: (event) => {
4679
+ if (event.button === 1) {
4680
+ event.preventDefault()
4681
+ store.closeTab(tab.id)
4682
+ }
4683
+ },
4684
+ }, [
4685
+ h(DwIcon, { key: 'ic', name: 'database', size: 12 }),
4686
+ h('span', { key: 'lb', className: 'dw-tab-label' }, tab.title),
4687
+ // Several environments can hold a schema of the same name, so the tab says
4688
+ // which one it is; the full text stays in the tooltip.
4689
+ tab.env !== '' ? h('span', { key: 'env', className: 'dw-badge', style: { marginLeft: 2 } }, tab.env) : null,
4690
+ h('button', {
4691
+ key: 'cl',
4692
+ type: 'button',
4693
+ className: 'dw-tab-close',
4694
+ title: tr('closeTab'),
4695
+ 'aria-label': tr('closeTab'),
4696
+ onClick: (event) => {
4697
+ event.stopPropagation()
4698
+ store.closeTab(tab.id)
4699
+ },
4700
+ }, h(DwIcon, { name: 'close', size: 10 })),
4701
+ ])
4702
+ })),
4703
+ menuLayer,
4704
+ ])
4416
4705
  }
4417
4706
 
4418
4707
  /** A draggable horizontal divider that resizes the editor. */
@@ -4849,59 +5138,136 @@ function DwEditor({ store, tab, tr, onRun, height, schema }) {
4849
5138
  ])
4850
5139
  }
4851
5140
 
4852
- /** The DDL document: the create statement plus the column summary above it. */
4853
- function DwDdlView({ tab, tr, store }) {
4854
- const bar = h('div', { key: 'bar', className: 'dw-result-bar' }, [
4855
- h('span', { key: 'n' }, [tab.env, tab.database, tab.table].filter((part) => typeof part === 'string' && part !== '').join(' / ')),
4856
- h('span', { key: 'c' }, `${tab.columns.length} ${tr('columns')}`),
4857
- h('span', { key: 'sp', className: 'dw-spacer' }),
4858
- h('button', {
4859
- key: 'data',
4860
- type: 'button',
4861
- className: 'dw-btn',
4862
- onClick: () => {
4863
- store.seedStatement(
4864
- { dbId: tab.dbId, database: tab.database, table: tab.table, env: tab.env, instanceLabel: tab.instanceLabel },
4865
- `SELECT *\nFROM \`${tab.database}\`.\`${tab.table}\`\nLIMIT 100`,
4866
- )
4867
- void store.runActiveTab()
4868
- },
4869
- }, [h(DwIcon, { key: 'i', name: 'table', size: 11 }), h('span', { key: 't' }, tr('openData'))]),
4870
- h('button', {
4871
- key: 'copy',
4872
- type: 'button',
4873
- className: 'dw-btn',
4874
- onClick: () => {
4875
- globalThis.navigator?.clipboard?.writeText?.(tab.ddl).catch(() => undefined)
4876
- store.pushLog('info', tr('log.copiedDdl', { table: tab.table }))
4877
- },
4878
- }, [h(DwIcon, { key: 'i', name: 'copy', size: 11 }), h('span', { key: 't' }, tr('copyDdl'))]),
4879
- h('button', {
4880
- key: 'refresh',
4881
- type: 'button',
4882
- className: 'dw-btn dw-btn-icon',
4883
- title: tr('refreshDdl'),
4884
- disabled: tab.loading === true,
4885
- onClick: () => void store.refreshDdl(tab.id),
4886
- }, h(DwIcon, { name: tab.loading === true ? 'spinner' : 'refresh', size: 12 })),
4887
- ])
5141
+ /** The create statement as a dialog: copy it and close, no work tab involved. */
5142
+ function DwDdlDialog({ node, tr, store, onClose }) {
5143
+ const allTables = node.kind === 'database'
5144
+ const [phase, setPhase] = useState('loading')
5145
+ const [ddl, setDdl] = useState('')
5146
+ const [error, setError] = useState('')
5147
+ const [progress, setProgress] = useState({ done: 0, total: 0 })
5148
+ const [failureCount, setFailureCount] = useState(0)
5149
+ const [count, setCount] = useState(0)
5150
+
5151
+ useEffect(() => {
5152
+ let alive = true
5153
+ const fail = (failure, name) => {
5154
+ if (!alive) return
5155
+ const message = dwExplainFailure(tr, failure)
5156
+ setError(message)
5157
+ setPhase('error')
5158
+ store.pushLog('error', tr('log.loadFailed', { name, message }))
5159
+ }
5160
+
5161
+ const loadTable = async () => {
5162
+ try {
5163
+ const value = await dwRpc('ddl', { id: node.dbId, table: node.table })
5164
+ if (!alive) return
5165
+ setDdl(String(value?.ddl ?? ''))
5166
+ setCount(1)
5167
+ setPhase('done')
5168
+ store.pushLog('info', tr('log.ddl', { table: node.table, ms: dwDuration(value?.statementTime ?? 0) }))
5169
+ } catch (failure) {
5170
+ fail(failure, node.table)
5171
+ }
5172
+ }
4888
5173
 
4889
- if (tab.loading === true) {
4890
- return h('div', { className: 'dw-ddl' }, [bar, h('div', { key: 'body', className: 'dw-empty' }, [
5174
+ // A whole database: list the tables, then read each statement in turn so the
5175
+ // dialog can show progress and a closed dialog stops issuing round trips.
5176
+ const loadDatabase = async () => {
5177
+ const startedAt = Date.now()
5178
+ try {
5179
+ const listed = await dwRpc('tables', { id: node.dbId })
5180
+ if (!alive) return
5181
+ const names = (Array.isArray(listed?.tables) ? listed.tables : [])
5182
+ .map((table) => String(table?.name ?? ''))
5183
+ .filter((name) => name !== '')
5184
+ setProgress({ done: 0, total: names.length })
5185
+ const parts = []
5186
+ const failures = []
5187
+ for (let index = 0; index < names.length; index += 1) {
5188
+ if (!alive) return
5189
+ try {
5190
+ const value = await dwRpc('ddl', { id: node.dbId, table: names[index] })
5191
+ const text = String(value?.ddl ?? '').trim().replace(/;+$/, '')
5192
+ if (text !== '') parts.push(`-- ${names[index]}\n${text};`)
5193
+ } catch (failure) {
5194
+ failures.push(`${names[index]}: ${dwExplainFailure(tr, failure).replace(/\s+/g, ' ')}`)
5195
+ }
5196
+ if (alive) setProgress({ done: index + 1, total: names.length })
5197
+ }
5198
+ if (!alive) return
5199
+ const failedBlock = failures.length === 0 ? '' : failures.map((line) => `-- ${line}`).join('\n')
5200
+ setDdl([...parts, failedBlock].filter((part) => part !== '').join('\n\n'))
5201
+ setCount(parts.length)
5202
+ setFailureCount(failures.length)
5203
+ setPhase('done')
5204
+ store.pushLog('info', tr('log.ddlAll', { database: node.database, count: parts.length, ms: Date.now() - startedAt }))
5205
+ } catch (failure) {
5206
+ fail(failure, node.database)
5207
+ }
5208
+ }
5209
+
5210
+ if (allTables) void loadDatabase()
5211
+ else void loadTable()
5212
+ return () => { alive = false }
5213
+ }, [])
5214
+
5215
+ const loadingHint = allTables && progress.total > 0
5216
+ ? `${tr('ddlLoading')} ${progress.done}/${progress.total}`
5217
+ : tr('ddlLoading')
5218
+ const body = phase === 'loading'
5219
+ ? h('div', { key: 'loading', className: 'dw-empty', style: { minHeight: 120 } }, [
4891
5220
  h(DwIcon, { key: 'i', name: 'spinner', size: 18 }),
4892
- h('div', { key: 't', className: 'dw-empty-hint' }, tr('ddlLoading')),
4893
- ])])
4894
- }
4895
- if (tab.error !== '') {
4896
- return h('div', { className: 'dw-ddl' }, [bar, h('div', { key: 'body', className: 'dw-empty' }, [
4897
- h('div', { key: 't', className: 'dw-empty-title', style: { color: 'var(--dsw-alias-state-error-primary)' } }, tr('ddlFailed')),
4898
- h('div', { key: 'm', className: 'dw-error-text' }, tab.error),
4899
- ])])
4900
- }
4901
- return h('div', { className: 'dw-ddl' }, [
4902
- bar,
4903
- h('pre', { key: 'body', className: 'dw-ddl-body' }, h('code', null, tab.ddl === '' ? tr('ddlEmpty') : tab.ddl)),
4904
- ])
5221
+ h('div', { key: 't', className: 'dw-empty-hint' }, loadingHint),
5222
+ ])
5223
+ : phase === 'error'
5224
+ ? h('div', { key: 'error' }, [
5225
+ h('div', { key: 't', className: 'dw-empty-title', style: { color: 'var(--dsw-alias-state-error-primary)', fontSize: 12 } }, tr('ddlFailed')),
5226
+ h('div', { key: 'm', className: 'dw-error-text' }, error),
5227
+ ])
5228
+ : h('div', { key: 'done', className: 'dw-ddl-result' }, [
5229
+ failureCount > 0
5230
+ ? h('div', { key: 'warn', className: 'dw-log-warn' }, tr('ddlAllPartial', { count: failureCount }))
5231
+ : null,
5232
+ h('pre', { key: 'ddl', className: 'dw-cell-view dw-ddl-code' },
5233
+ ddl === '' ? tr(allTables ? 'ddlAllEmpty' : 'ddlEmpty') : ddl),
5234
+ ])
5235
+
5236
+ return h('div', { className: 'dw-modal', onClick: onClose }, h('div', {
5237
+ key: 'card',
5238
+ className: 'dw-modal-card dw-ddl-dialog',
5239
+ onClick: (event) => event.stopPropagation(),
5240
+ }, [
5241
+ h('div', { key: 'title', className: 'dw-modal-title' }, [
5242
+ h(DwIcon, { key: 'i', name: 'ddl', size: 13 }),
5243
+ h('span', { key: 't' }, tr(allTables ? 'menuDdlAll' : 'menuDdl')),
5244
+ h('span', { key: 'p', style: { color: 'var(--dsw-alias-label-secondary)', fontWeight: 400, fontSize: 11 } },
5245
+ [node.env, node.database, node.table].filter((part) => typeof part === 'string' && part !== '').join(' / ')),
5246
+ ]),
5247
+ h('div', { key: 'body', className: 'dw-modal-body' }, body),
5248
+ h('div', { key: 'foot', className: 'dw-modal-foot' }, [
5249
+ phase === 'done' && ddl !== ''
5250
+ ? h('button', {
5251
+ key: 'copy',
5252
+ type: 'button',
5253
+ className: 'dw-btn',
5254
+ onClick: () => {
5255
+ const write = globalThis.navigator?.clipboard?.writeText?.(ddl)
5256
+ if (write === undefined) {
5257
+ store.pushLog('warn', tr('copyUpdateFailed'))
5258
+ return
5259
+ }
5260
+ write
5261
+ .then(() => store.pushLog('info', allTables
5262
+ ? tr('log.copiedDdlAll', { database: node.database, count })
5263
+ : tr('log.copiedDdl', { table: node.table })))
5264
+ .catch(() => store.pushLog('warn', tr('copyUpdateFailed')))
5265
+ },
5266
+ }, [h(DwIcon, { key: 'i', name: 'copy', size: 11 }), h('span', { key: 't' }, tr('copyDdl'))])
5267
+ : null,
5268
+ h('button', { key: 'close', type: 'button', className: 'dw-btn dw-btn-accent', onClick: onClose }, tr('close')),
5269
+ ]),
5270
+ ]))
4905
5271
  }
4906
5272
 
4907
5273
 
@@ -5884,6 +6250,7 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
5884
6250
  const [aiOpen, setAiOpen] = useState(false)
5885
6251
  const [manualOpen, setManualOpen] = useState(false)
5886
6252
  const [schemaTarget, setSchemaTarget] = useState(null)
6253
+ const [ddlTarget, setDdlTarget] = useState(null)
5887
6254
  const [renameTarget, setRenameTarget] = useState(null)
5888
6255
  const [removeEnvTarget, setRemoveEnvTarget] = useState(null)
5889
6256
  const aiPrompted = useRef(false)
@@ -5986,10 +6353,10 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
5986
6353
  if (!isDdl) return
5987
6354
  const selected = store.getState().selectedNode
5988
6355
  if (selected === null || selected === undefined) return
5989
- if (selected.kind !== 'table' && selected.kind !== 'view') return
6356
+ if (selected.kind !== 'table' && selected.kind !== 'view' && selected.kind !== 'database') return
5990
6357
  event.preventDefault()
5991
6358
  event.stopPropagation()
5992
- void store.openDdl(selected)
6359
+ setDdlTarget(selected)
5993
6360
  }
5994
6361
  globalThis.addEventListener('keydown', onKey, true)
5995
6362
  return () => globalThis.removeEventListener('keydown', onKey, true)
@@ -6088,7 +6455,7 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6088
6455
 
6089
6456
  const selectedTable = state.selectedNode !== null
6090
6457
  && state.selectedNode !== undefined
6091
- && (state.selectedNode.kind === 'table' || state.selectedNode.kind === 'view')
6458
+ && (state.selectedNode.kind === 'table' || state.selectedNode.kind === 'view' || state.selectedNode.kind === 'database')
6092
6459
 
6093
6460
  const side = h('aside', { key: 'side', className: 'dw-side', style: { width: sideWidth } }, [
6094
6461
  h('div', { key: 'head', className: 'dw-side-head' }, [
@@ -6168,9 +6535,7 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6168
6535
  h(DwTabs, { key: 'tabs', store, state, tr }),
6169
6536
  activeTab === undefined
6170
6537
  ? h(DwEmpty, { key: 'empty', tr, state, onPick: pickWorkspace, onOpenAi: () => setAiOpen(true), onOpenManual: () => setManualOpen(true) })
6171
- : activeTab.kind === 'ddl'
6172
- ? h(DwDdlView, { key: activeTab.id, tab: activeTab, tr, store })
6173
- : h(React.Fragment, { key: activeTab.id }, [
6538
+ : h(React.Fragment, { key: activeTab.id }, [
6174
6539
  h(DwEditor, {
6175
6540
  key: 'editor',
6176
6541
  store,
@@ -6246,7 +6611,7 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6246
6611
  left: Math.max(rect === undefined ? 0 : rect.left, left),
6247
6612
  top: Math.max(rect === undefined ? 0 : rect.top, top),
6248
6613
  },
6249
- }, dwMenuItems(menu.node, store, tr, () => setMenu(null), (node) => setSchemaTarget(node), (node) => setRenameTarget(node), (node) => setRemoveEnvTarget(node))),
6614
+ }, dwMenuItems(menu.node, store, tr, () => setMenu(null), (node) => setSchemaTarget(node), (node) => setRenameTarget(node), (node) => setRemoveEnvTarget(node), (node) => setDdlTarget(node))),
6250
6615
  ])
6251
6616
  }
6252
6617
 
@@ -6285,6 +6650,13 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6285
6650
  onClose: () => setManualOpen(false),
6286
6651
  onSaved: () => void store.loadDiscovery({ quiet: true }),
6287
6652
  }) : null,
6653
+ ddlTarget === null ? null : h(DwDdlDialog, {
6654
+ key: 'ddl-dialog',
6655
+ store,
6656
+ tr,
6657
+ node: ddlTarget,
6658
+ onClose: () => setDdlTarget(null),
6659
+ }),
6288
6660
  removeEnvTarget === null ? null : h(DwConfirmDialog, {
6289
6661
  key: 'remove-env-dialog',
6290
6662
  tr,
@@ -6323,7 +6695,7 @@ function dwClock(date) {
6323
6695
  }
6324
6696
 
6325
6697
  /** The context menu of one node. */
6326
- function dwMenuItems(node, store, tr, close, openSchemaDialog, openRenameEnv, openRemoveEnv) {
6698
+ function dwMenuItems(node, store, tr, close, openSchemaDialog, openRenameEnv, openRemoveEnv, openDdlDialog) {
6327
6699
  const items = []
6328
6700
  const add = (key, label, shortcut, run, tone) => items.push(h('button', {
6329
6701
  key,
@@ -6336,7 +6708,7 @@ function dwMenuItems(node, store, tr, close, openSchemaDialog, openRenameEnv, op
6336
6708
  }, [h('span', { key: 'l' }, label), shortcut === '' ? null : h('span', { key: 's', className: 'dw-menu-shortcut' }, shortcut)]))
6337
6709
 
6338
6710
  if (node.kind === 'table' || node.kind === 'view') {
6339
- add('ddl', tr('menuDdl'), 'F4', () => void store.openDdl(node))
6711
+ add('ddl', tr('menuDdl'), 'F4', () => openDdlDialog(node))
6340
6712
  add('data', tr('menuOpenData'), '', () => {
6341
6713
  const statement = `SELECT *\nFROM \`${node.database}\`.\`${node.table}\`\nLIMIT 100`
6342
6714
  store.seedStatement(node, statement)
@@ -6349,6 +6721,7 @@ function dwMenuItems(node, store, tr, close, openSchemaDialog, openRenameEnv, op
6349
6721
  })
6350
6722
  } else if (node.kind === 'database') {
6351
6723
  add('open', tr('menuOpenConsole'), '', () => store.openDatabase(node))
6724
+ add('ddl', tr('menuDdlAll'), 'F4', () => openDdlDialog(node))
6352
6725
  add('refresh', tr('refreshStructure'), '', () => void store.refreshNode(node))
6353
6726
  if (node.remembered === true) {
6354
6727
  add('forget-database', tr('forgetDatabase'), '', () => void store.forgetDatabase(node), 'dw-menu-danger')
@@ -7499,6 +7872,97 @@ function DwAiSettingsRow({ tr, prefs, onOpen }) {
7499
7872
  * overwrite user SQL" rule intact.
7500
7873
  */
7501
7874
 
7875
+ /** SQL tokens keep whitespace, so the diff can highlight words without reformatting. */
7876
+ const DW_DIFF_TOKEN = /(\s+|[A-Za-z0-9_$]+|[^\sA-Za-z0-9_$]+)/g
7877
+
7878
+ function dwDiffTokenize(text) {
7879
+ const tokens = []
7880
+ DW_DIFF_TOKEN.lastIndex = 0
7881
+ let match
7882
+ const source = String(text ?? '')
7883
+ while ((match = DW_DIFF_TOKEN.exec(source)) !== null) tokens.push({ value: match[1], space: /^\s+$/.test(match[1]) })
7884
+ return tokens
7885
+ }
7886
+
7887
+ /**
7888
+ * Token-level LCS between the two statements.
7889
+ *
7890
+ * Line-based diffs are useless here: a model often returns the same query as one
7891
+ * long line, so every line would look changed. Common prefixes and suffixes are
7892
+ * trimmed first; the matrix is capped so a pathological statement cannot hang the
7893
+ * dialog (the middle is then reported as changed as a whole).
7894
+ */
7895
+ function dwDiffMarks(leftTokens, rightTokens) {
7896
+ const a = leftTokens.filter((token) => !token.space)
7897
+ const b = rightTokens.filter((token) => !token.space)
7898
+ const removed = new Array(a.length).fill(false)
7899
+ const added = new Array(b.length).fill(false)
7900
+ let start = 0
7901
+ while (start < a.length && start < b.length && a[start].value === b[start].value) start += 1
7902
+ let endA = a.length - 1
7903
+ let endB = b.length - 1
7904
+ while (endA >= start && endB >= start && a[endA].value === b[endB].value) {
7905
+ endA -= 1
7906
+ endB -= 1
7907
+ }
7908
+ const n = endA - start + 1
7909
+ const m = endB - start + 1
7910
+ if (n > 0 && m > 0 && n * m <= 2000000) {
7911
+ const width = m + 1
7912
+ const dp = new Uint32Array((n + 1) * width)
7913
+ for (let i = n - 1; i >= 0; i -= 1) {
7914
+ for (let j = m - 1; j >= 0; j -= 1) {
7915
+ dp[i * width + j] = a[start + i].value === b[start + j].value
7916
+ ? dp[(i + 1) * width + j + 1] + 1
7917
+ : Math.max(dp[(i + 1) * width + j], dp[i * width + j + 1])
7918
+ }
7919
+ }
7920
+ let i = 0
7921
+ let j = 0
7922
+ while (i < n && j < m) {
7923
+ if (a[start + i].value === b[start + j].value) {
7924
+ i += 1
7925
+ j += 1
7926
+ } else if (dp[(i + 1) * width + j] >= dp[i * width + j + 1]) {
7927
+ removed[start + i] = true
7928
+ i += 1
7929
+ } else {
7930
+ added[start + j] = true
7931
+ j += 1
7932
+ }
7933
+ }
7934
+ while (i < n) {
7935
+ removed[start + i] = true
7936
+ i += 1
7937
+ }
7938
+ while (j < m) {
7939
+ added[start + j] = true
7940
+ j += 1
7941
+ }
7942
+ } else {
7943
+ for (let i = start; i <= endA; i += 1) removed[i] = true
7944
+ for (let j = start; j <= endB; j += 1) added[j] = true
7945
+ }
7946
+ return { removed, added }
7947
+ }
7948
+
7949
+ /** Render one side: changed significant tokens wrapped, whitespace left alone. */
7950
+ function dwDiffNodes(tokens, marks, className) {
7951
+ const nodes = []
7952
+ let significant = 0
7953
+ for (let index = 0; index < tokens.length; index += 1) {
7954
+ const token = tokens[index]
7955
+ if (token.space) {
7956
+ nodes.push(token.value)
7957
+ continue
7958
+ }
7959
+ const changed = marks[significant] === true
7960
+ significant += 1
7961
+ nodes.push(changed ? h('span', { key: index, className }, token.value) : token.value)
7962
+ }
7963
+ return nodes
7964
+ }
7965
+
7502
7966
  function dwOptimizeModelName(model) {
7503
7967
  return String(model?.name ?? model?.model ?? '')
7504
7968
  }
@@ -7508,6 +7972,15 @@ function DwSqlOptimizeDialog({ store, tr, sql, database, onClose }) {
7508
7972
  const [result, setResult] = useState(null)
7509
7973
  const [error, setError] = useState('')
7510
7974
  const model = dwAiModel()
7975
+ const leftRef = useRef(null)
7976
+ const rightRef = useRef(null)
7977
+ const originalTokens = useMemo(() => dwDiffTokenize(sql), [sql])
7978
+ const optimizedTokens = useMemo(() => dwDiffTokenize(result?.sql ?? ''), [result?.sql])
7979
+ const diffMarks = useMemo(() => dwDiffMarks(originalTokens, optimizedTokens), [originalTokens, optimizedTokens])
7980
+ const syncScroll = (from, to) => (event) => {
7981
+ const target = to.current
7982
+ if (target !== null) target.scrollTop = event.currentTarget.scrollTop
7983
+ }
7511
7984
 
7512
7985
  useEffect(() => {
7513
7986
  if (model === null) {
@@ -7550,7 +8023,26 @@ function DwSqlOptimizeDialog({ store, tr, sql, database, onClose }) {
7550
8023
  h('div', { key: 'm', className: 'dw-optimize-model' }, tr('optimizeModelLabel', {
7551
8024
  model: dwOptimizeModelName(result?.model) === '' ? tr('aiModelUnknown') : dwOptimizeModelName(result?.model),
7552
8025
  })),
7553
- h('pre', { key: 'sql', className: 'dw-cell-view' }, result?.sql ?? ''),
8026
+ h('div', { key: 'diff', className: 'dw-diff' }, [
8027
+ h('div', { key: 'left', className: 'dw-diff-col' }, [
8028
+ h('div', { key: 'h', className: 'dw-diff-head' }, tr('optimizeOriginal')),
8029
+ h('pre', {
8030
+ key: 'p',
8031
+ className: 'dw-diff-pane',
8032
+ ref: leftRef,
8033
+ onScroll: syncScroll(leftRef, rightRef),
8034
+ }, dwDiffNodes(originalTokens, diffMarks.removed, 'dw-diff-del')),
8035
+ ]),
8036
+ h('div', { key: 'right', className: 'dw-diff-col' }, [
8037
+ h('div', { key: 'h', className: 'dw-diff-head' }, tr('optimizeOptimized')),
8038
+ h('pre', {
8039
+ key: 'p',
8040
+ className: 'dw-diff-pane',
8041
+ ref: rightRef,
8042
+ onScroll: syncScroll(rightRef, leftRef),
8043
+ }, dwDiffNodes(optimizedTokens, diffMarks.added, 'dw-diff-add')),
8044
+ ]),
8045
+ ]),
7554
8046
  result?.notes === undefined || result.notes === ''
7555
8047
  ? null
7556
8048
  : h('div', { key: 'notes' }, [