dsh-data-window 0.1.2 → 0.1.3

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
@@ -12,7 +12,10 @@ window.__ModuleLoader__.load({
12
12
  "openPanel": "Data window",
13
13
  "openPanelHint": "Open the data window",
14
14
  "treeTitle": "Explorer",
15
+ "treeTabsLabel": "Resource manager tabs",
16
+ "treeTabDatabases": "Databases",
15
17
  "filterPlaceholder": "Filter the loaded databases and tables",
18
+ "filterFavoritesPlaceholder": "Filter saved SQL by name, schema or table",
16
19
  "treeLoading": "Loading…",
17
20
  "treeNoMatch": "Nothing matches this filter",
18
21
  "treeEmpty": "No database configuration found for this workspace",
@@ -101,6 +104,7 @@ window.__ModuleLoader__.load({
101
104
  "warning.unparsed-jdbc-url": "A datasource URL could not be parsed as jdbc:mysql.",
102
105
  "projectSwitch": "Switch workspace",
103
106
  "resizeTree": "Drag to resize the list (double-click resets)",
107
+ "resizeLog": "Drag to resize the run log (double-click resets)",
104
108
  "hideSidebar": "Hide the DSH sidebar",
105
109
  "showSidebar": "Show the DSH sidebar",
106
110
  "formatSql": "Format",
@@ -306,12 +310,56 @@ window.__ModuleLoader__.load({
306
310
  "ddlAllPartial": "{count} table(s) could not be read; noted at the end of the script",
307
311
  "log.ddlAll": "Read all create statements of {database}: {count} tables · {ms}",
308
312
  "log.copiedDdlAll": "Copied all create statements of {database} ({count} tables)",
313
+ "favoritesTitle": "Favorites",
314
+ "favoritesCount": "saved",
315
+ "favoritesEmptyHint": "No saved SQL yet. Right-click in the editor and choose “Save SQL”.",
316
+ "favoritesReload": "Reload favorites",
317
+ "favoriteNoTable": "No table",
318
+ "favoriteNoDatabase": "Unknown schema",
319
+ "favoriteSave": "Save SQL",
320
+ "favoriteSaveTitle": "Save SQL",
321
+ "favoriteEditTitle": "Edit saved SQL",
322
+ "favoriteDialogHint": "The schema and table are stored with the statement and group the favorites node; typing @ indexes it by name.",
323
+ "favoriteName": "Name",
324
+ "favoriteNameHint": "Unique among saved SQL, and the keyword used by the @ index",
325
+ "favoriteDatabase": "Schema",
326
+ "favoriteDatabaseHint": "Prefilled from the workbench; editable",
327
+ "favoriteTable": "Table",
328
+ "favoriteTableHint": "Optional; empty goes under “No table”",
329
+ "favoriteSql": "SQL",
330
+ "favoriteSaveAction": "Save",
331
+ "favoriteUpdateAction": "Save changes",
332
+ "favoriteNameRequired": "Give this statement a name first",
333
+ "favoriteDatabaseRequired": "A schema name is required",
334
+ "favoriteMentionLabel": "Saved SQL",
335
+ "favoriteMentionEmpty": "No saved SQL matches",
336
+ "favoriteMentionNoFavorites": "No saved SQL yet: right-click in the editor and choose “Save SQL”",
337
+ "suggestFavorite": "saved",
338
+ "menuOpenFavorite": "Open saved SQL",
339
+ "menuCopyFavoriteSql": "Copy SQL",
340
+ "menuEditFavorite": "Edit saved SQL",
341
+ "menuRemoveFavorite": "Delete saved SQL",
342
+ "removeFavoriteTitle": "Delete saved SQL",
343
+ "removeFavoriteHint": "Delete “{name}”? This cannot be undone.",
344
+ "removeFavoriteConfirm": "Delete",
345
+ "log.favoriteSaved": "Saved SQL: {name} ({database})",
346
+ "log.favoriteRemoved": "Deleted saved SQL: {name}",
347
+ "log.favoriteOpened": "Opened saved SQL: {name}",
348
+ "log.favoriteNoDatabase": "The tree has no schema {database}, so this saved statement cannot be opened",
349
+ "log.favoriteLoadFailed": "Reading saved SQL failed: {message}",
350
+ "log.favoriteInserted": "Inserted saved SQL: {name}",
351
+ "log.favoriteCopied": "Copied saved SQL: {name}",
352
+ "log.favoriteRemoveFailed": "Deleting saved SQL failed: {message}",
353
+ "error.duplicateFavorite": "That name is already taken by another saved statement",
309
354
  }
310
355
  const DW_TEXT_ZH = {
311
356
  "openPanel": "数据窗口",
312
357
  "openPanelHint": "打开数据窗口",
313
358
  "treeTitle": "资源管理器",
359
+ "treeTabsLabel": "资源管理标签",
360
+ "treeTabDatabases": "数据库",
314
361
  "filterPlaceholder": "过滤已加载的库名与表名",
362
+ "filterFavoritesPlaceholder": "过滤收藏的名称、库名与表名",
315
363
  "treeLoading": "加载中…",
316
364
  "treeNoMatch": "没有匹配的节点",
317
365
  "treeEmpty": "没有在当前工作区发现数据库配置",
@@ -400,6 +448,7 @@ window.__ModuleLoader__.load({
400
448
  "warning.unparsed-jdbc-url": "有数据源地址无法解析为 jdbc:mysql。",
401
449
  "projectSwitch": "切换工作区",
402
450
  "resizeTree": "拖动调整列表宽度(双击还原)",
451
+ "resizeLog": "拖动调整运行日志高度(双击还原)",
403
452
  "hideSidebar": "隐藏 DSH 侧栏",
404
453
  "showSidebar": "显示 DSH 侧栏",
405
454
  "formatSql": "格式化",
@@ -605,6 +654,47 @@ window.__ModuleLoader__.load({
605
654
  "ddlAllPartial": "{count} 张表读取失败,已在脚本末尾用注释标出",
606
655
  "log.ddlAll": "读取 {database} 的全部建表语句:{count} 张表 · {ms}",
607
656
  "log.copiedDdlAll": "已复制 {database} 的全部建表语句({count} 张表)",
657
+ "favoritesTitle": "收藏夹",
658
+ "favoritesCount": "条",
659
+ "favoritesEmptyHint": "还没有收藏 SQL。在编辑器里右键 →「收藏 SQL」即可收藏当前语句。",
660
+ "favoritesReload": "刷新收藏夹",
661
+ "favoriteNoTable": "未指定表",
662
+ "favoriteNoDatabase": "未知库",
663
+ "favoriteSave": "收藏 SQL",
664
+ "favoriteSaveTitle": "收藏 SQL",
665
+ "favoriteEditTitle": "编辑收藏",
666
+ "favoriteDialogHint": "保存时会连同库名与表名一起记录,收藏夹按这两层分组;输入 @ 时用名称索引这条 SQL。",
667
+ "favoriteName": "名称",
668
+ "favoriteNameHint": "名称在收藏夹里唯一,也是 @ 索引时输入的关键字",
669
+ "favoriteDatabase": "库名",
670
+ "favoriteDatabaseHint": "从工作台带入,可修改",
671
+ "favoriteTable": "表名",
672
+ "favoriteTableHint": "可选;留空归入「未指定表」",
673
+ "favoriteSql": "SQL",
674
+ "favoriteSaveAction": "收藏",
675
+ "favoriteUpdateAction": "保存修改",
676
+ "favoriteNameRequired": "请先给这条 SQL 起一个名称",
677
+ "favoriteDatabaseRequired": "请填写库名",
678
+ "favoriteMentionLabel": "收藏的 SQL",
679
+ "favoriteMentionEmpty": "没有匹配的收藏 SQL",
680
+ "favoriteMentionNoFavorites": "还没有收藏 SQL:在编辑器里右键 →「收藏 SQL」",
681
+ "suggestFavorite": "收藏",
682
+ "menuOpenFavorite": "打开收藏的 SQL",
683
+ "menuCopyFavoriteSql": "复制 SQL",
684
+ "menuEditFavorite": "编辑收藏",
685
+ "menuRemoveFavorite": "删除收藏",
686
+ "removeFavoriteTitle": "删除收藏",
687
+ "removeFavoriteHint": "确定删除收藏「{name}」?删除后不可恢复。",
688
+ "removeFavoriteConfirm": "删除",
689
+ "log.favoriteSaved": "已收藏 SQL:{name}({database})",
690
+ "log.favoriteRemoved": "已删除收藏:{name}",
691
+ "log.favoriteOpened": "已打开收藏的 SQL:{name}",
692
+ "log.favoriteNoDatabase": "资源树里没有库 {database},无法打开这条收藏",
693
+ "log.favoriteLoadFailed": "读取收藏夹失败:{message}",
694
+ "log.favoriteInserted": "已插入收藏的 SQL:{name}",
695
+ "log.favoriteCopied": "已复制收藏的 SQL:{name}",
696
+ "log.favoriteRemoveFailed": "删除收藏失败:{message}",
697
+ "error.duplicateFavorite": "这个名称已经被收藏了,请换一个名称",
608
698
  }
609
699
 
610
700
  // ---- 00-css.js -----------------------------------------------------------
@@ -751,6 +841,13 @@ const DW_CSS = `
751
841
  color: var(--dsw-alias-label-primary-inverted, #fff);
752
842
  font-weight: 600;
753
843
  }
844
+ /*
845
+ * The panel and the sidebar-foot action each inject this stylesheet, so the second
846
+ * copy's plain .dw-btn color rule would otherwise override the first copy's accent
847
+ * label and paint white text on the brand fill. The extra class keeps the inverted
848
+ * label winning wherever the rules land.
849
+ */
850
+ .dw-btn.dw-btn-accent { color: var(--dsw-alias-label-primary-inverted, #fff); }
754
851
  .dw-btn-accent:hover { filter: brightness(1.08); background: var(--dsw-alias-brand-primary, #4b8bf5); }
755
852
  .dw-btn-icon { width: 26px; padding: 0; justify-content: center; }
756
853
  /*
@@ -835,6 +932,59 @@ const DW_CSS = `
835
932
  letter-spacing: .04em;
836
933
  text-transform: uppercase;
837
934
  }
935
+ /* The resource manager's tabs: the configured tree and the saved statements. */
936
+ .dw-tree-tabs {
937
+ display: flex;
938
+ align-items: center;
939
+ gap: 2px;
940
+ flex: 0 0 auto;
941
+ padding: 4px 6px 0;
942
+ border-bottom: 1px solid var(--dsw-alias-border-l1, #2c2f36);
943
+ }
944
+ .dw-tree-tab {
945
+ display: inline-flex;
946
+ align-items: center;
947
+ gap: 5px;
948
+ height: 24px;
949
+ padding: 0 8px;
950
+ border: 0;
951
+ border-bottom: 2px solid transparent;
952
+ border-radius: 6px 6px 0 0;
953
+ background: transparent;
954
+ color: var(--dsw-alias-label-secondary, #8b919d);
955
+ font: inherit;
956
+ font-size: 11.5px;
957
+ cursor: pointer;
958
+ white-space: nowrap;
959
+ }
960
+ .dw-tree-tab:hover { background: var(--dsw-alias-interactive-bg-hover, rgba(127, 127, 127, .12)); color: var(--dsw-alias-label-primary, #e6e8ec); }
961
+ .dw-tree-tab.on {
962
+ color: var(--dsw-alias-label-primary, #e6e8ec);
963
+ border-bottom-color: var(--dsw-alias-brand-primary, #4b8bf5);
964
+ }
965
+ .dw-tree-tab-count {
966
+ min-width: 14px;
967
+ padding: 0 4px;
968
+ border-radius: 7px;
969
+ background: var(--dsw-alias-interactive-bg-hover, rgba(127, 127, 127, .12));
970
+ color: var(--dsw-alias-label-secondary, #8b919d);
971
+ font-size: 10px;
972
+ line-height: 14px;
973
+ text-align: center;
974
+ }
975
+ .dw-tree-tabs .dw-btn {
976
+ width: 22px;
977
+ height: 22px;
978
+ padding: 0;
979
+ justify-content: center;
980
+ border-color: transparent;
981
+ background: transparent;
982
+ color: var(--dsw-alias-label-secondary, #8b919d);
983
+ }
984
+ .dw-tree-tabs .dw-btn:hover:not(:disabled) {
985
+ background: var(--dsw-alias-interactive-bg-hover, rgba(127, 127, 127, .12));
986
+ color: var(--dsw-alias-label-primary, #e6e8ec);
987
+ }
838
988
  .dw-tree { flex: 1 1 auto; overflow: auto; padding: 4px 0 12px; }
839
989
  .dw-node {
840
990
  display: flex;
@@ -1060,6 +1210,32 @@ const DW_CSS = `
1060
1210
  .dw-complete-label { flex: 1 1 auto; font-family: var(--ds-font-family-code, ui-monospace, Menlo, monospace); font-size: 12px; }
1061
1211
  .dw-complete-detail { flex: 0 1 auto; max-width: 170px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--dsw-alias-label-secondary, #8b919d); font-size: 10.5px; }
1062
1212
  .dw-complete-kind { flex: 0 0 auto; color: var(--dsw-alias-label-secondary, #8b919d); font-size: 10px; opacity: .8; }
1213
+ .dw-complete-empty {
1214
+ padding: 6px 9px;
1215
+ max-width: 300px;
1216
+ color: var(--dsw-alias-label-secondary, #8b919d);
1217
+ font-size: 11.5px;
1218
+ line-height: 1.55;
1219
+ }
1220
+ /* The at-sign index: statements, so a little wider than the column list. */
1221
+ .dw-mention { min-width: 280px; max-width: 420px; }
1222
+ .dw-fav-sql {
1223
+ margin: 0;
1224
+ max-height: 170px;
1225
+ overflow: auto;
1226
+ padding: 8px 10px;
1227
+ border: 1px solid var(--dsw-alias-border-l1, #31353d);
1228
+ border-radius: 6px;
1229
+ background: var(--dsw-alias-bg-layer-2, #262930);
1230
+ color: var(--dsw-alias-label-primary, #e6e8ec);
1231
+ font-family: var(--ds-font-family-code, ui-monospace, Menlo, monospace);
1232
+ font-size: 11.5px;
1233
+ line-height: 1.55;
1234
+ white-space: pre;
1235
+ }
1236
+ .dw-fav-dialog { width: min(620px, 100%); }
1237
+ .dw-fav-split { display: flex; gap: 10px; }
1238
+ .dw-fav-split .dw-form-row { flex: 1 1 0; min-width: 0; }
1063
1239
 
1064
1240
  .dw-drag {
1065
1241
  height: 5px;
@@ -1806,6 +1982,8 @@ function DwIcon({ name, size = 14, className }) {
1806
1982
  h('circle', { key: 'a', cx: 8, cy: 8, r: 2.4 }),
1807
1983
  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
1984
  ])
1985
+ case 'star':
1986
+ return h('svg', common, [h('path', { d: 'M8 2.1l1.82 3.69 4.07.59-2.94 2.87.69 4.06L8 11.4l-3.64 1.91.69-4.06L2.11 6.38l4.07-.59z' })])
1809
1987
  case 'close':
1810
1988
  return h('svg', common, [h('path', { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' })])
1811
1989
  case 'download':
@@ -2418,6 +2596,20 @@ function dwLogEntry(level, text) {
2418
2596
  return { id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, at: new Date(), level, text }
2419
2597
  }
2420
2598
 
2599
+ /**
2600
+ * Whether a key event belongs to an input-method composition.
2601
+ *
2602
+ * The Enter/Escape that picks or cancels a Chinese or Japanese candidate belongs
2603
+ * to the IME, not to this window: it must never submit a dialog, blur a cell or
2604
+ * pick a suggestion. Chromium marks those events with `isComposing` and the legacy
2605
+ * 229 keyCode; React's synthetic keyboard event does not expose `isComposing`, so
2606
+ * the native event is what is checked.
2607
+ */
2608
+ function dwImeComposing(event) {
2609
+ const native = event?.nativeEvent ?? event
2610
+ return native?.isComposing === true || (native?.keyCode ?? event?.keyCode) === 229
2611
+ }
2612
+
2421
2613
  /**
2422
2614
  * Turn a Host failure into a sentence.
2423
2615
  *
@@ -2441,6 +2633,7 @@ function dwExplainFailure(translate, error) {
2441
2633
  'ER_QUERY_INTERRUPTED': 'error.interrupted',
2442
2634
  'manual-connect-failed': 'error.manualConnectFailed',
2443
2635
  'saved-connection-missing': 'error.savedConnectionMissing',
2636
+ 'duplicate-favorite': 'error.duplicateFavorite',
2444
2637
  }
2445
2638
  const key = known[code]
2446
2639
  if (key !== undefined) {
@@ -2512,6 +2705,19 @@ const DW_CONSOLE_KEY = 'dsh-data-window:consoles'
2512
2705
  /** Client-side preferences edited in the plugin's settings section. */
2513
2706
  const DW_PREFS_KEY = 'dsh-data-window:prefs'
2514
2707
 
2708
+ /** Which side-panel tab was last shown: the database tree or the favorites list. */
2709
+ const DW_TREE_TAB_KEY = 'dsh-data-window:tree-tab'
2710
+
2711
+ /** The remembered side-panel tab; unknown or blocked storage means the tree. */
2712
+ function dwReadTreeTab() {
2713
+ try {
2714
+ return globalThis.localStorage?.getItem(DW_TREE_TAB_KEY) === 'favorites' ? 'favorites' : 'databases'
2715
+ } catch (error) {
2716
+ void error
2717
+ return 'databases'
2718
+ }
2719
+ }
2720
+
2515
2721
  /** Read the display preferences, tolerating a blocked storage. */
2516
2722
  function dwReadPrefs() {
2517
2723
  const fallback = { autoHideSidebar: true, defaultLimit: 0, shortcutOpen: null, aiModel: null }
@@ -2613,6 +2819,9 @@ function dwCreateStore(translate) {
2613
2819
  aiRunning: false,
2614
2820
  // tree
2615
2821
  filter: '',
2822
+ // The resource manager has two tabs, like DataGrip's Database window: the
2823
+ // configured tree and the saved statements. Both read the same filter.
2824
+ treeTab: dwReadTreeTab(),
2616
2825
  expanded: new Set(),
2617
2826
  loadState: new Map(),
2618
2827
  children: new Map(),
@@ -2624,6 +2833,11 @@ function dwCreateStore(translate) {
2624
2833
  // Table/column maps for the editor's completion, one per database.
2625
2834
  schemas: new Map(),
2626
2835
  limit: DW_DEFAULT_LIMIT,
2836
+ // Saved statements (machine-wide, not per workspace) and the `@` index they
2837
+ // feed; the tree's favorites node is rendered from this list.
2838
+ favorites: [],
2839
+ favoritesLoading: false,
2840
+ favoritesError: '',
2627
2841
  // log
2628
2842
  logOpen: false,
2629
2843
  log: [dwLogEntry('info', t('log.ready'))],
@@ -3027,6 +3241,108 @@ function dwCreateStore(translate) {
3027
3241
  }
3028
3242
  },
3029
3243
 
3244
+ /**
3245
+ * Read the saved statements.
3246
+ *
3247
+ * The list belongs to the machine, not to one workspace, so it is loaded when
3248
+ * the panel opens; saves and deletes patch it in place. No workspace is needed.
3249
+ */
3250
+ async loadFavorites(options = {}) {
3251
+ if (state.favoritesLoading === true && options.force !== true) return
3252
+ patch({ favoritesLoading: true })
3253
+ try {
3254
+ const value = await dwRpc('favorites')
3255
+ patch({
3256
+ favorites: Array.isArray(value?.favorites) ? value.favorites : [],
3257
+ favoritesLoading: false,
3258
+ favoritesError: '',
3259
+ })
3260
+ } catch (error) {
3261
+ patch({ favoritesLoading: false, favoritesError: dwExplainFailure(t, error) })
3262
+ if (options.quiet !== true) pushLog('warn', t('log.favoriteLoadFailed', { message: dwExplainFailure(t, error) }))
3263
+ }
3264
+ },
3265
+
3266
+ /** Save one statement under its unique name, and open the favorites node. */
3267
+ async saveFavorite(input) {
3268
+ const value = await dwRpc('saveFavorite', { favorite: { ...input } })
3269
+ const favorite = value?.favorite
3270
+ if (favorite !== undefined && favorite !== null) {
3271
+ const favorites = [...state.favorites]
3272
+ const index = favorites.findIndex((entry) => entry.id === favorite.id)
3273
+ if (index >= 0) favorites[index] = favorite
3274
+ else favorites.push(favorite)
3275
+ patch({ favorites })
3276
+ pushLog('info', t('log.favoriteSaved', { name: favorite.name, database: favorite.database }))
3277
+ const tableKey = String(favorite.table ?? '').trim().toLowerCase()
3278
+ // The saved statement lives on the favorites tab now; switching there and
3279
+ // expanding its schema/table is the only visible acknowledgement that the
3280
+ // save landed, since the database tree cannot show it.
3281
+ store.setTreeTab('favorites')
3282
+ store.expand(
3283
+ dwNodeKey('favoriteDatabase', favorite.database),
3284
+ dwNodeKey('favoriteTable', favorite.database, tableKey),
3285
+ )
3286
+ const favoriteKey = dwNodeKey('favorite', favorite.id)
3287
+ store.select({ key: favoriteKey, kind: 'favorite', label: favorite.name, favorite })
3288
+ }
3289
+ return value
3290
+ },
3291
+
3292
+ /** Delete one saved statement. */
3293
+ async removeFavorite(id) {
3294
+ const value = await dwRpc('removeFavorite', { id })
3295
+ if (value?.removed === true) {
3296
+ const favorite = state.favorites.find((entry) => entry.id === id)
3297
+ patch({ favorites: state.favorites.filter((entry) => entry.id !== id) })
3298
+ pushLog('info', t('log.favoriteRemoved', { name: favorite?.name ?? id }))
3299
+ }
3300
+ return value
3301
+ },
3302
+
3303
+ /**
3304
+ * Open a saved statement in the workbench of the schema it was saved from.
3305
+ *
3306
+ * Opening by name is what keeps a favorite useful across workspaces: the
3307
+ * statement was written in `bw_order` in one project and is still a `bw_order`
3308
+ * statement in the next tree. When that schema is not in the tree at all, the
3309
+ * log says which one is missing instead of opening an unrelated console.
3310
+ */
3311
+ openFavorite(favorite) {
3312
+ if (favorite === null || favorite === undefined) return false
3313
+ const target = dwFindDatabaseTarget(state.environments, favorite.database, favorite.env)
3314
+ if (target === undefined) {
3315
+ pushLog('warn', t('log.favoriteNoDatabase', { database: favorite.database }))
3316
+ return false
3317
+ }
3318
+ const opened = store.openDatabase(target.node)
3319
+ const tabId = typeof opened?.id === 'string' ? opened.id : ''
3320
+ if (tabId === '') return false
3321
+ store.appendStatement(tabId, favorite.sql)
3322
+ pushLog('info', t('log.favoriteOpened', { name: favorite.name }))
3323
+ return true
3324
+ },
3325
+
3326
+ /** Append a statement to one console without touching what is already typed. */
3327
+ appendStatement(tabId, sql) {
3328
+ const statement = String(sql ?? '').trim()
3329
+ const tab = state.tabs.find((entry) => entry.id === tabId)
3330
+ if (statement === '' || tab === undefined) return
3331
+ const current = String(tab.sql ?? '').replace(/\s+$/, '')
3332
+ if (current.includes(statement)) {
3333
+ store.setActiveTab(tabId)
3334
+ return
3335
+ }
3336
+ const next = current === '' ? statement : `${current}\n\n${statement}`
3337
+ patch({
3338
+ tabs: state.tabs.map((entry) => (entry.id === tabId
3339
+ ? { ...entry, sql: next, result: undefined, error: '' }
3340
+ : entry)),
3341
+ activeTab: tabId,
3342
+ })
3343
+ scheduleConsoles()
3344
+ },
3345
+
3030
3346
  /** Delete a whole manually added environment, then re-read the tree. */
3031
3347
  async removeManualEnvironment(label) {
3032
3348
  const root = state.root
@@ -3209,6 +3525,18 @@ function dwCreateStore(translate) {
3209
3525
  patch({ selected: node?.key ?? '', selectedNode: node ?? null })
3210
3526
  },
3211
3527
 
3528
+ /** Switch the resource manager between the database tree and the favorites. */
3529
+ setTreeTab(tab) {
3530
+ const next = tab === 'favorites' ? 'favorites' : 'databases'
3531
+ if (next === state.treeTab) return
3532
+ try {
3533
+ globalThis.localStorage?.setItem(DW_TREE_TAB_KEY, next)
3534
+ } catch (error) {
3535
+ void error
3536
+ }
3537
+ patch({ treeTab: next })
3538
+ },
3539
+
3212
3540
  /**
3213
3541
  * Open (or focus) the SQL workbench of one database.
3214
3542
  *
@@ -3615,7 +3943,7 @@ function dwCreateStore(translate) {
3615
3943
  */
3616
3944
 
3617
3945
  /** One nested tree of what the store currently knows, before filtering. */
3618
- function dwBuildTree(state, tr) {
3946
+ function dwBuildTree(state, tr, mode = 'databases') {
3619
3947
  const loadStateOf = (key) => state.loadState.get(key)
3620
3948
  const childrenOf = (node, depth) => {
3621
3949
  const rows = []
@@ -3631,7 +3959,12 @@ function dwBuildTree(state, tr) {
3631
3959
  return rows
3632
3960
  }
3633
3961
 
3634
- const environments = []
3962
+ // The favorites tab is derived from the saved list, not from `children`: it never
3963
+ // needs a round trip to expand, and a save anywhere in the panel is visible the
3964
+ // moment the store patches the list.
3965
+ if (mode === 'favorites') return dwBuildFavoriteRows(state.favorites, tr)
3966
+
3967
+ const rows = []
3635
3968
  for (const environment of state.environments ?? []) {
3636
3969
  const envKey = dwNodeKey('env', environment.env)
3637
3970
  const instanceRows = []
@@ -3678,7 +4011,7 @@ function dwBuildTree(state, tr) {
3678
4011
  children: databaseRows,
3679
4012
  })
3680
4013
  }
3681
- environments.push({
4014
+ rows.push({
3682
4015
  node: {
3683
4016
  key: envKey,
3684
4017
  kind: 'env',
@@ -3692,7 +4025,7 @@ function dwBuildTree(state, tr) {
3692
4025
  children: instanceRows,
3693
4026
  })
3694
4027
  }
3695
- return environments
4028
+ return rows
3696
4029
  }
3697
4030
 
3698
4031
  /** Prune a tree to the nodes that match, keeping their ancestors. */
@@ -3735,7 +4068,7 @@ function dwFlattenTree(tree, state, filter, depth = 0, into = []) {
3735
4068
  /** One row per visible node, in display order. */
3736
4069
  function dwVisibleRows(state, tr) {
3737
4070
  const filter = String(state.filter ?? '').trim().toLowerCase()
3738
- const tree = dwPruneTree(dwBuildTree(state, tr), filter)
4071
+ const tree = dwPruneTree(dwBuildTree(state, tr, state.treeTab), filter)
3739
4072
  return dwFlattenTree(tree, state, filter)
3740
4073
  }
3741
4074
 
@@ -3748,6 +4081,9 @@ function dwNodeIconName(node) {
3748
4081
  case 'view': return 'view'
3749
4082
  case 'table': return 'table'
3750
4083
  case 'column': return node.column?.key === 'PRI' ? 'key' : 'column'
4084
+ case 'favorite': return 'star'
4085
+ case 'favoriteDatabase': return 'database'
4086
+ case 'favoriteTable': return 'table'
3751
4087
  case 'retry': return 'refresh'
3752
4088
  case 'error': return 'close'
3753
4089
  default: return 'panel'
@@ -3757,7 +4093,7 @@ function dwNodeIconName(node) {
3757
4093
  function DwTree({ store, state, tr, onContextMenu, onChooseDatabases }) {
3758
4094
  const rows = useMemo(
3759
4095
  () => dwVisibleRows(state, tr),
3760
- [state.environments, state.expanded, state.children, state.loadState, state.filter],
4096
+ [state.root, state.treeTab, state.environments, state.expanded, state.children, state.loadState, state.filter, state.favorites, state.favoritesError],
3761
4097
  )
3762
4098
 
3763
4099
  // A row click only selects: expanding belongs to the twisty (and to double-click
@@ -3769,6 +4105,9 @@ function DwTree({ store, state, tr, onContextMenu, onChooseDatabases }) {
3769
4105
  return
3770
4106
  }
3771
4107
  store.select(node)
4108
+ // The favorites branches exist to be browsed, so a single click unfolds them;
4109
+ // every other row keeps the "select only" behaviour of the tree.
4110
+ if (node.kind === 'favoriteDatabase' || node.kind === 'favoriteTable') void store.toggleNode(node)
3772
4111
  }
3773
4112
 
3774
4113
  const openRow = (row) => {
@@ -3778,6 +4117,10 @@ function DwTree({ store, state, tr, onContextMenu, onChooseDatabases }) {
3778
4117
  return
3779
4118
  }
3780
4119
  store.select(node)
4120
+ if (node.kind === 'favorite') {
4121
+ store.openFavorite(node.favorite)
4122
+ return
4123
+ }
3781
4124
  if (node.kind === 'database') {
3782
4125
  store.openDatabase(node)
3783
4126
  if (row.open !== true) void store.toggleNode(node)
@@ -3805,14 +4148,21 @@ function DwTree({ store, state, tr, onContextMenu, onChooseDatabases }) {
3805
4148
  }
3806
4149
 
3807
4150
  if (rows.length === 0) {
3808
- const empty = state.phase === 'loading'
3809
- ? tr('treeLoading')
3810
- : String(state.filter ?? '') !== ''
4151
+ const filtered = String(state.filter ?? '') !== ''
4152
+ const empty = state.treeTab === 'favorites'
4153
+ ? filtered
3811
4154
  ? tr('treeNoMatch')
3812
- : tr('treeEmpty')
4155
+ : String(state.favoritesError ?? '') !== ''
4156
+ ? tr('log.favoriteLoadFailed', { message: state.favoritesError })
4157
+ : tr('favoritesEmptyHint')
4158
+ : state.phase === 'loading'
4159
+ ? tr('treeLoading')
4160
+ : filtered
4161
+ ? tr('treeNoMatch')
4162
+ : tr('treeEmpty')
3813
4163
  return h('div', { className: 'dw-tree' }, h('div', { className: 'dw-empty', style: { padding: 18 } }, [
3814
4164
  h('div', { key: 't', className: 'dw-empty-hint' }, empty),
3815
- String(state.filter ?? '') !== ''
4165
+ filtered
3816
4166
  ? h('button', {
3817
4167
  key: 'c',
3818
4168
  type: 'button',
@@ -4528,6 +4878,338 @@ function dwFormatSql(text) {
4528
4878
  }
4529
4879
 
4530
4880
 
4881
+ // ---- 27-favorites.js -----------------------------------------------------
4882
+ /**
4883
+ * Saved SQL: the favorites tab's rows, the dialog that names one, and the `@`
4884
+ * index the workbench inserts from.
4885
+ *
4886
+ * One statement is saved with its name, its schema and its table. The favorites
4887
+ * tab groups by schema then table, which is the shape the user recognised the
4888
+ * statement in; the workbench only needs the name, because the caret is already in
4889
+ * a console. Both views read the same list, so a save from one is visible in the
4890
+ * other without a reload.
4891
+ */
4892
+
4893
+ /** A console's table, from its id (`sql:<dbId>:tbl:<table>`). */
4894
+ function dwTabTableName(tab) {
4895
+ const id = String(tab?.id ?? '')
4896
+ const index = id.indexOf(':tbl:')
4897
+ return index < 0 ? '' : id.slice(index + 5)
4898
+ }
4899
+
4900
+ /** Every schema name the tree knows, for the favorite dialog's datalist. */
4901
+ function dwDatabaseNames(environments) {
4902
+ const names = new Set()
4903
+ for (const environment of Array.isArray(environments) ? environments : []) {
4904
+ for (const instance of Array.isArray(environment?.instances) ? environment.instances : []) {
4905
+ for (const database of Array.isArray(instance?.databases) ? instance.databases : []) {
4906
+ const name = String(database?.name ?? '')
4907
+ if (name !== '') names.add(name)
4908
+ }
4909
+ }
4910
+ }
4911
+ return [...names].sort((left, right) => left.localeCompare(right))
4912
+ }
4913
+
4914
+ /**
4915
+ * The tree node a favorite's schema name points at.
4916
+ *
4917
+ * A favorite stores a name, not a database id, because the tree is shared and the
4918
+ * same schema may be reachable through another workspace later. The environment
4919
+ * the statement was saved under breaks ties when two environments hold a schema of
4920
+ * the same name.
4921
+ */
4922
+ function dwFindDatabaseTarget(environments, database, env) {
4923
+ const name = String(database ?? '').trim().toLowerCase()
4924
+ if (name === '') return undefined
4925
+ const preferred = String(env ?? '').trim().toLowerCase()
4926
+ let fallback
4927
+ for (const environment of Array.isArray(environments) ? environments : []) {
4928
+ for (const instance of Array.isArray(environment?.instances) ? environment.instances : []) {
4929
+ for (const entry of Array.isArray(instance?.databases) ? instance.databases : []) {
4930
+ if (String(entry?.name ?? '').toLowerCase() !== name) continue
4931
+ if (typeof entry?.id !== 'string' || entry.id === '') continue
4932
+ const target = {
4933
+ env: environment.env,
4934
+ node: {
4935
+ key: dwNodeKey('db', entry.id),
4936
+ kind: 'database',
4937
+ label: entry.name,
4938
+ detail: '',
4939
+ dbId: entry.id,
4940
+ database: entry.name,
4941
+ env: environment.env,
4942
+ instanceLabel: instance.label ?? '',
4943
+ configured: entry.discovered !== true,
4944
+ },
4945
+ }
4946
+ if (preferred !== '' && String(environment.env ?? '').toLowerCase() === preferred) return target
4947
+ if (fallback === undefined) fallback = target
4948
+ }
4949
+ }
4950
+ }
4951
+ return fallback
4952
+ }
4953
+
4954
+ /** One favorite as a tree leaf. */
4955
+ function dwFavoriteLeaf(favorite) {
4956
+ const reference = [favorite.database, favorite.table].filter((part) => typeof part === 'string' && part !== '').join('.')
4957
+ return {
4958
+ node: {
4959
+ key: dwNodeKey('favorite', favorite.id),
4960
+ kind: 'favorite',
4961
+ label: favorite.name,
4962
+ detail: '',
4963
+ title: `${favorite.name} · ${reference}\n\n${favorite.sql}`,
4964
+ favorite,
4965
+ },
4966
+ children: [],
4967
+ }
4968
+ }
4969
+
4970
+ /**
4971
+ * The favorites tab's rows: schema → table → statement.
4972
+ *
4973
+ * A statement saved without a table name still gets a table group, so the tab
4974
+ * keeps one shape instead of mixing leaves and groups under a schema.
4975
+ */
4976
+ function dwBuildFavoriteRows(favorites, tr) {
4977
+ const list = (Array.isArray(favorites) ? favorites : []).filter((favorite) => favorite !== null
4978
+ && typeof favorite === 'object'
4979
+ && typeof favorite.id === 'string'
4980
+ && favorite.id !== '')
4981
+ if (list.length === 0) return []
4982
+ const byDatabase = new Map()
4983
+ for (const favorite of list) {
4984
+ const database = String(favorite.database ?? '').trim() || tr('favoriteNoDatabase')
4985
+ const table = String(favorite.table ?? '').trim()
4986
+ const tableKey = table === '' ? '' : table.toLowerCase()
4987
+ if (!byDatabase.has(database)) byDatabase.set(database, new Map())
4988
+ const tables = byDatabase.get(database)
4989
+ if (!tables.has(tableKey)) tables.set(tableKey, { table, favorites: [] })
4990
+ tables.get(tableKey).favorites.push(favorite)
4991
+ }
4992
+
4993
+ const rows = []
4994
+ const databaseNames = [...byDatabase.keys()].sort((left, right) => left.localeCompare(right))
4995
+ for (const databaseName of databaseNames) {
4996
+ const tables = byDatabase.get(databaseName)
4997
+ const tableKeys = [...tables.keys()].sort((left, right) => {
4998
+ if (left === '') return 1
4999
+ if (right === '') return -1
5000
+ return left.localeCompare(right)
5001
+ })
5002
+ const tableRows = []
5003
+ let statementCount = 0
5004
+ for (const tableKey of tableKeys) {
5005
+ const group = tables.get(tableKey)
5006
+ const leaves = group.favorites
5007
+ .slice()
5008
+ .sort((left, right) => String(left.name ?? '').localeCompare(String(right.name ?? '')))
5009
+ .map(dwFavoriteLeaf)
5010
+ statementCount += leaves.length
5011
+ tableRows.push({
5012
+ node: {
5013
+ key: dwNodeKey('favoriteTable', databaseName, tableKey),
5014
+ kind: 'favoriteTable',
5015
+ label: tableKey === '' ? tr('favoriteNoTable') : group.table,
5016
+ detail: `${leaves.length} ${tr('favoritesCount')}`,
5017
+ title: `${databaseName}${tableKey === '' ? '' : `.${group.table}`}`,
5018
+ database: databaseName,
5019
+ table: group.table,
5020
+ },
5021
+ children: leaves,
5022
+ })
5023
+ }
5024
+ rows.push({
5025
+ node: {
5026
+ key: dwNodeKey('favoriteDatabase', databaseName),
5027
+ kind: 'favoriteDatabase',
5028
+ label: databaseName,
5029
+ detail: `${statementCount} ${tr('favoritesCount')}`,
5030
+ title: `${tr('favoritesTitle')} · ${databaseName}`,
5031
+ database: databaseName,
5032
+ },
5033
+ children: tableRows,
5034
+ })
5035
+ }
5036
+ return rows
5037
+ }
5038
+
5039
+ /** Whether an `@` typed at `index` starts a favorite mention rather than `@var`. */
5040
+ function dwFavoriteMentionStart(text, index) {
5041
+ if (index <= 0) return true
5042
+ const before = text[index - 1]
5043
+ return /\s/.test(before) || '(),;=<>+-*/'.includes(before)
5044
+ }
5045
+
5046
+ /** The saved statements matching what was typed after `@`, name first. */
5047
+ function dwFavoriteMatches(favorites, query) {
5048
+ const needle = String(query ?? '').trim().toLowerCase()
5049
+ const list = (Array.isArray(favorites) ? favorites : []).filter((favorite) => favorite !== null
5050
+ && typeof favorite === 'object'
5051
+ && typeof favorite.name === 'string')
5052
+ const matched = needle === ''
5053
+ ? list
5054
+ : list.filter((favorite) => [favorite.name, favorite.database, favorite.table]
5055
+ .some((value) => String(value ?? '').toLowerCase().includes(needle)))
5056
+ return matched
5057
+ .slice()
5058
+ .sort((left, right) => left.name.localeCompare(right.name))
5059
+ .slice(0, 50)
5060
+ }
5061
+
5062
+ /**
5063
+ * Name one statement and keep it.
5064
+ *
5065
+ * The SQL is a read-only preview: what is collected is exactly the selection (or
5066
+ * the whole editor) the user right-clicked, and a rename or a re-collection is the
5067
+ * way to change it. The schema and table are editable because the console only
5068
+ * knows its own database — a statement that joins another schema is the user's
5069
+ * call, and it is what the tree groups by.
5070
+ */
5071
+ function DwFavoriteDialog({ store, tr, draft, onClose, onSaved }) {
5072
+ const editing = String(draft?.id ?? '') !== ''
5073
+ const [name, setName] = useState(String(draft?.name ?? ''))
5074
+ const [database, setDatabase] = useState(String(draft?.database ?? ''))
5075
+ const [table, setTable] = useState(String(draft?.table ?? ''))
5076
+ const [saving, setSaving] = useState(false)
5077
+ const [error, setError] = useState('')
5078
+ const sql = String(draft?.sql ?? '')
5079
+ const savingRef = useRef(false)
5080
+ savingRef.current = saving
5081
+ // A Chinese/Japanese name is typed through the IME: its Enter belongs to the
5082
+ // candidate list, not to the dialog. Chromium already flags the composition
5083
+ // keystroke, and the short grace period covers a browser that ends the
5084
+ // composition just before delivering that Enter.
5085
+ const composingRef = useRef(false)
5086
+ const compositionEndedAtRef = useRef(0)
5087
+ const imeBusy = (event) => dwImeComposing(event)
5088
+ || composingRef.current === true
5089
+ || Date.now() - compositionEndedAtRef.current < 100
5090
+ const databaseNames = dwDatabaseNames(store.getState?.()?.environments)
5091
+
5092
+ useEffect(() => {
5093
+ const onKey = (event) => {
5094
+ if (event.key !== 'Escape' || savingRef.current) return
5095
+ if (imeBusy(event)) return
5096
+ onClose()
5097
+ }
5098
+ globalThis.addEventListener('keydown', onKey)
5099
+ return () => globalThis.removeEventListener('keydown', onKey)
5100
+ }, [onClose])
5101
+
5102
+ const submit = async () => {
5103
+ if (saving === true) return
5104
+ const nextName = name.trim()
5105
+ const nextDatabase = database.trim()
5106
+ if (nextName === '') {
5107
+ setError(tr('favoriteNameRequired'))
5108
+ return
5109
+ }
5110
+ if (nextDatabase === '') {
5111
+ setError(tr('favoriteDatabaseRequired'))
5112
+ return
5113
+ }
5114
+ // The Host owns the real check; this one only saves a round trip on the
5115
+ // failure the user is most likely to hit while typing a name.
5116
+ const taken = (store.getState?.()?.favorites ?? []).find((favorite) => String(favorite?.name ?? '').trim().toLowerCase() === nextName.toLowerCase()
5117
+ && favorite?.id !== draft?.id)
5118
+ if (taken !== undefined) {
5119
+ setError(tr('error.duplicateFavorite'))
5120
+ return
5121
+ }
5122
+ setSaving(true)
5123
+ setError('')
5124
+ try {
5125
+ const value = await store.saveFavorite({
5126
+ id: draft?.id,
5127
+ name: nextName,
5128
+ database: nextDatabase,
5129
+ table: table.trim(),
5130
+ env: draft?.env ?? '',
5131
+ sql,
5132
+ })
5133
+ if (typeof onSaved === 'function') onSaved(value?.favorite)
5134
+ onClose()
5135
+ } catch (failure) {
5136
+ setError(dwExplainFailure(tr, failure))
5137
+ setSaving(false)
5138
+ }
5139
+ }
5140
+
5141
+ const field = (key, label, value, onChange, hint, options) => h('label', { key, className: 'dw-form-row' }, [
5142
+ h('span', { key: 'l', className: 'dw-form-label' }, label),
5143
+ h('input', {
5144
+ key: 'i',
5145
+ className: 'dw-form-input',
5146
+ value,
5147
+ spellCheck: false,
5148
+ autoComplete: 'off',
5149
+ autoFocus: options?.focus === true,
5150
+ list: options?.list,
5151
+ maxLength: options?.maxLength,
5152
+ onChange: (event) => onChange(event.target.value),
5153
+ onCompositionStart: () => {
5154
+ composingRef.current = true
5155
+ },
5156
+ onCompositionEnd: () => {
5157
+ composingRef.current = false
5158
+ compositionEndedAtRef.current = Date.now()
5159
+ },
5160
+ onKeyDown: (event) => {
5161
+ if (event.key !== 'Enter') return
5162
+ if (imeBusy(event)) return
5163
+ void submit()
5164
+ },
5165
+ }),
5166
+ hint === undefined ? null : h('span', { key: 'h', className: 'dw-form-hint' }, hint),
5167
+ ])
5168
+
5169
+ return h('div', {
5170
+ className: 'dw-modal',
5171
+ onClick: (event) => {
5172
+ if (event.target === event.currentTarget && saving !== true) onClose()
5173
+ },
5174
+ }, h('div', {
5175
+ key: 'card',
5176
+ className: 'dw-modal-card dw-favorite-dialog',
5177
+ role: 'dialog',
5178
+ 'aria-modal': 'true',
5179
+ 'aria-label': tr(editing ? 'favoriteEditTitle' : 'favoriteSaveTitle'),
5180
+ }, [
5181
+ h('div', { key: 'title', className: 'dw-modal-title' }, [
5182
+ h(DwIcon, { key: 'i', name: 'star', size: 15 }),
5183
+ h('span', { key: 't' }, tr(editing ? 'favoriteEditTitle' : 'favoriteSaveTitle')),
5184
+ ]),
5185
+ h('div', { key: 'body', className: 'dw-modal-body' }, h('div', { key: 'form', className: 'dw-form' }, [
5186
+ field('name', tr('favoriteName'), name, setName, tr('favoriteNameHint'), { focus: true, maxLength: 80 }),
5187
+ h('div', { key: 'split', className: 'dw-fav-split' }, [
5188
+ field('database', tr('favoriteDatabase'), database, setDatabase, tr('favoriteDatabaseHint'), { list: 'dw-favorite-databases', maxLength: 64 }),
5189
+ field('table', tr('favoriteTable'), table, setTable, tr('favoriteTableHint'), { maxLength: 64 }),
5190
+ ]),
5191
+ h('datalist', { key: 'names', id: 'dw-favorite-databases' }, databaseNames.map((value) => h('option', { key: value, value }))),
5192
+ h('div', { key: 'sql-label', className: 'dw-form-label' }, tr('favoriteSql')),
5193
+ h('pre', { key: 'sql', className: 'dw-fav-sql' }, sql),
5194
+ h('div', { key: 'hint', className: 'dw-ai-note' }, tr('favoriteDialogHint')),
5195
+ error === ''
5196
+ ? null
5197
+ : h('div', { key: 'err', className: 'dw-ai-note dw-ai-warn' }, error),
5198
+ ])),
5199
+ h('div', { key: 'foot', className: 'dw-modal-foot' }, [
5200
+ h('button', { key: 'cancel', type: 'button', className: 'dw-btn', disabled: saving === true, onClick: onClose }, tr('cancel')),
5201
+ h('button', {
5202
+ key: 'save',
5203
+ type: 'button',
5204
+ className: 'dw-btn dw-btn-accent',
5205
+ disabled: saving === true,
5206
+ onClick: () => void submit(),
5207
+ }, saving === true ? tr('schemaApplying') : tr(editing ? 'favoriteUpdateAction' : 'favoriteSaveAction')),
5208
+ ]),
5209
+ ]))
5210
+ }
5211
+
5212
+
4531
5213
  // ---- 30-editor.js --------------------------------------------------------
4532
5214
  /**
4533
5215
  * Workbench tabs, the SQL editor and the DDL document.
@@ -4585,7 +5267,7 @@ function dwInsertComposerText(text) {
4585
5267
  }
4586
5268
  }
4587
5269
 
4588
- function DwTabs({ store, state, tr }) {
5270
+ function DwTabs({ store, state, tr, onFavorite }) {
4589
5271
  const [menu, setMenu] = useState(null)
4590
5272
  if ((state.tabs ?? []).length === 0) return null
4591
5273
 
@@ -4647,6 +5329,9 @@ function DwTabs({ store, state, tr }) {
4647
5329
  menuItem('close-left', 'arrow-left', tr('tabCloseLeft'), index <= 0, () => store.closeTabsToLeft(menu.tab.id)),
4648
5330
  menuItem('close-right', 'arrow-right', tr('tabCloseRight'), index < 0 || index >= (state.tabs ?? []).length - 1, () => store.closeTabsToRight(menu.tab.id)),
4649
5331
  h('div', { key: 'sep', className: 'dw-tabmenu-sep' }),
5332
+ menuItem('favorite', 'star', tr('favoriteSave'), String(menu.tab.sql ?? '').trim() === '', () => {
5333
+ if (typeof onFavorite === 'function') onFavorite(menu.tab)
5334
+ }),
4650
5335
  menuItem('copy-reference', 'copy', tr('copyReference'), false, () => copyReference(menu.tab)),
4651
5336
  menuItem('copy-reference-chat', 'at', tr('copyReferenceToChat'), false, () => copyReferenceToChat(menu.tab)),
4652
5337
  ]))
@@ -4668,7 +5353,7 @@ function DwTabs({ store, state, tr }) {
4668
5353
  const left = rect === null || rect === undefined ? 8 : Math.max(8, rect.left + 8)
4669
5354
  const top = rect === null || rect === undefined ? 8 : Math.max(8, rect.top + 8)
4670
5355
  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
5356
+ const bottom = (rect === null || rect === undefined ? (globalThis.innerHeight ?? 800) : rect.bottom) - 268
4672
5357
  setMenu({
4673
5358
  x: Math.max(left, Math.min(event.clientX, Math.max(left, right))),
4674
5359
  y: Math.max(top, Math.min(event.clientY, Math.max(top, bottom))),
@@ -4704,24 +5389,36 @@ function DwTabs({ store, state, tr }) {
4704
5389
  ])
4705
5390
  }
4706
5391
 
4707
- /** A draggable horizontal divider that resizes the editor. */
4708
- function DwDragHandle({ value, onChange, min, max }) {
5392
+ /**
5393
+ * A draggable horizontal divider.
5394
+ *
5395
+ * `invert` is for a handle whose panel grows upward (the run log): dragging up
5396
+ * must make it taller. `onCommit` fires once on release, which is when a caller
5397
+ * should persist the value; writing on every pointermove would hit storage
5398
+ * sixty times a second.
5399
+ */
5400
+ function DwDragHandle({ value, onChange, min, max, invert, title, onStart, onCommit, onReset }) {
4709
5401
  return h('div', {
4710
5402
  className: 'dw-drag',
4711
5403
  role: 'separator',
4712
5404
  'aria-orientation': 'horizontal',
4713
- title: '↕',
5405
+ title: title ?? '↕',
5406
+ onDoubleClick: typeof onReset === 'function' ? onReset : undefined,
4714
5407
  onPointerDown: (event) => {
4715
5408
  event.preventDefault()
5409
+ if (typeof onStart === 'function') onStart()
4716
5410
  const startY = event.clientY
4717
5411
  const startValue = value
5412
+ const direction = invert === true ? -1 : 1
5413
+ let latest = value
4718
5414
  const onMove = (moveEvent) => {
4719
- const next = Math.min(max, Math.max(min, startValue + (moveEvent.clientY - startY)))
4720
- onChange(next)
5415
+ latest = Math.min(max, Math.max(min, startValue + (moveEvent.clientY - startY) * direction))
5416
+ onChange(latest)
4721
5417
  }
4722
5418
  const onUp = () => {
4723
5419
  globalThis.removeEventListener('pointermove', onMove)
4724
5420
  globalThis.removeEventListener('pointerup', onUp)
5421
+ if (typeof onCommit === 'function') onCommit(latest)
4725
5422
  }
4726
5423
  globalThis.addEventListener('pointermove', onMove)
4727
5424
  globalThis.addEventListener('pointerup', onUp)
@@ -4763,17 +5460,21 @@ function dwCaretPoint(area, text, caret) {
4763
5460
  }
4764
5461
 
4765
5462
  /** The SQL editor: highlighted text, completion and one-keystroke formatting. */
4766
- function DwEditor({ store, tab, tr, onRun, height, schema }) {
5463
+ function DwEditor({ store, tab, tr, onRun, height, schema, favorites }) {
4767
5464
  const value = tab.sql ?? ''
4768
5465
  const tokens = useMemo(() => dwSqlLex(value), [value])
4769
5466
  const lines = useMemo(() => value.split('\n').length, [value])
5467
+ const favoriteList = Array.isArray(favorites) ? favorites : []
4770
5468
  const gutterRef = useRef(null)
4771
5469
  const areaRef = useRef(null)
4772
5470
  const highlightRef = useRef(null)
4773
5471
  const completionRef = useRef(null)
5472
+ const mentionRef = useRef(null)
4774
5473
  const [completion, setCompletion] = useState(null)
5474
+ const [mention, setMention] = useState(null)
4775
5475
  const [editorMenu, setEditorMenu] = useState(null)
4776
5476
  const [optimize, setOptimize] = useState(null)
5477
+ const [favoriteDraft, setFavoriteDraft] = useState(null)
4777
5478
 
4778
5479
  useEffect(() => {
4779
5480
  const area = areaRef.current
@@ -4782,8 +5483,15 @@ function DwEditor({ store, tab, tr, onRun, height, schema }) {
4782
5483
  // lands where the user is about to type.
4783
5484
  area.focus()
4784
5485
  area.setSelectionRange(area.value.length, area.value.length)
5486
+ setMention(null)
4785
5487
  }, [tab.id])
4786
5488
 
5489
+ // The `@` index reads the machine-wide saved statements; one round trip the
5490
+ // first time a console opens, cached in the store afterwards.
5491
+ useEffect(() => {
5492
+ void store.loadFavorites()
5493
+ }, [store])
5494
+
4787
5495
  // The completion list needs the schema of this database; one round trip, cached
4788
5496
  // by the store. A failure only degrades the list to keywords.
4789
5497
  useEffect(() => {
@@ -4821,6 +5529,7 @@ function DwEditor({ store, tab, tr, onRun, height, schema }) {
4821
5529
  // Re-evaluate the caret once the map arrives so the popup appears on its own.
4822
5530
  useEffect(() => {
4823
5531
  if (schema === undefined) return
5532
+ if (mention !== null) return
4824
5533
  const area = areaRef.current
4825
5534
  if (area === null || document.activeElement !== area) return
4826
5535
  refreshCompletion(value, area.selectionStart)
@@ -4839,6 +5548,18 @@ function DwEditor({ store, tab, tr, onRun, height, schema }) {
4839
5548
  else if (bottom > popup.scrollTop + popup.clientHeight) popup.scrollTop = bottom - popup.clientHeight
4840
5549
  }, [completion])
4841
5550
 
5551
+ // Same keyboard-follows-list behaviour for the `@` index.
5552
+ useEffect(() => {
5553
+ const popup = mentionRef.current
5554
+ if (popup === null || mention === null) return
5555
+ const active = popup.querySelector('.dw-complete-row.active')
5556
+ if (active === null) return
5557
+ const top = active.offsetTop
5558
+ const bottom = top + active.offsetHeight
5559
+ if (top < popup.scrollTop) popup.scrollTop = top
5560
+ else if (bottom > popup.scrollTop + popup.clientHeight) popup.scrollTop = bottom - popup.clientHeight
5561
+ }, [mention])
5562
+
4842
5563
  const applyCompletion = (item) => {
4843
5564
  const current = completion
4844
5565
  if (current === null || item === undefined) return
@@ -4854,6 +5575,54 @@ function DwEditor({ store, tab, tr, onRun, height, schema }) {
4854
5575
  })
4855
5576
  }
4856
5577
 
5578
+ /**
5579
+ * The text a mention is filtering on, or `undefined` when the caret left it.
5580
+ *
5581
+ * A name may contain spaces (and Chinese), so the popup only ends at characters
5582
+ * that cannot appear in a name the user would type.
5583
+ */
5584
+ const mentionQueryAt = (text, from, caret) => {
5585
+ if (from < 0 || text[from] !== '@' || caret <= from) return undefined
5586
+ const query = text.slice(from + 1, caret)
5587
+ if (query.length > 60 || /[\r\n,;()]/.test(query)) return undefined
5588
+ // `@ ` is a sentence, not a mention: keep whitespace only once a name started.
5589
+ if (query !== '' && query.trim() === '') return undefined
5590
+ return query
5591
+ }
5592
+
5593
+ /** Grow the mention popup while its query is typed, or close it. */
5594
+ const refreshMention = (area, text, caret) => {
5595
+ const query = mentionQueryAt(text, mention.from, caret)
5596
+ if (query === undefined) {
5597
+ setMention(null)
5598
+ return false
5599
+ }
5600
+ const point = dwCaretPoint(area, text, caret)
5601
+ setMention({ ...mention, to: caret, query, index: 0, left: point.left, top: point.top + 20 })
5602
+ return true
5603
+ }
5604
+
5605
+ /** Put one saved statement where the `@…` token is, and keep the caret after it. */
5606
+ const insertFavorite = (favorite) => {
5607
+ const current = mention
5608
+ if (current === null || favorite === undefined || favorite === null) return
5609
+ const statement = String(favorite.sql ?? '')
5610
+ if (statement.trim() === '') return
5611
+ const next = `${value.slice(0, current.from)}${statement}${value.slice(current.to)}`
5612
+ const position = current.from + statement.length
5613
+ store.setTabSql(tab.id, next)
5614
+ setMention(null)
5615
+ requestAnimationFrame(() => {
5616
+ const area = areaRef.current
5617
+ if (area === null) return
5618
+ area.focus()
5619
+ area.setSelectionRange(position, position)
5620
+ })
5621
+ store.pushLog('info', tr('log.favoriteInserted', { name: favorite.name }))
5622
+ }
5623
+
5624
+ const mentionItems = mention === null ? [] : dwFavoriteMatches(favoriteList, mention.query)
5625
+
4857
5626
  const runStatement = () => {
4858
5627
  const area = areaRef.current
4859
5628
  const selected = area !== null && area.selectionEnd > area.selectionStart
@@ -4951,6 +5720,28 @@ function DwEditor({ store, tab, tr, onRun, height, schema }) {
4951
5720
  setOptimize({ sql: text, database: tab.database })
4952
5721
  }
4953
5722
 
5723
+ // Collect the selection when there is one, the whole console otherwise: that is
5724
+ // exactly the statement the user right-clicked. The schema comes from the console
5725
+ // and the table from its id, falling back to the first table the statement names.
5726
+ const openFavorite = () => {
5727
+ const area = areaRef.current
5728
+ const selected = area !== null && area.selectionEnd > area.selectionStart
5729
+ ? value.slice(area.selectionStart, area.selectionEnd)
5730
+ : ''
5731
+ const text = selected.trim() === '' ? value.trim() : selected.trim()
5732
+ if (text === '') {
5733
+ store.pushLog('warn', tr('log.noStatement'))
5734
+ return
5735
+ }
5736
+ setFavoriteDraft({
5737
+ sql: text,
5738
+ name: '',
5739
+ database: tab.database,
5740
+ table: dwTabTableName(tab) || (dwSqlTableRefs(text)[0]?.table ?? ''),
5741
+ env: tab.env ?? '',
5742
+ })
5743
+ }
5744
+
4954
5745
  const menuItem = (key, label, shortcut, run) => h('button', {
4955
5746
  key,
4956
5747
  type: 'button',
@@ -5015,6 +5806,7 @@ function DwEditor({ store, tab, tr, onRun, height, schema }) {
5015
5806
  menuItem('paste', tr('editorPaste'), '⌘V', () => void editorPaste()),
5016
5807
  menuItem('select-all', tr('editorSelectAll'), '⌘A', editorSelectAll),
5017
5808
  h('div', { key: 'sep2', className: 'dw-project-sep' }),
5809
+ menuItem('favorite', tr('favoriteSave'), '', openFavorite),
5018
5810
  menuItem('optimize', tr('sqlOptimize'), '', openOptimize),
5019
5811
  ]),
5020
5812
  ])
@@ -5044,13 +5836,29 @@ function DwEditor({ store, tab, tr, onRun, height, schema }) {
5044
5836
  const text = event.target.value
5045
5837
  const caret = event.target.selectionStart
5046
5838
  store.setTabSql(tab.id, text)
5839
+ if (mention !== null) {
5840
+ // Still inside the same `@…` token: filter it instead of letting the
5841
+ // column list fight the favorites list for the same keystrokes.
5842
+ if (refreshMention(event.target, text, caret)) return
5843
+ }
5844
+ if (caret > 0 && text[caret - 1] === '@' && dwFavoriteMentionStart(text, caret - 1)) {
5845
+ const point = dwCaretPoint(event.target, text, caret)
5846
+ setCompletion(null)
5847
+ setMention({ from: caret - 1, to: caret, query: '', index: 0, left: point.left, top: point.top + 20 })
5848
+ return
5849
+ }
5047
5850
  refreshCompletion(text, caret)
5048
5851
  },
5049
- onClick: (event) => refreshCompletion(event.target.value, event.target.selectionStart),
5852
+ onClick: (event) => {
5853
+ setMention(null)
5854
+ refreshCompletion(event.target.value, event.target.selectionStart)
5855
+ },
5050
5856
  onContextMenu: (event) => {
5051
5857
  event.preventDefault()
5858
+ setMention(null)
5859
+ setCompletion(null)
5052
5860
  const width = 210
5053
- const height = 268
5861
+ const height = 300
5054
5862
  const maxX = (globalThis.innerWidth ?? 1200) - width
5055
5863
  const maxY = (globalThis.innerHeight ?? 800) - height
5056
5864
  setEditorMenu({
@@ -5058,10 +5866,42 @@ function DwEditor({ store, tab, tr, onRun, height, schema }) {
5058
5866
  y: Math.max(8, Math.min(event.clientY, maxY)),
5059
5867
  })
5060
5868
  },
5061
- onBlur: () => setCompletion(null),
5869
+ onBlur: () => {
5870
+ setCompletion(null)
5871
+ setMention(null)
5872
+ },
5062
5873
  onScroll: (event) => syncScroll(event.target),
5063
5874
  onKeyDown: (event) => {
5875
+ // An IME candidate key (Enter to commit, Escape to cancel, arrows to
5876
+ // move through the list) belongs to the IME: never turn it into a
5877
+ // command, a suggestion pick or a run.
5878
+ if (dwImeComposing(event)) return
5064
5879
  const modifier = event.metaKey || event.ctrlKey
5880
+ if (mention !== null) {
5881
+ const size = mentionItems.length
5882
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
5883
+ if (size === 0) {
5884
+ setMention(null)
5885
+ return
5886
+ }
5887
+ event.preventDefault()
5888
+ const delta = event.key === 'ArrowDown' ? 1 : -1
5889
+ setMention({ ...mention, index: (mention.index + delta + size) % size })
5890
+ return
5891
+ }
5892
+ if ((event.key === 'Enter' && !modifier) || event.key === 'Tab') {
5893
+ if (size > 0) {
5894
+ event.preventDefault()
5895
+ insertFavorite(mentionItems[Math.min(mention.index, size - 1)])
5896
+ return
5897
+ }
5898
+ }
5899
+ if (event.key === 'Escape') {
5900
+ event.preventDefault()
5901
+ setMention(null)
5902
+ return
5903
+ }
5904
+ }
5065
5905
  if (completion !== null) {
5066
5906
  if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
5067
5907
  event.preventDefault()
@@ -5124,6 +5964,32 @@ function DwEditor({ store, tab, tr, onRun, height, schema }) {
5124
5964
  h('span', { key: 'd', className: 'dw-complete-detail' }, item.detail ?? ''),
5125
5965
  h('span', { key: 'k', className: 'dw-complete-kind' }, item.kind === 'column' ? tr('suggestColumn') : item.kind === 'table' ? tr('suggestTable') : tr('suggestKeyword')),
5126
5966
  ]))),
5967
+ mention === null
5968
+ ? null
5969
+ : h('div', {
5970
+ key: 'mention',
5971
+ ref: mentionRef,
5972
+ className: 'dw-complete dw-mention',
5973
+ style: { left: mention.left, top: mention.top },
5974
+ role: 'listbox',
5975
+ 'aria-label': tr('favoriteMentionLabel'),
5976
+ }, mentionItems.length === 0
5977
+ ? h('div', { key: 'none', className: 'dw-complete-empty' },
5978
+ favoriteList.length === 0 ? tr('favoriteMentionNoFavorites') : tr('favoriteMentionEmpty'))
5979
+ : mentionItems.map((favorite, index) => h('div', {
5980
+ key: favorite.id,
5981
+ role: 'option',
5982
+ 'aria-selected': index === mention.index,
5983
+ className: index === mention.index ? 'dw-complete-row active' : 'dw-complete-row',
5984
+ onMouseDown: (event) => event.preventDefault(),
5985
+ onClick: () => insertFavorite(favorite),
5986
+ }, [
5987
+ h('span', { key: 'ic', className: 'dw-node-icon' }, h(DwIcon, { name: 'star', size: 11 })),
5988
+ h('span', { key: 'l', className: 'dw-complete-label' }, favorite.name),
5989
+ h('span', { key: 'd', className: 'dw-complete-detail' },
5990
+ [favorite.database, favorite.table].filter((part) => typeof part === 'string' && part !== '').join('.')),
5991
+ h('span', { key: 'k', className: 'dw-complete-kind' }, tr('suggestFavorite')),
5992
+ ]))),
5127
5993
  ]),
5128
5994
  ]),
5129
5995
  editorMenuLayer,
@@ -5135,6 +6001,13 @@ function DwEditor({ store, tab, tr, onRun, height, schema }) {
5135
6001
  database: optimize.database,
5136
6002
  onClose: () => setOptimize(null),
5137
6003
  }),
6004
+ favoriteDraft === null ? null : h(DwFavoriteDialog, {
6005
+ key: 'favorite',
6006
+ store,
6007
+ tr,
6008
+ draft: favoriteDraft,
6009
+ onClose: () => setFavoriteDraft(null),
6010
+ }),
5138
6011
  ])
5139
6012
  }
5140
6013
 
@@ -5365,6 +6238,9 @@ const DwGrid = React.memo(function DwGrid({
5365
6238
  props.title = tr('editingCellHint')
5366
6239
  props.onBlur = (event) => onEditCommit(rowIndex, cellIndex, column.name, event.currentTarget.textContent)
5367
6240
  props.onKeyDown = (event) => {
6241
+ // Committing an IME candidate with Enter must not blur the editor: the
6242
+ // cell is still being typed, and blur would write the pre-commit value.
6243
+ if (dwImeComposing(event)) return
5368
6244
  if (event.key === 'Enter') {
5369
6245
  event.preventDefault()
5370
6246
  event.currentTarget.blur()
@@ -6070,6 +6946,19 @@ const DW_SIDE_MAX = 720
6070
6946
  const DW_SIDE_DEFAULT = 268
6071
6947
  const DW_SIDE_KEY = 'dsh-data-window:side-width'
6072
6948
 
6949
+ /** Bounds for the run log at the bottom of the panel, in pixels. */
6950
+ const DW_LOG_MIN = 72
6951
+ const DW_LOG_DEFAULT = 132
6952
+ const DW_LOG_MAX = 560
6953
+ const DW_LOG_KEY = 'dsh-data-window:log-height'
6954
+
6955
+ /** Stored run-log height, clamped so a bad value cannot hide the workbench. */
6956
+ function dwReadLogHeight() {
6957
+ const raw = Number(globalThis.localStorage?.getItem(DW_LOG_KEY))
6958
+ if (!Number.isFinite(raw) || raw <= 0) return DW_LOG_DEFAULT
6959
+ return Math.min(DW_LOG_MAX, Math.max(DW_LOG_MIN, raw))
6960
+ }
6961
+
6073
6962
  /** Wide layouts collapse the navigation column; below this the toggle is a drawer. */
6074
6963
  const DW_WIDE_LAYOUT = 1024
6075
6964
 
@@ -6246,6 +7135,8 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6246
7135
  const [menu, setMenu] = useState(null)
6247
7136
  const [editorHeight, setEditorHeight] = useState(168)
6248
7137
  const [sideWidth, setSideWidth] = useState(() => dwReadSideWidth())
7138
+ const [logHeight, setLogHeight] = useState(() => dwReadLogHeight())
7139
+ const [logDragging, setLogDragging] = useState(false)
6249
7140
  const [sidebarHidden, setSidebarHidden] = useState(false)
6250
7141
  const [aiOpen, setAiOpen] = useState(false)
6251
7142
  const [manualOpen, setManualOpen] = useState(false)
@@ -6253,6 +7144,8 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6253
7144
  const [ddlTarget, setDdlTarget] = useState(null)
6254
7145
  const [renameTarget, setRenameTarget] = useState(null)
6255
7146
  const [removeEnvTarget, setRemoveEnvTarget] = useState(null)
7147
+ const [favoriteDraft, setFavoriteDraft] = useState(null)
7148
+ const [removeFavoriteTarget, setRemoveFavoriteTarget] = useState(null)
6256
7149
  const aiPrompted = useRef(false)
6257
7150
  const panelRef = useRef(null)
6258
7151
  const logRef = useRef(null)
@@ -6271,6 +7164,12 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6271
7164
  if (detected !== '') store.setDetectedRoot(detected)
6272
7165
  }, [detected, store])
6273
7166
 
7167
+ // Saved statements are shared by every workspace, so they load once when the
7168
+ // panel opens rather than on each discovery.
7169
+ useEffect(() => {
7170
+ void store.loadFavorites()
7171
+ }, [store])
7172
+
6274
7173
  // First open of a workspace the rule-based scan cannot read: offer the model
6275
7174
  // picker instead of leaving the user with an empty tree and no next step. It
6276
7175
  // asks once per mount and only while no model has been chosen yet.
@@ -6345,6 +7244,20 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6345
7244
  globalThis.localStorage?.setItem(DW_SIDE_KEY, String(DW_SIDE_DEFAULT))
6346
7245
  }
6347
7246
 
7247
+ /** Keep the run-log height for the next open; release is the write moment. */
7248
+ const persistLogHeight = (height) => {
7249
+ try {
7250
+ globalThis.localStorage?.setItem(DW_LOG_KEY, String(height))
7251
+ } catch (error) {
7252
+ void error
7253
+ }
7254
+ }
7255
+
7256
+ const resetLogHeight = () => {
7257
+ setLogHeight(DW_LOG_DEFAULT)
7258
+ persistLogHeight(DW_LOG_DEFAULT)
7259
+ }
7260
+
6348
7261
  // Requirement 3: one keystroke from the selected table to its create statement.
6349
7262
  useEffect(() => {
6350
7263
  const onKey = (event) => {
@@ -6440,29 +7353,47 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6440
7353
  title: sidebarHidden ? tr('showSidebar') : tr('hideSidebar'),
6441
7354
  'aria-label': sidebarHidden ? tr('showSidebar') : tr('hideSidebar'),
6442
7355
  }, h(DwIcon, { name: 'panel', size: 13 })),
6443
- h('button', {
6444
- key: 'refresh',
6445
- type: 'button',
6446
- className: 'dw-btn',
6447
- disabled: state.root === '' || state.refreshing === true || state.phase === 'loading',
6448
- onClick: () => void store.loadDiscovery({ refresh: true }),
6449
- title: tr('refreshHint'),
6450
- }, [
6451
- h(DwIcon, { key: 'i', name: state.refreshing === true || state.phase === 'loading' ? 'spinner' : 'refresh', size: 12 }),
6452
- h('span', { key: 't' }, tr('refresh')),
6453
- ]),
6454
7356
  ])
6455
7357
 
6456
7358
  const selectedTable = state.selectedNode !== null
6457
7359
  && state.selectedNode !== undefined
6458
7360
  && (state.selectedNode.kind === 'table' || state.selectedNode.kind === 'view' || state.selectedNode.kind === 'database')
6459
7361
 
7362
+ // The resource manager has two tabs, like DataGrip's Database window: the
7363
+ // configured tree and the saved statements. The tab strip sits above the filter
7364
+ // so the same search applies to whichever list is showing.
7365
+ const treeTab = state.treeTab === 'favorites' ? 'favorites' : 'databases'
7366
+ const treeTabButton = (key, icon, label, count) => h('button', {
7367
+ key,
7368
+ type: 'button',
7369
+ role: 'tab',
7370
+ 'aria-selected': treeTab === key,
7371
+ className: treeTab === key ? 'dw-tree-tab on' : 'dw-tree-tab',
7372
+ onClick: () => store.setTreeTab(key),
7373
+ }, [
7374
+ h(DwIcon, { key: 'i', name: icon, size: 12 }),
7375
+ h('span', { key: 'l' }, label),
7376
+ typeof count === 'number' && count > 0
7377
+ ? h('span', { key: 'c', className: 'dw-tree-tab-count' }, String(count))
7378
+ : null,
7379
+ ])
7380
+
6460
7381
  const side = h('aside', { key: 'side', className: 'dw-side', style: { width: sideWidth } }, [
6461
7382
  h('div', { key: 'head', className: 'dw-side-head' }, [
6462
7383
  h('span', { key: 't' }, tr('treeTitle')),
6463
7384
  h('span', { key: 'sp', className: 'dw-spacer' }),
6464
7385
  selectedTable === true ? h('span', { key: 'n' }, tr('ddlShortcutHint')) : null,
6465
- // These two belong to the tree, so they live in the tree's own header.
7386
+ // These belong to the explorer, so they live in the explorer's own header:
7387
+ // re-read the workspace, let a model look at it, or add a connection.
7388
+ h('button', {
7389
+ key: 'reload-workspace',
7390
+ type: 'button',
7391
+ className: 'dw-btn dw-btn-icon',
7392
+ disabled: state.root === '' || state.refreshing === true || state.phase === 'loading',
7393
+ onClick: () => void store.loadDiscovery({ refresh: true }),
7394
+ title: tr('refreshHint'),
7395
+ 'aria-label': tr('refresh'),
7396
+ }, h(DwIcon, { key: 'i', name: state.refreshing === true || state.phase === 'loading' ? 'spinner' : 'refresh', size: 12 })),
6466
7397
  h('button', {
6467
7398
  key: 'ai',
6468
7399
  type: 'button',
@@ -6484,12 +7415,27 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6484
7415
  'aria-label': tr('manualOpen'),
6485
7416
  }, h(DwIcon, { key: 'i', name: 'plus', size: 12 })),
6486
7417
  ]),
7418
+ h('div', { key: 'tabs', className: 'dw-tree-tabs', role: 'tablist', 'aria-label': tr('treeTabsLabel') }, [
7419
+ treeTabButton('databases', 'database', tr('treeTabDatabases')),
7420
+ treeTabButton('favorites', 'star', tr('favoritesTitle'), (state.favorites ?? []).length),
7421
+ h('span', { key: 'sp', className: 'dw-spacer' }),
7422
+ treeTab === 'favorites'
7423
+ ? h('button', {
7424
+ key: 'reload-favorites',
7425
+ type: 'button',
7426
+ className: 'dw-btn dw-btn-icon',
7427
+ title: tr('favoritesReload'),
7428
+ 'aria-label': tr('favoritesReload'),
7429
+ onClick: () => void store.loadFavorites({ force: true }),
7430
+ }, h(DwIcon, { key: 'i', name: 'refresh', size: 12 }))
7431
+ : null,
7432
+ ]),
6487
7433
  h('div', { key: 'filter', style: { padding: '5px 8px', borderBottom: '1px solid var(--dsw-alias-border-l1)' } }, [
6488
7434
  h('input', {
6489
7435
  key: 'i',
6490
7436
  type: 'search',
6491
7437
  value: state.filter ?? '',
6492
- placeholder: tr('filterPlaceholder'),
7438
+ placeholder: tr(treeTab === 'favorites' ? 'filterFavoritesPlaceholder' : 'filterPlaceholder'),
6493
7439
  onChange: (event) => store.patch({ filter: event.target.value }),
6494
7440
  style: {
6495
7441
  width: '100%',
@@ -6532,7 +7478,28 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6532
7478
  ]))
6533
7479
  } else {
6534
7480
  main = h('div', { key: 'main', className: 'dw-main' }, [
6535
- h(DwTabs, { key: 'tabs', store, state, tr }),
7481
+ h(DwTabs, {
7482
+ key: 'tabs',
7483
+ store,
7484
+ state,
7485
+ tr,
7486
+ // A console tab can be collected whole: the tab knows its schema and table,
7487
+ // which is exactly what the favorite has to carry.
7488
+ onFavorite: (tab) => {
7489
+ const sql = String(tab.sql ?? '').trim()
7490
+ if (sql === '') {
7491
+ store.pushLog('warn', tr('log.noStatement'))
7492
+ return
7493
+ }
7494
+ setFavoriteDraft({
7495
+ sql,
7496
+ name: '',
7497
+ database: tab.database,
7498
+ table: dwTabTableName(tab),
7499
+ env: tab.env ?? '',
7500
+ })
7501
+ },
7502
+ }),
6536
7503
  activeTab === undefined
6537
7504
  ? h(DwEmpty, { key: 'empty', tr, state, onPick: pickWorkspace, onOpenAi: () => setAiOpen(true), onOpenManual: () => setManualOpen(true) })
6538
7505
  : h(React.Fragment, { key: activeTab.id }, [
@@ -6543,6 +7510,7 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6543
7510
  tr,
6544
7511
  height: editorHeight,
6545
7512
  schema: state.schemas?.get(activeTab.dbId),
7513
+ favorites: state.favorites ?? [],
6546
7514
  onRun: (statement) => void store.runActiveTab(statement),
6547
7515
  }),
6548
7516
  h(DwDragHandle, {
@@ -6557,7 +7525,23 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6557
7525
  ])
6558
7526
  }
6559
7527
 
6560
- const log = h('div', { key: 'log', className: `dw-log${state.logOpen === true ? '' : ' dw-log-collapsed'}` }, [
7528
+ // The log grows upward; leave the tab strip plus a usable editor/results area
7529
+ // above it, and never exceed the fixed ceiling.
7530
+ const panelHeight = panelRef.current?.getBoundingClientRect?.().height ?? (globalThis.innerHeight ?? 800)
7531
+ const logMax = Math.max(DW_LOG_MIN + 40, Math.min(DW_LOG_MAX, Math.round(panelHeight - 300)))
7532
+ // A window that shrank after the height was stored must not push the workbench
7533
+ // out of the panel; the stored value is kept for when there is room again.
7534
+ const visibleLogHeight = Math.min(logHeight, logMax)
7535
+
7536
+ const log = h('div', {
7537
+ key: 'log',
7538
+ className: `dw-log${state.logOpen === true ? '' : ' dw-log-collapsed'}`,
7539
+ // An open log follows the stored height; while dragging, the CSS open/close
7540
+ // transition must not lag behind the pointer.
7541
+ style: state.logOpen === true
7542
+ ? { height: visibleLogHeight, transition: logDragging === true ? 'none' : undefined }
7543
+ : undefined,
7544
+ }, [
6561
7545
  h('div', { key: 'bar', className: 'dw-log-bar' }, [
6562
7546
  h('button', {
6563
7547
  key: 'toggle',
@@ -6611,7 +7595,18 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6611
7595
  left: Math.max(rect === undefined ? 0 : rect.left, left),
6612
7596
  top: Math.max(rect === undefined ? 0 : rect.top, top),
6613
7597
  },
6614
- }, dwMenuItems(menu.node, store, tr, () => setMenu(null), (node) => setSchemaTarget(node), (node) => setRenameTarget(node), (node) => setRemoveEnvTarget(node), (node) => setDdlTarget(node))),
7598
+ }, dwMenuItems(
7599
+ menu.node,
7600
+ store,
7601
+ tr,
7602
+ () => setMenu(null),
7603
+ (node) => setSchemaTarget(node),
7604
+ (node) => setRenameTarget(node),
7605
+ (node) => setRemoveEnvTarget(node),
7606
+ (node) => setDdlTarget(node),
7607
+ (favorite) => setFavoriteDraft({ ...favorite }),
7608
+ (favorite) => setRemoveFavoriteTarget(favorite),
7609
+ )),
6615
7610
  ])
6616
7611
  }
6617
7612
 
@@ -6631,6 +7626,23 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6631
7626
  }),
6632
7627
  main,
6633
7628
  ]),
7629
+ state.logOpen === true
7630
+ ? h(DwDragHandle, {
7631
+ key: 'log-drag',
7632
+ value: visibleLogHeight,
7633
+ min: DW_LOG_MIN,
7634
+ max: logMax,
7635
+ invert: true,
7636
+ title: tr('resizeLog'),
7637
+ onChange: setLogHeight,
7638
+ onStart: () => setLogDragging(true),
7639
+ onCommit: (height) => {
7640
+ setLogDragging(false)
7641
+ persistLogHeight(height)
7642
+ },
7643
+ onReset: resetLogHeight,
7644
+ })
7645
+ : null,
6634
7646
  log,
6635
7647
  menuLayer,
6636
7648
  aiOpen ? h(DwAiDialog, {
@@ -6684,6 +7696,30 @@ function DwPanel({ store, translate, useSessions, useWorkspaces, pickDirectory }
6684
7696
  instance: schemaTarget,
6685
7697
  onClose: () => setSchemaTarget(null),
6686
7698
  }),
7699
+ favoriteDraft === null ? null : h(DwFavoriteDialog, {
7700
+ key: 'favorite-dialog',
7701
+ store,
7702
+ tr,
7703
+ draft: favoriteDraft,
7704
+ onClose: () => setFavoriteDraft(null),
7705
+ onSaved: () => setMenu(null),
7706
+ }),
7707
+ removeFavoriteTarget === null ? null : h(DwConfirmDialog, {
7708
+ key: 'remove-favorite-dialog',
7709
+ tr,
7710
+ title: tr('removeFavoriteTitle'),
7711
+ message: tr('removeFavoriteHint', { name: removeFavoriteTarget.name }),
7712
+ confirmLabel: tr('removeFavoriteConfirm'),
7713
+ onClose: () => setRemoveFavoriteTarget(null),
7714
+ onConfirm: async () => {
7715
+ try {
7716
+ await store.removeFavorite(removeFavoriteTarget.id)
7717
+ } catch (error) {
7718
+ store.pushLog('error', tr('log.favoriteRemoveFailed', { message: dwExplainFailure(tr, error) }))
7719
+ }
7720
+ setRemoveFavoriteTarget(null)
7721
+ },
7722
+ }),
6687
7723
  ])
6688
7724
  }
6689
7725
 
@@ -6695,7 +7731,7 @@ function dwClock(date) {
6695
7731
  }
6696
7732
 
6697
7733
  /** The context menu of one node. */
6698
- function dwMenuItems(node, store, tr, close, openSchemaDialog, openRenameEnv, openRemoveEnv, openDdlDialog) {
7734
+ function dwMenuItems(node, store, tr, close, openSchemaDialog, openRenameEnv, openRemoveEnv, openDdlDialog, openFavoriteDialog, confirmRemoveFavorite) {
6699
7735
  const items = []
6700
7736
  const add = (key, label, shortcut, run, tone) => items.push(h('button', {
6701
7737
  key,
@@ -6707,7 +7743,18 @@ function dwMenuItems(node, store, tr, close, openSchemaDialog, openRenameEnv, op
6707
7743
  },
6708
7744
  }, [h('span', { key: 'l' }, label), shortcut === '' ? null : h('span', { key: 's', className: 'dw-menu-shortcut' }, shortcut)]))
6709
7745
 
6710
- if (node.kind === 'table' || node.kind === 'view') {
7746
+ if (node.kind === 'favorite') {
7747
+ const favorite = node.favorite
7748
+ add('open-favorite', tr('menuOpenFavorite'), '', () => store.openFavorite(favorite))
7749
+ add('copy-favorite-sql', tr('menuCopyFavoriteSql'), '', () => {
7750
+ const write = globalThis.navigator?.clipboard?.writeText?.(String(favorite.sql ?? ''))
7751
+ if (write !== undefined) write.then(() => store.pushLog('info', tr('log.favoriteCopied', { name: favorite.name }))).catch(() => undefined)
7752
+ })
7753
+ add('edit-favorite', tr('menuEditFavorite'), '', () => openFavoriteDialog(favorite))
7754
+ add('remove-favorite', tr('menuRemoveFavorite'), '', () => confirmRemoveFavorite(favorite), 'dw-menu-danger')
7755
+ } else if (node.kind === 'favoriteDatabase' || node.kind === 'favoriteTable') {
7756
+ add('expand', tr('menuExpand'), '', () => void store.toggleNode(node))
7757
+ } else if (node.kind === 'table' || node.kind === 'view') {
6711
7758
  add('ddl', tr('menuDdl'), 'F4', () => openDdlDialog(node))
6712
7759
  add('data', tr('menuOpenData'), '', () => {
6713
7760
  const statement = `SELECT *\nFROM \`${node.database}\`.\`${node.table}\`\nLIMIT 100`
@@ -7035,6 +8082,7 @@ function DwSchemaDialog({ store, tr, instance, onClose }) {
7035
8082
  useEffect(() => {
7036
8083
  const onKey = (event) => {
7037
8084
  if (event.key !== 'Escape' || savingRef.current) return
8085
+ if (dwImeComposing(event)) return
7038
8086
  onClose()
7039
8087
  }
7040
8088
  globalThis.addEventListener('keydown', onKey)
@@ -7220,6 +8268,7 @@ function DwManualDialog({ store, tr, onClose, onSaved }) {
7220
8268
  useEffect(() => {
7221
8269
  const onKey = (event) => {
7222
8270
  if (event.key !== 'Escape' || savingRef.current) return
8271
+ if (dwImeComposing(event)) return
7223
8272
  onClose()
7224
8273
  }
7225
8274
  globalThis.addEventListener('keydown', onKey)
@@ -7401,6 +8450,7 @@ function DwRenameEnvDialog({ store, tr, label, onClose, onRenamed }) {
7401
8450
  useEffect(() => {
7402
8451
  const onKey = (event) => {
7403
8452
  if (event.key !== 'Escape' || savingRef.current) return
8453
+ if (dwImeComposing(event)) return
7404
8454
  onClose()
7405
8455
  }
7406
8456
  globalThis.addEventListener('keydown', onKey)
@@ -7454,7 +8504,9 @@ function DwRenameEnvDialog({ store, tr, label, onClose, onRenamed }) {
7454
8504
  autoComplete: 'off',
7455
8505
  onChange: (event) => setValue(event.target.value),
7456
8506
  onKeyDown: (event) => {
7457
- if (event.key === 'Enter') void save()
8507
+ if (event.key !== 'Enter') return
8508
+ if (dwImeComposing(event)) return
8509
+ void save()
7458
8510
  },
7459
8511
  }),
7460
8512
  ]),
@@ -7490,6 +8542,7 @@ function DwConfirmDialog({ tr, title, message, confirmLabel, onConfirm, onClose
7490
8542
  useEffect(() => {
7491
8543
  const onKey = (event) => {
7492
8544
  if (event.key !== 'Escape' || busyRef.current) return
8545
+ if (dwImeComposing(event)) return
7493
8546
  onClose()
7494
8547
  }
7495
8548
  globalThis.addEventListener('keydown', onKey)
@@ -7638,6 +8691,7 @@ function DwAiDialog({ store, tr, onClose, onManual }) {
7638
8691
  const onKey = (event) => {
7639
8692
  if (event.key !== 'Escape') return
7640
8693
  if (modeRef.current === 'running') return
8694
+ if (dwImeComposing(event)) return
7641
8695
  onClose()
7642
8696
  }
7643
8697
  globalThis.addEventListener('keydown', onKey)