@antelopejs/dms-database 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/README.md +19 -7
  2. package/dist/automation/index.js.map +1 -1
  3. package/dist/automation/tableWatch.d.ts +3 -2
  4. package/dist/automation/tableWatch.js +9 -6
  5. package/dist/automation/tableWatch.js.map +1 -1
  6. package/dist/db/tables/query_history.table.d.ts +2 -1
  7. package/dist/db/tables/query_history.table.js.map +1 -1
  8. package/dist/db/tables/saved_queries.table.d.ts +2 -1
  9. package/dist/db/tables/saved_queries.table.js.map +1 -1
  10. package/dist/i18n/messages.js.map +1 -1
  11. package/dist/module.js +5 -1
  12. package/dist/module.js.map +1 -1
  13. package/dist/pages/schemas.js.map +1 -1
  14. package/dist/routes/data.d.ts +1 -1
  15. package/dist/routes/data.js +36 -237
  16. package/dist/routes/data.js.map +1 -1
  17. package/dist/routes/diagram.js +61 -42
  18. package/dist/routes/diagram.js.map +1 -1
  19. package/dist/routes/query.js +44 -46
  20. package/dist/routes/query.js.map +1 -1
  21. package/dist/routes/tables.js +13 -7
  22. package/dist/routes/tables.js.map +1 -1
  23. package/dist/service/browse.d.ts +37 -0
  24. package/dist/service/browse.js +135 -0
  25. package/dist/service/browse.js.map +1 -0
  26. package/dist/service/fieldDescriptor.d.ts +6 -6
  27. package/dist/service/fieldDescriptor.js +9 -13
  28. package/dist/service/fieldDescriptor.js.map +1 -1
  29. package/dist/service/health.js.map +1 -1
  30. package/dist/service/introspect.js +13 -12
  31. package/dist/service/introspect.js.map +1 -1
  32. package/dist/service/overview.js.map +1 -1
  33. package/dist/service/queryInspection.d.ts +4 -3
  34. package/dist/service/queryInspection.js +25 -24
  35. package/dist/service/queryInspection.js.map +1 -1
  36. package/dist/service/references.js +2 -6
  37. package/dist/service/references.js.map +1 -1
  38. package/dist/service/rowEdit.d.ts +2 -0
  39. package/dist/service/rowEdit.js +81 -0
  40. package/dist/service/rowEdit.js.map +1 -0
  41. package/dist/service/schemaFilters.d.ts +1 -1
  42. package/dist/service/schemaFilters.js.map +1 -1
  43. package/dist/service/schemaRegistry.js.map +1 -1
  44. package/dist/service/stagedSerialization.d.ts +7 -6
  45. package/dist/service/stagedSerialization.js +29 -21
  46. package/dist/service/stagedSerialization.js.map +1 -1
  47. package/dist/types/json.d.ts +8 -0
  48. package/dist/types/json.js +32 -0
  49. package/dist/types/json.js.map +1 -0
  50. package/dist/utils/guards.d.ts +7 -0
  51. package/dist/utils/guards.js +31 -0
  52. package/dist/utils/guards.js.map +1 -0
  53. package/dist/utils/query.d.ts +6 -7
  54. package/dist/utils/query.js +13 -24
  55. package/dist/utils/query.js.map +1 -1
  56. package/dist/utils/requestValidation.d.ts +1 -2
  57. package/dist/utils/requestValidation.js +4 -9
  58. package/dist/utils/requestValidation.js.map +1 -1
  59. package/frontend-vue/app/build/components/DataGridEmpty.vue +89 -0
  60. package/frontend-vue/app/build/components/DataGridFooter.vue +113 -0
  61. package/frontend-vue/app/build/components/DataGridReadOnlyBanner.vue +50 -0
  62. package/frontend-vue/app/build/components/DataGridSaveStatus.vue +73 -0
  63. package/frontend-vue/app/build/components/DataGridToolbar.vue +72 -0
  64. package/frontend-vue/app/build/components/DiagramLegend.vue +48 -0
  65. package/frontend-vue/app/build/components/DiagramSearchBar.vue +82 -0
  66. package/frontend-vue/app/build/components/DiagramStatusBar.vue +89 -0
  67. package/frontend-vue/app/build/components/DiagramToolbar.vue +102 -0
  68. package/frontend-vue/app/build/components/DiagramViewBar.vue +103 -0
  69. package/frontend-vue/app/build/components/diagramFloat.css +21 -0
  70. package/frontend-vue/app/build/composables/useDiagramDrag.ts +84 -0
  71. package/frontend-vue/app/build/composables/useDiagramNotes.ts +146 -0
  72. package/frontend-vue/app/build/composables/useDiagramSaveStatus.ts +50 -0
  73. package/frontend-vue/app/build/composables/useDiagramSearch.ts +77 -0
  74. package/frontend-vue/app/build/composables/useDiagramView.ts +125 -0
  75. package/frontend-vue/app/build/composables/useElsewhereInstances.ts +94 -0
  76. package/frontend-vue/app/build/composables/useTableSample.ts +176 -0
  77. package/frontend-vue/app/build/data/gridData.ts +66 -0
  78. package/frontend-vue/app/build/data/useStagedSave.ts +13 -20
  79. package/frontend-vue/app/build/diagram/autosave.ts +3 -3
  80. package/frontend-vue/app/build/diagram/graph.ts +67 -485
  81. package/frontend-vue/app/build/diagram/graphModel.ts +368 -0
  82. package/frontend-vue/app/build/diagram/layout.ts +135 -0
  83. package/frontend-vue/app/build/query/failures.ts +17 -0
  84. package/frontend-vue/app/components/DataGrid.vue +64 -358
  85. package/frontend-vue/app/components/QueryConsole.vue +27 -116
  86. package/frontend-vue/app/components/SchemaDiagram.vue +118 -678
  87. package/frontend-vue/app/components/TableInspector.vue +12 -136
  88. package/frontend-vue/build/backend-boundary.ts +122 -0
  89. package/frontend-vue/dms.frontend.build.ts +6 -0
  90. package/frontend-vue/package.json +3 -2
  91. package/frontend-vue/pnpm-lock.yaml +8 -5
  92. package/frontend-vue/tests/apiErrorPresentation.test.ts +83 -0
  93. package/frontend-vue/tests/backend-boundary.test.ts +134 -0
  94. package/frontend-vue/tests/clientNavigation.test.ts +5 -7
  95. package/frontend-vue/tests/fixtures/serverRender.ts +13 -1
  96. package/frontend-vue/tests/locales.test.ts +16 -89
  97. package/frontend-vue/tests/queryConsole.test.ts +20 -0
  98. package/frontend-vue/tests/registration.test.ts +0 -18
  99. package/frontend-vue/vitest.config.ts +5 -2
  100. package/package.json +23 -12
  101. package/skills/dms-database/SKILL.md +1 -1
  102. package/skills/dms-database/cases.json +48 -0
