diff --git a/src/App.svelte b/src/App.svelte index b3429a5..3b96c27 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -22,17 +22,24 @@ import { openDocs } from '$lib/help'; import UpdateNotice from '$lib/views/UpdateNotice.svelte'; import { updates } from '$lib/state/updates.svelte'; + import { copyAsCurl } from '$lib/copycurl'; let ready = $state(false); onMount(() => { ws.restore().finally(() => (ready = true)); updates.start(); + // Keep unsaved drafts safe across restarts and crashes. + const draftTimer = setInterval(() => ready && ws.persistDrafts(), 4000); + const saveDrafts = () => ws.persistDrafts(); + window.addEventListener('beforeunload', saveDrafts); const un = listen<{ collection: string; paths: string[] }>('collection-changed', (e) => { ws.onDiskChange(e.payload.collection, e.payload.paths); }); const unLink = onDeepLink(); return () => { + clearInterval(draftTimer); + window.removeEventListener('beforeunload', saveDrafts); un.then((f) => f()); unLink.then((f) => f?.()); }; @@ -93,6 +100,9 @@ } else if (k === 'p' || (k === 'f' && e.shiftKey)) { e.preventDefault(); ui.sidebarFilterRequest += 1; + } else if (k === 'c' && e.shiftKey) { + e.preventDefault(); + copyAsCurl(); } else if (k === 'j' && e.shiftKey) { e.preventDefault(); ui.toggleJsonModeRequest += 1; diff --git a/src/lib/copycurl.ts b/src/lib/copycurl.ts new file mode 100644 index 0000000..6577d51 --- /dev/null +++ b/src/lib/copycurl.ts @@ -0,0 +1,22 @@ +import { invoke } from '@tauri-apps/api/core'; +import { toast } from '@joshicodes/cock'; +import { errorText } from './api'; +import { plain } from './plain.svelte'; +import { ws, type Tab } from './state/workspace.svelte'; +import type { Request } from './types'; + +/** Copies the request as a cURL command with variables and auth filled in; secrets stay masked. */ +export async function copyAsCurl(tab: Tab | undefined = ws.active) { + if (!tab?.draft) return; + try { + const code = await invoke('code_snippet', { + args: { col: tab.col, request_id: tab.id, request: plain(tab.draft) as Request, env: ws.env(tab.col) }, + lang: 'curl', + resolve: true + }); + await navigator.clipboard.writeText(code); + toast.success('Copied as cURL', { description: 'Secret values are masked.' }); + } catch (e) { + toast.error('Could not build the cURL command', { description: errorText(e) }); + } +} diff --git a/src/lib/state/ui.svelte.ts b/src/lib/state/ui.svelte.ts index 18b56cc..a45c0e8 100644 --- a/src/lib/state/ui.svelte.ts +++ b/src/lib/state/ui.svelte.ts @@ -7,6 +7,8 @@ class Ui { sendRequest = $state(0); /** Inline rename target in the sidebar: `${col}:${id}`. */ renaming = $state(null); + /** Sidebar should expand to and select `${col}:${id}`. */ + revealRequest = $state(null); } export const ui = new Ui(); diff --git a/src/lib/state/workspace.svelte.ts b/src/lib/state/workspace.svelte.ts index 0b714a1..5f7251c 100644 --- a/src/lib/state/workspace.svelte.ts +++ b/src/lib/state/workspace.svelte.ts @@ -122,6 +122,7 @@ class Workspace { 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(); } @@ -138,6 +139,48 @@ class Workspace { 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; @@ -299,6 +342,7 @@ class Workspace { this.activeKey = this.tabs[Math.min(i, this.tabs.length - 1)]?.key ?? null; } this.persistOpen(); + this.persistDrafts(); } moveTab(from: number, to: number) { @@ -344,6 +388,7 @@ class Workspace { tab.preview = false; tab.diskChanged = false; this.persistOpen(); + this.persistDrafts(); return true; } catch (e) { toast.error('Could not save', { description: errorText(e) }); diff --git a/src/lib/views/Sidebar.svelte b/src/lib/views/Sidebar.svelte index 3144405..6f99ed5 100644 --- a/src/lib/views/Sidebar.svelte +++ b/src/lib/views/Sidebar.svelte @@ -30,6 +30,28 @@ } }); + // "Show in sidebar" from a tab: open the folders above it and select it. + $effect(() => { + const target = ui.revealRequest; + if (!target) return; + const [col, ...rest] = target.split(':'); + const id = rest.join(':'); + const next = new Set(expanded); + next.delete(`closed:${col}`); + const segs = id.split('/'); + for (let i = 1; i < segs.length; i++) next.add(`${col}:${segs.slice(0, i).join('/')}`); + expanded = next; + persistExpanded(); + panel = 'tree'; + filter = ''; + selected = target; + ui.revealRequest = null; + queueMicrotask(() => { + const i = rows.findIndex((r) => r.key === target); + if (i >= 0) ensureVisible(i); + }); + }); + function persistExpanded() { localStorage.setItem('knock.expanded', JSON.stringify([...expanded])); } diff --git a/src/lib/views/TabStrip.svelte b/src/lib/views/TabStrip.svelte index 6de6387..5efa832 100644 --- a/src/lib/views/TabStrip.svelte +++ b/src/lib/views/TabStrip.svelte @@ -2,6 +2,11 @@ import Icon from '$lib/ui/Icon.svelte'; import { ws, type Tab } from '$lib/state/workspace.svelte'; import { methodColor } from '$lib/request'; + import { ContextMenu, MenuItem, MenuSeparator } from '@joshicodes/cock'; + import { copyAsCurl } from '$lib/copycurl'; + import { ui } from '$lib/state/ui.svelte'; + + let menuTab = $state(null); let dragFrom = $state(null); let dragOver = $state(null); @@ -22,7 +27,8 @@ }; -
+ + {#snippet children()}
{#each ws.tabs as t, i (t.key)} {@const active = t.key === ws.activeKey} @@ -35,6 +41,7 @@ class="group relative flex max-w-[220px] shrink-0 items-center gap-1.5 border-r border-line pl-3 pr-1.5 {active ? 'bg-panel text-strong' : 'text-fg-muted hover:bg-hover/40'} {dragOver === i ? 'shadow-[inset_2px_0_0_var(--knock-cyan)]' : ''}" onclick={() => ws.activate(t.key)} ondblclick={() => ws.pin(t.key)} + oncontextmenu={() => (menuTab = t)} onauxclick={(e) => { if (e.button === 1) ws.closeTab(t.key); }} @@ -84,4 +91,22 @@ -
+ {/snippet} + {#snippet menu()} + {#if menuTab} + {@const t = menuTab} + ws.closeTab(t.key)} hint="Ctrl+W">Close + ws.closeOthers(t.key)}>Close others + ws.closeOthers(t.key, true)}>Close to the right + ws.closeOthers('')}>Close all + {#if t.kind === 'request'} + + ws.duplicateTab(t.key)}>Duplicate + copyAsCurl(t)} hint="Ctrl+Shift+C">Copy as cURL + {#if t.id && t.col} + (ui.revealRequest = `${t.col}:${t.id}`)}>Show in sidebar + {/if} + {/if} + {/if} + {/snippet} +
diff --git a/src/lib/views/response/ResponsePane.svelte b/src/lib/views/response/ResponsePane.svelte index ce91670..575f1ca 100644 --- a/src/lib/views/response/ResponsePane.svelte +++ b/src/lib/views/response/ResponsePane.svelte @@ -36,6 +36,13 @@ let assertsTotal = $derived(out?.asserts.length ?? 0); let authHint = $derived(resp && (resp.status === 401 || resp.status === 403) && out?.auth); + async function copyBody() { + await loadBody(tab); + const text = tab.result?.bodyText ?? ''; + await navigator.clipboard.writeText(text); + toast.success('Body copied'); + } + async function saveBody() { const id = tab.result?.result.body_id; if (!id) return; @@ -85,6 +92,7 @@ {/if} {#if resp} + {/if}