dsh-data-window 0.1.1 → 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.
@@ -134,6 +134,20 @@ function dwLogEntry(level, text) {
134
134
  return { id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, at: new Date(), level, text }
135
135
  }
136
136
 
137
+ /**
138
+ * Whether a key event belongs to an input-method composition.
139
+ *
140
+ * The Enter/Escape that picks or cancels a Chinese or Japanese candidate belongs
141
+ * to the IME, not to this window: it must never submit a dialog, blur a cell or
142
+ * pick a suggestion. Chromium marks those events with `isComposing` and the legacy
143
+ * 229 keyCode; React's synthetic keyboard event does not expose `isComposing`, so
144
+ * the native event is what is checked.
145
+ */
146
+ function dwImeComposing(event) {
147
+ const native = event?.nativeEvent ?? event
148
+ return native?.isComposing === true || (native?.keyCode ?? event?.keyCode) === 229
149
+ }
150
+
137
151
  /**
138
152
  * Turn a Host failure into a sentence.
139
153
  *
@@ -157,6 +171,7 @@ function dwExplainFailure(translate, error) {
157
171
  'ER_QUERY_INTERRUPTED': 'error.interrupted',
158
172
  'manual-connect-failed': 'error.manualConnectFailed',
159
173
  'saved-connection-missing': 'error.savedConnectionMissing',
174
+ 'duplicate-favorite': 'error.duplicateFavorite',
160
175
  }
161
176
  const key = known[code]
162
177
  if (key !== undefined) {
@@ -228,6 +243,19 @@ const DW_CONSOLE_KEY = 'dsh-data-window:consoles'
228
243
  /** Client-side preferences edited in the plugin's settings section. */
229
244
  const DW_PREFS_KEY = 'dsh-data-window:prefs'
230
245
 
246
+ /** Which side-panel tab was last shown: the database tree or the favorites list. */
247
+ const DW_TREE_TAB_KEY = 'dsh-data-window:tree-tab'
248
+
249
+ /** The remembered side-panel tab; unknown or blocked storage means the tree. */
250
+ function dwReadTreeTab() {
251
+ try {
252
+ return globalThis.localStorage?.getItem(DW_TREE_TAB_KEY) === 'favorites' ? 'favorites' : 'databases'
253
+ } catch (error) {
254
+ void error
255
+ return 'databases'
256
+ }
257
+ }
258
+
231
259
  /** Read the display preferences, tolerating a blocked storage. */
