@romedb/studio 0.0.0-stage → 0.1.1

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 (38) hide show
  1. package/LICENSE.md +20 -0
  2. package/README.md +15 -2
  3. package/package.json +36 -4
  4. package/src/components/CodeEditor.ts +298 -0
  5. package/src/components/studio/BrowseTab.ts +457 -0
  6. package/src/components/studio/CellEditorSheet.ts +165 -0
  7. package/src/components/studio/DatabaseTab.ts +148 -0
  8. package/src/components/studio/GraphCanvas.ts +90 -0
  9. package/src/components/studio/GraphTab.ts +110 -0
  10. package/src/components/studio/InsertRowSheet.ts +180 -0
  11. package/src/components/studio/MapCanvas.ts +177 -0
  12. package/src/components/studio/MapTab.ts +121 -0
  13. package/src/components/studio/NewObjectSheet.ts +235 -0
  14. package/src/components/studio/QueryHistorySheet.ts +111 -0
  15. package/src/components/studio/RowSheets.ts +226 -0
  16. package/src/components/studio/SqlConsole.ts +281 -0
  17. package/src/components/studio/StructureTab.ts +209 -0
  18. package/src/components/studio/icon-button.ts +21 -0
  19. package/src/lib/filters.ts +44 -0
  20. package/src/lib/graph.ts +214 -0
  21. package/src/lib/romeql.ts +106 -0
  22. package/src/lib/spatial.ts +518 -0
  23. package/src/lib/sql-text.ts +208 -0
  24. package/src/lib/studio-types.ts +268 -0
  25. package/src/lib/values.ts +305 -0
  26. package/src/monaco-standalone.d.ts +27 -0
  27. package/src/schema-draft.ts +41 -0
  28. package/src/schema-store.ts +8 -0
  29. package/src/server/backend.ts +77 -0
  30. package/src/server/data.ts +142 -0
  31. package/src/server/edits.ts +92 -0
  32. package/src/server/graph.ts +66 -0
  33. package/src/server/queries.ts +108 -0
  34. package/src/server/schema.ts +272 -0
  35. package/src/server/spatial.ts +74 -0
  36. package/src/studio-page.ts +84 -0
  37. package/src/workspace/StudioWorkspace.ts +1970 -0
  38. package/src/workspace/workspace.css +38 -0