@@ -0,0 +1,103 @@
1
+ <script setup lang="ts">
2
+ defineProps<{
3
+ zoomPercent: string
4
+ isEmpty: boolean
5
+ }>()
6
+
7
+ const panMode = defineModel<boolean>('panMode', { required: true })
8
+
9
+ const emit = defineEmits<{
10
+ zoomOut: []
11
+ resetZoom: []
12
+ zoomIn: []
13
+ fit: []
14
+ addNote: []
15
+ }>()
16
+
17
+ const { t } = useI18n()
18
+ </script>
19
+
20
+ <template>
21
+ <div class="diagram-float">
22
+ <UTooltip :text="t('dms_database.diagram.toolbar.select')" :kbds="['v']">
23
+ <UButton
24
+ size="sm"
25
+ icon="i-ph-cursor"
26
+ :color="panMode ? 'neutral' : 'primary'"
27
+ :variant="panMode ? 'ghost' : 'soft'"
28
+ :aria-pressed="!panMode"
29
+ :aria-label="t('dms_database.diagram.toolbar.select')"
30
+ @click="panMode = false"
31
+ />
32
+ </UTooltip>
33
+ <UTooltip :text="t('dms_database.diagram.toolbar.pan')" :kbds="['h']">
34
+ <UButton
35
+ size="sm"
36
+ icon="i-ph-hand"
37
+ :color="panMode ? 'primary' : 'neutral'"
38
+ :variant="panMode ? 'soft' : 'ghost'"
39
+ :aria-pressed="panMode"
40
+ :aria-label="t('dms_database.diagram.toolbar.pan')"
41
+ @click="panMode = true"
42
+ />
43
+ </UTooltip>
44
+ <span class="diagram-float__sep" />
45
+ <UTooltip :text="t('dms_database.diagram.toolbar.zoom_out')">
46
+ <UButton
47
+ size="sm"
48
+ color="neutral"
49
+ variant="ghost"
50
+ icon="i-ph-magnifying-glass-minus"
51
+ :aria-label="t('dms_database.diagram.toolbar.zoom_out')"
52
+ @click="emit('zoomOut')"
53
+ />
54
+ </UTooltip>
55
+ <UTooltip
56
+ :text="t('dms_database.diagram.toolbar.reset_zoom')"
57
+ :kbds="['0']"
58
+ >
59
+ <button
60
+ type="button"
61
+ class="text-muted hover:text-highlighted hover:bg-elevated min-w-12 rounded-md px-2 font-mono text-[11.5px] tabular-nums"
62
+ :aria-label="t('dms_database.diagram.toolbar.reset_zoom')"
63
+ @click="emit('resetZoom')"
64
+ >
65
+ {{ zoomPercent }}
66
+ </button>
67
+ </UTooltip>
68
+ <UTooltip :text="t('dms_database.diagram.toolbar.zoom_in')">
69
+ <UButton
70
+ size="sm"
71
+ color="neutral"
72
+ variant="ghost"
73
+ icon="i-ph-magnifying-glass-plus"
74
+ :aria-label="t('dms_database.diagram.toolbar.zoom_in')"
75
+ @click="emit('zoomIn')"
76
+ />
77
+ </UTooltip>
78
+ <UTooltip :text="t('dms_database.diagram.toolbar.fit')" :kbds="['1']">
79
+ <UButton
80
+ size="sm"
81
+ color="neutral"
82
+ variant="ghost"
83
+ icon="i-ph-arrows-out"
84
+ :aria-label="t('dms_database.diagram.toolbar.fit')"
85
+ @click="emit('fit')"
86
+ />
87
+ </UTooltip>
88
+ <span class="diagram-float__sep" />
89
+ <UTooltip :text="t('dms_database.diagram.toolbar.note_hint')" :kbds="['n']">
90
+ <UButton
91
+ size="sm"
92
+ color="neutral"
93
+ variant="ghost"
94
+ icon="i-ph-note-pencil"
95
+ :label="t('dms_database.diagram.toolbar.note')"
96
+ :disabled="isEmpty"
97
+ @click="emit('addNote')"
98
+ />
99
+ </UTooltip>
100
+ </div>
101
+ </template>
102
+
103
+ <style scoped src="./diagramFloat.css"></style>
@@ -0,0 +1,21 @@
1
+ /* As wide as its content: a centred panel only gets half the canvas, which
2
+ would wrap a bar that fits. It wraps only when the screen is narrower. */
3
+ .diagram-float {
4
+ display: flex;
5
+ flex-wrap: wrap;
6
+ width: max-content;
7
+ max-width: calc(100vw - 4rem);
8
+ align-items: center;
9
+ gap: 2px;
10
+ padding: 4px;
11
+ border: 1px solid var(--ui-border-accented);
12
+ border-radius: var(--ui-radius);
13
+ background: var(--ui-bg-elevated);
14
+ box-shadow: 0 8px 24px rgb(0 0 0 / 0.18);
15
+ }
16
+ .diagram-float__sep {
17
+ width: 1px;
18
+ height: 18px;
19
+ margin: 0 4px;
20
+ background: var(--ui-border);
21
+ }
@@ -0,0 +1,84 @@
1
+ import type { NodeDragEvent } from '@vue-flow/core'
2
+ import type { Ref } from 'vue'
3
+ import {
4
+ type DiagramNode,
5
+ NOTE_NODE_TYPE,
6
+ TABLE_NODE_TYPE,
7
+ } from '../diagram/graph'
8
+ import type { DiagramOperation, DiagramState } from '../diagram/history'
9
+
10
+ /** What dragging reads and writes of the diagram page. */
11
+ interface DragContext {
12
+ state: DiagramState
13
+ preview: Readonly<Ref<object | null>>
14
+ selectedId: Ref<string | null>
15
+ record: (op: DiagramOperation) => void
16
+ render: () => void
17
+ selectNode: (nodeId: string) => void
18
+ }
19
+
20
+ /** Moving tables and notes on the canvas: each move is recorded for undo. */
21
+ export function useDiagramDrag({
22
+ state,
23
+ preview,
24
+ selectedId,
25
+ record,
26
+ render,
27
+ selectNode,
28
+ }: DragContext) {
29
+ const dragStarts = new Map<string, { x: number; y: number }>()
30
+
31
+ // With `select-nodes-on-drag` off, Vue Flow lets go of the selection when a
32
+ // node not selected is grabbed, so a note left selected does not follow a
33
+ // table, which Vue Flow cannot select.
34
+ function onNodeDragStart({ node, nodes }: NodeDragEvent) {
35
+ for (const dragged of nodes.length ? nodes : [node])
36
+ dragStarts.set(dragged.id, { ...dragged.position })
37
+ }
38
+
39
+ function tableMoved(node: DiagramNode, from: { x: number; y: number }) {
40
+ const tableName = (node.data as { tableName: string }).tableName
41
+ const to = { x: node.position.x, y: node.position.y }
42
+ state.positions[tableName] = to
43
+ if (preview.value) return
44
+ record({ kind: 'tableMove', tableName, from, to })
45
+ }
46
+
47
+ function noteMoved(node: DiagramNode, from: { x: number; y: number }) {
48
+ const noteId = (node.data as { noteId: string }).noteId
49
+ const to = { x: node.position.x, y: node.position.y }
50
+ const note = state.notes.find((n) => n.id === noteId)
51
+ if (!note) return
52
+ Object.assign(note, to)
53
+ record({ kind: 'noteMove', noteId, from, to })
54
+ }
55
+
56
+ const DRAG_HANDLERS: Record<
57
+ string,
58
+ (node: DiagramNode, from: { x: number; y: number }) => void
59
+ > = {
60
+ [TABLE_NODE_TYPE]: tableMoved,
61
+ [NOTE_NODE_TYPE]: noteMoved,
62
+ }
63
+
64
+ function onNodeDragStop({ node, nodes }: NodeDragEvent) {
65
+ for (const dragged of nodes.length ? nodes : [node]) {
66
+ const from = dragStarts.get(dragged.id)
67
+ dragStarts.delete(dragged.id)
68
+ const { x, y } = dragged.position
69
+ if (!from || (from.x === x && from.y === y)) continue
70
+ DRAG_HANDLERS[dragged.type ?? '']?.(
71
+ dragged as unknown as DiagramNode,
72
+ from,
73
+ )
74
+ }
75
+ // The node put down becomes the selection: a table through
76
+ // `data.selected` (D-9), a note through Vue Flow. Set once the drag is
77
+ // over, as setting the nodes during it would put the dragged one back.
78
+ selectedId.value = node.type === TABLE_NODE_TYPE ? node.id : null
79
+ if (node.type === NOTE_NODE_TYPE && !node.selected) selectNode(node.id)
80
+ render()
81
+ }
82
+
83
+ return { onNodeDragStart, onNodeDragStop }
84
+ }
@@ -0,0 +1,146 @@
1
+ import type { VueFlowStore } from '@vue-flow/core'
2
+ import type { ComputedRef, Ref, ShallowRef, ShallowUnwrapRef } from 'vue'
3
+ import {
4
+ freeSpot,
5
+ NODE_WIDTH,
6
+ nodeHeight,
7
+ type NoteDraft,
8
+ noteNodeId,
9
+ TABLE_NODE_TYPE,
10
+ type TableNodeData,
11
+ } from '../diagram/graph'
12
+ import type { DiagramOperation, DiagramState } from '../diagram/history'
13
+ import type { Rect } from '../diagram/packing'
14
+ import type { SchemaSummary } from './useDatabaseSchemas'
15
+
16
+ const NOTE_WIDTH = 220
17
+ const NOTE_HEIGHT = 140
18
+
19
+ /** What the notes read and write of the diagram page. */
20
+ interface NotesContext {
21
+ state: DiagramState
22
+ canvas: ShallowRef<ShallowUnwrapRef<VueFlowStore> | null>
23
+ canvasWrapper: Readonly<ShallowRef<HTMLElement | null>>
24
+ schema: ComputedRef<SchemaSummary | null>
25
+ schemaId: ComputedRef<string | null>
26
+ viewport: Ref<{ x: number; y: number; zoom: number }>
27
+ selectedId: Ref<string | null>
28
+ editNoteId: Ref<string | null>
29
+ record: (op: DiagramOperation) => void
30
+ render: () => void
31
+ }
32
+
33
+ /** The notes of the diagram: added, written, moved, deleted, with undo. */
34
+ export function useDiagramNotes({
35
+ state,
36
+ canvas,
37
+ canvasWrapper,
38
+ schema,
39
+ schemaId,
40
+ viewport,
41
+ selectedId,
42
+ editNoteId,
43
+ record,
44
+ render,
45
+ }: NotesContext) {
46
+ // What a new note should not cover: the tables drawn, and every note. Sizes
47
+ // come from the schema and the notes, as a node just added is not measured.
48
+ function takenRects(): Rect[] {
49
+ const tables = (canvas.value?.getNodes ?? []).flatMap((node) => {
50
+ if (node.type !== TABLE_NODE_TYPE) return []
51
+ const { table, expanded: open } = node.data as TableNodeData
52
+ if (!schema.value) return []
53
+ return [
54
+ {
55
+ x: node.position.x,
56
+ y: node.position.y,
57
+ width: NODE_WIDTH,
58
+ height: nodeHeight(schema.value, table, open),
59
+ },
60
+ ]
61
+ })
62
+ return [...tables, ...state.notes]
63
+ }
64
+
65
+ function selectNode(nodeId: string) {
66
+ const flow = canvas.value
67
+ const node = flow?.findNode(nodeId)
68
+ if (!flow || !node) return
69
+ flow.removeSelectedNodes(flow.getSelectedNodes)
70
+ flow.addSelectedNodes([node])
71
+ }
72
+
73
+ // A new note goes in the free space nearest the centre of the view, above
74
+ // the tables, selected and ready to write (D-8).
75
+ function addNote() {
76
+ if (!schemaId.value) return
77
+ const rect = canvasWrapper.value?.getBoundingClientRect()
78
+ const { x, y, zoom } = viewport.value
79
+ const centre = {
80
+ x: ((rect?.width ?? 800) / 2 - x) / zoom - NOTE_WIDTH / 2,
81
+ y: ((rect?.height ?? 600) / 2 - y) / zoom - NOTE_HEIGHT / 2,
82
+ }
83
+ const spot = freeSpot(
84
+ centre,
85
+ { width: NOTE_WIDTH, height: NOTE_HEIGHT },
86
+ takenRects(),
87
+ )
88
+ const note: NoteDraft = {
89
+ id: `temp-${Date.now()}`,
90
+ schemaName: schemaId.value,
91
+ text: '',
92
+ x: Math.round(spot.x),
93
+ y: Math.round(spot.y),
94
+ width: NOTE_WIDTH,
95
+ height: NOTE_HEIGHT,
96
+ color: null,
97
+ isTemp: true,
98
+ }
99
+ state.notes.push(note)
100
+ record({ kind: 'noteCreate', snapshot: { ...note } })
101
+ editNoteId.value = note.id
102
+ selectedId.value = null
103
+ render()
104
+ nextTick(() => selectNode(noteNodeId(note.id)))
105
+ }
106
+
107
+ function changeNoteText(noteId: string, text: string) {
108
+ const note = state.notes.find((n) => n.id === noteId)
109
+ if (!note || note.text === text) return
110
+ record({ kind: 'noteText', noteId, from: note.text, to: text })
111
+ note.text = text
112
+ render()
113
+ }
114
+
115
+ function endNoteEdit(noteId: string) {
116
+ if (editNoteId.value !== noteId) return
117
+ editNoteId.value = null
118
+ render()
119
+ }
120
+
121
+ function deleteNote(noteId: string) {
122
+ const note = state.notes.find((n) => n.id === noteId)
123
+ if (!note) return
124
+ state.notes = state.notes.filter((n) => n.id !== noteId)
125
+ if (editNoteId.value === noteId) editNoteId.value = null
126
+ record({ kind: 'noteDelete', snapshot: { ...note } })
127
+ render()
128
+ }
129
+
130
+ // Delete or Backspace on the canvas: only notes go, with undo (D-3).
131
+ function onDeleteNodes(ids: string[]) {
132
+ const doomed = new Set(ids)
133
+ for (const note of [...state.notes]) {
134
+ if (doomed.has(noteNodeId(note.id))) deleteNote(note.id)
135
+ }
136
+ }
137
+
138
+ return {
139
+ addNote,
140
+ changeNoteText,
141
+ deleteNote,
142
+ endNoteEdit,
143
+ onDeleteNodes,
144
+ selectNode,
145
+ }
146
+ }
@@ -0,0 +1,50 @@
1
+ import { useNow } from '@vueuse/core'
2
+ import { type SaveStatus } from '../diagram/autosave'
3
+ import type { DiagramSync } from '../diagram/sync'
4
+
5
+ const MINUTE_MS = 60_000
6
+
7
+ /**
8
+ * What the save bar says of the layout's autosave: the status of the schema
9
+ * shown, and a failure of one left before its save ended.
10
+ */
11
+ export function useDiagramSaveStatus(shown: () => DiagramSync | null) {
12
+ const { t } = useI18n()
13
+ const { presentError } = useApiErrorPresenter()
14
+ const now = useNow({ interval: MINUTE_MS / 2 })
15
+ const saveState = ref<SaveStatus>('idle')
16
+ const savedAt = ref<Date | null>(null)
17
+
18
+ /** Shows the save status of the schema shown; a schema left reports a failure. */
19
+ function statusReporter(owner: DiagramSync) {
20
+ return (status: SaveStatus, error?: unknown) => {
21
+ if (status === 'error')
22
+ presentError(error, {
23
+ fallbackKey:
24
+ owner === shown()
25
+ ? 'dms_database.diagram.save.error'
26
+ : 'dms_database.diagram.save.error_other',
27
+ params: { schema: owner.schemaId },
28
+ })
29
+ if (owner === shown()) {
30
+ saveState.value = status
31
+ if (status === 'saved') savedAt.value = new Date()
32
+ }
33
+ }
34
+ }
35
+
36
+ const savedLabel = computed(() => {
37
+ if (saveState.value === 'saving')
38
+ return t('dms_database.diagram.save.saving')
39
+ if (saveState.value === 'error') return t('dms_database.diagram.save.error')
40
+ if (!savedAt.value) return t('dms_database.diagram.save.idle')
41
+ const minutes = Math.round(
42
+ (now.value.getTime() - savedAt.value.getTime()) / MINUTE_MS,
43
+ )
44
+ return minutes < 1
45
+ ? t('dms_database.diagram.save.just_now')
46
+ : t('dms_database.diagram.save.minutes', { count: minutes })
47
+ })
48
+
49
+ return { saveState, savedAt, savedLabel, statusReporter }
50
+ }
@@ -0,0 +1,77 @@
1
+ import type { ComputedRef, Ref, ShallowRef } from 'vue'
2
+ import { expandForSearch, searchTables, tableNodeId } from '../diagram/graph'
3
+ import type { SchemaSummary } from './useDatabaseSchemas'
4
+
5
+ /** What the search reads and writes of the diagram page. */
6
+ interface SearchContext {
7
+ schema: ComputedRef<SchemaSummary | null>
8
+ schemaId: ComputedRef<string | null>
9
+ focusIds: ComputedRef<Set<string> | null>
10
+ focusId: Ref<string | null>
11
+ expanded: ShallowRef<Set<string>>
12
+ setExpanded: (next: Set<string>) => void
13
+ render: () => void
14
+ centerOn: (nodeId: string) => boolean
15
+ }
16
+
17
+ /** A table or a column; Enter goes from match to match (D-13). */
18
+ export function useDiagramSearch({
19
+ schema,
20
+ schemaId,
21
+ focusIds,
22
+ focusId,
23
+ expanded,
24
+ setExpanded,
25
+ render,
26
+ centerOn,
27
+ }: SearchContext) {
28
+ const search = ref('')
29
+ const searchIndex = ref(-1)
30
+
31
+ const searchMatches = computed(() =>
32
+ schema.value ? searchTables(schema.value, search.value) : [],
33
+ )
34
+ const searchMissed = computed(
35
+ () => search.value.trim() !== '' && searchMatches.value.length === 0,
36
+ )
37
+ const searchPosition = computed(() =>
38
+ searchIndex.value >= 0 && searchMatches.value.length > 1
39
+ ? `${searchIndex.value + 1}/${searchMatches.value.length}`
40
+ : null,
41
+ )
42
+
43
+ // Synchronous: an Enter right after the text changed starts from the first
44
+ // match of the new text.
45
+ watch(
46
+ search,
47
+ () => {
48
+ searchIndex.value = -1
49
+ },
50
+ { flush: 'sync' },
51
+ )
52
+
53
+ function runSearch() {
54
+ const matches = searchMatches.value
55
+ if (!matches.length || !schemaId.value) return
56
+ searchIndex.value = (searchIndex.value + 1) % matches.length
57
+ const tableName = matches[searchIndex.value] ?? ''
58
+ const id = tableNodeId(schemaId.value, tableName)
59
+ if (focusIds.value && !focusIds.value.has(id)) focusId.value = null
60
+ // A column found in a folded table unfolds it.
61
+ if (schema.value) {
62
+ const next = expandForSearch(
63
+ schema.value,
64
+ tableName,
65
+ search.value,
66
+ expanded.value,
67
+ )
68
+ if (next !== expanded.value) {
69
+ setExpanded(next)
70
+ render()
71
+ }
72
+ }
73
+ nextTick(() => centerOn(id))
74
+ }
75
+
76
+ return { search, searchIndex, searchMissed, searchPosition, runSearch }
77
+ }
@@ -0,0 +1,125 @@
1
+ import type { VueFlowStore } from '@vue-flow/core'
2
+ import type { ComputedRef, Ref, ShallowRef, ShallowUnwrapRef } from 'vue'
3
+ import { NODE_WIDTH, tableNodeId } from '../diagram/graph'
4
+ import { boundsOf, fitZoom, startViewport } from '../diagram/packing'
5
+ import type { SchemaSummary } from './useDatabaseSchemas'
6
+
7
+ export const RESET_ZOOM = 1
8
+ // Room around the tables for the floating toolbars.
9
+ const FIT_PADDING = 0.25
10
+ // Below this zoom a table cannot be read: a diagram too large to fit at it
11
+ // starts there, on its top-left corner, clear of the toolbars.
12
+ const START_MIN_ZOOM = 0.4
13
+ const START_INSET = { x: 32, y: 80 }
14
+
15
+ /** What the view reads and writes of the diagram page. */
16
+ interface ViewContext {
17
+ canvas: ShallowRef<ShallowUnwrapRef<VueFlowStore> | null>
18
+ canvasWrapper: Readonly<ShallowRef<HTMLElement | null>>
19
+ viewport: Ref<{ x: number; y: number; zoom: number }>
20
+ selectedId: Ref<string | null>
21
+ schema: ComputedRef<SchemaSummary | null>
22
+ route: ReturnType<typeof useDmsRoute>
23
+ router: ReturnType<typeof useDmsRouter>
24
+ warn: (title: string) => void
25
+ }
26
+
27
+ /** Where the canvas looks: the first frame, a fit, a table centred. */
28
+ export function useDiagramView({
29
+ canvas,
30
+ canvasWrapper,
31
+ viewport,
32
+ selectedId,
33
+ schema,
34
+ route,
35
+ router,
36
+ warn,
37
+ }: ViewContext) {
38
+ const { t } = useI18n()
39
+ let fitPending = true
40
+
41
+ /** The next measured nodes frame the diagram again. */
42
+ function requestFit() {
43
+ fitPending = true
44
+ }
45
+
46
+ // The nodes have been measured: the first fit, or the one a schema change or
47
+ // a focus asks for, can frame them.
48
+ function onNodesInitialized() {
49
+ if (!fitPending) return
50
+ fitPending = false
51
+ if (!centerOnQueryTable()) startView()
52
+ }
53
+
54
+ function fitAll() {
55
+ canvas.value?.fitView({ padding: FIT_PADDING, maxZoom: RESET_ZOOM })
56
+ }
57
+
58
+ // The whole diagram when it fits at a readable zoom; else its top-left
59
+ // corner at that zoom, the minimap and "Fit view" giving the overview.
60
+ function startView() {
61
+ const flow = canvas.value
62
+ const rect = canvasWrapper.value?.getBoundingClientRect()
63
+ if (!flow || !rect?.width || !rect.height) return fitAll()
64
+ const bounds = boundsOf(
65
+ flow.getNodes.map((node) => ({
66
+ x: node.position.x,
67
+ y: node.position.y,
68
+ width: node.dimensions.width,
69
+ height: node.dimensions.height,
70
+ })),
71
+ )
72
+ const view = startViewport(
73
+ bounds,
74
+ fitZoom(bounds, rect, FIT_PADDING),
75
+ START_MIN_ZOOM,
76
+ START_INSET,
77
+ )
78
+ if (view) flow.setViewport(view)
79
+ else fitAll()
80
+ }
81
+
82
+ function centerOn(nodeId: string): boolean {
83
+ const node = canvas.value?.findNode(nodeId)
84
+ if (!node) return false
85
+ selectedId.value = nodeId
86
+ canvas.value?.setCenter(
87
+ node.position.x + NODE_WIDTH / 2,
88
+ node.position.y + 120,
89
+ {
90
+ zoom: Math.max(viewport.value.zoom, RESET_ZOOM),
91
+ duration: 300,
92
+ },
93
+ )
94
+ return true
95
+ }
96
+
97
+ // The table the URL names; one that does not exist is reported and dropped
98
+ // from the URL (D-12).
99
+ function centerOnQueryTable(): boolean {
100
+ const table = route.query.table
101
+ const asked = route.query.schema
102
+ if (typeof table !== 'string' || !schema.value) return false
103
+ if (typeof asked === 'string' && asked !== schema.value.id) return false
104
+ if (!schema.value.tables.some((entry) => entry.name === table)) {
105
+ warn(
106
+ t('dms_database.diagram.not_found.table', {
107
+ schema: schema.value.id,
108
+ table,
109
+ }),
110
+ )
111
+ router.replace({ query: { ...route.query, table: undefined } })
112
+ return false
113
+ }
114
+ return centerOn(tableNodeId(schema.value.id, table))
115
+ }
116
+
117
+ return {
118
+ RESET_ZOOM,
119
+ fitAll,
120
+ startView,
121
+ centerOn,
122
+ onNodesInitialized,
123
+ requestFit,
124
+ }
125
+ }
@@ -0,0 +1,94 @@
1
+ import type { Ref } from 'vue'
2
+ import type { InstanceRows } from '../../components/QueryResultPanel.vue'
3
+ import type { QueryTarget } from '../query/target'
4
+ import type { SchemaSummary } from './useDatabaseSchemas'
5
+ import type { ExecuteResult } from './useQueryStore'
6
+
7
+ const BROWSE_COUNT = '/api/database/browse/count'
8
+
9
+ /**
10
+ * The named instances holding rows of the table a read found empty in the
11
+ * default instance (decision 11): counted after the run, in the browser.
12
+ */
13
+ export function useElsewhereInstances(schemas: Ref<SchemaSummary[]>) {
14
+ // Named instances holding rows of a table the last read found empty in the
15
+ // default instance.
16
+ const elsewhere = ref<InstanceRows[]>([])
17
+
18
+ type CountRows = (query: Record<string, string>) => Promise<{ total: number }>
19
+
20
+ /**
21
+ * The named instances of a table that hold rows, each with its count: asked
22
+ * only when a read found the table empty in the default instance (decision
23
+ * 11). An instance whose count fails is left out.
24
+ */
25
+ async function instancesWithRows(
26
+ target: QueryTarget,
27
+ count: CountRows,
28
+ ): Promise<InstanceRows[]> {
29
+ const instances =
30
+ schemas.value.find((schema) => schema.id === target.schema)?.instances ??
31
+ []
32
+ const counts = await Promise.all(
33
+ instances.map((id) =>
34
+ count({
35
+ filter_schema: `is:${target.schema}`,
36
+ filter_table: `is:${target.table}`,
37
+ filter_instance: `is:${id}`,
38
+ }).then(
39
+ (res) => ({ id, count: res.total }),
40
+ () => ({ id, count: 0 }),
41
+ ),
42
+ ),
43
+ )
44
+ return counts.filter((entry) => entry.count > 0)
45
+ }
46
+
47
+ // The table the last read found empty, whose instances are counted: in the
48
+ // browser, after a run.
49
+ const emptyTarget = shallowRef<QueryTarget | null>(null)
50
+ const elsewhereRead = useApiData<InstanceRows[]>(
51
+ () =>
52
+ emptyTarget.value
53
+ ? `dms-database:elsewhere:${JSON.stringify([
54
+ emptyTarget.value.schema,
55
+ emptyTarget.value.table,
56
+ ])}`
57
+ : null,
58
+ ({ $authFetch, signal }) =>
59
+ instancesWithRows(emptyTarget.value as QueryTarget, (query) =>
60
+ $authFetch<{ total: number }>(BROWSE_COUNT, { query, signal }),
61
+ ),
62
+ {
63
+ immediate: false,
64
+ server: false,
65
+ watch: false,
66
+ refreshOnPageRefresh: false,
67
+ },
68
+ )
69
+
70
+ // Each run drops the instances found for the previous one; a slow answer
71
+ // for an older run is ignored.
72
+ let runId = 0
73
+
74
+ async function findElsewhere(
75
+ answer: Pick<ExecuteResult, 'mutation' | 'rows'>,
76
+ next: QueryTarget,
77
+ ) {
78
+ const id = ++runId
79
+ elsewhere.value = []
80
+ if (
81
+ answer.mutation ||
82
+ answer.rows.length > 0 ||
83
+ next.instance !== '' ||
84
+ !next.schema ||
85
+ !next.table
86
+ )
87
+ return
88
+ emptyTarget.value = next
89
+ await elsewhereRead.execute()
90
+ if (id === runId) elsewhere.value = elsewhereRead.data.value ?? []
91
+ }
92
+
93
+ return { elsewhere, findElsewhere }
94
+ }