@romedb/studio 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.
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/components/studio/FilesTab.ts +121 -0
- package/src/lib/managed-files.ts +77 -0
- package/src/server/managed-files.ts +50 -0
- package/src/studio-page.ts +1 -1
- package/src/workspace/StudioWorkspace.ts +90 -2
package/README.md
CHANGED
package/package.json
CHANGED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// The Files tab: what a database's managed files add up to, and the files themselves.
|
|
2
|
+
// It reads the rows of `romedb_files` and changes nothing; a row is edited in Browse.
|
|
3
|
+
import { Component, Cossack } from '@cossackframework/core';
|
|
4
|
+
import { component, html } from '@cossackframework/renderer';
|
|
5
|
+
import { Badge, Button, SegmentBar } from '@cossackframework/ui';
|
|
6
|
+
import { bytesText, kindOf, kindShares, shareText, type FileEntry, type FilesList, type FilesOverview, type FilesView } from '../../lib/managed-files';
|
|
7
|
+
import { formatCount } from '../../lib/values';
|
|
8
|
+
|
|
9
|
+
interface FilesTabProps {
|
|
10
|
+
active: boolean;
|
|
11
|
+
connected: boolean;
|
|
12
|
+
/** The database has the collection `romedb_files`. */
|
|
13
|
+
hasFiles: boolean;
|
|
14
|
+
view: FilesView;
|
|
15
|
+
overview: FilesOverview | null;
|
|
16
|
+
list: FilesList | null;
|
|
17
|
+
/** A short-lived address of the small picture of a listed file, by file id. */
|
|
18
|
+
previews: Record<string, string>;
|
|
19
|
+
/** True while the list shows a page that is not the newest. */
|
|
20
|
+
paged: boolean;
|
|
21
|
+
busy: boolean;
|
|
22
|
+
error: string;
|
|
23
|
+
onView?: (view: FilesView) => void;
|
|
24
|
+
onRefresh?: () => void;
|
|
25
|
+
onOlder?: () => void;
|
|
26
|
+
onNewest?: () => void;
|
|
27
|
+
onDownload?: (file: FileEntry) => void;
|
|
28
|
+
[key: string]: unknown;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const when = (ms: number) => ms ? `${new Date(ms).toISOString().slice(0, 16).replace('T', ' ')} UTC` : '';
|
|
32
|
+
const plural = (count: number, one: string, many: string) => `${formatCount(count)} ${count === 1 ? one : many}`;
|
|
33
|
+
const cell = 'border-b px-3 py-2 align-middle', head = 'border-b bg-muted/50 px-3 py-2 text-left text-xs font-medium uppercase tracking-wide text-muted-foreground';
|
|
34
|
+
|
|
35
|
+
@Component()
|
|
36
|
+
export class FilesTab extends Cossack {
|
|
37
|
+
declare props: FilesTabProps;
|
|
38
|
+
|
|
39
|
+
render() {
|
|
40
|
+
const { props } = this, shown = props.active ? 'block' : 'hidden';
|
|
41
|
+
if (!props.connected)
|
|
42
|
+
return html`<div class="${props.active ? 'grid' : 'hidden'} min-h-0 flex-1 place-items-center p-6 text-muted-foreground">Connect a database to see its files.</div>`;
|
|
43
|
+
if (!props.hasFiles)
|
|
44
|
+
return html`<div class="${props.active ? 'grid' : 'hidden'} min-h-0 flex-1 place-items-center p-6" data-testid="files-none">
|
|
45
|
+
<div class="max-w-md text-center"><p class="font-medium">This database has no managed files</p>
|
|
46
|
+
<p class="mt-1 text-sm text-muted-foreground">RomeDB Cloud keeps the files of an application beside its database, and lists them in the collection romedb_files. This database has no such collection yet.</p></div></div>`;
|
|
47
|
+
const tab = (view: FilesView, label: string) => component(Button, { variant: props.view === view ? 'secondary' : 'ghost', size: 'sm', role: 'tab',
|
|
48
|
+
'aria-selected': props.view === view, 'data-testid': `files-view-${view}`, '@click': () => props.onView?.(view) }, label);
|
|
49
|
+
return html`
|
|
50
|
+
<div class="${shown} min-h-0 flex-1 overflow-auto p-5" data-testid="files-panel">
|
|
51
|
+
<header class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
|
52
|
+
<div><h2 class="text-lg font-semibold">Files</h2>
|
|
53
|
+
<p class="mt-1 max-w-3xl text-sm text-muted-foreground">The managed files of this database, read from its collection romedb_files. To change a name, a description or tags, edit the row in Browse.</p></div>
|
|
54
|
+
<div class="flex items-center gap-2">
|
|
55
|
+
<div class="flex items-center gap-1" role="tablist" aria-label="Files views">${tab('overview', 'Overview')}${tab('list', 'List')}</div>
|
|
56
|
+
${component(Button, { variant: 'outline', size: 'sm', disabled: props.busy, 'data-testid': 'files-refresh', '@click': () => props.onRefresh?.() }, props.busy ? 'Loading…' : 'Refresh')}
|
|
57
|
+
</div>
|
|
58
|
+
</header>
|
|
59
|
+
${props.error ? html`<p role="alert" class="mb-4 rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive" data-testid="files-error">${props.error}</p>` : null}
|
|
60
|
+
${props.view === 'overview' ? overview(props) : list(props)}
|
|
61
|
+
</div>`;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Plain functions, not methods: a method without a decorator runs on the server only.
|
|
66
|
+
function overview(props: FilesTabProps) {
|
|
67
|
+
const all = props.overview;
|
|
68
|
+
if (!all) return html`<p class="text-sm text-muted-foreground">${props.busy ? 'Reading the files…' : 'Nothing is loaded yet.'}</p>`;
|
|
69
|
+
const kinds = kindShares(all.types), uploaded = { files: all.files - all.made.files, bytes: all.bytes - all.made.bytes };
|
|
70
|
+
const stat = (label: string, value: string, note: string) => html`<div class="rounded-lg border p-4" data-testid="files-stat"><p class="text-xs text-muted-foreground">${label}</p>
|
|
71
|
+
<p class="mt-1 text-2xl font-semibold">${value}</p><p class="mt-1 text-xs text-muted-foreground">${note}</p></div>`;
|
|
72
|
+
return html`<div class="space-y-5" data-testid="files-overview">
|
|
73
|
+
<div class="grid gap-4 md:grid-cols-3">
|
|
74
|
+
${stat('Files', formatCount(all.files), `${formatCount(uploaded.files)} uploaded, ${formatCount(all.made.files)} made by jobs`)}
|
|
75
|
+
${stat('Stored', bytesText(all.bytes), `${bytesText(uploaded.bytes)} uploaded, ${bytesText(all.made.bytes)} made by jobs`)}
|
|
76
|
+
${stat('Kinds of file', formatCount(kinds.filter(kind => kind.files > 0).length), plural(all.types.length, 'media type', 'media types'))}
|
|
77
|
+
</div>
|
|
78
|
+
${all.files === 0 ? html`<p class="text-sm text-muted-foreground">No files are stored for this database.</p>` : html`
|
|
79
|
+
<section class="rounded-lg border p-4"><h3 class="mb-3 text-sm font-medium">Storage by kind</h3>
|
|
80
|
+
${component(SegmentBar, { label: 'Stored bytes by kind of file',
|
|
81
|
+
items: kinds.map(kind => ({ id: kind.kind, label: kind.kind, value: kind.bytes, valueText: `${bytesText(kind.bytes)} in ${plural(kind.files, 'file', 'files')}` })) })}</section>
|
|
82
|
+
<div class="grid gap-5 xl:grid-cols-2">
|
|
83
|
+
<section class="overflow-hidden rounded-lg border"><table class="w-full text-sm" data-testid="files-types">
|
|
84
|
+
<thead><tr><th class=${head}>Media type</th><th class=${head}>Files</th><th class=${head}>Size</th><th class=${head}>Share</th></tr></thead>
|
|
85
|
+
<tbody>${all.types.slice(0, 12).map(type => html`<tr><td class=${cell}><span class="font-medium">${type.mediaType || 'unknown'}</span><span class="block text-xs text-muted-foreground">${kindOf(type.mediaType)}</span></td>
|
|
86
|
+
<td class="${cell} text-muted-foreground">${formatCount(type.files)}</td><td class="${cell} whitespace-nowrap text-muted-foreground">${bytesText(type.bytes)}</td>
|
|
87
|
+
<td class="${cell} text-muted-foreground">${shareText(type.bytes, all.bytes)}</td></tr>`)}</tbody></table></section>
|
|
88
|
+
<section class="overflow-hidden rounded-lg border"><table class="w-full text-sm" data-testid="files-largest">
|
|
89
|
+
<thead><tr><th class=${head}>Largest files</th><th class=${head}>Size</th><th class=${head}>Share</th></tr></thead>
|
|
90
|
+
<tbody>${all.largest.map(file => html`<tr><td class=${cell}><span class="font-medium">${file.name}</span><span class="block text-xs text-muted-foreground">${file.mediaType || 'unknown'}</span></td>
|
|
91
|
+
<td class="${cell} whitespace-nowrap text-muted-foreground">${bytesText(file.size)}</td><td class="${cell} text-muted-foreground">${shareText(file.size, all.bytes)}</td></tr>`)}</tbody></table></section>
|
|
92
|
+
</div>`}
|
|
93
|
+
</div>`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function list(props: FilesTabProps) {
|
|
97
|
+
const list = props.list;
|
|
98
|
+
if (!list) return html`<p class="text-sm text-muted-foreground">${props.busy ? 'Reading the files…' : 'Nothing is loaded yet.'}</p>`;
|
|
99
|
+
const names = new Map(list.files.map(file => [file.id, file.name]));
|
|
100
|
+
return html`<div class="space-y-3" data-testid="files-list">
|
|
101
|
+
<section class="overflow-hidden rounded-lg border"><table class="w-full text-sm">
|
|
102
|
+
<thead><tr><th class="${head} w-16">Preview</th><th class=${head}>Name</th><th class=${head}>Type</th><th class=${head}>Size</th><th class=${head}>Added</th><th class=${head}>Added by</th><th class=${head}><span class="sr-only">Actions</span></th></tr></thead>
|
|
103
|
+
<tbody>${list.files.length ? list.files.map(file => html`<tr data-testid="files-row">
|
|
104
|
+
<td class=${cell}>${props.previews[file.id]
|
|
105
|
+
? html`<img src=${props.previews[file.id]} alt="" loading="lazy" decoding="async" width="48" height="48" class="size-12 rounded border bg-muted object-cover" data-testid="files-preview">`
|
|
106
|
+
: html`<span class="flex size-12 items-center justify-center rounded border bg-muted text-[10px] font-medium uppercase text-muted-foreground" aria-hidden="true">${(file.name.includes('.') ? file.name.split('.').pop() ?? '' : kindOf(file.mediaType)).slice(0, 4)}</span>`}</td>
|
|
107
|
+
<td class=${cell}><span class="font-medium">${file.name}</span>
|
|
108
|
+
${file.sourceId ? html`<span class="ml-2 inline-flex align-middle">${component(Badge, { variant: 'secondary' }, 'Made by a job')}</span>
|
|
109
|
+
<span class="block text-xs text-muted-foreground">From ${names.get(file.sourceId) ?? 'another file'}</span>` : null}
|
|
110
|
+
${file.description ? html`<span class="block text-xs text-muted-foreground">${file.description}</span>` : null}</td>
|
|
111
|
+
<td class="${cell} text-muted-foreground">${file.mediaType || 'unknown'}</td>
|
|
112
|
+
<td class="${cell} whitespace-nowrap text-muted-foreground">${bytesText(file.size)}</td>
|
|
113
|
+
<td class="${cell} whitespace-nowrap text-muted-foreground">${when(file.createdAt)}</td>
|
|
114
|
+
<td class="${cell} text-muted-foreground">${file.createdBy}</td>
|
|
115
|
+
<td class="${cell} text-right">${component(Button, { variant: 'ghost', size: 'sm', 'data-testid': 'files-download', '@click': () => props.onDownload?.(file) }, 'Download')}</td>
|
|
116
|
+
</tr>`) : html`<tr><td class="${cell} text-muted-foreground" colspan="7">${props.paged ? 'No older files.' : 'No files are stored for this database.'}</td></tr>`}</tbody></table></section>
|
|
117
|
+
${props.paged || list.older ? html`<div class="flex justify-end gap-2">
|
|
118
|
+
${props.paged ? component(Button, { variant: 'outline', size: 'sm', disabled: props.busy, '@click': () => props.onNewest?.() }, 'Newest') : null}
|
|
119
|
+
${list.older ? component(Button, { variant: 'outline', size: 'sm', disabled: props.busy, 'data-testid': 'files-older', '@click': () => props.onOlder?.() }, 'Older') : null}</div>` : null}
|
|
120
|
+
</div>`;
|
|
121
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Managed files of a database, as the Files tab shows them. A RomeDB Cloud database (and
|
|
2
|
+
// a local service that stores files) keeps one row for each file in the collection
|
|
3
|
+
// `romedb_files`; the tab reads those rows. This module has no server code: the browser loads it.
|
|
4
|
+
|
|
5
|
+
export const FILES_COLLECTION = 'romedb_files';
|
|
6
|
+
export const FILES_PAGE = 50;
|
|
7
|
+
|
|
8
|
+
export type FilesView = 'overview' | 'list';
|
|
9
|
+
export type FileEntry = {
|
|
10
|
+
id: string; name: string; description: string; size: number; mediaType: string; createdAt: number; createdBy: string;
|
|
11
|
+
/** The file a processing job made this one from. */
|
|
12
|
+
sourceId: string;
|
|
13
|
+
};
|
|
14
|
+
export type TypeShare = { mediaType: string; files: number; bytes: number };
|
|
15
|
+
export type FilesOverview = {
|
|
16
|
+
files: number; bytes: number;
|
|
17
|
+
/** Files a processing job made, counted in the totals too. */
|
|
18
|
+
made: { files: number; bytes: number };
|
|
19
|
+
/** Every media type with its files and bytes, largest first. */
|
|
20
|
+
types: TypeShare[];
|
|
21
|
+
largest: FileEntry[];
|
|
22
|
+
};
|
|
23
|
+
export type FilesList = { files: FileEntry[]; /** `createdAt` to ask older files from, or 0 when there are none. */ older: number };
|
|
24
|
+
/**
|
|
25
|
+
* What a server method of the Files tab answers. A failure is a value, not a thrown error:
|
|
26
|
+
* the page must show the reason, and a thrown error reaches the browser without one.
|
|
27
|
+
*/
|
|
28
|
+
export type Loaded<T> = { ok: true; value: T } | { ok: false; error: string };
|
|
29
|
+
export async function loaded<T>(work: () => Promise<T>): Promise<Loaded<T>> {
|
|
30
|
+
try { return { ok: true, value: await work() }; }
|
|
31
|
+
catch (error) { return { ok: false, error: error instanceof Error ? error.message : String(error) }; }
|
|
32
|
+
}
|
|
33
|
+
export const EMPTY_OVERVIEW: FilesOverview = { files: 0, bytes: 0, made: { files: 0, bytes: 0 }, types: [], largest: [] };
|
|
34
|
+
|
|
35
|
+
const KINDS: readonly [string, (type: string) => boolean][] = [
|
|
36
|
+
['Pictures', type => type.startsWith('image/')], ['Video', type => type.startsWith('video/')], ['Sound', type => type.startsWith('audio/')],
|
|
37
|
+
['Documents', type => type.startsWith('text/') || ['application/pdf', 'application/json', 'application/msword', 'application/rtf'].includes(type)
|
|
38
|
+
|| type.startsWith('application/vnd.openxmlformats-officedocument.') || type.startsWith('application/vnd.oasis.opendocument.') || type.startsWith('application/vnd.ms-')],
|
|
39
|
+
];
|
|
40
|
+
/** Pictures, Video, Sound, Documents or Other: the kind a media type is shown under. */
|
|
41
|
+
export const kindOf = (mediaType: string) => KINDS.find(([, matches]) => matches(mediaType))?.[0] ?? 'Other';
|
|
42
|
+
|
|
43
|
+
/** The bytes and files of each kind, in a fixed order, for the bar of the overview. */
|
|
44
|
+
export function kindShares(types: readonly TypeShare[]): { kind: string; files: number; bytes: number }[] {
|
|
45
|
+
return [...KINDS.map(([kind]) => kind), 'Other'].map(kind => {
|
|
46
|
+
const own = types.filter(type => kindOf(type.mediaType) === kind);
|
|
47
|
+
return { kind, files: own.reduce((sum, type) => sum + type.files, 0), bytes: own.reduce((sum, type) => sum + type.bytes, 0) };
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const PICTURES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/avif'], PICTURE_BYTES = 8 * 1024 * 1024;
|
|
52
|
+
/**
|
|
53
|
+
* For each listed file, the file whose bytes are its small picture: the smallest picture
|
|
54
|
+
* among the file itself and the files on the same page that a job made from it (a
|
|
55
|
+
* thumbnail of a photo, the poster of a video). A file with no such picture has no entry.
|
|
56
|
+
*/
|
|
57
|
+
export function previewSources(files: readonly FileEntry[]): Record<string, string> {
|
|
58
|
+
const chosen = new Map<string, FileEntry>();
|
|
59
|
+
const offer = (owner: string, picture: FileEntry) => {
|
|
60
|
+
if (!PICTURES.includes(picture.mediaType) || picture.size > PICTURE_BYTES) return;
|
|
61
|
+
const current = chosen.get(owner);
|
|
62
|
+
if (!current || picture.size < current.size) chosen.set(owner, picture);
|
|
63
|
+
};
|
|
64
|
+
for (const file of files) { offer(file.id, file); if (file.sourceId) offer(file.sourceId, file); }
|
|
65
|
+
const listed = new Set(files.map(file => file.id));
|
|
66
|
+
return Object.fromEntries([...chosen].filter(([owner]) => listed.has(owner)).map(([owner, picture]) => [owner, picture.id]));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB'];
|
|
70
|
+
/** Bytes in decimal units, as storage is sold: 1,500,000 is "1.5 MB". */
|
|
71
|
+
export function bytesText(value: number): string {
|
|
72
|
+
let amount = Math.max(0, value), unit = 0;
|
|
73
|
+
while (amount >= 1000 && unit < UNITS.length - 1) { amount /= 1000; unit++; }
|
|
74
|
+
return `${unit === 0 ? amount : amount >= 100 ? Math.round(amount) : amount >= 10 ? Math.round(amount * 10) / 10 : Math.round(amount * 100) / 100} ${UNITS[unit]}`;
|
|
75
|
+
}
|
|
76
|
+
/** The share of `part` in `whole`, as "12.3%". */
|
|
77
|
+
export const shareText = (part: number, whole: number) => whole > 0 ? `${Math.round(part / whole * 1000) / 10}%` : '0%';
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// What the Files tab reads: the database's own rows of `romedb_files`, through the same
|
|
2
|
+
// connections as every other query of the workspace. Nothing here changes a file.
|
|
3
|
+
import type { Context } from 'hono';
|
|
4
|
+
import type { PortableValue } from '@romedb/client';
|
|
5
|
+
import { workspaceConnections } from './backend';
|
|
6
|
+
import { toJson } from '../lib/values';
|
|
7
|
+
import { EMPTY_OVERVIEW, FILES_PAGE, type FileEntry, type FilesList, type FilesOverview } from '../lib/managed-files';
|
|
8
|
+
|
|
9
|
+
const FIELDS = 'id, name, size, mediaType, createdAt, createdBy, description, source';
|
|
10
|
+
const TYPES = 'SELECT mediaType, count(*) AS files, sum(size) AS bytes FROM romedb_files GROUP BY mediaType ORDER BY bytes DESC LIMIT 200';
|
|
11
|
+
const MADE = 'SELECT count(*), sum(size) FROM romedb_files WHERE source IS NOT NULL';
|
|
12
|
+
const LARGEST = `SELECT ${FIELDS} FROM romedb_files ORDER BY size DESC LIMIT 5`;
|
|
13
|
+
|
|
14
|
+
type Row = readonly (PortableValue | undefined)[];
|
|
15
|
+
const amount = (value: PortableValue | undefined) => { const number = Number(value ? toJson(value) : 0); return Number.isFinite(number) && number > 0 ? number : 0; };
|
|
16
|
+
const text = (value: PortableValue | undefined) => value?.type === 'String' ? value.value : '';
|
|
17
|
+
const recordKey = (value: PortableValue | undefined) => value?.type === 'Record' ? String(value.value.key.value) : '';
|
|
18
|
+
const entry = (row: Row): FileEntry => ({ id: recordKey(row[0]), name: text(row[1]), size: amount(row[2]), mediaType: text(row[3]), createdAt: amount(row[4]),
|
|
19
|
+
createdBy: text(row[5]), description: text(row[6]), sourceId: recordKey(row[7]) });
|
|
20
|
+
|
|
21
|
+
async function read(context: Context, connectionId: string, statements: { sql: string }[]): Promise<{ rows: Row[] }[]> {
|
|
22
|
+
const actor = context.get('user') as { id?: string } | undefined;
|
|
23
|
+
if (!actor?.id) throw new Error('Studio session required');
|
|
24
|
+
const reply = await workspaceConnections(context).execute(actor.id, connectionId, crypto.randomUUID(), statements, 'read');
|
|
25
|
+
if (!('results' in reply) || !reply.results) throw new Error('error' in reply && reply.error ? reply.error.message : 'Invalid database response');
|
|
26
|
+
return reply.results;
|
|
27
|
+
}
|
|
28
|
+
// A database that never had a managed file has no `romedb_files`.
|
|
29
|
+
const noFiles = (error: unknown) => /no such table: romedb_files/.test(error instanceof Error ? error.message : String(error));
|
|
30
|
+
|
|
31
|
+
/** The sums of the Overview: files and bytes, what jobs made, every media type, the largest files. */
|
|
32
|
+
export async function loadFilesOverview(context: Context, connectionId: string): Promise<FilesOverview> {
|
|
33
|
+
let results;
|
|
34
|
+
try { results = await read(context, connectionId, [{ sql: TYPES }, { sql: MADE }, { sql: LARGEST }]); }
|
|
35
|
+
catch (error) { if (noFiles(error)) return EMPTY_OVERVIEW; throw error; }
|
|
36
|
+
const types = (results[0]?.rows ?? []).map(row => ({ mediaType: text(row[0]), files: amount(row[1]), bytes: amount(row[2]) }));
|
|
37
|
+
const made = results[1]?.rows[0] ?? [];
|
|
38
|
+
return { files: types.reduce((sum, type) => sum + type.files, 0), bytes: types.reduce((sum, type) => sum + type.bytes, 0),
|
|
39
|
+
made: { files: amount(made[0]), bytes: amount(made[1]) }, types, largest: (results[2]?.rows ?? []).map(entry) };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One page of files, newest first. `before` is the `older` of the page before it. */
|
|
43
|
+
export async function loadFilesList(context: Context, connectionId: string, before = 0): Promise<FilesList> {
|
|
44
|
+
if (!Number.isSafeInteger(before) || before < 0) throw new Error('Invalid place in the list of files');
|
|
45
|
+
let results;
|
|
46
|
+
try { results = await read(context, connectionId, [{ sql: `SELECT ${FIELDS} FROM romedb_files${before ? ` WHERE createdAt < ${before}` : ''} ORDER BY createdAt DESC LIMIT ${FILES_PAGE + 1}` }]); }
|
|
47
|
+
catch (error) { if (noFiles(error)) return { files: [], older: 0 }; throw error; }
|
|
48
|
+
const files = (results[0]?.rows ?? []).map(entry), page = files.slice(0, FILES_PAGE);
|
|
49
|
+
return { files: page, older: files.length > FILES_PAGE ? page[page.length - 1].createdAt : 0 };
|
|
50
|
+
}
|
package/src/studio-page.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ValueKind } from './lib/values';
|
|
2
2
|
|
|
3
3
|
export type CellMode = 'null' | 'value';
|
|
4
|
-
export type StudioTab = 'browse' | 'structure' | 'sql' | 'graph' | 'map' | 'database';
|
|
4
|
+
export type StudioTab = 'browse' | 'structure' | 'sql' | 'graph' | 'map' | 'files' | 'database';
|
|
5
5
|
export type InsertMode = 'omit' | 'null' | 'value';
|
|
6
6
|
export type InsertSelection = ValueKind | Exclude<InsertMode, 'value'>;
|
|
7
7
|
export type CellSelection = ValueKind | 'null';
|
|
@@ -12,6 +12,7 @@ import { DangerTriangleIcon } from '@cossackframework/solar-icons/danger-triangl
|
|
|
12
12
|
import { DatabaseIcon } from '@cossackframework/solar-icons/database';
|
|
13
13
|
import { DocumentsIcon } from '@cossackframework/solar-icons/documents';
|
|
14
14
|
import { EyeIcon } from '@cossackframework/solar-icons/eye';
|
|
15
|
+
import { FileIcon } from '@cossackframework/solar-icons/file';
|
|
15
16
|
import { MapIcon } from '@cossackframework/solar-icons/map';
|
|
16
17
|
import { RefreshIcon } from '@cossackframework/solar-icons/refresh';
|
|
17
18
|
import { SettingsMinimalisticIcon } from '@cossackframework/solar-icons/settings-minimalistic';
|
|
@@ -41,6 +42,8 @@ import {
|
|
|
41
42
|
import { BrowseTab } from '../components/studio/BrowseTab';
|
|
42
43
|
import { CellEditorSheet } from '../components/studio/CellEditorSheet';
|
|
43
44
|
import { DatabaseTab } from '../components/studio/DatabaseTab';
|
|
45
|
+
import { FilesTab } from '../components/studio/FilesTab';
|
|
46
|
+
import { FILES_COLLECTION, previewSources, type FileEntry, type FilesList, type FilesOverview, type FilesView, type Loaded } from '../lib/managed-files';
|
|
44
47
|
import { GraphTab } from '../components/studio/GraphTab';
|
|
45
48
|
import { MapTab, type MapBoxField } from '../components/studio/MapTab';
|
|
46
49
|
import { InsertRowSheet } from '../components/studio/InsertRowSheet';
|
|
@@ -61,7 +64,7 @@ type WriteReply = Awaited<ReturnType<typeof saveEdit>>;
|
|
|
61
64
|
type WriteOutcome = { ok: true; sequence: number } | { ok: false; error: string };
|
|
62
65
|
|
|
63
66
|
export const DEFAULT_SQL = 'SELECT sqlite_version() AS version;';
|
|
64
|
-
export const WORKSPACE_TABS: readonly StudioTab[] = ['browse', 'structure', 'sql', 'graph', 'map', 'database'];
|
|
67
|
+
export const WORKSPACE_TABS: readonly StudioTab[] = ['browse', 'structure', 'sql', 'graph', 'map', 'files', 'database'];
|
|
65
68
|
|
|
66
69
|
export abstract class StudioWorkspace extends Cossack {
|
|
67
70
|
@ClientState() activeConnection = '';
|
|
@@ -83,6 +86,15 @@ export abstract class StudioWorkspace extends Cossack {
|
|
|
83
86
|
@ClientState() restorePointsFor = '';
|
|
84
87
|
@ClientState() restorePointsError = '';
|
|
85
88
|
@ClientState() restorePointsBusy = false;
|
|
89
|
+
@ClientState() filesView: FilesView = 'overview';
|
|
90
|
+
@ClientState() filesOverview: FilesOverview | null = null;
|
|
91
|
+
@ClientState() filesList: FilesList | null = null;
|
|
92
|
+
@ClientState() filesPreviews: Record<string, string> = {};
|
|
93
|
+
/** The connection the loaded files belong to, and the place in the list (0 is the newest page). */
|
|
94
|
+
@ClientState() filesFor = '';
|
|
95
|
+
@ClientState() filesBefore = 0;
|
|
96
|
+
@ClientState() filesError = '';
|
|
97
|
+
@ClientState() filesBusy = false;
|
|
86
98
|
|
|
87
99
|
@ClientState() showFilter = false;
|
|
88
100
|
@ClientState() filters: BrowseFilter[] = [];
|
|
@@ -187,6 +199,17 @@ export abstract class StudioWorkspace extends Cossack {
|
|
|
187
199
|
abstract exploreGraph(id: string, request: GraphRequest): Promise<GraphView>;
|
|
188
200
|
abstract fetchMap(id: string, request: MapRequest): Promise<MapView>;
|
|
189
201
|
abstract fetchRestorePoints(id: string): Promise<RestorePoints>;
|
|
202
|
+
// The Files tab. A page that shows the tab provides these three as server methods; a
|
|
203
|
+
// page that leaves `files` out of `workspaceTabs` need not.
|
|
204
|
+
// Each answers a value or the reason it has none (`Loaded`).
|
|
205
|
+
/** The sums of the database's managed files. */
|
|
206
|
+
async fetchFilesOverview(_id: string): Promise<Loaded<FilesOverview>> { return { ok: false, error: 'Files are not available here' }; }
|
|
207
|
+
/** One page of managed files, newest first; `before` is the `older` of the page before it. */
|
|
208
|
+
async fetchFilesList(_id: string, _before: number): Promise<Loaded<FilesList>> { return { ok: false, error: 'Files are not available here' }; }
|
|
209
|
+
/** Short-lived addresses that show files in the page, by file id. None when the service gives none. */
|
|
210
|
+
async fetchFilePreviews(_id: string, _fileIds: string[]): Promise<Loaded<Record<string, string>>> { return { ok: true, value: {} }; }
|
|
211
|
+
/** A short-lived address that downloads one file. */
|
|
212
|
+
async fetchFileDownload(_id: string, _fileId: string): Promise<Loaded<string>> { return { ok: false, error: 'Files are not available here' }; }
|
|
190
213
|
abstract restoreAtPoint(id: string, sequence: number): Promise<RestoredDatabase>;
|
|
191
214
|
abstract cancelOperation(operation: string): Promise<boolean>;
|
|
192
215
|
abstract recoverWrite(id: string, operation: string, recovery: string): ReturnType<typeof recoverQuery>;
|
|
@@ -274,7 +297,8 @@ export abstract class StudioWorkspace extends Cossack {
|
|
|
274
297
|
@Client()
|
|
275
298
|
async restoreViewFromUrl(params: URLSearchParams) {
|
|
276
299
|
const requestedTab = params.get('tab');
|
|
277
|
-
this.tab = requestedTab === 'structure' || requestedTab === 'sql' || requestedTab === 'graph' || requestedTab === 'map' || requestedTab === 'database' ? requestedTab : 'browse';
|
|
300
|
+
this.tab = requestedTab === 'structure' || requestedTab === 'sql' || requestedTab === 'graph' || requestedTab === 'map' || requestedTab === 'files' || requestedTab === 'database' ? requestedTab : 'browse';
|
|
301
|
+
if (this.tab === 'files') void this.loadFiles();
|
|
278
302
|
const size = Number(params.get('pageSize') ?? 100);
|
|
279
303
|
this.pageSize = PAGE_SIZES.includes(size) ? size : 100;
|
|
280
304
|
const object = this.schema.objects.find(candidate => candidate.name === params.get('table'));
|
|
@@ -417,6 +441,64 @@ export abstract class StudioWorkspace extends Cossack {
|
|
|
417
441
|
this.tab = tab;
|
|
418
442
|
this.syncUrl(true);
|
|
419
443
|
}, ['studio-tab']);
|
|
444
|
+
if (tab === 'files' && this.filesFor !== this.activeConnection) void this.loadFiles();
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** True when the open database has the collection of managed files. */
|
|
448
|
+
@Shared()
|
|
449
|
+
hasManagedFiles(): boolean { return this.schema.objects.some(object => object.name === FILES_COLLECTION); }
|
|
450
|
+
|
|
451
|
+
/** Loads the view of the Files tab that is showing. `before` 0 is the newest page of the list. */
|
|
452
|
+
@Client()
|
|
453
|
+
async loadFiles(before = 0) {
|
|
454
|
+
const id = this.activeConnection, view = this.filesView;
|
|
455
|
+
if (!id || !this.hasManagedFiles()) return;
|
|
456
|
+
this.filesBusy = true; this.filesError = '';
|
|
457
|
+
try {
|
|
458
|
+
if (view === 'overview') {
|
|
459
|
+
const overview = await this.fetchFilesOverview(id);
|
|
460
|
+
if (this.activeConnection !== id) return;
|
|
461
|
+
if (!overview.ok) throw new Error(overview.error);
|
|
462
|
+
this.filesOverview = overview.value;
|
|
463
|
+
} else {
|
|
464
|
+
const answer = await this.fetchFilesList(id, before);
|
|
465
|
+
if (this.activeConnection !== id) return;
|
|
466
|
+
if (!answer.ok) throw new Error(answer.error);
|
|
467
|
+
const list = answer.value;
|
|
468
|
+
this.filesList = list; this.filesBefore = before; this.filesPreviews = {};
|
|
469
|
+
// The pictures come after the list: the list shows without them when the service has none.
|
|
470
|
+
const pictures = previewSources(list.files), wanted = [...new Set(Object.values(pictures))];
|
|
471
|
+
if (wanted.length) {
|
|
472
|
+
const shown = await this.fetchFilePreviews(id, wanted).catch(() => null);
|
|
473
|
+
const urls = shown?.ok ? shown.value : {};
|
|
474
|
+
if (this.activeConnection !== id || this.filesList !== list) return;
|
|
475
|
+
this.filesPreviews = Object.fromEntries(Object.entries(pictures).filter(([, picture]) => urls[picture]).map(([owner, picture]) => [owner, urls[picture]]));
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
this.filesFor = id;
|
|
479
|
+
} catch (error) {
|
|
480
|
+
this.filesFor = id;
|
|
481
|
+
this.filesError = error instanceof Error ? error.message : String(error);
|
|
482
|
+
} finally { this.filesBusy = false; }
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
@Client()
|
|
486
|
+
async showFilesView(view: FilesView) {
|
|
487
|
+
this.filesView = view;
|
|
488
|
+
if (view === 'overview' ? !this.filesOverview || this.filesFor !== this.activeConnection : !this.filesList || this.filesFor !== this.activeConnection) await this.loadFiles();
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** Opens the address of one file's bytes; the browser saves the file and stays in Studio. */
|
|
492
|
+
@Client()
|
|
493
|
+
async downloadFile(file: FileEntry) {
|
|
494
|
+
const id = this.activeConnection;
|
|
495
|
+
if (!id) return;
|
|
496
|
+
this.filesError = '';
|
|
497
|
+
try {
|
|
498
|
+
const address = await this.fetchFileDownload(id, file.id);
|
|
499
|
+
if (address.ok) window.location.assign(address.value);
|
|
500
|
+
else { this.filesError = address.error; this.filesFor = id; }
|
|
501
|
+
} catch (error) { this.filesError = error instanceof Error ? error.message : String(error); this.filesFor = id; }
|
|
420
502
|
}
|
|
421
503
|
|
|
422
504
|
@Client()
|
|
@@ -1619,6 +1701,7 @@ export abstract class StudioWorkspace extends Cossack {
|
|
|
1619
1701
|
['sql', CodeSquareIcon, 'Console'],
|
|
1620
1702
|
['graph', ShareCircleIcon, 'Graph'],
|
|
1621
1703
|
['map', MapIcon, 'Map'],
|
|
1704
|
+
['files', FileIcon, 'Files'],
|
|
1622
1705
|
['database', SettingsMinimalisticIcon, 'Database'],
|
|
1623
1706
|
] as const).filter(([item]) => tabs.includes(item)).map(([item, icon, label]) => component(Button, {
|
|
1624
1707
|
variant: this.tab === item ? 'secondary' : 'ghost',
|
|
@@ -1800,6 +1883,11 @@ export abstract class StudioWorkspace extends Cossack {
|
|
|
1800
1883
|
onOpenRecord: (record: PortableValue) => this.followRecord(record),
|
|
1801
1884
|
onOpenSql: this.openMapInSql,
|
|
1802
1885
|
})}
|
|
1886
|
+
${component(FilesTab, { active: this.tab === 'files', connected: !!this.schema.connection, hasFiles: this.hasManagedFiles(), view: this.filesView,
|
|
1887
|
+
overview: this.filesFor === this.activeConnection ? this.filesOverview : null, list: this.filesFor === this.activeConnection ? this.filesList : null,
|
|
1888
|
+
previews: this.filesPreviews, paged: this.filesBefore > 0, busy: this.filesBusy, error: this.filesFor === this.activeConnection ? this.filesError : '',
|
|
1889
|
+
onView: this.showFilesView, onRefresh: () => this.loadFiles(this.filesView === 'list' ? this.filesBefore : 0),
|
|
1890
|
+
onOlder: () => this.loadFiles(this.filesList?.older ?? 0), onNewest: () => this.loadFiles(0), onDownload: this.downloadFile })}
|
|
1803
1891
|
${component(DatabaseTab, { schema: this.schema, active: this.tab === 'database',
|
|
1804
1892
|
restorePoints: this.restorePointsFor === this.activeConnection ? this.restorePoints : null,
|
|
1805
1893
|
restorePointsError: this.restorePointsFor === this.activeConnection ? this.restorePointsError : '',
|