Files
knock/src/lib/state/workspace.svelte.ts
T
JoshiCodes 59a8000cc0 Tab menu, copy as cURL, drafts survive restarts, copy response body
- Right click a tab: close, close others, close to the right, close all,
  duplicate, copy as cURL, show in sidebar
- Ctrl+Shift+C copies the request as cURL with variables and auth filled
  in; secrets stay masked
- Unsaved edits and scratch requests come back after a restart or crash
- Copy button for the response body
2026-11-27 21:57:25 +01:00

415 lines
12 KiB
TypeScript

import { api, errorText } from '$lib/api';
import type { CollectionView, Request, SendResult, TreeNode } from '$lib/types';
import { toast } from '@joshicodes/cock';
import { newRequest, normalizeRequest } from '$lib/request';
export type TabKind = 'request' | 'folder' | 'collection' | 'environment' | 'settings' | 'history';
export interface ResultState {
result: SendResult;
/** Decoded body text, filled lazily by the viewer. */
bodyText?: string;
bodyBytes?: Uint8Array;
at: number;
}
export interface Tab {
key: string;
kind: TabKind;
col: string | null;
/** Request or folder id inside the collection; env id for environment tabs. */
id: string | null;
title: string;
preview: boolean;
draft?: Request;
saved?: string;
sending?: boolean;
result?: ResultState;
previous?: ResultState;
error?: string;
diskChanged?: boolean;
}
function load<T>(key: string, fallback: T): T {
try {
const v = localStorage.getItem(key);
return v ? (JSON.parse(v) as T) : fallback;
} catch {
return fallback;
}
}
function store(key: string, value: unknown) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
/* storage blocked; settings just do not persist */
}
}
export function snapshot(r: Request | undefined): string {
return JSON.stringify(r ?? null);
}
class Workspace {
collections = $state<CollectionView[]>([]);
envByCol = $state<Record<string, string | null>>(load('knock.env', {}));
tabs = $state<Tab[]>([]);
activeKey = $state<string | null>(null);
layout = $state<'columns' | 'rows'>(load('knock.layout', 'columns'));
maskSecrets = $state<boolean>(load('knock.mask', false));
sidebarWidth = $state<number>(load('knock.sidebar', 280));
paletteOpen = $state(false);
/** Collection that new requests and commands act on. */
focusCol = $state<string | null>(null);
get active(): Tab | undefined {
return this.tabs.find((t) => t.key === this.activeKey);
}
collection(id: string | null): CollectionView | undefined {
return this.collections.find((c) => c.id === id);
}
/**
* Active environment. Until one is picked, `local` (or the first one) is
* active, so variables resolve right away. Picking "No environment" is
* remembered as an explicit null.
*/
env(col: string | null): string | null {
if (!col) return null;
const c = this.collection(col);
const chosen = this.envByCol[col];
if (chosen === null) return null;
if (chosen && c?.environments.some((e) => e.id === chosen)) return chosen;
const envs = c?.environments ?? [];
return (envs.find((e) => e.id === 'local') ?? envs[0])?.id ?? null;
}
setEnv(col: string, env: string | null) {
this.envByCol[col] = env;
store('knock.env', this.envByCol);
}
setLayout(l: 'columns' | 'rows') {
this.layout = l;
store('knock.layout', l);
}
setMask(m: boolean) {
this.maskSecrets = m;
store('knock.mask', m);
}
setSidebarWidth(w: number) {
this.sidebarWidth = w;
store('knock.sidebar', w);
}
// ------------------------------------------------------------ collections
async restore() {
// Read everything first: opening a collection saves the (still empty) tab list.
const open: string[] = load('knock.open', []);
const savedTabs: { kind: TabKind; col: string | null; id: string | null }[] = load('knock.tabs', []);
const active = load<string | null>('knock.activeTab', null);
for (const root of open) {
try {
this.upsert(await api.collectionOpen(root));
} catch {
/* folder moved or deleted; it simply is not reopened */
}
}
for (const t of savedTabs) {
if (t.kind === 'request' && t.col && t.id) await this.openRequest(t.col, t.id, false);
}
this.restoreDrafts();
if (active && this.tabs.some((t) => t.key === active)) this.activeKey = active;
this.persistOpen();
}
persistOpen() {
store(
'knock.open',
this.collections.map((c) => c.root)
);
store(
'knock.tabs',
this.tabs.filter((t) => t.kind === 'request' && !t.preview).map((t) => ({ kind: t.kind, col: t.col, id: t.id }))
);
store('knock.activeTab', this.activeKey);
}
/**
* Unsaved edits and scratch requests survive a restart (or a crash):
* their drafts are kept in local storage until saved or closed.
*/
persistDrafts() {
const drafts = this.tabs
.filter((t) => t.kind === 'request' && t.draft && (this.isDirty(t) || !t.id) && !t.key.startsWith('history:'))
.map((t) => ({ key: t.key, col: t.col, id: t.id, draft: $state.snapshot(t.draft), saved: t.saved ?? '' }));
store('knock.drafts', drafts);
}
private restoreDrafts() {
const drafts: { key: string; col: string | null; id: string | null; draft: Request; saved: string }[] = load('knock.drafts', []);
for (const d of drafts) {
const open = this.tabs.find((t) => t.key === d.key);
if (open) {
open.draft = normalizeRequest(d.draft);
open.preview = false;
continue;
}
if (d.id) continue; // file tab that was closed; its draft is gone with it
this.tabs.push({ key: d.key, kind: 'request', col: d.col, id: null, title: d.draft.name, preview: false, draft: normalizeRequest(d.draft), saved: d.saved });
}
}
closeOthers(key: string, onlyRight = false) {
const i = this.tabs.findIndex((t) => t.key === key);
const victims = this.tabs.filter((t, j) => t.key !== key && (!onlyRight || j > i));
const dirty = victims.filter((t) => this.isDirty(t));
if (dirty.length && !confirm(`${dirty.length} tab(s) have unsaved changes. Close anyway?`)) return;
for (const t of victims) this.closeTab(t.key, true);
if (this.tabs.some((t) => t.key === key)) this.activate(key);
}
duplicateTab(key: string) {
const t = this.tabs.find((x) => x.key === key);
if (!t?.draft) return;
const draft = normalizeRequest(JSON.parse(JSON.stringify($state.snapshot(t.draft))));
draft.name = `${draft.name} copy`;
this.insertTab({ key: `scratch:${crypto.randomUUID()}`, kind: 'request', col: t.col, id: null, title: draft.name, preview: false, draft, saved: '' });
}
upsert(c: CollectionView) {
const i = this.collections.findIndex((x) => x.id === c.id);
if (i >= 0) this.collections[i] = c;
else this.collections.push(c);
if (!this.focusCol) this.focusCol = c.id;
this.persistOpen();
}
async open(path: string) {
try {
const c = await api.collectionOpen(path);
this.upsert(c);
this.focusCol = c.id;
if (c.problems.length) {
toast.warning(`${c.problems.length} file(s) could not be read`, {
description: c.problems.map((p) => p.path).join(', ')
});
}
return c;
} catch (e) {
toast.error('Could not open collection', { description: errorText(e) });
}
}
async create(path: string, name: string) {
try {
const c = await api.collectionCreate(path, name);
this.upsert(c);
this.focusCol = c.id;
return c;
} catch (e) {
toast.error('Could not create collection', { description: errorText(e) });
}
}
async close(id: string) {
const dirty = this.tabs.filter((t) => t.col === id && this.isDirty(t));
if (dirty.length && !confirm(`${dirty.length} unsaved request(s) in this collection. Close anyway?`)) return;
await api.collectionClose(id);
this.collections = this.collections.filter((c) => c.id !== id);
this.tabs = this.tabs.filter((t) => t.col !== id);
if (!this.tabs.some((t) => t.key === this.activeKey)) this.activeKey = this.tabs.at(-1)?.key ?? null;
if (this.focusCol === id) this.focusCol = this.collections[0]?.id ?? null;
this.persistOpen();
}
/** Called when files changed on disk. Clean tabs reload, dirty ones get a banner. */
async onDiskChange(col: string, paths: string[]) {
try {
this.upsert(await api.collectionGet(col));
} catch {
return;
}
for (const t of this.tabs) {
if (t.col !== col || t.kind !== 'request' || !t.id || !paths.includes(t.id)) continue;
let fresh: Request;
try {
fresh = normalizeRequest(await api.requestGet(col, t.id));
} catch {
continue; // deleted or mid-write; the tree already reflects it
}
if (snapshot(fresh) === t.saved) continue;
if (this.isDirty(t)) t.diskChanged = true;
else {
t.draft = fresh;
t.saved = snapshot(fresh);
t.title = fresh.name;
}
}
}
// ------------------------------------------------------------ tabs
isDirty(t: Tab): boolean {
return t.kind === 'request' && t.draft !== undefined && snapshot(t.draft) !== t.saved;
}
activate(key: string) {
this.activeKey = key;
const t = this.active;
if (t?.col) this.focusCol = t.col;
this.persistOpen();
}
async openRequest(col: string, id: string, preview = true) {
const key = `${col}:${id}`;
const existing = this.tabs.find((t) => t.key === key);
if (existing) {
if (!preview) existing.preview = false;
this.activate(key);
return;
}
let req: Request;
try {
req = normalizeRequest(await api.requestGet(col, id));
} catch (e) {
toast.error('Could not open request', { description: errorText(e) });
return;
}
const tab: Tab = {
key,
kind: 'request',
col,
id,
title: req.name,
preview,
draft: req,
saved: snapshot(req)
};
this.insertTab(tab);
}
openSpecial(kind: TabKind, col: string | null, id: string | null, title: string) {
const key = `${kind}:${col ?? ''}:${id ?? ''}`;
if (this.tabs.some((t) => t.key === key)) return this.activate(key);
this.insertTab({ key, kind, col, id, title, preview: false });
}
private insertTab(tab: Tab) {
const previewIdx = tab.preview ? this.tabs.findIndex((t) => t.preview && !this.isDirty(t)) : -1;
if (previewIdx >= 0) this.tabs[previewIdx] = tab;
else {
const at = this.tabs.findIndex((t) => t.key === this.activeKey);
this.tabs.splice(at >= 0 ? at + 1 : this.tabs.length, 0, tab);
}
this.activate(tab.key);
}
/** A scratch request that lives only in a tab until saved. */
newScratch(kind: Request['type'] = 'http') {
const req = newRequest(kind);
const key = `scratch:${crypto.randomUUID()}`;
this.insertTab({
key,
kind: 'request',
col: this.focusCol,
id: null,
title: req.name,
preview: false,
draft: req,
saved: ''
});
}
pin(key: string) {
const t = this.tabs.find((x) => x.key === key);
if (t) t.preview = false;
this.persistOpen();
}
closeTab(key: string, force = false) {
const i = this.tabs.findIndex((t) => t.key === key);
if (i < 0) return;
const t = this.tabs[i];
if (!force && this.isDirty(t) && !confirm(`"${t.title}" has unsaved changes. Close anyway?`)) return;
if (t.sending) api.cancel(t.key);
this.tabs.splice(i, 1);
if (this.activeKey === key) {
this.activeKey = this.tabs[Math.min(i, this.tabs.length - 1)]?.key ?? null;
}
this.persistOpen();
this.persistDrafts();
}
moveTab(from: number, to: number) {
const [t] = this.tabs.splice(from, 1);
this.tabs.splice(to, 0, t);
this.persistOpen();
}
/** Rename/move in the tree changes ids; keep open tabs pointing at the right file. */
retarget(col: string, oldId: string, newId: string) {
for (const t of this.tabs) {
if (t.col !== col || !t.id) continue;
if (t.id === oldId || t.id.startsWith(oldId + '/')) {
t.id = newId + t.id.slice(oldId.length);
t.key = `${col}:${t.id}`;
}
}
if (this.activeKey?.startsWith(`${col}:${oldId}`)) {
this.activeKey = `${col}:${newId}${this.activeKey.slice(`${col}:${oldId}`.length)}`;
}
this.persistOpen();
}
async save(tab: Tab | undefined = this.active): Promise<boolean> {
if (!tab || tab.kind !== 'request' || !tab.draft) return false;
if (!tab.col) {
toast.info('Open or create a collection to save requests');
return false;
}
try {
if (!tab.id) {
const r = await api.requestCreate(tab.col, '', tab.draft);
this.upsert(r.collection);
const oldKey = tab.key;
tab.id = r.id;
tab.key = `${tab.col}:${r.id}`;
if (this.activeKey === oldKey) this.activeKey = tab.key;
} else {
this.upsert(await api.requestSave(tab.col, tab.id, tab.draft));
}
tab.saved = snapshot(tab.draft);
tab.title = tab.draft.name;
tab.preview = false;
tab.diskChanged = false;
this.persistOpen();
this.persistDrafts();
return true;
} catch (e) {
toast.error('Could not save', { description: errorText(e) });
return false;
}
}
findNode(col: string, id: string): TreeNode | undefined {
const walk = (nodes: TreeNode[]): TreeNode | undefined => {
for (const n of nodes) {
if (n.id === id) return n;
if (n.node === 'folder') {
const f = walk(n.children);
if (f) return f;
}
}
};
const c = this.collection(col);
return c ? walk(c.tree.children) : undefined;
}
}
export const ws = new Workspace();