@@ -0,0 +1,148 @@
1
+ // RomeDB counterpart of Cossack Studio's Pragmas tab: negotiated connection settings and limits.
2
+ import { Component, Cossack } from '@cossackframework/core';
3
+ import { component, html } from '@cossackframework/renderer';
4
+ import { Badge, Button } from '@cossackframework/ui';
5
+ import type { RestorePoints, StudioSchema } from '../../lib/studio-types';
6
+ import { formatCount } from '../../lib/values';
7
+
8
+ interface DatabaseTabProps {
9
+ schema: StudioSchema;
10
+ active: boolean;
11
+ restorePoints?: RestorePoints | null;
12
+ restorePointsError?: string;
13
+ restorePointsBusy?: boolean;
14
+ onLoadRestorePoints?: () => void;
15
+ onRestorePoint?: (sequence: number) => void;
16
+ [key: string]: unknown;
17
+ }
18
+
19
+ const CAPABILITY_LABELS: Record<string, string> = {
20
+ readVersion: 'Read protocol version',
21
+ atomicWrites: 'Atomic multi-statement writes',
22
+ replayWindow: 'Duplicate-request replay window',
23
+ exactSequenceCondition: 'Expected-revision writes',
24
+ sequenceScope: 'Revision scope',
25
+ replayDurability: 'Replay durability',
26
+ metadata: 'Logical metadata',
27
+ checkedWork: 'Work budgets',
28
+ foreignKeys: 'Foreign keys enforced',
29
+ provenance: 'Capability source',
30
+ };
31
+
32
+ const LIMIT_LABELS: Record<string, string> = {
33
+ maxRequestBytes: 'Maximum request size (bytes)',
34
+ maxStatements: 'Statements per request',
35
+ maxRows: 'Rows per result',
36
+ maxResultBytes: 'Maximum result size (bytes)',
37
+ activeRequests: 'Concurrent requests',
38
+ queuedRequests: 'Queued requests',
39
+ rowsRead: 'Rows read per request',
40
+ rowMutations: 'Row changes per request',
41
+ vmSteps: 'VM steps per request',
42
+ };
43
+
44
+ @Component()
45
+ export class DatabaseTab extends Cossack {
46
+ declare props: DatabaseTabProps;
47
+
48
+ render() {
49
+ const connection = this.props.schema.connection;
50
+ if (!connection) {
51
+ return html`<div class="${this.props.active ? 'grid' : 'hidden'} min-h-0 flex-1 place-items-center p-6 text-muted-foreground">Connect a database to inspect its settings.</div>`;
52
+ }
53
+ const tables = this.props.schema.objects.filter(object => object.model === 'relational').length;
54
+ const collections = this.props.schema.objects.filter(object => object.model === 'document').length;
55
+ const views = this.props.schema.objects.filter(object => object.model === 'view').length;
56
+ return html`
57
+ <div class="${this.props.active ? 'block' : 'hidden'} min-h-0 flex-1 overflow-auto p-5" data-testid="database-panel">
58
+ <header class="mb-5">
59
+ <h2 class="text-lg font-semibold">Database settings</h2>
60
+ <p class="mt-1 max-w-3xl text-sm text-muted-foreground">
61
+ RomeDB negotiates these settings when Studio connects. They are the same for local files, the local
62
+ service and Cloud. PRAGMA statements are not available through the RomeDB client, and foreign keys are always enforced.
63
+ </p>
64
+ </header>
65
+
66
+ <section class="mb-6 overflow-hidden rounded-lg border">
67
+ <table class="w-full text-sm" data-testid="connection-table">
68
+ <tbody>
69
+ ${row('Connection', connection.name)}
70
+ ${row('Access', html`${connection.kind === 'file' ? 'Embedded file' : connection.remote ? 'Cloud database URL' : 'Local service URL'}
71
+ ${connection.remote ? component(Badge, { variant: 'destructive', class: 'ml-2' }, 'Remote') : ''}`)}
72
+ ${row(connection.kind === 'file' ? 'File' : 'URL', html`<span class="break-all font-mono">${connection.endpoint}</span>`)}
73
+ ${row('Database ID', html`<span class="font-mono">${connection.databaseId}</span>`)}
74
+ ${row('Current revision', String(this.props.schema.sequence || connection.sequence))}
75
+ ${connection.journalMode ? row('Journal mode', connection.journalMode.toUpperCase()) : ''}
76
+ ${connection.databaseVersion ? row('Engine', connection.databaseVersion) : ''}
77
+ ${connection.clientVersion ? row('Studio client', `RomeDB Node SDK ${connection.clientVersion}`) : ''}
78
+ ${row('Objects', `${tables} table${tables === 1 ? '' : 's'} · ${collections} collection${collections === 1 ? '' : 's'} · ${views} view${views === 1 ? '' : 's'}`)}
79
+ </tbody>
80
+ </table>
81
+ </section>
82
+
83
+ <div class="grid gap-6 xl:grid-cols-2">
84
+ <section>
85
+ <h3 class="mb-2 font-semibold">Capabilities</h3>
86
+ <div class="overflow-hidden rounded-lg border">
87
+ <table class="w-full text-sm" data-testid="capabilities-table">
88
+ <thead><tr class="border-b bg-muted/40 text-left"><th class="p-3">Capability</th><th class="p-3">Value</th></tr></thead>
89
+ <tbody>${Object.entries(connection.capabilities).map(([name, value]) => row(CAPABILITY_LABELS[name] ?? name, settingValue(value)))}</tbody>
90
+ </table>
91
+ </div>
92
+ </section>
93
+ <section>
94
+ <h3 class="mb-2 font-semibold">Request limits</h3>
95
+ <div class="overflow-hidden rounded-lg border">
96
+ <table class="w-full text-sm" data-testid="limits-table">
97
+ <thead><tr class="border-b bg-muted/40 text-left"><th class="p-3">Limit</th><th class="p-3">Value</th></tr></thead>
98
+ <tbody>
99
+ ${Object.keys(connection.limits).length
100
+ ? Object.entries(connection.limits).map(([name, value]) => row(LIMIT_LABELS[name] ?? name, settingValue(value)))
101
+ : html`<tr><td class="p-3 text-muted-foreground" colspan="2">This connection did not report limits.</td></tr>`}
102
+ </tbody>
103
+ </table>
104
+ </div>
105
+ </section>
106
+ </div>
107
+ ${connection.remote ? this.restoreSection() : ''}
108
+ </div>
109
+ `;
110
+ }
111
+
112
+ // RomeDB Cloud keeps restore points per database; restoring from Studio
113
+ // always creates a new database (needs an organization key with manage access).
114
+ restoreSection() {
115
+ const points = this.props.restorePoints, busy = this.props.restorePointsBusy === true;
116
+ return html`
117
+ <section class="mt-6" data-testid="restore-points">
118
+ <div class="mb-2 flex items-center gap-3">
119
+ <h3 class="font-semibold">Restore points</h3>
120
+ ${component(Button, { variant: 'outline', size: 'sm', disabled: busy, '@click': () => this.props.onLoadRestorePoints?.() }, points ? 'Refresh' : 'Load restore points')}
121
+ </div>
122
+ ${this.props.restorePointsError ? html`<p class="text-sm text-destructive">${this.props.restorePointsError}</p>` : ''}
123
+ ${points ? html`
124
+ <p class="mb-2 text-sm text-muted-foreground">Kept for ${points.retentionDays} day${points.retentionDays === 1 ? '' : 's'} on this plan. A restore creates a new database and leaves this one unchanged.</p>
125
+ <div class="overflow-hidden rounded-lg border">
126
+ <table class="w-full text-sm">
127
+ <thead><tr class="border-b bg-muted/40 text-left"><th class="p-3">Time (UTC)</th><th class="p-3">Revision</th><th class="p-3">Kind</th><th class="p-3"></th></tr></thead>
128
+ <tbody>${points.points.length ? points.points.slice(0, 100).map(point => html`<tr class="border-b last:border-b-0">
129
+ <td class="p-3 font-mono">${new Date(point.at).toISOString()}</td><td class="p-3">${point.sequence}</td>
130
+ <td class="p-3">${point.kind === 'flush' ? 'Between checkpoints' : 'Checkpoint'}</td>
131
+ <td class="p-3 text-right">${component(Button, { variant: 'outline', size: 'sm', disabled: busy, '@click': () => this.props.onRestorePoint?.(point.sequence) }, 'Restore into new database')}</td></tr>`)
132
+ : html`<tr><td class="p-3 text-muted-foreground" colspan="4">No restore point yet.</td></tr>`}</tbody>
133
+ </table>
134
+ </div>` : ''}
135
+ </section>`;
136
+ }
137
+ }
138
+
139
+ function row(label: string, value: unknown) {
140
+ return html`<tr class="border-b last:border-b-0"><th class="w-64 p-3 text-left align-top font-medium">${label}</th><td class="p-3">${value}</td></tr>`;
141
+ }
142
+
143
+ function settingValue(value: unknown): string {
144
+ if (typeof value === 'boolean') return value ? 'Yes' : 'No';
145
+ if (typeof value === 'number') return formatCount(value);
146
+ if (typeof value === 'string') return value;
147
+ return JSON.stringify(value);
148
+ }
@@ -0,0 +1,90 @@
1
+ // Concentric SVG drawing of graph nodes and directed edges. Node clicks report the record.
2
+ import { Component, Cossack } from '@cossackframework/core';
3
+ import { html, svg } from '@cossackframework/renderer';
4
+ import { layoutGraph, tableColor } from '../../lib/graph';
5
+ import type { GraphEdge, GraphNode } from '../../lib/studio-types';
6
+
7
+ interface GraphCanvasProps {
8
+ nodes: GraphNode[];
9
+ edges: GraphEdge[];
10
+ selected?: string;
11
+ onSelectNode?: (node: GraphNode) => void;
12
+ 'data-testid'?: string;
13
+ [key: string]: unknown;
14
+ }
15
+
16
+ const RADIUS = 18;
17
+
18
+ @Component()
19
+ export class GraphCanvas extends Cossack {
20
+ declare props: GraphCanvasProps;
21
+
22
+ render() {
23
+ const { nodes, edges } = this.props;
24
+ if (!nodes.length) return html``;
25
+ const { placements, size } = layoutGraph(nodes, edges);
26
+ const tables = [...new Set(nodes.map(node => node.table))];
27
+ return html`
28
+ <div class="grid gap-2" data-testid="${this.props['data-testid'] ?? 'graph-canvas'}">
29
+ <svg
30
+ class="h-[min(70vh,44rem)] w-full rounded-md border bg-card"
31
+ viewBox="0 0 ${size} ${size}"
32
+ role="img"
33
+ aria-label="Graph of ${nodes.length} node${nodes.length === 1 ? '' : 's'} and ${edges.length} edge${edges.length === 1 ? '' : 's'}"
34
+ >
35
+ <defs>
36
+ <marker id="studio-graph-arrow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
37
+ <path d="M 0 0 L 10 5 L 0 10 z" fill="currentColor" class="text-muted-foreground"></path>
38
+ </marker>
39
+ </defs>
40
+ ${edges.map(edge => {
41
+ const from = placements.get(edge.source);
42
+ const to = placements.get(edge.target);
43
+ if (!from || !to) return svg``;
44
+ if (edge.source === edge.target) {
45
+ return svg`<g data-testid="graph-edge" data-edge="${edge.key}">
46
+ <circle cx="${from.x + RADIUS}" cy="${from.y - RADIUS}" r="${RADIUS * 0.8}" fill="none" stroke="currentColor" class="text-muted-foreground" stroke-width="1.5"></circle>
47
+ <title>${edge.key}: ${edge.source} → ${edge.target}</title>
48
+ </g>`;
49
+ }
50
+ const dx = to.x - from.x;
51
+ const dy = to.y - from.y;
52
+ const length = Math.max(1, Math.hypot(dx, dy));
53
+ const x1 = from.x + (dx / length) * RADIUS;
54
+ const y1 = from.y + (dy / length) * RADIUS;
55
+ const x2 = to.x - (dx / length) * (RADIUS + 2);
56
+ const y2 = to.y - (dy / length) * (RADIUS + 2);
57
+ return svg`<g data-testid="graph-edge" data-edge="${edge.key}">
58
+ <line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="currentColor" class="text-muted-foreground" stroke-width="1.5" marker-end="url(#studio-graph-arrow)"></line>
59
+ <text x="${(x1 + x2) / 2 + 6}" y="${(y1 + y2) / 2}" text-anchor="start" class="fill-muted-foreground text-[10px]">${edge.label}</text>
60
+ <title>${edge.key}: ${edge.source} → ${edge.target}</title>
61
+ </g>`;
62
+ })}
63
+ ${nodes.map(node => {
64
+ const place = placements.get(node.key);
65
+ if (!place) return svg``;
66
+ const selected = node.key === this.props.selected;
67
+ return svg`<g
68
+ data-testid="graph-node"
69
+ data-node="${node.key}"
70
+ class="cursor-pointer"
71
+ role="button"
72
+ tabindex="0"
73
+ aria-label="${node.key}"
74
+ @click="${() => this.props.onSelectNode?.(node)}"
75
+ @keydown="${(event: KeyboardEvent) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); this.props.onSelectNode?.(node); } }}"
76
+ >
77
+ <circle cx="${place.x}" cy="${place.y}" r="${RADIUS}" fill="${tableColor(node.table)}" stroke="${selected ? 'var(--foreground)' : 'var(--background)'}" stroke-width="${selected ? 3 : 2}"></circle>
78
+ <text x="${place.x}" y="${place.y + RADIUS + 14}" text-anchor="middle" class="fill-foreground text-[11px] font-mono">${node.label.length > 28 ? `${node.label.slice(0, 27)}…` : node.label}</text>
79
+ <title>${node.key}</title>
80
+ </g>`;
81
+ })}
82
+ </svg>
83
+ <div class="flex flex-wrap items-center gap-3 text-xs text-muted-foreground" data-testid="graph-legend">
84
+ ${tables.map(table => html`<span class="inline-flex items-center gap-1.5"><span class="inline-block size-2.5 rounded-full" style="background:${tableColor(table)}"></span>${table}</span>`)}
85
+ <span>· ${nodes.length} node${nodes.length === 1 ? '' : 's'} · ${edges.length} edge${edges.length === 1 ? '' : 's'}</span>
86
+ </div>
87
+ </div>
88
+ `;
89
+ }
90
+ }
@@ -0,0 +1,110 @@
1
+ // Neighborhood explorer for edge tables declared with CREATE EDGE TABLE.
2
+ import { Component, Cossack } from '@cossackframework/core';
3
+ import { component, html } from '@cossackframework/renderer';
4
+ import { PlayIcon } from '@cossackframework/solar-icons/play';
5
+ import { Alert, Button, Icon, Input } from '@cossackframework/ui';
6
+ import { MAX_EXPLORE_DEPTH } from '../../lib/graph';
7
+ import type { GraphDirection, GraphNode, GraphView, StudioSchema } from '../../lib/studio-types';
8
+ import { GraphCanvas } from './GraphCanvas';
9
+
10
+ export interface GraphTabProps {
11
+ active: boolean;
12
+ schema: StudioSchema;
13
+ root: string;
14
+ edge: string;
15
+ direction: GraphDirection;
16
+ depth: number;
17
+ view: GraphView | null;
18
+ loading: boolean;
19
+ onRootChange: (root: string) => void;
20
+ onEdgeChange: (edge: string) => void;
21
+ onDirectionChange: (direction: GraphDirection) => void;
22
+ onDepthChange: (depth: number) => void;
23
+ onExplore: () => void;
24
+ onSelectNode: (node: GraphNode) => void;
25
+ onOpenSql: () => void;
26
+ [key: string]: unknown;
27
+ }
28
+
29
+ @Component()
30
+ export class GraphTab extends Cossack {
31
+ declare props: GraphTabProps;
32
+
33
+ render() {
34
+ const { schema, view } = this.props;
35
+ const edgeTables = schema.objects.filter(object => object.edge);
36
+ const selectClass = 'h-9 rounded-md border border-input bg-background px-2 text-sm';
37
+ return html`
38
+ <div class="${this.props.active ? 'flex' : 'hidden'} min-h-0 flex-1 flex-col overflow-auto p-5" data-testid="graph-panel">
39
+ ${edgeTables.length ? html`
40
+ <form
41
+ class="grid gap-3 md:grid-cols-[minmax(0,2fr)_minmax(0,1.5fr)_auto_auto_auto] md:items-end"
42
+ @submit="${(event: Event) => { event.preventDefault(); this.props.onExplore(); }}"
43
+ >
44
+ <label class="grid gap-1 text-sm font-medium">
45
+ Start record
46
+ ${component(Input, {
47
+ class: 'font-mono',
48
+ placeholder: 'people:alice',
49
+ 'data-testid': 'graph-root',
50
+ '.value': this.props.root,
51
+ '@input': (event: InputEvent) => this.props.onRootChange((event.target as HTMLInputElement).value),
52
+ })}
53
+ </label>
54
+ <label class="grid gap-1 text-sm font-medium">
55
+ Edge table
56
+ <select class="${selectClass}" data-testid="graph-edge-table" .value="${this.props.edge}"
57
+ @change="${(event: Event) => this.props.onEdgeChange((event.target as HTMLSelectElement).value)}">
58
+ ${edgeTables.map(object => html`<option value="${object.name}" ?selected="${object.name === this.props.edge}">${object.name} (${object.edge!.source} → ${object.edge!.target})</option>`)}
59
+ </select>
60
+ </label>
61
+ <label class="grid gap-1 text-sm font-medium">
62
+ Direction
63
+ <select class="${selectClass}" data-testid="graph-direction" .value="${this.props.direction}"
64
+ @change="${(event: Event) => this.props.onDirectionChange((event.target as HTMLSelectElement).value as GraphDirection)}">
65
+ ${([['out', 'Outgoing'], ['in', 'Incoming'], ['both', 'Both']] as const).map(([value, label]) => html`<option value="${value}" ?selected="${value === this.props.direction}">${label}</option>`)}
66
+ </select>
67
+ </label>
68
+ <label class="grid gap-1 text-sm font-medium">
69
+ Depth
70
+ <select class="${selectClass}" data-testid="graph-depth" .value="${String(this.props.depth)}"
71
+ @change="${(event: Event) => this.props.onDepthChange(Number((event.target as HTMLSelectElement).value))}">
72
+ ${Array.from({ length: MAX_EXPLORE_DEPTH }, (_, index) => index + 1).map(depth => html`<option value="${depth}" ?selected="${depth === this.props.depth}">${depth}</option>`)}
73
+ </select>
74
+ </label>
75
+ ${component(Button, { type: 'submit', class: 'gap-2', disabled: this.props.loading || !this.props.root.trim(), 'data-testid': 'graph-explore' },
76
+ html`${component(Icon, { entry: PlayIcon, size: 16 })}<span>${this.props.loading ? 'Exploring…' : 'Explore'}</span>`)}
77
+ </form>
78
+ <p class="mt-2 text-xs text-muted-foreground">
79
+ A self-referencing edge table is explored recursively up to the chosen depth, each node at its shortest
80
+ distance. Other edge tables follow one hop in the direction their declaration allows. Click a node to explore from it.
81
+ </p>
82
+ ` : html`
83
+ <div class="text-sm text-muted-foreground" data-testid="graph-empty">
84
+ <p>This database has no edge tables.</p>
85
+ <p class="mt-2">Create one with <code class="rounded bg-muted px-1">CREATE EDGE TABLE follows FROM people TO people</code>,
86
+ add edges with <code class="rounded bg-muted px-1">RELATE people:alice -&gt; follows -&gt; people:bob</code>, then explore them here.</p>
87
+ </div>
88
+ `}
89
+ ${view?.error ? component(Alert, { variant: 'destructive', class: 'mt-4', title: 'Could not explore the graph', 'data-testid': 'graph-error' }, view.error) : ''}
90
+ ${view && !view.error ? html`
91
+ <div class="mt-4 grid gap-3">
92
+ ${component(GraphCanvas, {
93
+ nodes: view.nodes,
94
+ edges: view.edges,
95
+ selected: view.nodes[0]?.key,
96
+ onSelectNode: this.props.onSelectNode,
97
+ 'data-testid': 'graph-explorer-canvas',
98
+ })}
99
+ ${view.nodes.length <= 1 ? html`<p class="text-sm text-muted-foreground" data-testid="graph-no-neighbors">No connected records were found.</p>` : ''}
100
+ <div class="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
101
+ <code class="min-w-0 flex-1 break-all rounded bg-muted px-2 py-1" data-testid="graph-query">${view.query}</code>
102
+ <span>${view.durationMs.toFixed(1)} ms · revision ${view.sequence}</span>
103
+ ${component(Button, { size: 'sm', variant: 'outline', 'data-testid': 'graph-open-sql', '@click': this.props.onOpenSql }, 'Open in Console')}
104
+ </div>
105
+ </div>
106
+ ` : ''}
107
+ </div>
108
+ `;
109
+ }
110
+ }
@@ -0,0 +1,180 @@
1
+ // Adapted from Cossack Studio's InsertRowSheet (MIT); collections insert a JSON document instead.
2
+ import { Component, Cossack } from '@cossackframework/core';
3
+ import { component, html } from '@cossackframework/renderer';
4
+ import { RefreshIcon } from '@cossackframework/solar-icons/refresh';
5
+ import { Alert, Button, DatePicker, Icon, Input, Sheet, isCalendarDate } from '@cossackframework/ui';
6
+ import type { StudioObject } from '../../lib/studio-types';
7
+ import { VALUE_KINDS, declaredKind, type ValueKind } from '../../lib/values';
8
+ import type { InsertFieldState, InsertSelection } from '../../studio-page';
9
+ import { CodeEditor } from '../CodeEditor';
10
+
11
+ interface InsertRowSheetProps {
12
+ object?: StudioObject;
13
+ open: boolean;
14
+ fields: Record<string, InsertFieldState>;
15
+ document: string;
16
+ error: string;
17
+ theme: 'light' | 'dark';
18
+ inserting: boolean;
19
+ onClose: () => void;
20
+ onValueChange: (column: string, value: string) => void;
21
+ onSelectionChange: (column: string, selection: InsertSelection) => void;
22
+ onRegenerateValue: (column: string, kind: ValueKind) => void;
23
+ onDocumentChange: (value: string) => void;
24
+ onSubmit: () => void;
25
+ [key: string]: unknown;
26
+ }
27
+
28
+ @Component()
29
+ export class InsertRowSheet extends Cossack {
30
+ declare props: InsertRowSheetProps;
31
+
32
+ render() {
33
+ const { object } = this.props;
34
+ const isDocument = object?.model === 'document';
35
+ return component(Sheet, {
36
+ open: Boolean(this.props.open && object?.editable),
37
+ side: 'right',
38
+ size: 'min(42rem, 94vw)',
39
+ onOpenChange: this.props.onClose,
40
+ 'data-testid': 'insert-form',
41
+ 'aria-label': isDocument ? 'Insert document' : 'Insert row',
42
+ }, html`
43
+ <header class="shrink-0 border-b p-5">
44
+ <h2 class="font-semibold">${isDocument ? 'Insert document' : 'Insert row'}</h2>
45
+ <p class="mt-1 text-sm text-muted-foreground">
46
+ Add a new ${isDocument ? 'document' : 'row'} to ${object?.name ?? 'the selected table'}. The insert runs as one atomic write.
47
+ </p>
48
+ </header>
49
+ <div class="min-h-0 flex-1 overflow-auto p-5">
50
+ ${this.props.error ? component(Alert, {
51
+ variant: 'destructive',
52
+ title: isDocument ? 'Could not insert document' : 'Could not insert row',
53
+ class: 'mb-4',
54
+ 'data-testid': 'insert-error',
55
+ }, this.props.error) : ''}
56
+ ${isDocument ? html`
57
+ <div class="flex h-full min-h-[24rem] flex-col gap-3">
58
+ ${component(CodeEditor, {
59
+ class: 'min-h-[22rem] flex-1',
60
+ value: this.props.document,
61
+ language: 'json',
62
+ theme: this.props.theme,
63
+ enabled: this.props.open,
64
+ ariaLabel: `JSON document for ${object?.name ?? 'collection'}`,
65
+ 'data-testid': 'insert-document',
66
+ onChange: this.props.onDocumentChange,
67
+ onRun: this.props.onSubmit,
68
+ })}
69
+ <p class="text-xs text-muted-foreground">
70
+ The <code class="rounded bg-muted px-1">id</code> must be a record ID in this collection, for example
71
+ <code class="rounded bg-muted px-1">{"$record": "${object?.name ?? 'users'}:tan"}</code>.
72
+ Whole numbers are stored as Integer; use <code class="rounded bg-muted px-1">{"$number": 3}</code> for a floating-point value.
73
+ </p>
74
+ </div>
75
+ ` : html`
76
+ <div class="grid grid-cols-1 gap-4">
77
+ ${object?.columns.filter(column => !column.hidden).map(column => {
78
+ const field = this.props.fields[column.name] ?? { mode: 'value', valueKind: declaredKind(column), value: '' };
79
+ const { mode, valueKind, value } = field;
80
+ const inputId = `insert-value-${encodeURIComponent(column.name)}`;
81
+ const selection: InsertSelection = mode === 'value' ? valueKind : mode;
82
+ const activeClass = mode === 'value' ? 'studio-insert-value' : 'bg-muted/60';
83
+ const generated = valueKind === 'uuid-v4' || valueKind === 'uuid-v7' || valueKind === 'timestamp';
84
+ return html`
85
+ <div class="grid gap-1.5 text-sm" data-testid="insert-field-${column.name}">
86
+ <label class="font-medium" for=${inputId}>
87
+ ${column.name}
88
+ <small class="ml-1 font-normal text-muted-foreground">
89
+ ${column.dataType}${column.primaryKeyPosition ? ' · primary key' : ''}${column.nullable ? '' : ' · required'}${column.defaultValue !== null ? ` · default ${column.defaultValue}` : ''}
90
+ </small>
91
+ </label>
92
+ <div class="flex items-start gap-2">
93
+ <div class="min-w-0 flex-1 ${mode === 'value' ? '' : 'pointer-events-none opacity-60'}">
94
+ ${valueKind === 'json' ? component(CodeEditor, {
95
+ class: `h-[10rem] ${activeClass}`,
96
+ value,
97
+ language: 'json',
98
+ theme: this.props.theme,
99
+ readOnly: mode !== 'value',
100
+ lineNumbers: 'off',
101
+ ariaLabel: `JSON value for ${column.name}`,
102
+ 'data-testid': `insert-value-${column.name}`,
103
+ onChange: (next: string) => this.props.onValueChange(column.name, next),
104
+ }) : valueKind === 'date' && (!value || isCalendarDate(value)) ? html`
105
+ <div class="rounded-md ${activeClass}" data-testid="insert-value-${column.name}">
106
+ ${component(DatePicker, {
107
+ id: inputId,
108
+ disabled: mode !== 'value',
109
+ value,
110
+ onValueChange: (next: string) => this.props.onValueChange(column.name, next),
111
+ })}
112
+ </div>
113
+ ` : valueKind === 'boolean' ? html`
114
+ <select
115
+ id=${inputId}
116
+ class="h-10 w-full rounded-md border border-input px-3 ${activeClass}"
117
+ data-testid="insert-value-${column.name}"
118
+ ?disabled="${mode !== 'value'}"
119
+ .value="${value}"
120
+ @change="${(event: Event) => this.props.onValueChange(column.name, (event.target as HTMLSelectElement).value)}"
121
+ >
122
+ <option value="true" ?selected="${value !== 'false'}">True</option>
123
+ <option value="false" ?selected="${value === 'false'}">False</option>
124
+ </select>
125
+ ` : html`
126
+ <div class="flex gap-2">
127
+ ${component(Input, {
128
+ id: inputId,
129
+ class: `min-w-0 flex-1 font-mono ${activeClass}`,
130
+ type: valueKind === 'datetime' ? 'datetime-local' : 'text',
131
+ inputmode: valueKind === 'integer' || valueKind === 'number' ? 'decimal' : undefined,
132
+ placeholder: valueKind === 'record' ? 'users:tan' : valueKind === 'binary' ? 'Hexadecimal or base64' : '',
133
+ disabled: mode !== 'value',
134
+ 'data-testid': `insert-value-${column.name}`,
135
+ '.value': value,
136
+ '@input': (event: InputEvent) => this.props.onValueChange(column.name, (event.target as HTMLInputElement).value),
137
+ })}
138
+ ${generated ? component(Button, {
139
+ variant: 'outline',
140
+ size: 'icon',
141
+ title: valueKind === 'timestamp' ? 'Use current timestamp' : 'Generate another UUID',
142
+ 'aria-label': valueKind === 'timestamp' ? 'Use current timestamp' : 'Generate another UUID',
143
+ '@click': () => this.props.onRegenerateValue(column.name, valueKind),
144
+ }, component(Icon, { entry: RefreshIcon, size: 16 })) : ''}
145
+ </div>
146
+ `}
147
+ </div>
148
+ <select
149
+ class="studio-insert-option h-10 w-40 shrink-0 rounded-md border border-input bg-background px-2 text-foreground"
150
+ data-testid="insert-option-${column.name}"
151
+ aria-label="Value type or insert mode for ${column.name}"
152
+ .value="${selection}"
153
+ @change="${(event: Event) => this.props.onSelectionChange(column.name, (event.target as HTMLSelectElement).value as InsertSelection)}"
154
+ >
155
+ <optgroup label="Value type">
156
+ ${VALUE_KINDS.map(kind => html`<option value="${kind.value}" ?selected="${selection === kind.value}">${kind.label}</option>`)}
157
+ </optgroup>
158
+ <optgroup label="Special">
159
+ <option value="omit" ?selected="${selection === 'omit'}">Omit / default</option>
160
+ ${column.nullable ? html`<option value="null" ?selected="${selection === 'null'}">NULL</option>` : ''}
161
+ </optgroup>
162
+ </select>
163
+ </div>
164
+ </div>
165
+ `;
166
+ }) ?? ''}
167
+ </div>
168
+ `}
169
+ </div>
170
+ <footer class="flex shrink-0 justify-end gap-2 border-t p-4">
171
+ ${component(Button, { variant: 'ghost', '@click': this.props.onClose }, 'Cancel')}
172
+ ${component(Button, {
173
+ disabled: this.props.inserting,
174
+ 'data-testid': 'submit-insert',
175
+ '@click': this.props.onSubmit,
176
+ }, this.props.inserting ? 'Inserting…' : isDocument ? 'Insert document' : 'Insert row')}
177
+ </footer>
178
+ `);
179
+ }
180
+ }