This commit is contained in:
Reudy 2026-09-26 19:13:02 +02:00
commit 0ad405c26e
78 changed files with 9127 additions and 0 deletions

View file

@ -0,0 +1,132 @@
<script lang="ts">
import { onMount } from 'svelte';
import { settings } from '$lib/state/settings.svelte';
import { workspace } from '$lib/state/workspace.svelte';
import { sync } from '$lib/sync/sync.svelte';
import { displayName, vault } from '$lib/storage/vault.svelte';
import Ribbon from './Ribbon.svelte';
import FileExplorer from './FileExplorer.svelte';
import SearchPanel from './SearchPanel.svelte';
import CanvasView from './CanvasView.svelte';
import SettingsModal from './SettingsModal.svelte';
import ContextMenu from './ContextMenu.svelte';
import Toasts from './Toasts.svelte';
import EmptyState from './EmptyState.svelte';
let ready = $state(false);
onMount(() => {
workspace.init().then(() => {
ready = true;
sync.start();
handleLaunchedFiles();
});
const onHide = () => {
if (document.visibilityState === 'hidden') void workspace.flush();
};
document.addEventListener('visibilitychange', onHide);
window.addEventListener('pagehide', onHide);
return () => {
document.removeEventListener('visibilitychange', onHide);
window.removeEventListener('pagehide', onHide);
};
});
/** PDFs opened with the installed app (manifest file_handlers). */
function handleLaunchedFiles() {
const lq = (window as unknown as { launchQueue?: { setConsumer(fn: (p: { files: FileSystemFileHandle[] }) => void): void } }).launchQueue;
lq?.setConsumer(async ({ files }) => {
for (const handle of files) {
const file = await handle.getFile();
const path = await vault.importPdfAsCanvas('', file);
await workspace.open(path);
}
});
}
$effect(() => {
document.documentElement.dataset.theme = settings.dark ? 'dark' : 'light';
});
$effect(() => {
const doc = workspace.doc;
document.title = doc ? `${displayName(doc.path)} — Papure` : 'Papure';
});
function onKey(e: KeyboardEvent) {
const mod = e.ctrlKey || e.metaKey;
if (mod && e.key.toLowerCase() === 's') {
e.preventDefault();
void workspace.flush().then(() => sync.syncNow());
} else if (mod && e.shiftKey && e.key.toLowerCase() === 'f') {
e.preventDefault();
workspace.panel = 'search';
} else if (mod && e.key === ',') {
e.preventDefault();
workspace.settingsOpen = true;
}
}
</script>
<svelte:window onkeydown={onKey} />
<div class="app">
<Ribbon />
{#if workspace.panel}
<aside class="sidebar">
{#if workspace.panel === 'files'}
<FileExplorer />
{:else}
<SearchPanel />
{/if}
</aside>
{/if}
<main>
{#if ready && workspace.doc}
{#key workspace.doc}
<CanvasView doc={workspace.doc} />
{/key}
{:else if ready}
<EmptyState />
{/if}
</main>
</div>
{#if workspace.settingsOpen}
<SettingsModal />
{/if}
<ContextMenu />
<Toasts />
<style>
.app {
display: flex;
height: 100dvh;
width: 100vw;
}
.sidebar {
width: 260px;
flex: none;
background: var(--bg-2);
border-right: 1px solid var(--border);
display: flex;
flex-direction: column;
min-height: 0;
}
main {
flex: 1;
min-width: 0;
position: relative;
background: var(--bg-canvas);
}
@media (max-width: 700px) {
.sidebar {
position: absolute;
left: 44px;
top: 0;
bottom: 0;
z-index: 20;
box-shadow: var(--shadow);
}
}
</style>

View file

@ -0,0 +1,754 @@
<script lang="ts">
import { onMount, untrack } from 'svelte';
import CirclePlusIcon from '@lucide/svelte/icons/circle-plus';
import DownloadIcon from '@lucide/svelte/icons/download';
import EllipsisIcon from '@lucide/svelte/icons/ellipsis';
import ArrowUpIcon from '@lucide/svelte/icons/arrow-up';
import TrashIcon from '@lucide/svelte/icons/trash-2';
import CheckIcon from '@lucide/svelte/icons/check';
import type { CanvasDoc } from '$lib/state/doc.svelte';
import { viewport } from '$lib/state/viewport.svelte';
import { tools } from '$lib/state/tools.svelte';
import { settings } from '$lib/state/settings.svelte';
import { workspace } from '$lib/state/workspace.svelte';
import { menu, type MenuItem } from '$lib/state/menu.svelte';
import { dirName, displayName } from '$lib/storage/vault.svelte';
import { bounds, intersects, rectBeside, type Rect } from '$lib/model/layout';
import { canInsert, freeSlots, freeSlotsOf, neighbor, type Dir, type Slot } from '$lib/model/tree';
import { PAGE_PRESETS, type Stroke } from '$lib/model/types';
import { PalmRejector } from '$lib/ink/palm';
import { StrokeRecorder, hitStroke } from '$lib/ink/stroke';
import { pageCssVars } from '$lib/editor/pageStyle';
import { downloadCanvas } from './download';
import PageView from './PageView.svelte';
import Toolbar from './Toolbar.svelte';
let { doc }: { doc: CanvasDoc } = $props();
let stage: HTMLDivElement;
const cssVars = pageCssVars();
// ---- autosave --------------------------------------------------------
$effect(() => {
if (doc.version > 0) untrack(() => workspace.scheduleSave());
});
// ---- viewport --------------------------------------------------------
onMount(() => {
const ro = new ResizeObserver(() => {
const r = stage.getBoundingClientRect();
const first = viewport.width === 0;
viewport.width = r.width;
viewport.height = r.height;
if (first) fitPage(workspace.focusPage ?? doc.activeId);
});
viewport.width = 0;
ro.observe(stage);
stage.addEventListener('wheel', onWheel, { passive: false });
return () => {
ro.disconnect();
stage.removeEventListener('wheel', onWheel);
};
});
// Search hits etc. ask for a page to be revealed.
$effect(() => {
const id = workspace.focusPage;
if (!id || !viewport.width) return;
untrack(() => {
if (doc.pages[id]) {
doc.activeId = id;
fitPage(id);
}
workspace.focusPage = null;
});
});
function fitPage(id: string | null) {
const r = (id && doc.rectOf(id)) || doc.rectOf(doc.order[0]);
if (r) viewport.fit(r);
}
function fitAll() {
const b = bounds(doc.rects.values());
if (b) viewport.fit(b, 48);
}
const visible = $derived.by(() => {
const w = viewport.world;
// One extra screen of margin around the view so panning doesn't pop.
const area = { x: w.x - w.width, y: w.y - w.height, width: w.width * 3, height: w.height * 3 };
return doc.order.filter((id) => {
const r = doc.rects.get(id);
return r && intersects(r, area);
});
});
// ---- adding pages ----------------------------------------------------
const ghostSlots = $derived.by((): Slot[] => {
if (tools.placing || !doc.activeId) return [];
return freeSlotsOf(doc.tree, doc.activeId);
});
const placeSlots = $derived(tools.placing ? freeSlots(doc.tree) : []);
// Show every possible spot when an imported PDF is waiting to be placed.
$effect(() => {
if (!tools.placing) return;
untrack(() => {
const size = tools.placing!.pages[0];
const rects = [...doc.rects.values(), ...placeSlots.map((s) => slotRect(s, size)).filter((r): r is Rect => !!r)];
const b = bounds(rects);
if (b) viewport.fit(b, 48);
});
});
function slotRect(slot: Slot, size?: { width: number; height: number }): Rect | null {
const a = doc.rectOf(slot.anchor);
if (!a) return null;
const page = doc.pages[slot.anchor];
const s = size ?? (page && !page.origin ? { width: page.width, height: page.height } : { width: 595.28, height: 841.89 });
return rectBeside(a, slot.dir, s);
}
/** Run a tree change without the anchor page jumping on screen. */
function keepAnchor(anchor: string, fn: () => void) {
const before = doc.rectOf(anchor);
fn();
const after = doc.rectOf(anchor);
if (before && after) viewport.panBy(-(after.x - before.x) * viewport.scale, -(after.y - before.y) * viewport.scale);
}
function revealPage(id: string) {
const r = doc.rectOf(id);
if (!r) return;
const w = viewport.world;
const inView = r.x >= w.x && r.y >= w.y && r.x + r.width <= w.x + w.width && r.y + r.height <= w.y + w.height;
if (!inView) {
const fits = r.width * viewport.scale <= viewport.width && r.height * viewport.scale <= viewport.height;
if (fits) viewport.center(r);
else viewport.fit(r);
}
}
function addPage(anchor: string, dir: Dir) {
let id: string | null = null;
keepAnchor(anchor, () => (id = doc.addBlankPage(anchor, dir)));
if (id) revealPage(id);
}
function place(slot: Slot) {
const p = tools.placing;
if (!p) return;
let ok = false;
keepAnchor(slot.anchor, () => (ok = doc.insertPages(slot.anchor, slot.dir, p.pages)));
if (ok) {
tools.placing = null;
revealPage(p.pages[0].id);
workspace.toast(`Placed ${p.pages.length} page${p.pages.length === 1 ? '' : 's'} from ${p.name}`);
}
}
function go(dir: Dir) {
const id = doc.activeId;
if (!id) return;
const next = neighbor(doc.tree, id, dir);
if (next) {
doc.activeId = next;
revealPage(next);
} else if (canInsert(doc.tree, id, dir)) addPage(id, dir);
}
// ---- page menu -------------------------------------------------------
function pageMenu(x: number, y: number, id: string) {
const page = doc.pages[id];
if (!page) return;
doc.activeId = id;
const dirs: [Dir, string][] = [
['up', 'Insert page above'],
['down', 'Insert page below'],
['left', 'Insert page left'],
['right', 'Insert page right']
];
const items: MenuItem[] = dirs.map(([dir, label]) => ({
label,
disabled: !canInsert(doc.tree, id, dir),
action: () => addPage(id, dir)
}));
if (!page.origin) {
items.push('separator');
for (const p of PAGE_PRESETS) {
const current = Math.abs(p.width - page.width) < 0.5 && Math.abs(p.height - page.height) < 0.5;
items.push({
label: p.label,
icon: current ? CheckIcon : undefined,
hint: `${Math.round(p.width)}×${Math.round(p.height)}`,
action: () => keepAnchor(id, () => doc.resizePage(id, p.width, p.height))
});
}
items.push({ label: 'Custom size…', action: () => customSize(id) });
}
items.push('separator', { label: 'Delete page', icon: TrashIcon, danger: true, action: () => doc.deletePage(id) });
menu.show(x, y, items);
}
function customSize(id: string) {
const page = doc.pages[id];
const mm = (pt: number) => Math.round((pt / 72) * 25.4);
const answer = prompt('Page size in millimetres (width × height)', `${mm(page.width)} × ${mm(page.height)}`);
const m = answer && /^\s*(\d+(?:\.\d+)?)\s*[x×*,\s]\s*(\d+(?:\.\d+)?)\s*$/i.exec(answer);
if (!m) return;
const pt = (v: string) => Math.min(5000, Math.max(50, (parseFloat(v) / 25.4) * 72));
keepAnchor(id, () => doc.resizePage(id, pt(m[1]), pt(m[2])));
}
const activeMenuPos = $derived.by(() => {
const id = doc.activeId;
const r = id && doc.rects.get(id);
if (!r || tools.placing) return null;
const p = viewport.toScreen(r.x + r.width, r.y);
return { x: p.x + 6, y: p.y };
});
// ---- input -----------------------------------------------------------
const palm = new PalmRejector(settings.data.palm);
$effect(() => {
palm.options = settings.data.palm;
});
type Gesture =
| { kind: 'draw'; pointerId: number; pointerType: string; pageId: string; rec: StrokeRecorder }
| { kind: 'erase'; pointerId: number; pointerType: string; hits: Map<string, Set<string>> }
| { kind: 'pan'; pointerId: number; lastX: number; lastY: number; startX: number; startY: number; moved: boolean; tap: boolean }
| { kind: 'pinch' };
let gesture: Gesture | null = null;
const touches = new Map<number, { x: number; y: number }>();
let pinchLast: { dist: number; mx: number; my: number } | null = null;
let spaceDown = $state(false);
// Reactive bits for rendering in-progress ink.
let live = $state.raw<{ pageId: string; stroke: Stroke } | null>(null);
let tick = $state(0);
let erasing = $state.raw<Set<string>>(new Set());
let eraserAt = $state<{ x: number; y: number } | null>(null);
function local(e: PointerEvent | MouseEvent) {
const r = stage.getBoundingClientRect();
return { x: e.clientX - r.left, y: e.clientY - r.top };
}
function pageAt(sx: number, sy: number): string | null {
const w = viewport.toWorld(sx, sy);
for (const id of visible) {
const r = doc.rects.get(id)!;
if (w.x >= r.x && w.x <= r.x + r.width && w.y >= r.y && w.y <= r.y + r.height) return id;
}
return null;
}
function pagePoint(pageId: string, sx: number, sy: number) {
const r = doc.rects.get(pageId)!;
const w = viewport.toWorld(sx, sy);
return { x: w.x - r.x, y: w.y - r.y };
}
/** Pointer capture can throw if the pointer is already gone; drawing still works without it. */
function capture(id: number) {
try {
stage.setPointerCapture(id);
} catch {
/* ignore */
}
}
const isEraserButton = (e: PointerEvent) => e.pointerType === 'pen' && (e.button === 5 || (e.buttons & 32) !== 0);
function onPointerDown(e: PointerEvent) {
palm.track(e);
if (menu.open) menu.close();
const target = e.target as Element;
if (target.closest('.no-stage')) return;
const p = local(e);
if (e.pointerType === 'touch') {
const decision = palm.evaluate(e);
if (!decision.accept) return; // palm: ignore entirely
touches.set(e.pointerId, p);
if (touches.size >= 2) {
cancelGesture();
gesture = { kind: 'pinch' };
pinchLast = pinchState();
return;
}
}
const onPage = pageAt(p.x, p.y);
const inEditor = !!target.closest('.cm-editor');
// Pressing anywhere outside the text leaves the editor (preventDefault
// below would otherwise keep focus in it).
if (!inEditor) (document.activeElement as HTMLElement | null)?.blur?.();
// Panning: middle mouse, space+drag, or background drags.
const wantsPan =
e.button === 1 ||
spaceDown ||
(e.pointerType === 'touch' && (!tools.inking || !settings.data.fingerDraw)) ||
(e.pointerType === 'mouse' && e.button === 0 && !onPage && !target.closest('.ghost, .slot'));
if (wantsPan) {
if (onPage && !inEditor) doc.activeId = onPage;
gesture = { kind: 'pan', pointerId: e.pointerId, lastX: p.x, lastY: p.y, startX: p.x, startY: p.y, moved: false, tap: inEditor || !!target.closest('.ghost, .slot') };
if (e.pointerType !== 'touch' || !gesture.tap) {
if (e.pointerType !== 'touch') e.preventDefault();
capture(e.pointerId);
}
return;
}
if (onPage) doc.activeId = onPage;
if (e.button !== 0 && e.pointerType === 'mouse') return;
const eraser = tools.tool === 'eraser' || isEraserButton(e);
if ((tools.inking || isEraserButton(e)) && onPage) {
e.preventDefault();
capture(e.pointerId);
if (eraser) {
gesture = { kind: 'erase', pointerId: e.pointerId, pointerType: e.pointerType, hits: new Map() };
erasing = new Set();
eraseAt(e);
} else {
const tool = tools.tool === 'highlighter' ? 'highlighter' : 'pen';
const rec = new StrokeRecorder(tool, tools.color, tools.width, e.pointerType === 'pen');
const pt = pagePoint(onPage, p.x, p.y);
rec.recordPoint(pt.x, pt.y, e);
gesture = { kind: 'draw', pointerId: e.pointerId, pointerType: e.pointerType, pageId: onPage, rec };
live = { pageId: onPage, stroke: rec.stroke };
tick++;
}
}
}
function onPointerMove(e: PointerEvent) {
palm.track(e);
const p = local(e);
if (tools.tool === 'eraser' || isEraserButton(e)) eraserAt = p;
if (e.pointerType === 'touch' && touches.has(e.pointerId)) {
touches.set(e.pointerId, p);
if (gesture?.kind === 'pinch') {
const s = pinchState();
if (s && pinchLast) {
viewport.zoomAt(s.dist / pinchLast.dist, s.mx, s.my);
viewport.panBy(s.mx - pinchLast.mx, s.my - pinchLast.my);
}
pinchLast = s;
return;
}
}
if (!gesture || gesture.kind === 'pinch' || gesture.pointerId !== e.pointerId) return;
if (gesture.kind === 'pan') {
const dx = p.x - gesture.lastX;
const dy = p.y - gesture.lastY;
if (!gesture.moved && Math.hypot(p.x - gesture.startX, p.y - gesture.startY) < 8) return;
if (!gesture.moved && gesture.tap) capture(e.pointerId);
gesture.moved = true;
viewport.panBy(dx, dy);
gesture.lastX = p.x;
gesture.lastY = p.y;
return;
}
// A touch stroke is cut off as soon as the palm policy rejects it
// (e.g. the pen just came into range).
if (gesture.pointerType === 'touch' && !palm.evaluate(e).accept) {
cancelGesture();
return;
}
if (gesture.kind === 'erase') {
eraseAt(e);
return;
}
const events = typeof e.getCoalescedEvents === 'function' ? e.getCoalescedEvents() : [];
for (const ev of events.length ? events : [e]) {
const q = local(ev);
const pt = pagePoint(gesture.pageId, q.x, q.y);
gesture.rec.recordPoint(pt.x, pt.y, ev);
}
tick++;
}
function onPointerUp(e: PointerEvent) {
palm.track(e);
touches.delete(e.pointerId);
if (gesture?.kind === 'pinch') {
if (touches.size < 2) {
gesture = null;
pinchLast = null;
}
return;
}
if (!gesture || gesture.pointerId !== e.pointerId) return;
const g = gesture;
gesture = null;
if (g.kind === 'draw') {
live = null;
if (e.type === 'pointerup') doc.addStroke(g.pageId, g.rec.stroke);
} else if (g.kind === 'erase') {
for (const [pageId, ids] of g.hits) doc.setStrokes(pageId, (s) => s.filter((x) => !ids.has(x.id)));
erasing = new Set();
}
}
function cancelGesture() {
if (gesture?.kind === 'draw') live = null;
if (gesture?.kind === 'erase') erasing = new Set();
gesture = null;
}
function eraseAt(e: PointerEvent) {
if (gesture?.kind !== 'erase') return;
const p = local(e);
const pageId = pageAt(p.x, p.y);
if (!pageId) return;
const pt = pagePoint(pageId, p.x, p.y);
const r = tools.eraserRadius / viewport.scale;
let set = gesture.hits.get(pageId);
let changed = false;
for (const s of doc.pages[pageId].strokes) {
if (set?.has(s.id) || !hitStroke(s, pt.x, pt.y, r)) continue;
if (!set) gesture.hits.set(pageId, (set = new Set()));
set.add(s.id);
changed = true;
}
if (changed) erasing = new Set([...gesture.hits.values()].flatMap((x) => [...x]));
}
function pinchState() {
const pts = [...touches.values()];
if (pts.length < 2) return null;
const [a, b] = pts;
return { dist: Math.max(1, Math.hypot(a.x - b.x, a.y - b.y)), mx: (a.x + b.x) / 2, my: (a.y + b.y) / 2 };
}
function onWheel(e: WheelEvent) {
e.preventDefault();
const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? viewport.height : 1;
const p = local(e);
if (e.ctrlKey || e.metaKey) {
viewport.zoomAt(Math.exp(-e.deltaY * unit * 0.0025), p.x, p.y);
} else if (e.shiftKey && !e.deltaX) {
viewport.panBy(-e.deltaY * unit, 0);
} else {
viewport.panBy(-e.deltaX * unit, -e.deltaY * unit);
}
}
function onContextMenu(e: MouseEvent) {
if ((e.target as Element).closest('.cm-editor') && !tools.inking) return; // native menu for text
e.preventDefault();
const p = local(e);
const id = pageAt(p.x, p.y);
if (id) pageMenu(e.clientX, e.clientY, id);
}
// ---- keyboard --------------------------------------------------------
function editable(t: EventTarget | null) {
const el = t as HTMLElement | null;
return !!el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName));
}
function onKeyDown(e: KeyboardEvent) {
if (workspace.settingsOpen) return;
const mod = e.ctrlKey || e.metaKey;
const k = e.key.toLowerCase();
if (mod && (k === '=' || k === '+')) return void (e.preventDefault(), viewport.zoomAt(1.25));
if (mod && k === '-') return void (e.preventDefault(), viewport.zoomAt(0.8));
if (mod && k === '0') return void (e.preventDefault(), fitPage(doc.activeId));
if (mod && k === '9') return void (e.preventDefault(), fitAll());
if (editable(e.target)) return;
if (mod && k === 'z' && !e.shiftKey) return void (e.preventDefault(), doc.undo());
if (mod && ((k === 'z' && e.shiftKey) || k === 'y')) return void (e.preventDefault(), doc.redo());
if (e.key === 'Escape') {
if (tools.placing) tools.placing = null;
return;
}
if (e.altKey && e.key.startsWith('Arrow')) {
e.preventDefault();
go(e.key.slice(5).toLowerCase() as Dir);
return;
}
if (e.key === ' ' && !e.repeat) {
spaceDown = true;
e.preventDefault();
return;
}
if (mod || e.altKey) return;
const shortcuts: Record<string, typeof tools.tool> = { t: 'text', p: 'pen', h: 'highlighter', e: 'eraser' };
if (shortcuts[k]) tools.tool = shortcuts[k];
}
function onKeyUp(e: KeyboardEvent) {
if (e.key === ' ') spaceDown = false;
}
const panning = $derived(spaceDown);
</script>
<svelte:window onkeydown={onKeyDown} onkeyup={onKeyUp} onblur={() => (spaceDown = false)} />
<div class="view">
<header class="titlebar">
<div class="crumbs">
{#if dirName(doc.path)}<span class="dir">{dirName(doc.path).replaceAll('/', ' / ')} /</span>{/if}
<span class="name">{displayName(doc.path)}</span>
</div>
<button class="icon-btn" title="Download PDF" onclick={() => downloadCanvas(doc.path)}>
<DownloadIcon size={16} strokeWidth={1.75} />
</button>
</header>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="stage"
class:inking={tools.inking}
class:panning
class:erasing={tools.tool === 'eraser'}
bind:this={stage}
onpointerdown={onPointerDown}
onpointermove={onPointerMove}
onpointerup={onPointerUp}
onpointercancel={onPointerUp}
onpointerleave={(e) => {
palm.track(e);
eraserAt = null;
}}
oncontextmenu={onContextMenu}
>
<div
class="world"
style="transform: translate({viewport.x}px, {viewport.y}px) scale({viewport.scale}); --s: {viewport.scale}; {cssVars}"
>
{#each visible as id (id)}
{@const page = doc.pages[id]}
{@const rect = doc.rects.get(id)}
{#if page && rect}
<PageView
{page}
{rect}
active={doc.activeId === id}
invert={settings.dark && settings.data.pageStyle === 'match'}
scale={viewport.scale}
live={live?.pageId === id ? live.stroke : null}
{tick}
{erasing}
onchange={() => doc.touch()}
onactivate={() => (doc.activeId = id)}
/>
{/if}
{/each}
{#each ghostSlots as slot (slot.anchor + slot.dir)}
{@const r = slotRect(slot)}
{#if r}
<button
class="ghost"
style="left:{r.x}px; top:{r.y}px; width:{r.width}px; height:{r.height}px"
title="Add page ({slot.dir})"
onclick={() => addPage(slot.anchor, slot.dir)}
>
<span class="plus" style="--icon: {Math.min(r.width, r.height) * 0.14}px">
<CirclePlusIcon size="100%" strokeWidth={1.25} />
</span>
</button>
{/if}
{/each}
{#if tools.placing}
{#each placeSlots as slot (slot.anchor + slot.dir)}
{@const first = tools.placing.pages[0]}
{@const r = slotRect(slot, first)}
{#if r}
<button
class="slot"
style="left:{r.x}px; top:{r.y}px; width:{r.width}px; height:{r.height}px"
onclick={() => place(slot)}
>
<span class="arrow" data-dir={slot.dir} style="--icon: {Math.min(r.width, r.height) * 0.16}px">
<ArrowUpIcon size="100%" strokeWidth={1.25} />
</span>
</button>
{/if}
{/each}
{/if}
</div>
{#if activeMenuPos && doc.activeId}
<button
class="icon-btn page-menu no-stage"
style="left:{activeMenuPos.x}px; top:{activeMenuPos.y}px"
title="Page options"
onclick={(e) => {
const r = e.currentTarget.getBoundingClientRect();
pageMenu(r.left, r.bottom + 4, doc.activeId!);
}}
>
<EllipsisIcon size={16} />
</button>
{/if}
{#if eraserAt && tools.tool === 'eraser'}
<div class="eraser-ring" style="left:{eraserAt.x}px; top:{eraserAt.y}px; width:{tools.eraserRadius * 2}px; height:{tools.eraserRadius * 2}px"></div>
{/if}
{#if tools.placing}
<div class="banner no-stage">
Choose where to place <b>{tools.placing.name}</b> ({tools.placing.pages.length} page{tools.placing.pages.length === 1 ? '' : 's'})
<button class="btn" onclick={() => (tools.placing = null)}>Cancel</button>
</div>
{/if}
</div>
<Toolbar {doc} onfit={() => fitPage(doc.activeId)} onfitall={fitAll} />
</div>
<style>
.view {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
}
.titlebar {
height: 38px;
flex: none;
display: flex;
align-items: center;
justify-content: center;
position: relative;
background: var(--bg);
border-bottom: 1px solid var(--border);
padding: 0 8px;
}
.crumbs {
display: flex;
gap: 6px;
min-width: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: var(--text);
}
.crumbs .dir {
color: var(--faint);
}
.titlebar .icon-btn {
position: absolute;
right: 8px;
}
.stage {
position: relative;
flex: 1;
overflow: hidden;
touch-action: none;
user-select: none;
-webkit-user-select: none;
background: var(--bg-canvas);
}
.stage :global(.cm-content) {
user-select: text;
-webkit-user-select: text;
}
.stage.inking {
cursor: crosshair;
}
.stage.erasing {
cursor: none;
}
.stage.inking :global(.page .md),
.stage.panning :global(.page .md) {
pointer-events: none;
}
.stage.panning {
cursor: grab;
}
.world {
position: absolute;
left: 0;
top: 0;
transform-origin: 0 0;
}
.ghost,
.slot {
position: absolute;
display: grid;
place-items: center;
background: var(--ghost);
border: calc(1px / var(--s)) dashed var(--ghost-border);
border-radius: calc(4px / var(--s));
color: var(--faint);
cursor: pointer;
padding: 0;
transition: background 0.12s, color 0.12s;
}
.ghost:hover,
.slot:hover {
background: var(--accent-soft);
color: var(--accent);
border-color: var(--accent);
}
.slot {
border-style: solid;
color: var(--accent);
border-color: color-mix(in srgb, var(--accent) 50%, transparent);
}
.plus,
.arrow {
display: grid;
width: var(--icon);
height: var(--icon);
}
.arrow[data-dir='down'] {
transform: rotate(180deg);
}
.arrow[data-dir='left'] {
transform: rotate(-90deg);
}
.arrow[data-dir='right'] {
transform: rotate(90deg);
}
.page-menu {
position: absolute;
width: 26px;
height: 26px;
background: var(--bg);
box-shadow: var(--shadow);
}
.eraser-ring {
position: absolute;
transform: translate(-50%, -50%);
border: 1.5px solid var(--muted);
border-radius: 50%;
pointer-events: none;
}
.banner {
position: absolute;
top: 12px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 12px;
padding: 6px 6px 6px 14px;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 8px;
box-shadow: var(--shadow);
white-space: nowrap;
}
</style>

View file

@ -0,0 +1,110 @@
<script lang="ts">
import { menu } from '$lib/state/menu.svelte';
let el = $state<HTMLDivElement>();
let pos = $state({ x: 0, y: 0 });
// Keep the menu on screen.
$effect(() => {
if (!menu.open || !el) return;
void menu.items;
const r = el.getBoundingClientRect();
let y = menu.above ? menu.y - r.height : menu.y;
const x = Math.min(menu.x, window.innerWidth - r.width - 8);
if (y + r.height > window.innerHeight - 8) y = window.innerHeight - r.height - 8;
pos = { x: Math.max(8, x), y: Math.max(8, y) };
});
function onDown(e: PointerEvent) {
if (menu.open && el && !el.contains(e.target as Node)) menu.close();
}
</script>
<svelte:window
onpointerdowncapture={onDown}
onkeydown={(e) => e.key === 'Escape' && menu.close()}
onblur={() => menu.close()}
onresize={() => menu.close()}
/>
{#if menu.open}
<div class="menu" role="menu" bind:this={el} style="left:{pos.x}px; top:{pos.y}px">
{#each menu.items as item, i (i)}
{#if item === 'separator'}
<div class="sep"></div>
{:else}
<button
role="menuitem"
class:danger={item.danger}
disabled={item.disabled}
onclick={() => {
menu.close();
item.action();
}}
>
<span class="icon">{#if item.icon}<item.icon size={15} strokeWidth={1.75} />{/if}</span>
<span class="label">{item.label}</span>
{#if item.hint}<span class="hint">{item.hint}</span>{/if}
</button>
{/if}
{/each}
</div>
{/if}
<style>
.menu {
position: fixed;
z-index: 100;
min-width: 190px;
padding: 4px;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 8px;
box-shadow: var(--shadow);
}
button {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 6px 10px 6px 6px;
border: 0;
background: none;
border-radius: 4px;
text-align: left;
cursor: pointer;
color: var(--text);
}
button:hover:not(:disabled) {
background: var(--hover);
}
button:disabled {
color: var(--faint);
cursor: default;
}
.danger {
color: var(--danger);
}
.icon {
display: inline-grid;
place-items: center;
width: 18px;
color: var(--muted);
}
.danger .icon {
color: inherit;
}
.label {
flex: 1;
}
.hint {
color: var(--faint);
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.sep {
height: 1px;
margin: 4px 6px;
background: var(--border);
}
</style>

View file

@ -0,0 +1,45 @@
<script lang="ts">
import { vault } from '$lib/storage/vault.svelte';
import { workspace } from '$lib/state/workspace.svelte';
async function create() {
const path = await vault.createCanvas('');
await workspace.open(path);
}
</script>
<div class="empty">
<p class="lead">No canvas open</p>
<button class="link" onclick={create}>Create a new canvas</button>
{#if vault.canvases.length}
<button class="link" onclick={() => (workspace.panel = 'files')}>Open a file</button>
{/if}
</div>
<style>
.empty {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
background: var(--bg);
}
.lead {
color: var(--faint);
font-size: 15px;
margin: 0 0 8px;
}
.link {
border: 0;
background: none;
color: var(--accent);
cursor: pointer;
padding: 4px;
}
.link:hover {
text-decoration: underline;
}
</style>

View file

@ -0,0 +1,231 @@
<script lang="ts">
import FilePlusIcon from '@lucide/svelte/icons/file-plus';
import FolderPlusIcon from '@lucide/svelte/icons/folder-plus';
import FileInputIcon from '@lucide/svelte/icons/file-input';
import PencilIcon from '@lucide/svelte/icons/pencil';
import TrashIcon from '@lucide/svelte/icons/trash-2';
import DownloadIcon from '@lucide/svelte/icons/download';
import { vault, baseName, dirName, displayName, joinPath, sanitizeName, EXT } from '$lib/storage/vault.svelte';
import { workspace } from '$lib/state/workspace.svelte';
import { menu, type MenuItem } from '$lib/state/menu.svelte';
import { downloadCanvas } from '$lib/components/download';
import FileTreeNode, { type Node } from './FileTreeNode.svelte';
const OPEN_KEY = 'papure:openFolders';
let open = $state<Set<string>>(loadOpen());
let renaming = $state<string | null>(null);
let importInput: HTMLInputElement;
let importDir = '';
function loadOpen() {
try {
return new Set<string>(JSON.parse(localStorage.getItem(OPEN_KEY) ?? '[]'));
} catch {
return new Set<string>();
}
}
function toggleFolder(path: string) {
const next = new Set(open);
if (next.has(path)) next.delete(path);
else next.add(path);
open = next;
try {
localStorage.setItem(OPEN_KEY, JSON.stringify([...next]));
} catch {
/* ignore */
}
}
function ensureOpen(dir: string) {
if (!dir) return;
const parts = dir.split('/');
const next = new Set(open);
for (let i = 1; i <= parts.length; i++) next.add(parts.slice(0, i).join('/'));
open = next;
}
const root = $derived.by(() => {
const nodes = new Map<string, Node>();
const top: Node = { path: '', name: '', kind: 'folder', children: [] };
const folderNode = (path: string): Node => {
if (!path) return top;
let n = nodes.get(path);
if (!n) {
n = { path, name: baseName(path), kind: 'folder', children: [] };
nodes.set(path, n);
folderNode(dirName(path)).children.push(n);
}
return n;
};
for (const f of vault.folders) folderNode(f);
for (const f of vault.canvases) {
folderNode(dirName(f.path)).children.push({ path: f.path, name: displayName(f.path), kind: 'canvas', children: [] });
}
const sort = (n: Node) => {
n.children.sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name, undefined, { numeric: true }) : a.kind === 'folder' ? -1 : 1));
n.children.forEach(sort);
};
sort(top);
return top;
});
async function newCanvas(dir = '') {
const path = await vault.createCanvas(dir);
ensureOpen(dir);
await workspace.open(path);
renaming = path;
}
async function newFolder(dir = '') {
const path = await vault.createFolder(dir);
ensureOpen(dir);
renaming = path;
}
function importHere(dir = '') {
importDir = dir;
importInput.click();
}
async function onImport(e: Event) {
const input = e.currentTarget as HTMLInputElement;
const files = [...(input.files ?? [])];
input.value = '';
for (const file of files) {
try {
const path = await vault.importPdfAsCanvas(importDir, file);
ensureOpen(importDir);
await workspace.open(path);
} catch (err) {
console.error(err);
workspace.toast(`Could not import ${file.name}`, 'error');
}
}
}
async function commitRename(path: string, kind: Node['kind'], name: string) {
if (renaming !== path) return; // Enter already committed; this is the blur
renaming = null;
const clean = sanitizeName(name);
if (!clean) return;
const target = joinPath(dirName(path), kind === 'canvas' ? clean + EXT : clean);
if (target === path) return;
if (vault.exists(target)) return workspace.toast(`"${clean}" already exists`, 'error');
await move(path, target);
}
async function move(from: string, to: string) {
await workspace.flush();
await vault.rename(from, to);
await workspace.renamed(from, to);
}
async function onDrop(target: string, source: string) {
if (!source || source === target || target.startsWith(source + '/') || dirName(source) === target) return;
const to = joinPath(target, baseName(source));
if (vault.exists(to)) return workspace.toast(`"${baseName(source)}" already exists there`, 'error');
ensureOpen(target);
await move(source, to);
}
async function remove(n: Node) {
const what = n.kind === 'folder' ? `folder "${n.name}" and everything in it` : `"${n.name}"`;
if (!confirm(`Delete ${what}?`)) return;
const openPath = workspace.doc?.path;
if (openPath && (openPath === n.path || openPath.startsWith(n.path + '/'))) workspace.close();
await vault.remove(n.path);
}
function contextMenu(e: MouseEvent, n: Node | null) {
e.preventDefault();
const dir = !n ? '' : n.kind === 'folder' ? n.path : dirName(n.path);
const items: MenuItem[] = [
{ label: 'New canvas', icon: FilePlusIcon, action: () => newCanvas(dir) },
{ label: 'New folder', icon: FolderPlusIcon, action: () => newFolder(dir) },
{ label: 'Import PDF…', icon: FileInputIcon, action: () => importHere(dir) }
];
if (n) {
items.push('separator', { label: 'Rename', icon: PencilIcon, action: () => (renaming = n.path) });
if (n.kind === 'canvas') items.push({ label: 'Download PDF', icon: DownloadIcon, action: () => downloadCanvas(n.path) });
items.push('separator', { label: 'Delete', icon: TrashIcon, danger: true, action: () => remove(n) });
}
menu.show(e.clientX, e.clientY, items);
}
</script>
<div class="head">
<span class="title">Files</span>
<div class="actions">
<button class="icon-btn" title="New canvas" onclick={() => newCanvas()}><FilePlusIcon size={16} strokeWidth={1.75} /></button>
<button class="icon-btn" title="New folder" onclick={() => newFolder()}><FolderPlusIcon size={16} strokeWidth={1.75} /></button>
<button class="icon-btn" title="Import PDF as canvas" onclick={() => importHere()}><FileInputIcon size={16} strokeWidth={1.75} /></button>
</div>
</div>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="tree"
oncontextmenu={(e) => contextMenu(e, null)}
ondragover={(e) => e.preventDefault()}
ondrop={(e) => {
e.preventDefault();
onDrop('', e.dataTransfer?.getData('text/x-papure-path') ?? '');
}}
>
{#each root.children as node (node.path)}
<FileTreeNode
{node}
depth={0}
{open}
{renaming}
activePath={workspace.doc?.path ?? null}
onToggle={toggleFolder}
onOpen={(p) => workspace.open(p)}
onContext={contextMenu}
onRename={commitRename}
onCancelRename={() => (renaming = null)}
{onDrop}
/>
{:else}
<p class="empty">No canvases yet.<br />Right-click or use the buttons above.</p>
{/each}
</div>
<input bind:this={importInput} type="file" accept="application/pdf,.pdf" multiple hidden onchange={onImport} />
<style>
.head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 8px 6px 14px;
}
.title {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--faint);
}
.actions {
display: flex;
gap: 2px;
}
.actions .icon-btn {
width: 26px;
height: 26px;
}
.tree {
flex: 1;
overflow: auto;
padding: 2px 6px 16px;
}
.empty {
color: var(--faint);
text-align: center;
margin-top: 32px;
font-size: 12px;
line-height: 1.6;
}
</style>

View file

@ -0,0 +1,168 @@
<script lang="ts" module>
export interface Node {
path: string;
name: string;
kind: 'folder' | 'canvas';
children: Node[];
}
</script>
<script lang="ts">
import ChevronRightIcon from '@lucide/svelte/icons/chevron-right';
import Self from './FileTreeNode.svelte';
interface Props {
node: Node;
depth: number;
open: Set<string>;
renaming: string | null;
activePath: string | null;
onToggle: (path: string) => void;
onOpen: (path: string) => void;
onContext: (e: MouseEvent, n: Node) => void;
onRename: (path: string, kind: Node['kind'], name: string) => void;
onCancelRename: () => void;
onDrop: (targetDir: string, source: string) => void;
}
let props: Props = $props();
const { node, depth } = $derived(props);
const isOpen = $derived(props.open.has(node.path));
let dragOver = $state(false);
function focusSelect(el: HTMLInputElement) {
el.focus();
el.select();
}
function onKey(e: KeyboardEvent) {
const input = e.currentTarget as HTMLInputElement;
if (e.key === 'Enter') props.onRename(node.path, node.kind, input.value);
else if (e.key === 'Escape') props.onCancelRename();
}
function click() {
if (node.kind === 'folder') props.onToggle(node.path);
else props.onOpen(node.path);
}
</script>
<div
class="row"
class:active={node.kind === 'canvas' && props.activePath === node.path}
class:drag-over={dragOver}
style="padding-left: {8 + depth * 14}px"
role="treeitem"
aria-selected={props.activePath === node.path}
aria-expanded={node.kind === 'folder' ? isOpen : undefined}
tabindex="0"
draggable={props.renaming !== node.path}
onclick={click}
onkeydown={(e) => e.key === 'Enter' && props.renaming !== node.path && click()}
oncontextmenu={(e) => {
e.stopPropagation();
props.onContext(e, node);
}}
ondragstart={(e) => e.dataTransfer?.setData('text/x-papure-path', node.path)}
ondragover={(e) => {
if (node.kind !== 'folder') return;
e.preventDefault();
e.stopPropagation();
dragOver = true;
}}
ondragleave={() => (dragOver = false)}
ondrop={(e) => {
if (node.kind !== 'folder') return;
e.preventDefault();
e.stopPropagation();
dragOver = false;
props.onDrop(node.path, e.dataTransfer?.getData('text/x-papure-path') ?? '');
}}
>
{#if node.kind === 'folder'}
<span class="chev" class:open={isOpen}><ChevronRightIcon size={14} strokeWidth={2} /></span>
{/if}
{#if props.renaming === node.path}
<input
class="rename"
value={node.name}
use:focusSelect
onkeydown={onKey}
onclick={(e) => e.stopPropagation()}
onblur={(e) => props.onRename(node.path, node.kind, e.currentTarget.value)}
/>
{:else}
<span class="name" class:folder={node.kind === 'folder'}>{node.name}</span>
{/if}
</div>
{#if node.kind === 'folder' && isOpen}
<div class="children" style="--guide: {14 + depth * 14}px">
{#each node.children as child (child.path)}
<Self {...props} node={child} depth={depth + 1} />
{/each}
</div>
{/if}
<style>
.row {
display: flex;
align-items: center;
gap: 2px;
height: 28px;
padding-right: 8px;
border-radius: 4px;
cursor: pointer;
color: var(--muted);
user-select: none;
outline: none;
}
.row:hover,
.row:focus-visible {
background: var(--hover);
color: var(--text);
}
.row.active {
background: var(--accent-soft);
color: var(--text);
}
.row.drag-over {
box-shadow: inset 0 0 0 1px var(--accent);
}
.chev {
display: inline-grid;
place-items: center;
width: 16px;
color: var(--faint);
transition: transform 0.12s;
}
.chev.open {
transform: rotate(90deg);
}
.name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding-left: 4px;
}
.name.folder {
padding-left: 0;
}
.rename {
flex: 1;
min-width: 0;
height: 22px;
padding: 2px 6px;
}
.children {
position: relative;
}
.children::before {
content: '';
position: absolute;
left: var(--guide);
top: 0;
bottom: 0;
border-left: 1px solid var(--border);
}
</style>

View file

@ -0,0 +1,57 @@
<script lang="ts">
import { svgPath, HIGHLIGHTER_OPACITY } from '$lib/ink/stroke';
import type { Stroke } from '$lib/model/types';
interface Props {
width: number;
height: number;
strokes: Stroke[];
/** Stroke being drawn right now (points mutate; `tick` changes). */
live?: Stroke | null;
tick?: number;
/** Strokes hidden while an eraser gesture is in progress. */
erasing?: Set<string>;
}
let { width, height, strokes, live = null, tick = 0, erasing }: Props = $props();
const livePath = $derived.by(() => {
void tick;
return live ? svgPath(live, true) : '';
});
</script>
<svg class="ink" viewBox="0 0 {width} {height}" preserveAspectRatio="none" aria-hidden="true">
{#each strokes as s (s.id)}
{#if !erasing?.has(s.id)}
<path
d={svgPath(s)}
fill={s.color}
fill-opacity={s.tool === 'highlighter' ? HIGHLIGHTER_OPACITY : 1}
class:hl={s.tool === 'highlighter'}
/>
{/if}
{/each}
{#if live}
<path
d={livePath}
fill={live.color}
fill-opacity={live.tool === 'highlighter' ? HIGHLIGHTER_OPACITY : 1}
class:hl={live.tool === 'highlighter'}
/>
{/if}
</svg>
<style>
.ink {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: none;
overflow: hidden;
}
.hl {
mix-blend-mode: multiply;
}
</style>

View file

@ -0,0 +1,181 @@
<script lang="ts">
import { onMount } from 'svelte';
import { EditorState } from '@codemirror/state';
import { EditorView, keymap, placeholder, drawSelection } from '@codemirror/view';
import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
import { livePreview } from '$lib/editor/livepreview';
import type { PageModel } from '$lib/state/doc.svelte';
interface Props {
page: PageModel;
onchange: () => void;
onfocus: () => void;
}
let { page, onchange, onfocus }: Props = $props();
let host: HTMLDivElement;
onMount(() => {
const view = new EditorView({
parent: host,
state: EditorState.create({
doc: page.markdown,
extensions: [
history(),
drawSelection(),
EditorState.tabSize.of(4),
keymap.of([...defaultKeymap, ...historyKeymap, indentWithTab]),
livePreview(),
page.origin ? [] : placeholder('Start typing…'),
EditorView.updateListener.of((u) => {
if (u.docChanged) {
page.markdown = u.state.doc.toString();
onchange();
}
if (u.focusChanged && u.view.hasFocus) onfocus();
}),
EditorView.domEventHandlers({
keydown: (e, v) => {
if (e.key === 'Escape') {
v.contentDOM.blur();
return true;
}
return false;
}
})
]
})
});
return () => view.destroy();
});
</script>
<div class="md" bind:this={host}></div>
<style>
.md {
position: absolute;
/* Bottom overflow is clipped by the page itself (as in the PDF). */
inset: var(--pg-margin) var(--pg-margin) 0 var(--pg-margin);
}
.md :global(.cm-editor) {
height: 100%;
background: transparent;
color: var(--pg-text);
font-family: var(--ui-font);
font-size: var(--pg-font);
/* The page is laid out at ~11px and then scaled; without this, glyph
advances are rounded at the small size and spacing looks uneven. */
text-rendering: geometricPrecision;
font-kerning: normal;
}
.md :global(.cm-editor.cm-focused) {
outline: none;
}
.md :global(.cm-scroller) {
font-family: inherit;
line-height: var(--pg-lh);
overflow: visible !important;
}
.md :global(.cm-content) {
padding: 0;
caret-color: var(--pg-text);
}
.md :global(.cm-line) {
padding: 0;
}
.md :global(.cm-cursor) {
border-left-color: var(--pg-text);
}
.md :global(.cm-selectionBackground) {
background: rgba(112, 93, 207, 0.18) !important;
}
.md :global(.cm-placeholder) {
color: #b5b5b5;
}
/* Live preview — keep in step with PAGE_STYLE / pdf/text.ts. */
.md :global(.md-h) {
font-weight: 700;
line-height: var(--pg-hlh);
}
.md :global(.md-h1) { font-size: var(--pg-h1); }
.md :global(.md-h2) { font-size: var(--pg-h2); }
.md :global(.md-h3) { font-size: var(--pg-h3); }
.md :global(.md-h4) { font-size: var(--pg-h4); }
.md :global(.md-h5) { font-size: var(--pg-h5); }
.md :global(.md-h6) { font-size: var(--pg-h6); }
.md :global(.md-strong) {
font-weight: 700;
}
.md :global(.md-em) {
font-style: italic;
}
.md :global(.md-strike) {
text-decoration: line-through;
}
.md :global(.md-link) {
color: var(--pg-link);
text-decoration: underline;
text-decoration-thickness: 0.5px;
text-underline-offset: 0.12em;
}
.md :global(.md-code) {
font-family: var(--mono-font);
font-size: 0.92em;
background: var(--pg-code-bg);
border-radius: 2px;
}
.md :global(.md-codeblock) {
font-family: var(--mono-font);
font-size: var(--pg-code);
line-height: var(--pg-code-lh);
background: var(--pg-code-bg);
margin: 0 -6px !important;
padding: 0 6px !important;
}
.md :global(.md-codeblock .md-code) {
background: none;
font-size: inherit;
}
.md :global(.md-mark) {
color: var(--pg-muted);
}
.md :global(.md-quote) {
padding-left: calc(var(--q) * var(--pg-quote)) !important;
background-image: repeating-linear-gradient(
to right,
var(--pg-quote-bar) 0 2px,
transparent 2px var(--pg-quote)
);
background-size: calc(var(--q) * var(--pg-quote)) 100%;
background-repeat: no-repeat;
}
.md :global(.md-hr) {
background: linear-gradient(var(--pg-rule), var(--pg-rule)) center / 100% 1px no-repeat;
}
.md :global(.md-bullet) {
color: var(--pg-text);
}
.md :global(.md-task) {
display: inline-block;
width: 0.85em;
height: 0.85em;
vertical-align: -0.05em;
border: 0.8px solid var(--pg-muted);
border-radius: 1px;
cursor: pointer;
position: relative;
}
.md :global(.md-task.done::after) {
content: '';
position: absolute;
left: 0.22em;
top: 0.04em;
width: 0.2em;
height: 0.45em;
border: solid var(--pg-text);
border-width: 0 1.1px 1.1px 0;
transform: rotate(45deg);
}
</style>

View file

@ -0,0 +1,74 @@
<script lang="ts">
import type { Rect } from '$lib/model/layout';
import type { Stroke } from '$lib/model/types';
import type { PageModel } from '$lib/state/doc.svelte';
import MarkdownEditor from './MarkdownEditor.svelte';
import PdfBackground from './PdfBackground.svelte';
import InkLayer from './InkLayer.svelte';
interface Props {
page: PageModel;
rect: Rect;
active: boolean;
invert: boolean;
scale: number;
live: Stroke | null;
tick: number;
erasing: Set<string>;
onchange: () => void;
onactivate: () => void;
}
let { page, rect, active, invert, scale, live, tick, erasing, onchange, onactivate }: Props = $props();
</script>
<div
class="page"
class:active
data-page={page.id}
style="left:{rect.x}px; top:{rect.y}px; width:{rect.width}px; height:{rect.height}px"
>
<div class="paper" class:invert>
{#if page.origin}
<PdfBackground origin={page.origin} width={page.width} height={page.height} {scale} />
{/if}
<MarkdownEditor {page} {onchange} onfocus={onactivate} />
<InkLayer width={page.width} height={page.height} strokes={page.strokes} {live} {tick} {erasing} />
</div>
{#if page.origin && active}
<div class="origin" style="font-size:{11 / scale}px; top:{-18 / scale}px">{page.origin.name} · p. {page.origin.pageIndex + 1}</div>
{/if}
</div>
<style>
.page {
position: absolute;
}
.paper {
position: absolute;
inset: 0;
background: #ffffff;
overflow: hidden;
box-shadow: var(--page-shadow);
}
.paper.invert {
filter: invert(0.88) hue-rotate(180deg);
}
.page.active::after {
content: '';
position: absolute;
/* --s is the zoom, set on the world layer: keep the ring 1.5 screen px. */
inset: calc(-3px / var(--s));
border: calc(1.5px / var(--s)) solid var(--accent);
border-radius: calc(3px / var(--s));
opacity: 0.55;
pointer-events: none;
}
.origin {
position: absolute;
left: 0;
white-space: nowrap;
color: var(--faint);
pointer-events: none;
}
</style>

View file

@ -0,0 +1,71 @@
<script lang="ts">
import { loadSource, renderPage } from '$lib/pdf/render';
import { vault } from '$lib/storage/vault.svelte';
import type { Origin } from '$lib/model/types';
interface Props {
origin: Origin;
width: number;
height: number;
/** Current zoom (screen px per PDF point). */
scale: number;
}
let { origin, width, height, scale }: Props = $props();
let canvas: HTMLCanvasElement;
let failed = $state(false);
// Render at a stepped resolution so zooming doesn't re-render constantly.
const STEPS = [0.25, 0.5, 1, 1.5, 2, 3, 4];
const MAX_PIXELS = 12_000_000;
const resolution = $derived.by(() => {
const want = scale * (window.devicePixelRatio || 1);
const step = STEPS.find((s) => s >= want) ?? STEPS[STEPS.length - 1];
const cap = Math.sqrt(MAX_PIXELS / (width * height));
return Math.min(step, cap);
});
$effect(() => {
const res = resolution;
const { sourceId, pageIndex } = origin;
let job: ReturnType<typeof renderPage> | null = null;
let cancelled = false;
const timer = setTimeout(async () => {
try {
const doc = await loadSource(sourceId, () => vault.getSource(sourceId));
if (cancelled) return;
job = renderPage(doc, pageIndex, canvas, res);
failed = false;
} catch {
failed = true;
}
}, 120);
return () => {
cancelled = true;
clearTimeout(timer);
job?.cancel();
};
});
</script>
<canvas bind:this={canvas} class="bg" class:failed></canvas>
{#if failed}
<div class="missing">Source PDF “{origin.name}” is not available</div>
{/if}
<style>
.bg {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
}
.missing {
position: absolute;
inset: 0;
display: grid;
place-items: center;
color: #999;
font-size: 12px;
}
</style>

View file

@ -0,0 +1,115 @@
<script lang="ts">
import FilesIcon from '@lucide/svelte/icons/files';
import SearchIcon from '@lucide/svelte/icons/search';
import SettingsIcon from '@lucide/svelte/icons/settings';
import SunIcon from '@lucide/svelte/icons/sun';
import MoonIcon from '@lucide/svelte/icons/moon';
import RefreshIcon from '@lucide/svelte/icons/refresh-cw';
import CloudOffIcon from '@lucide/svelte/icons/cloud-off';
import { settings } from '$lib/state/settings.svelte';
import { workspace, type Panel } from '$lib/state/workspace.svelte';
import { sync } from '$lib/sync/sync.svelte';
function toggle(p: Panel) {
workspace.panel = workspace.panel === p ? null : p;
}
const syncTitle = $derived.by(() => {
switch (sync.status) {
case 'disabled':
return 'Sync not set up — open settings';
case 'offline':
return `Offline · ${sync.pending} change(s) waiting`;
case 'syncing':
return 'Syncing…';
case 'error':
return `Sync failed: ${sync.error}`;
default:
return sync.pending
? `${sync.pending} unpushed change(s) — sync now`
: `Synced${sync.lastSync ? ' ' + new Date(sync.lastSync).toLocaleTimeString() : ''}`;
}
});
function onSync() {
if (sync.status === 'disabled') workspace.settingsOpen = true;
else void sync.syncNow();
}
</script>
<nav class="ribbon" aria-label="Ribbon">
<div class="group">
<button class="icon-btn" class:active={workspace.panel === 'files'} title="Files" onclick={() => toggle('files')}>
<FilesIcon size={18} strokeWidth={1.75} />
</button>
<button class="icon-btn" class:active={workspace.panel === 'search'} title="Search (Ctrl+Shift+F)" onclick={() => toggle('search')}>
<SearchIcon size={18} strokeWidth={1.75} />
</button>
</div>
<div class="group">
<button class="icon-btn sync" title={syncTitle} onclick={onSync} data-status={sync.status}>
{#if sync.status === 'disabled' || sync.status === 'offline'}
<CloudOffIcon size={18} strokeWidth={1.75} />
{:else}
<span class:spin={sync.status === 'syncing'}><RefreshIcon size={18} strokeWidth={1.75} /></span>
{/if}
{#if sync.status === 'error'}
<i class="dot error"></i>
{:else if sync.pending > 0 && sync.status !== 'disabled'}
<i class="dot pending"></i>
{/if}
</button>
<button class="icon-btn" title={settings.dark ? 'Light theme' : 'Dark theme'} onclick={() => settings.toggleTheme()}>
{#if settings.dark}<SunIcon size={18} strokeWidth={1.75} />{:else}<MoonIcon size={18} strokeWidth={1.75} />{/if}
</button>
<button class="icon-btn" title="Settings (Ctrl+,)" onclick={() => (workspace.settingsOpen = true)}>
<SettingsIcon size={18} strokeWidth={1.75} />
</button>
</div>
</nav>
<style>
.ribbon {
width: 44px;
flex: none;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
padding: 8px 0 10px;
background: var(--bg-2);
border-right: 1px solid var(--border);
z-index: 21;
}
.group {
display: flex;
flex-direction: column;
gap: 4px;
}
.sync {
position: relative;
}
.dot {
position: absolute;
top: 5px;
right: 5px;
width: 6px;
height: 6px;
border-radius: 50%;
}
.dot.pending {
background: var(--warn);
}
.dot.error {
background: var(--danger);
}
.spin {
display: inline-grid;
animation: spin 1s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
</style>

View file

@ -0,0 +1,122 @@
<script lang="ts">
import FileTextIcon from '@lucide/svelte/icons/file-text';
import { vault, displayName, dirName } from '$lib/storage/vault.svelte';
import { workspace } from '$lib/state/workspace.svelte';
let query = $state('');
let results = $state<Awaited<ReturnType<typeof vault.search>>>([]);
let timer: ReturnType<typeof setTimeout>;
$effect(() => {
const q = query;
clearTimeout(timer);
timer = setTimeout(async () => (results = await vault.search(q)), 120);
});
const grouped = $derived.by(() => {
const map = new Map<string, typeof results>();
for (const r of results) {
const list = map.get(r.path) ?? [];
list.push(r);
map.set(r.path, list);
}
return [...map];
});
function highlight(text: string, q: string) {
const esc = (s: string) => s.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`);
const i = text.toLowerCase().indexOf(q.toLowerCase());
if (!q || i < 0) return esc(text);
return esc(text.slice(0, i)) + '<mark>' + esc(text.slice(i, i + q.length)) + '</mark>' + esc(text.slice(i + q.length));
}
function focus(el: HTMLInputElement) {
el.focus();
}
</script>
<div class="head">
<input type="search" placeholder="Search text and PDF sources…" bind:value={query} use:focus />
</div>
<div class="results">
{#each grouped as [path, hits] (path)}
<div class="file">
<button class="file-name" onclick={() => workspace.open(path)}>
<FileTextIcon size={14} strokeWidth={1.75} />
<span>{displayName(path)}</span>
{#if dirName(path)}<small>{dirName(path)}</small>{/if}
</button>
{#each hits.filter((h) => h.pageId) as hit (hit.pageId)}
<button class="hit" onclick={() => workspace.open(path, { page: hit.pageId })}>
{#if hit.snippet}<span class="snippet">{@html highlight(hit.snippet, query.trim())}</span>{/if}
{#if hit.origin}<span class="origin">from {@html highlight(hit.origin, query.trim())}</span>{/if}
</button>
{/each}
</div>
{:else}
{#if query.trim()}<p class="empty">No matches.</p>{/if}
{/each}
</div>
<style>
.head {
padding: 10px 10px 6px;
}
.head input {
width: 100%;
}
.results {
flex: 1;
overflow: auto;
padding: 4px 6px 16px;
}
.file {
margin-bottom: 8px;
}
button {
display: flex;
width: 100%;
text-align: left;
border: 0;
background: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background: var(--hover);
}
.file-name {
align-items: center;
gap: 6px;
padding: 5px 8px;
color: var(--text);
font-weight: 600;
}
.file-name small {
margin-left: auto;
color: var(--faint);
font-weight: 400;
}
.hit {
flex-direction: column;
gap: 2px;
padding: 5px 8px 5px 28px;
color: var(--muted);
font-size: 12px;
}
.origin {
color: var(--faint);
font-size: 11px;
}
.hit :global(mark) {
background: var(--accent-soft);
color: var(--text);
border-radius: 2px;
}
.empty {
color: var(--faint);
text-align: center;
margin-top: 24px;
}
</style>

View file

@ -0,0 +1,345 @@
<script lang="ts">
import XIcon from '@lucide/svelte/icons/x';
import { settings } from '$lib/state/settings.svelte';
import { workspace } from '$lib/state/workspace.svelte';
import { sync } from '$lib/sync/sync.svelte';
import { GitHub } from '$lib/sync/github';
type Tab = 'appearance' | 'input' | 'sync';
let tab = $state<Tab>('appearance');
const s = settings.data;
let testing = $state(false);
let testResult = $state<{ ok: boolean; text: string } | null>(null);
function save() {
settings.save();
}
function close() {
settings.save();
sync.schedule();
workspace.settingsOpen = false;
}
async function testConnection() {
save();
testing = true;
testResult = null;
try {
const repo = await new GitHub(s.github).checkAccess();
testResult = { ok: true, text: `Connected. Default branch: ${repo.default_branch}` };
} catch (e) {
testResult = { ok: false, text: e instanceof Error ? e.message : String(e) };
} finally {
testing = false;
}
}
async function syncNow() {
save();
sync.schedule();
await sync.syncNow();
if (sync.status === 'error') testResult = { ok: false, text: sync.error };
else testResult = { ok: true, text: 'Synced.' };
}
</script>
<svelte:window onkeydown={(e) => e.key === 'Escape' && close()} />
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
<div class="backdrop" onclick={(e) => e.target === e.currentTarget && close()}>
<div class="modal" role="dialog" aria-modal="true" aria-label="Settings">
<nav>
<div class="nav-title">Options</div>
<button class:active={tab === 'appearance'} onclick={() => (tab = 'appearance')}>Appearance</button>
<button class:active={tab === 'input'} onclick={() => (tab = 'input')}>Pen &amp; touch</button>
<button class:active={tab === 'sync'} onclick={() => (tab = 'sync')}>Sync</button>
</nav>
<section>
<button class="icon-btn close" title="Close" onclick={close}><XIcon size={18} /></button>
{#if tab === 'appearance'}
<h2>Appearance</h2>
<div class="row">
<div><div class="name">Theme</div><div class="desc">Follow the system, or pick one.</div></div>
<select bind:value={s.theme} onchange={save}>
<option value="system">System</option>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
</div>
<div class="row">
<div>
<div class="name">Pages in dark theme</div>
<div class="desc">Dim pages to match the theme, or keep them white like paper. Only affects the screen; the PDF is always on white.</div>
</div>
<select bind:value={s.pageStyle} onchange={save}>
<option value="match">Match theme</option>
<option value="paper">Paper</option>
</select>
</div>
{:else if tab === 'input'}
<h2>Pen &amp; touch</h2>
<div class="row">
<div><div class="name">Draw with finger</div><div class="desc">When off, a single finger always pans; only pen and mouse draw.</div></div>
<input type="checkbox" class="toggle" bind:checked={s.fingerDraw} onchange={save} />
</div>
<h3>Palm rejection</h3>
<div class="row">
<div><div class="name">Pen session lockout</div><div class="desc">Ignore touches while the pen is writing or was used in the last 5 seconds.</div></div>
<input type="checkbox" class="toggle" bind:checked={s.palm.penSession} onchange={save} />
</div>
<div class="row">
<div><div class="name">Reject wide contacts</div><div class="desc">Ignore touches with a palm-sized contact area (over 35 px).</div></div>
<input type="checkbox" class="toggle" bind:checked={s.palm.geometry} onchange={save} />
</div>
<div class="row">
<div><div class="name">Reject touches right after pen activity</div><div class="desc">Ignore touches within 150 ms of pen activity.</div></div>
<input type="checkbox" class="toggle" bind:checked={s.palm.timing} onchange={save} />
</div>
<div class="row">
<div><div class="name">Lock out on pen hover</div><div class="desc">Ignore touches while the pen hovers above the screen.</div></div>
<input type="checkbox" class="toggle" bind:checked={s.palm.hover} onchange={save} />
</div>
{:else}
<h2>Sync</h2>
<p class="intro">
Canvases are stored as PDFs in a GitHub repository. Changes save on this device straight away and are pushed
periodically, or when you press sync. If a file changed in both places, the newer version wins.
</p>
<div class="row">
<div>
<div class="name">Personal access token</div>
<div class="desc">A fine-grained token with <b>Contents: read &amp; write</b> on the repository. It's stored only in this browser.</div>
</div>
<input type="password" autocomplete="off" bind:value={s.github.token} onchange={save} placeholder="github_pat_…" />
</div>
<div class="row">
<div><div class="name">Repository</div><div class="desc">Owner and name.</div></div>
<div class="pair">
<input bind:value={s.github.owner} onchange={save} placeholder="owner" />
<span>/</span>
<input bind:value={s.github.repo} onchange={save} placeholder="notes" />
</div>
</div>
<div class="row">
<div><div class="name">Branch</div></div>
<input bind:value={s.github.branch} onchange={save} placeholder="main" />
</div>
<div class="row">
<div><div class="name">Folder in repository</div><div class="desc">Leave empty to use the repository root.</div></div>
<input bind:value={s.github.dir} onchange={save} placeholder="(root)" />
</div>
<div class="row">
<div><div class="name">Push automatically every</div><div class="desc">Minutes. 0 means only when you press sync.</div></div>
<input type="number" min="0" max="120" bind:value={s.pushInterval} onchange={() => (save(), sync.schedule())} />
</div>
<div class="actions">
<button class="btn" disabled={testing || !settings.githubReady} onclick={testConnection}>Test connection</button>
<button class="btn primary" disabled={!settings.githubReady || sync.status === 'syncing'} onclick={syncNow}>
{sync.status === 'syncing' ? 'Syncing…' : 'Sync now'}
</button>
</div>
{#if testResult}
<p class="result" class:bad={!testResult.ok}>{testResult.text}</p>
{/if}
{/if}
</section>
</div>
</div>
<style>
.backdrop {
position: fixed;
inset: 0;
z-index: 50;
display: grid;
place-items: center;
background: rgba(0, 0, 0, 0.45);
padding: 16px;
}
.modal {
display: flex;
width: min(860px, 100%);
height: min(600px, 100%);
background: var(--bg);
border: 1px solid var(--border);
border-radius: 10px;
box-shadow: var(--shadow);
overflow: hidden;
}
nav {
width: 190px;
flex: none;
background: var(--bg-2);
border-right: 1px solid var(--border);
padding: 16px 8px;
display: flex;
flex-direction: column;
gap: 2px;
}
.nav-title {
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--faint);
padding: 0 10px 8px;
}
nav button {
text-align: left;
border: 0;
background: none;
padding: 6px 10px;
border-radius: 4px;
color: var(--muted);
cursor: pointer;
}
nav button:hover {
background: var(--hover);
color: var(--text);
}
nav button.active {
background: var(--accent-soft);
color: var(--text);
}
section {
position: relative;
flex: 1;
overflow: auto;
padding: 20px 28px 28px;
}
.close {
position: absolute;
right: 12px;
top: 12px;
}
h2 {
font-size: 17px;
margin: 4px 0 16px;
padding-bottom: 12px;
border-bottom: 1px solid var(--border);
}
h3 {
font-size: 13px;
margin: 24px 0 4px;
color: var(--muted);
}
.intro {
color: var(--muted);
margin: 0 0 8px;
line-height: 1.5;
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 12px 0;
border-bottom: 1px solid var(--border);
}
.row > :first-child {
flex: 1;
}
.name {
color: var(--text);
}
.desc {
color: var(--muted);
font-size: 12px;
margin-top: 3px;
line-height: 1.45;
}
.row input:not([type='checkbox']),
.row select {
width: 220px;
}
.row input[type='number'] {
width: 80px;
}
.pair {
display: flex;
align-items: center;
gap: 6px;
}
.pair input {
width: 104px !important;
}
.pair span {
color: var(--faint);
}
.toggle {
appearance: none;
width: 36px;
height: 20px;
border-radius: 10px;
background: var(--bg-3);
border: 0;
padding: 0;
position: relative;
cursor: pointer;
flex: none;
transition: background 0.15s;
}
.toggle::after {
content: '';
position: absolute;
top: 2px;
left: 2px;
width: 16px;
height: 16px;
border-radius: 50%;
background: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
transition: transform 0.15s;
}
.toggle:checked {
background: var(--accent);
}
.toggle:checked::after {
transform: translateX(16px);
}
.actions {
display: flex;
gap: 8px;
justify-content: flex-end;
margin-top: 18px;
}
.btn:disabled {
opacity: 0.5;
cursor: default;
}
.result {
text-align: right;
color: var(--success);
margin: 10px 0 0;
}
.result.bad {
color: var(--danger);
}
@media (max-width: 640px) {
.modal {
flex-direction: column;
}
nav {
width: auto;
flex-direction: row;
border-right: 0;
border-bottom: 1px solid var(--border);
padding: 8px;
}
.nav-title {
display: none;
}
.row {
flex-direction: column;
align-items: stretch;
gap: 8px;
}
.row input:not([type='checkbox']),
.row select {
width: 100%;
}
}
</style>

View file

@ -0,0 +1,34 @@
<script lang="ts">
import { workspace } from '$lib/state/workspace.svelte';
</script>
<div class="toasts" aria-live="polite">
{#each workspace.toasts as t (t.id)}
<div class="toast" class:error={t.kind === 'error'}>{t.text}</div>
{/each}
</div>
<style>
.toasts {
position: fixed;
top: 14px;
right: 14px;
display: flex;
flex-direction: column;
gap: 8px;
z-index: 200;
pointer-events: none;
}
.toast {
padding: 8px 14px;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 6px;
box-shadow: var(--shadow);
max-width: 340px;
}
.toast.error {
border-color: var(--danger);
color: var(--danger);
}
</style>

View file

@ -0,0 +1,208 @@
<script lang="ts">
import TypeIcon from '@lucide/svelte/icons/type';
import PenIcon from '@lucide/svelte/icons/pen-line';
import HighlighterIcon from '@lucide/svelte/icons/highlighter';
import EraserIcon from '@lucide/svelte/icons/eraser';
import FileUpIcon from '@lucide/svelte/icons/file-up';
import UndoIcon from '@lucide/svelte/icons/undo-2';
import RedoIcon from '@lucide/svelte/icons/redo-2';
import ZoomInIcon from '@lucide/svelte/icons/zoom-in';
import ZoomOutIcon from '@lucide/svelte/icons/zoom-out';
import ScanIcon from '@lucide/svelte/icons/scan';
import type { Component } from 'svelte';
import type { CanvasDoc } from '$lib/state/doc.svelte';
import { tools, PEN_WIDTHS, HIGHLIGHTER_WIDTHS, type Tool } from '$lib/state/tools.svelte';
import { settings } from '$lib/state/settings.svelte';
import { viewport } from '$lib/state/viewport.svelte';
import { workspace } from '$lib/state/workspace.svelte';
import { vault } from '$lib/storage/vault.svelte';
import { pagesFromPdf } from '$lib/pdf/read';
let { doc, onfit, onfitall }: { doc: CanvasDoc; onfit: () => void; onfitall: () => void } = $props();
let fileInput: HTMLInputElement;
let colorInput = $state<HTMLInputElement>();
const TOOLS: { id: Tool; label: string; key: string; icon: Component }[] = [
{ id: 'text', label: 'Text', key: 'T', icon: TypeIcon },
{ id: 'pen', label: 'Pen', key: 'P', icon: PenIcon },
{ id: 'highlighter', label: 'Highlighter', key: 'H', icon: HighlighterIcon },
{ id: 'eraser', label: 'Eraser', key: 'E', icon: EraserIcon }
];
const colors = $derived(tools.tool === 'highlighter' ? settings.data.highlighterColors : settings.data.penColors);
const widths = $derived(tools.tool === 'highlighter' ? HIGHLIGHTER_WIDTHS : PEN_WIDTHS);
const showInk = $derived(tools.tool === 'pen' || tools.tool === 'highlighter');
async function onFile(e: Event) {
const input = e.currentTarget as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (!file) return;
try {
const bytes = new Uint8Array(await file.arrayBuffer());
const { sourceId, pages } = await pagesFromPdf(bytes, file.name);
if (pages.length === 0) return workspace.toast('That PDF has no pages', 'error');
await vault.putSource(sourceId, bytes);
if (doc.isBlank) {
doc.replaceWith(pages);
onfit();
} else {
tools.placing = { name: file.name, pages };
}
} catch (err) {
console.error(err);
workspace.toast(`Could not read ${file.name}`, 'error');
}
}
function customColor(e: Event) {
const c = (e.currentTarget as HTMLInputElement).value;
tools.color = c;
const list = tools.tool === 'highlighter' ? settings.data.highlighterColors : settings.data.penColors;
if (!list.includes(c)) {
list.push(c);
if (list.length > 8) list.splice(1, 1); // keep the first (default) colour
settings.save();
}
}
</script>
<div class="dock no-stage">
<div class="bar" role="toolbar" aria-label="Tools">
{#each TOOLS as t (t.id)}
<button
class="icon-btn"
class:active={tools.tool === t.id}
title="{t.label} ({t.key})"
aria-pressed={tools.tool === t.id}
onclick={() => (tools.tool = t.id)}
>
<t.icon size={18} strokeWidth={1.75} />
</button>
{/each}
{#if showInk}
<span class="sep"></span>
{#each colors as c (c)}
<button
class="swatch"
class:selected={tools.color === c}
style="--c: {c}"
title={c}
aria-label="Colour {c}"
onclick={() => (tools.color = c)}
></button>
{/each}
<button class="swatch custom" title="Custom colour" aria-label="Custom colour" onclick={() => colorInput?.click()}></button>
<input bind:this={colorInput} type="color" class="hidden-color" value={tools.color} onchange={customColor} />
<span class="sep"></span>
{#each widths as w, i (w)}
<button class="icon-btn width" class:active={tools.width === w} title="Width {i + 1}" onclick={() => (tools.width = w)}>
<span class="dot" style="width:{4 + i * 4}px; height:{4 + i * 4}px"></span>
</button>
{/each}
{/if}
<span class="sep"></span>
<button class="icon-btn" title="Import PDF" onclick={() => fileInput.click()}><FileUpIcon size={18} strokeWidth={1.75} /></button>
<button class="icon-btn" title="Undo (Ctrl+Z)" disabled={!doc.canUndo} onclick={() => doc.undo()}><UndoIcon size={18} strokeWidth={1.75} /></button>
<button class="icon-btn" title="Redo (Ctrl+Shift+Z)" disabled={!doc.canRedo} onclick={() => doc.redo()}><RedoIcon size={18} strokeWidth={1.75} /></button>
<span class="sep"></span>
<button class="icon-btn" title="Zoom out (Ctrl+−)" onclick={() => viewport.zoomAt(0.8)}><ZoomOutIcon size={18} strokeWidth={1.75} /></button>
<button class="zoom" title="Fit page (Ctrl+0)" onclick={onfit}>{Math.round(viewport.scale * 100)}%</button>
<button class="icon-btn" title="Zoom in (Ctrl+=)" onclick={() => viewport.zoomAt(1.25)}><ZoomInIcon size={18} strokeWidth={1.75} /></button>
<button class="icon-btn" title="Show whole tree (Ctrl+9)" onclick={onfitall}><ScanIcon size={18} strokeWidth={1.75} /></button>
</div>
</div>
<input bind:this={fileInput} type="file" accept="application/pdf,.pdf" hidden onchange={onFile} />
<style>
.dock {
position: absolute;
left: 0;
right: 0;
bottom: max(14px, env(safe-area-inset-bottom));
display: flex;
justify-content: center;
pointer-events: none;
padding: 0 12px;
}
.bar {
pointer-events: auto;
display: flex;
align-items: center;
gap: 2px;
padding: 4px;
max-width: 100%;
overflow-x: auto;
scrollbar-width: none;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 10px;
box-shadow: var(--shadow);
}
.icon-btn {
width: 32px;
height: 32px;
}
.sep {
width: 1px;
height: 20px;
background: var(--border);
margin: 0 4px;
flex: none;
}
.swatch {
width: 22px;
height: 22px;
margin: 0 1px;
padding: 0;
flex: none;
border-radius: 50%;
border: 2px solid transparent;
background: var(--c);
background-clip: content-box;
box-shadow: inset 0 0 0 1px rgba(128, 128, 128, 0.35);
cursor: pointer;
}
.swatch.selected {
border-color: var(--accent);
padding: 2px;
}
.swatch.custom {
background: conic-gradient(#f43, #fd2, #3c6, #2be, #63f, #f3c, #f43);
background-clip: content-box;
}
.hidden-color {
position: absolute;
width: 0;
height: 0;
opacity: 0;
pointer-events: none;
border: 0;
padding: 0;
}
.width .dot {
display: block;
border-radius: 50%;
background: currentColor;
}
.zoom {
min-width: 48px;
height: 32px;
border: 0;
background: none;
border-radius: 4px;
color: var(--muted);
font-variant-numeric: tabular-nums;
cursor: pointer;
flex: none;
}
.zoom:hover {
background: var(--hover);
color: var(--text);
}
</style>

View file

@ -0,0 +1,19 @@
import { vault, baseName } from '$lib/storage/vault.svelte';
import { workspace } from '$lib/state/workspace.svelte';
/** Build a canvas's PDF and hand it to the browser as a download. */
export async function downloadCanvas(path: string) {
try {
await workspace.flush();
const bytes = await vault.buildPdf(path);
const url = URL.createObjectURL(new Blob([bytes as BlobPart], { type: 'application/pdf' }));
const a = document.createElement('a');
a.href = url;
a.download = baseName(path);
a.click();
setTimeout(() => URL.revokeObjectURL(url), 10_000);
} catch (e) {
console.error(e);
workspace.toast('Could not build the PDF', 'error');
}
}