Something went wrong. Try again.
Local-first knowledge base made for Typst and the Atmosphere. typbase.at
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830<script setup lang="ts">import type { StorageEntryStat } from "@typbase/storage";import type { PageMeta, WorkspaceInfo } from "@typbase/typing";
import { WorkspaceRegistry, WorkspaceStore, exportTauriStorageFile, isTauri, pagePath,} from "@typbase/storage";
import { formatAgo } from "~/lib/format";
/** * Debug surface for the active storage backend: a semantic view of the * workspace registry and Loro docs, and a raw tree over the same byte paths. * Actions that mutate workspace metadata go through the store, while raw file * actions only touch bytes and can break a workspace if misused. */
interface FileNode { name: string; path: string; kind: "file" | "directory"; size: number; modifiedAt?: number; expanded: boolean; children?: FileNode[];}
const { backend, storageLocation, workspaces, activeWorkspaceId, workspace, deleteWorkspace } = useWorkspace();const { t, locale } = useI18n();const { confirm } = useConfirm();
const props = defineProps<{ initialView?: "data" | "files" | "assets" }>();
const view = ref<"data" | "files" | "assets">(props.initialView ?? "data");const loading = ref(false);const error = ref("");const assetBrowser = useTemplateRef<{ refresh: () => Promise<void> }>("assetBrowser");
const isNative = computed(() => storageLocation.value.environment === "native");
function formatBytes(size: number): string { if (size < 1024) return `${size} B`; if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
return `${(size / (1024 * 1024)).toFixed(1)} MB`;}
function formatTime(timestamp: number | undefined): string { if (!timestamp) return "";
return formatAgo(timestamp, locale.value);}
/* Data view: registry entries plus a lazily opened store per workspace. */
const workspaceSizes = ref(new Map<string, number>());const expandedWorkspaceId = ref<string | null>(null);const expandedPages = ref<PageMeta[]>([]);const pageSizes = ref(new Map<string, number>());const storeCache = new Map<string, WorkspaceStore>();
async function directorySize(path: string): Promise<number> { const active = backend.value; if (!active) return 0;
let total = 0; for (const name of await active.list(path)) { const child = path ? `${path}/${name}` : name; const info = await active.stat(child); if (!info) continue; total += info.kind === "directory" ? await directorySize(child) : info.size; }
return total;}
async function refreshData(): Promise<void> { const active = backend.value; if (!active) return;
error.value = ""; const registry = new WorkspaceRegistry(active); const entries = await registry.list();
const sizes = new Map<string, number>(); for (const entry of entries) { sizes.set(entry.id, await directorySize(`workspaces/${entry.id}`)); } workspaceSizes.value = sizes;}
async function toggleWorkspace(info: WorkspaceInfo): Promise<void> { const active = backend.value; if (!active) return;
if (expandedWorkspaceId.value === info.id) { expandedWorkspaceId.value = null; return; }
error.value = ""; try { let store = storeCache.get(info.id); if (!store) { store = await WorkspaceStore.open(active, info.id); storeCache.set(info.id, store); } const pages = store.listPages(); const sizes = new Map<string, number>(); for (const page of pages) { const stat = await active.stat(pagePath(info.id, page.id)); if (stat) sizes.set(page.id, stat.size); } expandedPages.value = pages; pageSizes.value = sizes; expandedWorkspaceId.value = info.id; } catch (cause) { error.value = cause instanceof Error ? cause.message : String(cause); }}
async function deletePageEntry(info: WorkspaceInfo, page: PageMeta): Promise<void> { const active = backend.value; if (!active) return; const remove = await confirm({ title: t("explorer.deletePageTitle"), description: t("explorer.deletePageConfirm", { title: page.title }), }); if (!remove) return;
error.value = ""; try { if (activeWorkspaceId.value === info.id && workspace.value) { await workspace.value.deletePage(page.id); } else { const store = storeCache.get(info.id) ?? (await WorkspaceStore.open(active, info.id)); storeCache.set(info.id, store); await store.deletePage(page.id); } await toggleWorkspaceReopen(info); } catch (cause) { error.value = cause instanceof Error ? cause.message : String(cause); }}
/** Refreshes the expanded page list without collapsing the row. */async function toggleWorkspaceReopen(info: WorkspaceInfo): Promise<void> { expandedWorkspaceId.value = null; await toggleWorkspace(info);}
async function deleteWorkspaceEntry(info: WorkspaceInfo): Promise<void> { const remove = await confirm({ title: t("explorer.deleteWorkspaceTitle"), description: t("explorer.deleteWorkspaceConfirm", { name: info.name }), }); if (!remove) return;
error.value = ""; try { await deleteWorkspace(info.id); storeCache.delete(info.id); expandedWorkspaceId.value = null; await refreshData(); } catch (cause) { error.value = cause instanceof Error ? cause.message : String(cause); }}
async function reveal(relative: string): Promise<void> { try { const [{ revealItemsInDir }, { resolveStoragePath, tauriStorageState }] = await Promise.all([ import("@tauri-apps/plugin-opener"), import("@typbase/storage"), ]); await revealItemsInDir(resolveStoragePath(await tauriStorageState(), relative)); } catch (cause) { error.value = cause instanceof Error ? cause.message : String(cause); }}
/* Files view: a lazy tree over `list` + `stat`. */
const nodes = ref<FileNode[]>([]);/** Recursive folder totals, keyed by path. Filled in as listings arrive. */const folderSizes = ref(new Map<string, number>());const measuring = new Set<string>();
async function measureFolder(node: FileNode): Promise<void> { if (node.kind !== "directory" || folderSizes.value.has(node.path) || measuring.has(node.path)) { return; }
measuring.add(node.path); try { const size = await directorySize(node.path); const next = new Map(folderSizes.value); next.set(node.path, size); folderSizes.value = next; } catch (cause) { error.value = cause instanceof Error ? cause.message : String(cause); } finally { measuring.delete(node.path); }}
/** A file's own size, or a folder's total once its walk finishes. */function nodeMeta(node: FileNode): string { if (node.kind === "file") return formatBytes(node.size);
const size = folderSizes.value.get(node.path);
return size === undefined ? t("explorer.directory") : `${t("explorer.directory")} · ${formatBytes(size)}`;}
async function readChildren(path: string): Promise<FileNode[]> { const active = backend.value; if (!active) return [];
const result: FileNode[] = []; for (const name of await active.list(path)) { const child = path ? `${path}/${name}` : name; const info: StorageEntryStat | null = await active.stat(child); result.push({ name, path: child, kind: info?.kind ?? "file", size: info?.size ?? 0, modifiedAt: info?.modifiedAt, expanded: false, }); }
for (const node of result) { if (node.kind === "directory") void measureFolder(node); }
return result;}
async function refreshFiles(): Promise<void> { error.value = ""; folderSizes.value = new Map(); measuring.clear(); nodes.value = await readChildren("");}
async function toggleFolder(node: FileNode): Promise<void> { if (node.kind !== "directory") return;
error.value = ""; try { if (!node.children) node.children = await readChildren(node.path); node.expanded = !node.expanded; } catch (cause) { error.value = cause instanceof Error ? cause.message : String(cause); }}
interface FlatNode { node: FileNode; depth: number;}
const flatNodes = computed<FlatNode[]>(() => { const out: FlatNode[] = []; const walk = (list: FileNode[], depth: number) => { for (const node of list) { out.push({ node, depth }); if (node.kind === "directory" && node.expanded && node.children) { walk(node.children, depth + 1); } } }; walk(nodes.value, 0);
return out;});
async function download(node: FileNode): Promise<void> { const active = backend.value; if (!active || node.kind !== "file") return;
// The native shell has no reliable webview download path, so it goes // through the save dialog. Browsers get the anchor download. if (isTauri()) { try { if (await exportTauriStorageFile(node.path)) return; } catch (cause) { error.value = cause instanceof Error ? cause.message : String(cause); return; } }
const bytes = await active.read(node.path); if (!bytes) return;
const url = URL.createObjectURL(new Blob([bytes as BlobPart])); const anchor = document.createElement("a"); anchor.href = url; anchor.download = node.name; anchor.click(); URL.revokeObjectURL(url);}
async function upload(event: Event): Promise<void> { const active = backend.value; const input = event.target as HTMLInputElement; const file = input.files?.[0]; if (!active || !file) return;
error.value = ""; try { await active.write(file.name, new Uint8Array(await file.arrayBuffer())); input.value = ""; await refreshFiles(); } catch (cause) { error.value = cause instanceof Error ? cause.message : String(cause); }}
async function deleteNode(node: FileNode): Promise<void> { const active = backend.value; if (!active) return; const remove = await confirm({ title: t("explorer.deleteFileTitle"), description: t("explorer.deleteFileConfirm", { path: node.path }), }); if (!remove) return;
error.value = ""; try { await active.delete(node.path); await refreshFiles(); } catch (cause) { error.value = cause instanceof Error ? cause.message : String(cause); }}
async function refresh(): Promise<void> { const active = backend.value; if (!active) return;
loading.value = true; try { if (view.value === "assets") await assetBrowser.value?.refresh(); else await (view.value === "data" ? refreshData() : refreshFiles()); } catch (cause) { error.value = cause instanceof Error ? cause.message : String(cause); } finally { loading.value = false; }}
watch(view, () => void refresh());watch(backend, () => { storeCache.clear(); expandedWorkspaceId.value = null; void refresh();});
onMounted(() => void refresh());onBeforeUnmount(() => { for (const store of storeCache.values()) void store.flush();});</script>
<template> <section class="explorer"> <header class="explorer__header"> <h2 class="explorer__title">{{ $t("explorer.title") }}</h2> <div class="explorer__tabs"> <button type="button" class="explorer__tab" :class="{ 'explorer__tab--active': view === 'data' }" @click="view = 'data'" > {{ $t("explorer.tabData") }} </button> <button type="button" class="explorer__tab" :class="{ 'explorer__tab--active': view === 'files' }" @click="view = 'files'" > {{ $t("explorer.tabFiles") }} </button> <button type="button" class="explorer__tab" :class="{ 'explorer__tab--active': view === 'assets' }" @click="view = 'assets'" > {{ $t("explorer.tabAssets") }} </button> </div> <UiButton size="small" :disabled="loading" @click="refresh"> {{ loading ? $t("explorer.refreshing") : $t("explorer.refresh") }} </UiButton> </header>
<p class="explorer__location"> <span>{{ storageLocation.label }}</span> <span v-if="storageLocation.path" class="explorer__path">{{ storageLocation.path }}</span> <UiButton variant="ghost" size="small" v-if="isNative && storageLocation.path" @click="reveal('')" > {{ $t("explorer.reveal") }} </UiButton> </p>
<p v-if="error" class="explorer__error" role="alert">{{ error }}</p>
<div v-if="view === 'data'" class="explorer__panel"> <p v-if="!workspaces.length" class="explorer__empty">{{ $t("explorer.noWorkspaces") }}</p>
<div v-for="info in workspaces" :key="info.id" class="explorer__workspace"> <div class="explorer__row"> <UiTooltip :text=" expandedWorkspaceId === info.id ? $t('explorer.collapse') : $t('explorer.expand') " > <button type="button" class="explorer__expand" @click="toggleWorkspace(info)"> <MsIcon :name="expandedWorkspaceId === info.id ? 'keyboard_arrow_down' : 'chevron_right'" :size="20" /> </button> </UiTooltip> <button type="button" class="explorer__name" @click="toggleWorkspace(info)"> <span class="explorer__name-main">{{ info.name }}</span> <span class="explorer__name-meta"> {{ info.id }} · {{ formatBytes(workspaceSizes.get(info.id) ?? 0) }} <template v-if="info.lastOpenedAt"> · {{ $t("explorer.opened", { when: formatTime(info.lastOpenedAt) }) }} </template> <template v-if="info.id === activeWorkspaceId"> · {{ $t("explorer.active") }} </template> </span> </button> <span class="explorer__actions"> <UiIconButton v-if="isNative" icon="folder_open" :size="20" :label="$t('explorer.reveal')" variant="ghost" class="button--tiny" @click="reveal(`workspaces/${info.id}`)" /> <UiIconButton icon="delete" :size="20" :label="$t('common.delete')" variant="ghost" danger class="button--tiny" @click="deleteWorkspaceEntry(info)" /> </span> </div>
<ul v-if="expandedWorkspaceId === info.id" class="explorer__pages"> <li v-for="page in expandedPages" :key="page.id" class="explorer__page"> <span class="explorer__page-title">{{ page.title }}</span> <span class="explorer__page-path">{{ page.path }}</span> <span class="explorer__page-meta"> {{ formatBytes(pageSizes.get(page.id) ?? 0) }} <template v-if="page.updatedAt"> · {{ formatTime(page.updatedAt) }}</template> </span> <UiIconButton icon="delete" :size="20" :label="$t('common.delete')" variant="ghost" danger class="button--tiny" @click="deletePageEntry(info, page)" /> </li> </ul> </div> </div>
<div v-else-if="view === 'files'" class="explorer__panel"> <UiButton as="label" size="small" class="explorer__upload"> {{ $t("explorer.upload") }} <input type="file" hidden @change="upload" /> </UiButton>
<div v-for="entry in flatNodes" :key="entry.node.path" class="explorer__node" :style="{ '--depth': entry.depth }" > <span class="explorer__guides" aria-hidden="true"> <span v-for="level in entry.depth" :key="level" class="explorer__guide" /> </span> <UiTooltip v-if="entry.node.kind === 'directory'" :text="entry.node.expanded ? $t('explorer.collapse') : $t('explorer.expand')" > <button type="button" class="explorer__expand" @click="toggleFolder(entry.node)"> <MsIcon :name="entry.node.expanded ? 'keyboard_arrow_down' : 'chevron_right'" :size="20" /> </button> </UiTooltip> <span v-else class="explorer__expand explorer__expand--file"> <MsIcon name="draft" :size="18" /> </span> <button v-if="entry.node.kind === 'directory'" type="button" class="explorer__node-name explorer__node-name--dir explorer__node-name--toggle" :aria-expanded="entry.node.expanded" @click="toggleFolder(entry.node)" > {{ entry.node.name }} </button> <span v-else class="explorer__node-name">{{ entry.node.name }}</span> <span class="explorer__node-meta"> {{ nodeMeta(entry.node) }} <template v-if="entry.node.modifiedAt"> · {{ formatTime(entry.node.modifiedAt) }}</template > </span> <span class="explorer__actions"> <UiIconButton v-if="entry.node.kind === 'file'" icon="download" :size="20" :label="$t('explorer.download')" variant="ghost" class="button--tiny" @click="download(entry.node)" /> <UiIconButton v-if="isNative" icon="folder_open" :size="20" :label="$t('explorer.reveal')" variant="ghost" class="button--tiny" @click="reveal(entry.node.path)" /> <UiIconButton icon="delete" :size="20" :label="$t('common.delete')" variant="ghost" danger class="button--tiny" @click="deleteNode(entry.node)" /> </span> </div> </div>
<div v-else class="explorer__panel"> <AssetBrowser ref="assetBrowser" /> </div>
<p class="explorer__hint">{{ $t("explorer.hint") }}</p> </section></template>
<style>.explorer { display: flex; flex-direction: column; gap: var(--space-2); border: 1px solid var(--color-border); border-radius: var(--radius-md); padding: var(--space-3); background: var(--color-surface);}
.explorer__header { display: flex; align-items: center; gap: var(--space-3);}
.explorer__title { margin: 0; font-size: var(--text-lg); flex: 1;}
.explorer__tabs { display: flex; gap: var(--space-1);}
.explorer__tab { border: 1px solid var(--color-border); background: transparent; color: inherit; border-radius: var(--radius-sm); padding: var(--space-1) var(--space-2-5); font-size: var(--text-sm); cursor: pointer;}
.explorer__tab--active { border-color: var(--color-accent); background: var(--color-accent-soft);}
.explorer__location { display: flex; align-items: center; gap: var(--space-2); margin: 0; font-size: var(--text-sm); color: var(--color-text-secondary); flex-wrap: wrap;}
.explorer__path { font-family: var(--font-mono, monospace); overflow: hidden; text-overflow: ellipsis; max-width: 100%;}
.explorer__panel { display: flex; flex-direction: column; gap: var(--space-0-5);}
.explorer__empty,.explorer__error,.explorer__hint { margin: 0; font-size: var(--text-sm); color: var(--color-text-secondary);}
.explorer__error { color: var(--color-danger);}
.explorer__workspace { border-bottom: 1px solid var(--color-border);}
.explorer__row,.explorer__node { display: flex; align-items: center; gap: var(--space-1-5); min-width: 0;}
.explorer__row { padding: var(--space-1) 0;}
.explorer__node { position: relative; padding: var(--space-1) 0 var(--space-1) calc(var(--space-1-5) + var(--depth, 0) * var(--space-4));}
/* One line per ancestor. Positioned over the row's indent, so the lines run edge to edge down a folder's children. */.explorer__guides { position: absolute; top: 0; bottom: 0; left: var(--space-1-5); display: flex; pointer-events: none;}
.explorer__guide { position: relative; width: var(--space-4);}
.explorer__guide::before { content: ""; position: absolute; top: 0; bottom: 0; left: 50%; width: 1px; background: var(--color-border);}
.explorer__expand,.explorer__expand--file { display: inline-flex; align-items: center; justify-content: center; width: 1.3rem; flex: none; border: none; background: transparent; color: var(--color-text-secondary); cursor: pointer; padding: 0;}
.explorer__expand--file { cursor: default;}
.explorer__name { flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: flex-start; gap: var(--space-0-5); border: none; background: transparent; color: inherit; text-align: left; cursor: pointer; padding: 0;}
.explorer__name-main { font-size: var(--text-md);}
.explorer__name-meta,.explorer__page-meta { font-size: var(--text-xs); color: var(--color-text-secondary);}
.explorer__node-name { flex: 1; min-width: 0; font-size: var(--text-md); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}
.explorer__node-name--dir { font-weight: 600;}
.explorer__node-name--toggle { padding: 0; font-family: inherit; color: inherit; text-align: left; background: transparent; border: none; cursor: pointer;}
.explorer__node-name--toggle:hover { text-decoration: underline;}
.explorer__node-meta { font-size: var(--text-xs); color: var(--color-text-secondary); flex: none;}
.explorer__actions { display: flex; gap: var(--space-0-5); flex: none;}
.explorer__pages { list-style: none; margin: 0; padding: 0 0 var(--space-1-5) var(--space-6); display: flex; flex-direction: column; gap: var(--space-0-5);}
.explorer__page { display: flex; align-items: center; gap: var(--space-2); min-width: 0; font-size: var(--text-sm);}
.explorer__page-title { flex: none; max-width: 11rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}
.explorer__page-path { flex: 1; min-width: 0; color: var(--color-text-secondary); font-size: var(--text-xs); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}
.explorer__upload { align-self: flex-start; cursor: pointer;}</style>