232
260
  function dwReadPrefs() {
233
261
  const fallback = { autoHideSidebar: true, defaultLimit: 0, shortcutOpen: null, aiModel: null }
@@ -329,6 +357,9 @@ function dwCreateStore(translate) {
329
357
  aiRunning: false,
330
358
  // tree
331
359
  filter: '',
360
+ // The resource manager has two tabs, like DataGrip's Database window: the
361
+ // configured tree and the saved statements. Both read the same filter.
362
+ treeTab: dwReadTreeTab(),
332
363
  expanded: new Set(),
333
364
  loadState: new Map(),
334
365
  children: new Map(),
@@ -340,6 +371,11 @@ function dwCreateStore(translate) {
340
371
  // Table/column maps for the editor's completion, one per database.
341
372
  schemas: new Map(),
342
373
  limit: DW_DEFAULT_LIMIT,
374
+ // Saved statements (machine-wide, not per workspace) and the `@` index they
375
+ // feed; the tree's favorites node is rendered from this list.
376
+ favorites: [],
377
+ favoritesLoading: false,
378
+ favoritesError: '',
343
379
  // log
344
380
  logOpen: false,
345
381
  log: [dwLogEntry('info', t('log.ready'))],
@@ -743,6 +779,108 @@ function dwCreateStore(translate) {
743
779
  }
744
780
  },
745
781
 
782
+ /**
783
+ * Read the saved statements.
784
+ *
785
+ * The list belongs to the machine, not to one workspace, so it is loaded when
786
+ * the panel opens; saves and deletes patch it in place. No workspace is needed.
787
+ */
788
+ async loadFavorites(options = {}) {
789
+ if (state.favoritesLoading === true && options.force !== true) return
790
+ patch({ favoritesLoading: true })
791
+ try {
792
+ const value = await dwRpc('favorites')
793
+ patch({
794
+ favorites: Array.isArray(value?.favorites) ? value.favorites : [],
795
+ favoritesLoading: false,
796
+ favoritesError: '',
797
+ })
798
+ } catch (error) {
799
+ patch({ favoritesLoading: false, favoritesError: dwExplainFailure(t, error) })
800
+ if (options.quiet !== true) pushLog('warn', t('log.favoriteLoadFailed', { message: dwExplainFailure(t, error) }))
801
+ }
802
+ },
803
+
804
+ /** Save one statement under its unique name, and open the favorites node. */
805
+ async saveFavorite(input) {
806
+ const value = await dwRpc('saveFavorite', { favorite: { ...input } })
807
+ const favorite = value?.favorite
808
+ if (favorite !== undefined && favorite !== null) {
809
+ const favorites = [...state.favorites]
810
+ const index = favorites.findIndex((entry) => entry.id === favorite.id)
811
+ if (index >= 0) favorites[index] = favorite
812
+ else favorites.push(favorite)
813
+ patch({ favorites })
814
+ pushLog('info', t('log.favoriteSaved', { name: favorite.name, database: favorite.database }))
815
+ const tableKey = String(favorite.table ?? '').trim().toLowerCase()
816
+ // The saved statement lives on the favorites tab now; switching there and
817
+ // expanding its schema/table is the only visible acknowledgement that the
818
+ // save landed, since the database tree cannot show it.
819
+ store.setTreeTab('favorites')
820
+ store.expand(
821
+ dwNodeKey('favoriteDatabase', favorite.database),
822
+ dwNodeKey('favoriteTable', favorite.database, tableKey),
823
+ )
824
+ const favoriteKey = dwNodeKey('favorite', favorite.id)
825
+ store.select({ key: favoriteKey, kind: 'favorite', label: favorite.name, favorite })
826
+ }
827
+ return value
828
+ },
829
+
830
+ /** Delete one saved statement. */
831
+ async removeFavorite(id) {
832
+ const value = await dwRpc('removeFavorite', { id })
833
+ if (value?.removed === true) {
834
+ const favorite = state.favorites.find((entry) => entry.id === id)
835
+ patch({ favorites: state.favorites.filter((entry) => entry.id !== id) })
836
+ pushLog('info', t('log.favoriteRemoved', { name: favorite?.name ?? id }))
837
+ }
838
+ return value
839
+ },
840
+
841
+ /**
842
+ * Open a saved statement in the workbench of the schema it was saved from.
843
+ *
844
+ * Opening by name is what keeps a favorite useful across workspaces: the
845
+ * statement was written in `bw_order` in one project and is still a `bw_order`
846
+ * statement in the next tree. When that schema is not in the tree at all, the
847
+ * log says which one is missing instead of opening an unrelated console.
848
+ */
849
+ openFavorite(favorite) {
850
+ if (favorite === null || favorite === undefined) return false
851
+ const target = dwFindDatabaseTarget(state.environments, favorite.database, favorite.env)
852
+ if (target === undefined) {
853
+ pushLog('warn', t('log.favoriteNoDatabase', { database: favorite.database }))
854
+ return false
855
+ }
856
+ const opened = store.openDatabase(target.node)
857
+ const tabId = typeof opened?.id === 'string' ? opened.id : ''
858
+ if (tabId === '') return false
859
+ store.appendStatement(tabId, favorite.sql)
860
+ pushLog('info', t('log.favoriteOpened', { name: favorite.name }))
861
+ return true
862
+ },
863
+
864
+ /** Append a statement to one console without touching what is already typed. */
865
+ appendStatement(tabId, sql) {
866
+ const statement = String(sql ?? '').trim()
867
+ const tab = state.tabs.find((entry) => entry.id === tabId)
868
+ if (statement === '' || tab === undefined) return
869
+ const current = String(tab.sql ?? '').replace(/\s+$/, '')
870
+ if (current.includes(statement)) {
871
+ store.setActiveTab(tabId)
872
+ return
873
+ }
874
+ const next = current === '' ? statement : `${current}\n\n${statement}`
875
+ patch({
876
+ tabs: state.tabs.map((entry) => (entry.id === tabId
877
+ ? { ...entry, sql: next, result: undefined, error: '' }
878
+ : entry)),
879
+ activeTab: tabId,
880
+ })
881
+ scheduleConsoles()
882
+ },
883
+
746
884
  /** Delete a whole manually added environment, then re-read the tree. */
747
885
  async removeManualEnvironment(label) {
748
886
  const root = state.root
@@ -822,10 +960,6 @@ function dwCreateStore(translate) {
822
960
  void store.loadSchema(node.dbId)
823
961
  await store.ensureChildren(node)
824
962
  if (state.loadState.get(node.key) === 'error') return
825
- if (node.kind === 'table' || node.kind === 'view') {
826
- const tab = state.tabs.find((entry) => entry.kind === 'ddl' && entry.dbId === node.dbId && entry.table === node.table)
827
- if (tab !== undefined) await store.refreshDdl(tab.id)
828
- }
829
963
  pushLog('info', t('log.refreshedStructure', { name: node.label }))
830
964
  },
831
965
 
@@ -929,6 +1063,18 @@ function dwCreateStore(translate) {
929
1063
  patch({ selected: node?.key ?? '', selectedNode: node ?? null })
930
1064
  },
931
1065
 
1066
+ /** Switch the resource manager between the database tree and the favorites. */
1067
+ setTreeTab(tab) {
1068
+ const next = tab === 'favorites' ? 'favorites' : 'databases'
1069
+ if (next === state.treeTab) return
1070
+ try {
1071
+ globalThis.localStorage?.setItem(DW_TREE_TAB_KEY, next)
1072
+ } catch (error) {
1073
+ void error
1074
+ }
1075
+ patch({ treeTab: next })
1076
+ },
1077
+
932
1078
  /**
933
1079
  * Open (or focus) the SQL workbench of one database.
934
1080
  *
@@ -1060,73 +1206,45 @@ function dwCreateStore(translate) {
1060
1206
  return tab
1061
1207
  },
1062
1208
 
1063
- /**
1064
- * Open the DDL of one table.
1065
- *
1066
- * Requirement: the create statement is one keystroke away. The tab is keyed by
1067
- * table, so asking twice focuses the same document instead of stacking copies.
1068
- */
1069
- async openDdl(node) {
1070
- if (node === null || node === undefined || node.table === undefined) return
1071
- const id = `ddl:${node.dbId}:${node.table}`
1072
- const existing = state.tabs.find((tab) => tab.id === id)
1073
- if (existing !== undefined) {
1074
- patch({ activeTab: id })
1075
- if (existing.loading !== true && existing.ddl !== '') return
1076
- await store.refreshDdl(id)
1077
- return
1078
- }
1079
- const tab = {
1080
- id,
1081
- kind: 'ddl',
1082
- title: node.table,
1083
- env: node.env ?? '',
1084
- subtitle: [node.env, node.database].filter((part) => typeof part === 'string' && part !== '').join(' · '),
1085
- dbId: node.dbId,
1086
- database: node.database,
1087
- instanceLabel: node.instanceLabel ?? '',
1088
- table: node.table,
1089
- ddl: '',
1090
- columns: [],
1091
- loading: true,
1092
- error: '',
1209
+ /** Close one or more tabs and keep the active selection on a neighbour. */
1210
+ closeTabs(ids) {
1211
+ const removing = new Set(Array.isArray(ids) ? ids : [])
1212
+ if (removing.size === 0) return
1213
+ const tabs = state.tabs.filter((tab) => !removing.has(tab.id))
1214
+ let activeTab = state.activeTab
1215
+ if (removing.has(activeTab)) {
1216
+ const index = state.tabs.findIndex((tab) => tab.id === activeTab)
1217
+ const neighbour = state.tabs.slice(index + 1).find((tab) => !removing.has(tab.id))
1218
+ ?? state.tabs.slice(0, index).reverse().find((tab) => !removing.has(tab.id))
1219
+ activeTab = neighbour?.id ?? ''
1093
1220
  }
1094
- patch({ tabs: [...state.tabs, tab], activeTab: id })
1095
- await store.refreshDdl(id)
1221
+ patch({ tabs, activeTab })
1222
+ // Closing a console is deliberate: drop it from storage now, not later.
1223
+ flushConsoles()
1096
1224
  },
1097
1225
 
1098
- /** Re-read one DDL tab (a schema change is exactly why the tab exists). */
1099
- async refreshDdl(id) {
1100
- const tab = state.tabs.find((entry) => entry.id === id)
1101
- if (tab === undefined || tab.kind !== 'ddl') return
1102
- patch({ tabs: state.tabs.map((entry) => (entry.id === id ? { ...entry, loading: true, error: '' } : entry)) })
1103
- try {
1104
- const value = await call('ddl', { id: tab.dbId, table: tab.table })
1105
- patch({
1106
- tabs: state.tabs.map((entry) => (entry.id === id
1107
- ? { ...entry, ddl: value.ddl ?? '', columns: value.columns ?? [], loading: false, error: '' }
1108
- : entry)),
1109
- })
1110
- pushLog('info', t('log.ddl', { table: tab.table, ms: dwDuration(value.statementTime) }))
1111
- } catch (error) {
1112
- patch({ tabs: state.tabs.map((entry) => (entry.id === id ? { ...entry, loading: false, error: dwExplainFailure(t, error) } : entry)) })
1113
- pushLog('error', t('log.loadFailed', { name: tab.table, message: dwExplainFailure(t, error) }))
1114
- }
1226
+ closeTab(id) {
1227
+ store.closeTabs([id])
1115
1228
  },
1116
1229
 
1117
- /** Close one tab and pick a neighbour. */
1118
- closeTab(id) {
1230
+ closeOtherTabs(id) {
1231
+ store.closeTabs(state.tabs.filter((tab) => tab.id !== id).map((tab) => tab.id))
1232
+ },
1233
+
1234
+ closeAllTabs() {
1235
+ store.closeTabs(state.tabs.map((tab) => tab.id))
1236
+ },
1237
+
1238
+ closeTabsToLeft(id) {
1239
+ const index = state.tabs.findIndex((tab) => tab.id === id)
1240
+ if (index <= 0) return
1241
+ store.closeTabs(state.tabs.slice(0, index).map((tab) => tab.id))
1242
+ },
1243
+
1244
+ closeTabsToRight(id) {
1119
1245
  const index = state.tabs.findIndex((tab) => tab.id === id)
1120
1246
  if (index < 0) return
1121
- const tabs = state.tabs.filter((tab) => tab.id !== id)
1122
- let activeTab = state.activeTab
1123
- if (activeTab === id) {
1124
- const neighbour = tabs[index] ?? tabs[index - 1]
1125
- activeTab = neighbour?.id ?? ''
1126
- }
1127
- patch({ tabs, activeTab })
1128
- // Closing a console is deliberate: drop it from storage now, not later.
1129
- flushConsoles()
1247
+ store.closeTabs(state.tabs.slice(index + 1).map((tab) => tab.id))
1130
1248
  },
1131
1249
 
1132
1250
  setActiveTab(id) {
@@ -10,7 +10,7 @@
10
10
  */
11
11
 
12
12
  /** One nested tree of what the store currently knows, before filtering. */
13
- function dwBuildTree(state, tr) {
13
+ function dwBuildTree(state, tr, mode = 'databases') {
14
14
  const loadStateOf = (key) => state.loadState.get(key)
15
15
  const childrenOf = (node, depth) => {
16
16
  const rows = []
@@ -26,7 +26,12 @@ function dwBuildTree(state, tr) {
26
26
  return rows
27
27
  }
28
28
 
29
- const environments = []
29
+ // The favorites tab is derived from the saved list, not from `children`: it never
30
+ // needs a round trip to expand, and a save anywhere in the panel is visible the
31
+ // moment the store patches the list.
32
+ if (mode === 'favorites') return dwBuildFavoriteRows(state.favorites, tr)
33
+
34
+ const rows = []
30
35
  for (const environment of state.environments ?? []) {
31
36
  const envKey = dwNodeKey('env', environment.env)
32
37
  const instanceRows = []
@@ -73,7 +78,7 @@ function dwBuildTree(state, tr) {
73
78
  children: databaseRows,
74
79
  })
75
80
  }
76
- environments.push({
81
+ rows.push({
77
82
  node: {
78
83
  key: envKey,
79
84
  kind: 'env',
@@ -87,7 +92,7 @@ function dwBuildTree(state, tr) {
87
92
  children: instanceRows,
88
93
  })
89
94
  }
90
- return environments
95
+ return rows
91
96
  }
92
97
 
93
98
  /** Prune a tree to the nodes that match, keeping their ancestors. */
@@ -130,7 +135,7 @@ function dwFlattenTree(tree, state, filter, depth = 0, into = []) {
130
135
  /** One row per visible node, in display order. */
131
136
  function dwVisibleRows(state, tr) {
132
137
  const filter = String(state.filter ?? '').trim().toLowerCase()
133
- const tree = dwPruneTree(dwBuildTree(state, tr), filter)
138
+ const tree = dwPruneTree(dwBuildTree(state, tr, state.treeTab), filter)
134
139
  return dwFlattenTree(tree, state, filter)
135
140
  }
136
141
 
@@ -143,6 +148,9 @@ function dwNodeIconName(node) {
143
148
  case 'view': return 'view'
144
149
  case 'table': return 'table'
145
150
  case 'column': return node.column?.key === 'PRI' ? 'key' : 'column'
151
+ case 'favorite': return 'star'
152
+ case 'favoriteDatabase': return 'database'
153
+ case 'favoriteTable': return 'table'
146
154
  case 'retry': return 'refresh'
147
155
  case 'error': return 'close'
148
156
  default: return 'panel'
@@ -152,9 +160,11 @@ function dwNodeIconName(node) {
152
160
  function DwTree({ store, state, tr, onContextMenu, onChooseDatabases }) {
153
161
  const rows = useMemo(
154
162
  () => dwVisibleRows(state, tr),
155
- [state.environments, state.expanded, state.children, state.loadState, state.filter],
163
+ [state.root, state.treeTab, state.environments, state.expanded, state.children, state.loadState, state.filter, state.favorites, state.favoritesError],
156
164
  )
157
165
 
166
+ // A row click only selects: expanding belongs to the twisty (and to double-click
167
+ // for the kinds whose whole purpose is to be opened).
158
168
  const activate = (row) => {
159
169
  const node = row.node
160
170
  if (node.kind === 'retry') {
@@ -162,13 +172,31 @@ function DwTree({ store, state, tr, onContextMenu, onChooseDatabases }) {
162
172
  return
163
173
  }
164
174
  store.select(node)
175
+ // The favorites branches exist to be browsed, so a single click unfolds them;
176
+ // every other row keeps the "select only" behaviour of the tree.
177
+ if (node.kind === 'favoriteDatabase' || node.kind === 'favoriteTable') void store.toggleNode(node)
178
+ }
179
+
180
+ const openRow = (row) => {
181
+ const node = row.node
182
+ if (node.kind === 'retry') {
183
+ store.retryNode(node.retryOf)
184
+ return
185
+ }
186
+ store.select(node)
187
+ if (node.kind === 'favorite') {
188
+ store.openFavorite(node.favorite)
189
+ return
190
+ }
165
191
  if (node.kind === 'database') {
166
192
  store.openDatabase(node)
167
- // Opening the workbench also reveals its tables: that is the list the user
168
- // came for, and one click is better than two.
169
193
  if (row.open !== true) void store.toggleNode(node)
170
194
  return
171
195
  }
196
+ if (node.kind === 'table' || node.kind === 'view') {
197
+ openTableData(row)
198
+ return
199
+ }
172
200
  if (node.kind === 'instance' && (node.databases ?? []).length === 0) {
173
201
  onChooseDatabases(node)
174
202
  return
@@ -187,14 +215,21 @@ function DwTree({ store, state, tr, onContextMenu, onChooseDatabases }) {
187
215
  }
188
216
 
189
217
  if (rows.length === 0) {
190
- const empty = state.phase === 'loading'
191
- ? tr('treeLoading')
192
- : String(state.filter ?? '') !== ''
218
+ const filtered = String(state.filter ?? '') !== ''
219
+ const empty = state.treeTab === 'favorites'
220
+ ? filtered
193
221
  ? tr('treeNoMatch')
194
- : tr('treeEmpty')
222
+ : String(state.favoritesError ?? '') !== ''
223
+ ? tr('log.favoriteLoadFailed', { message: state.favoritesError })
224
+ : tr('favoritesEmptyHint')
225
+ : state.phase === 'loading'
226
+ ? tr('treeLoading')
227
+ : filtered
228
+ ? tr('treeNoMatch')
229
+ : tr('treeEmpty')
195
230
  return h('div', { className: 'dw-tree' }, h('div', { className: 'dw-empty', style: { padding: 18 } }, [
196
231
  h('div', { key: 't', className: 'dw-empty-hint' }, empty),
197
- String(state.filter ?? '') !== ''
232
+ filtered
198
233
  ? h('button', {
199
234
  key: 'c',
200
235
  type: 'button',
@@ -214,10 +249,9 @@ function DwTree({ store, state, tr, onContextMenu, onChooseDatabases }) {
214
249
  className: 'dw-node-twisty',
215
250
  style: { transform: row.open === true ? 'rotate(90deg)' : 'none', transition: 'transform 110ms ease', cursor: 'pointer' },
216
251
  onClick: (event) => {
217
- // The twisty is the only control that collapses a node: clicking the row
218
- // of a database opens its workbench and never closes the list.
252
+ // The twisty is the only control that expands or collapses a node;
253
+ // clicking the row never changes the expansion.
219
254
  event.stopPropagation()
220
- store.select(node)
221
255
  void store.toggleNode(node)
222
256
  },
223
257
  }, row.loading === true ? h(DwIcon, { name: 'spinner', size: 11 }) : h(DwIcon, { name: 'chevron', size: 11 }))
@@ -244,7 +278,7 @@ function DwTree({ store, state, tr, onContextMenu, onChooseDatabases }) {
244
278
  ].filter((part) => part !== '').join(' · ')
245
279
  : `${node.title ?? `${node.label}${node.detail ? ` ${node.detail}` : ''}`}`,
246
280
  onClick: () => activate(row),
247
- onDoubleClick: () => (node.kind === 'table' || node.kind === 'view' ? openTableData(row) : undefined),
281
+ onDoubleClick: () => openRow(row),
248
282
  onContextMenu: (event) => {
249
283
  event.preventDefault()
250
284
  store.select(node)