Merge pull request 'Add lasso selection and pasted images' (#14) from select-and-images into main

Reviewed-on: #14
This commit is contained in:
reudy 2026-09-29 23:41:57 +02:00
commit 8a3d2224a7
26 changed files with 1274 additions and 39 deletions

View file

@ -7,7 +7,7 @@ Lecture notes as a tree of pages ("comb") — live-preview markdown underneath,
```sh ```sh
npm install npm install
npm run dev # http://localhost:5173 npm run dev # http://localhost:5173
npm test # unit tests (tree, markdown, PDF round trip, sync against a fake GitHub) npm test # unit tests (tree, markdown, selection, PDF round trip, sync against a fake GitHub)
npm run check # type-check npm run check # type-check
npm run build # static PWA in build/ — serve it from any static host (HTTPS for PWA install) npm run build # static PWA in build/ — serve it from any static host (HTTPS for PWA install)
``` ```
@ -22,7 +22,9 @@ The image builds the PWA and serves it with nginx. Put an HTTPS reverse proxy in
## Using it ## Using it
- **Tools** (bottom bar): Text `T`, Pen `P`, Highlighter `H`, Eraser `E`, Import PDF, Undo/Redo, zoom. The pen's eraser end erases too. - **Tools** (bottom bar): Text `T`, Select `S`, Pen `P`, Highlighter `H`, Eraser `E`, Import PDF, Insert image, Undo/Redo, zoom. The pen's eraser end erases too.
- **Selecting**: with Select, draw a loop around ink and images (only things entirely inside are picked) or tap one. Holding the pen's side button lassoes with any tool. Drag the box to move, a corner to resize; the bar above it copies, cuts, duplicates, deletes or recolours. `Ctrl+C/X/V/D`, `Delete` and arrow keys work too.
- **Images**: paste (`Ctrl+V`), drop an image file on a page, or use Insert image. Large images are scaled down to 2400 px. Images stay in their own colours in dark mode. Copying a selection also puts a PNG of it on the system clipboard.
- **Pages**: the "+" circles beside the active page add a page there (a quick finger flick toward a free side offers one there; turn it off under Settings → Pen & touch); `Alt+Arrow` moves to (or creates) the neighbour. Right-click a page or use its `⋯` button to insert, resize or delete it. - **Pages**: the "+" circles beside the active page add a page there (a quick finger flick toward a free side offers one there; turn it off under Settings → Pen & touch); `Alt+Arrow` moves to (or creates) the neighbour. Right-click a page or use its `⋯` button to insert, resize or delete it.
- **Grid**: the faint background grid has one cell per active page; Settings → Appearance can hide it or subdivide it. - **Grid**: the faint background grid has one cell per active page; Settings → Appearance can hide it or subdivide it.
- **Importing a PDF** into a non-empty canvas shows every free spot; click one to place the chain. Into a blank canvas it simply replaces the empty page. The Files panel can also import a PDF as a new canvas. - **Importing a PDF** into a non-empty canvas shows every free spot; click one to place the chain. Into a blank canvas it simply replaces the empty page. The Files panel can also import a PDF as a new canvas.
@ -34,7 +36,8 @@ The image builds the PWA and serves it with nginx. Put an HTTPS reverse proxy in
- `src/lib/model` — page tree (pure functions: insert/remove/flatten/layout). - `src/lib/model` — page tree (pure functions: insert/remove/flatten/layout).
- `src/lib/editor` — markdown analysis shared by the CodeMirror live preview and the PDF text layout. - `src/lib/editor` — markdown analysis shared by the CodeMirror live preview and the PDF text layout.
- `src/lib/pdf` — PDF writer (vector text, Ink annotations, embedded source-of-truth files) and reader. - `src/lib/pdf` — PDF writer (vector text, Ink annotations, embedded source-of-truth files) and reader.
- `src/lib/ink` — stroke recording/outlines and palm rejection (ported from `palm-rejection-test.html`). - `src/lib/ink` — stroke recording/outlines, lasso selection and clipboard helpers, palm rejection (ported from `palm-rejection-test.html`).
- `src/lib/images` — pasted-image normalisation, asset storage/object URLs, PNG export of a selection.
- `src/lib/storage`, `src/lib/sync` — IndexedDB vault and GitHub sync. - `src/lib/storage`, `src/lib/sync` — IndexedDB vault and GitHub sync.
Fonts in `static/fonts` are pre-subset (`scripts/subset-fonts.sh`) because pdf-lib's own subsetter drops glyphs. Fonts in `static/fonts` are pre-subset (`scripts/subset-fonts.sh`) because pdf-lib's own subsetter drops glyphs.

29
spec.md
View file

@ -32,8 +32,8 @@ This is recomputed at export/save time (not creation order), since the trunk can
One canvas = **one `.pdf` file**, dual-layer: One canvas = **one `.pdf` file**, dual-layer:
- **Visual layer** (any standard PDF viewer sees this): rendered markdown as real vector text, ink drawn as PDF Ink annotations, original imported PDF content where applicable. Fully readable/printable by anyone, no app required. - **Visual layer** (any standard PDF viewer sees this): rendered markdown as real vector text, pasted images, ink drawn as PDF Ink annotations, original imported PDF content where applicable. Fully readable/printable by anyone, no app required.
- **Source-of-truth layer** (embedded file attachments, invisible in normal viewers): raw markdown source per page, full vector stroke data (points + pressure + tilt — richer than what Ink annotations can hold), and grid metadata (each page's tree position, size, and which PDF import it originated from, for provenance search). - **Source-of-truth layer** (embedded file attachments, invisible in normal viewers): raw markdown source per page, full vector stroke data (points + pressure + tilt — richer than what Ink annotations can hold), placed images per page (`papure/pages/<id>.images.json`) with each image's bytes stored once (`papure/assets/<hash>.png|jpg`), and grid metadata (each page's tree position, size, and which PDF import it originated from, for provenance search).
- App reads the attachment layer first to reconstruct the live editable canvas; falls back to parsing visual content only if attachments are missing. - App reads the attachment layer first to reconstruct the live editable canvas; falls back to parsing visual content only if attachments are missing.
**Libraries**: `pdf-lib` (write/edit/attach), `pdf.js` (render/import). **Libraries**: `pdf-lib` (write/edit/attach), `pdf.js` (render/import).
@ -61,6 +61,7 @@ Canvases (PDF files) live in a **file tree** you define, e.g. `school/english/le
- Live-rendered markdown (background layer) + vector ink (foreground layer), never converted to text. - Live-rendered markdown (background layer) + vector ink (foreground layer), never converted to text.
- Full ink toolset: colors, highlighter, eraser. - Full ink toolset: colors, highlighter, eraser.
- Lasso selection of ink and images; pasted images (§10).
- Search across typed markdown text. - Search across typed markdown text.
- Pages remember their PDF-import origin, searchable. - Pages remember their PDF-import origin, searchable.
- No export needed beyond the PDF itself (for now). - No export needed beyond the PDF itself (for now).
@ -93,10 +94,32 @@ Source: user-provided `palm-rejection-test.html` test harness. The acceptance po
- Undo/redo covers ink, erasing and page-tree changes. - Undo/redo covers ink, erasing and page-tree changes.
- Strokes are written to the PDF both as Ink annotations and as JSON attachments. - Strokes are written to the PDF both as Ink annotations and as JSON attachments.
## 10. Open Items ## 10. Selection & Images
**Page layers**, bottom to top: imported PDF → markdown → pasted images → ink. Ink can be written over an image.
**Select tool** (`S`, lasso):
- Drag draws a lasso; an ink stroke is selected only when *all* of its samples are inside it, an image only when all four corners are. A tap selects the single object under it (ink before images). Shift adds to the selection; `Ctrl+A` selects everything on the active page.
- A selection lives on one page. It shows as a dashed box with corner handles and an action bar (copy, cut, duplicate, delete, recolour ink).
- Drag the box to move, a corner to scale uniformly (ink width scales too); arrow keys nudge by 1 pt (Shift: 10 pt). Each move/resize is one undo step; the drag itself is only a preview.
- `Delete`/`Backspace` deletes, `Ctrl+C`/`X`/`V`/`D` copy, cut, paste, duplicate. `Escape`, pressing elsewhere or switching tools clears the selection.
- Holding the pen's barrel button lassoes whatever tool is active (Settings → Pen & touch → "Pen button selects"); its context menu is suppressed.
- Palm rejection: lassoing with a finger counts as drawing; dragging the selection box or its handles counts as navigating, so fingers can move a selection between pen strokes.
- The eraser never erases images; delete them with the Select tool.
**Clipboard**: copying keeps a vector copy in the app and writes a PNG of the selection to the system clipboard (for other apps). Pasting uses the vector copy while it's fresh (until the window loses focus or something else is copied); otherwise an image on the clipboard is pasted. Pastes land at the pointer if it's over a page, else in the middle of the visible part of the active page.
**Images** come in by paste, drag-and-drop, the toolbar's "Insert image" button, or "Paste" in the page menu.
- Normalised on the way in: the long edge is capped at 2400 px; transparent images stay PNG, JPEGs stay JPEG (quality 0.85, EXIF rotation applied), other images use whichever of PNG/JPEG is smaller. A PNG that already fits is kept byte for byte.
- Stored by SHA-256 content hash in IndexedDB (`assets` store), so one image placed many times is stored once — also in the PDF.
- Placed at 96 dpi (1 px = 0.75 pt), shrunk to at most 80 % of the page, and selected so it can be moved/resized straight away.
- Dark mode ("match" page style) inverts each page layer except images, so images keep their true colours. The ink layer is screen-blended so the highlighter still reads like it does in light mode.
## 11. Open Items
- [ ] Conflict copies: sync currently lets the newer version win silently; keep the losing version as a separate file. - [ ] Conflict copies: sync currently lets the newer version win silently; keep the losing version as a separate file.
- [ ] Tell the user when a new version of the app has been deployed (the service worker updates, but the open tab keeps old code until reload). - [ ] Tell the user when a new version of the app has been deployed (the service worker updates, but the open tab keeps old code until reload).
- [ ] CI that runs `check`, `test` and `build` on every pull request. - [ ] CI that runs `check`, `test` and `build` on every pull request.
- [ ] Use recorded tilt for rendering. - [ ] Use recorded tilt for rendering.
- [ ] GitLab sync. - [ ] GitLab sync.
- [ ] Selection: drag across pages, rotate; image crop; "paste as new page" for slide screenshots.

View file

@ -6,6 +6,10 @@
import ArrowUpIcon from '@lucide/svelte/icons/arrow-up'; import ArrowUpIcon from '@lucide/svelte/icons/arrow-up';
import TrashIcon from '@lucide/svelte/icons/trash-2'; import TrashIcon from '@lucide/svelte/icons/trash-2';
import CheckIcon from '@lucide/svelte/icons/check'; import CheckIcon from '@lucide/svelte/icons/check';
import CopyIcon from '@lucide/svelte/icons/copy';
import CopyPlusIcon from '@lucide/svelte/icons/copy-plus';
import ScissorsIcon from '@lucide/svelte/icons/scissors';
import ClipboardPasteIcon from '@lucide/svelte/icons/clipboard-paste';
import type { CanvasDoc } from '$lib/state/doc.svelte'; import type { CanvasDoc } from '$lib/state/doc.svelte';
import { viewport } from '$lib/state/viewport.svelte'; import { viewport } from '$lib/state/viewport.svelte';
import { tools } from '$lib/state/tools.svelte'; import { tools } from '$lib/state/tools.svelte';
@ -15,10 +19,24 @@
import { dirName, displayName } from '$lib/storage/vault.svelte'; import { dirName, displayName } from '$lib/storage/vault.svelte';
import { bounds, intersects, rectBeside, type Rect } from '$lib/model/layout'; import { bounds, intersects, rectBeside, type Rect } from '$lib/model/layout';
import { canInsert, freeSlots, freeSlotsOf, neighbor, type Dir, type Slot } from '$lib/model/tree'; import { canInsert, freeSlots, freeSlotsOf, neighbor, type Dir, type Slot } from '$lib/model/tree';
import { A4, PAGE_PRESETS, type Stroke } from '$lib/model/types'; import { A4, PAGE_PRESETS, newId, type PageImage, type Stroke } from '$lib/model/types';
import { PalmRejector, touchIntent } from '$lib/ink/palm'; import { PalmRejector, touchIntent } from '$lib/ink/palm';
import { flingDir, pushSample, type Sample } from '$lib/ink/fling'; import { flingDir, pushSample, type Sample } from '$lib/ink/fling';
import { StrokeRecorder, hitStroke } from '$lib/ink/stroke'; import { StrokeRecorder, hitStroke } from '$lib/ink/stroke';
import {
IDENTITY,
hitObject,
lassoSelect,
objectsBounds,
scaleAbout,
transformImage,
transformStroke,
translate,
type Transform
} from '$lib/ink/select';
import { imageSize, instantiate, makeClip, placeCentred, type Clip } from '$lib/ink/clip';
import { assets } from '$lib/images/assets.svelte';
import { renderClipPng } from '$lib/images/png';
import { pageCssVars } from '$lib/editor/pageStyle'; import { pageCssVars } from '$lib/editor/pageStyle';
import { downloadCanvas } from './download'; import { downloadCanvas } from './download';
import PageSizeDialog from './PageSizeDialog.svelte'; import PageSizeDialog from './PageSizeDialog.svelte';
@ -231,10 +249,12 @@
} }
// ---- page menu ------------------------------------------------------- // ---- page menu -------------------------------------------------------
function pageMenu(x: number, y: number, id: string) { /** `at`: stage-local point to paste at (the right-click position). */
function pageMenu(x: number, y: number, id: string, at?: { x: number; y: number }) {
const page = doc.pages[id]; const page = doc.pages[id];
if (!page) return; if (!page) return;
doc.activeId = id; doc.activeId = id;
const canRead = typeof navigator !== 'undefined' && !!navigator.clipboard?.read;
const dirs: [Dir, string][] = [ const dirs: [Dir, string][] = [
['up', 'Insert page above'], ['up', 'Insert page above'],
['down', 'Insert page below'], ['down', 'Insert page below'],
@ -259,6 +279,7 @@
} }
items.push({ label: 'Custom size…', action: () => customSize(id) }); items.push({ label: 'Custom size…', action: () => customSize(id) });
} }
items.push('separator', { label: 'Paste', icon: ClipboardPasteIcon, disabled: !clip && !canRead, action: () => void pasteFromMenu(at) });
items.push('separator', { label: 'Delete page', icon: TrashIcon, danger: true, action: () => doc.deletePage(id) }); items.push('separator', { label: 'Delete page', icon: TrashIcon, danger: true, action: () => doc.deletePage(id) });
menu.show(x, y, items); menu.show(x, y, items);
} }
@ -286,6 +307,9 @@
| { kind: 'erase'; pointerId: number; pointerType: string; hits: Map<string, Set<string>> } | { kind: 'erase'; pointerId: number; pointerType: string; hits: Map<string, Set<string>> }
| { kind: 'pan'; pointerId: number; pointerType: string; lastX: number; lastY: number; startX: number; startY: number; moved: boolean; tap: boolean; trail: Sample[] } | { kind: 'pan'; pointerId: number; pointerType: string; lastX: number; lastY: number; startX: number; startY: number; moved: boolean; tap: boolean; trail: Sample[] }
| { kind: 'add'; pointerId: number; pointerType: string; startX: number; startY: number; slot: Slot } | { kind: 'add'; pointerId: number; pointerType: string; startX: number; startY: number; slot: Slot }
| { kind: 'lasso'; pointerId: number; pointerType: string; pageId: string; points: number[]; additive: boolean; startX: number; startY: number; far: boolean }
| { kind: 'move'; pointerId: number; pointerType: string; pageId: string; startX: number; startY: number }
| { kind: 'resize'; pointerId: number; pointerType: string; pageId: string; ax: number; ay: number; cx: number; cy: number; minK: number }
| { kind: 'pinch' }; | { kind: 'pinch' };
let gesture: Gesture | null = null; let gesture: Gesture | null = null;
@ -298,6 +322,10 @@
let tick = $state(0); let tick = $state(0);
let erasing = $state.raw<Set<string>>(new Set()); let erasing = $state.raw<Set<string>>(new Set());
let eraserAt = $state<{ x: number; y: number } | null>(null); let eraserAt = $state<{ x: number; y: number } | null>(null);
/** Last pointer position over the stage (stage-local), where pastes land. */
let pointerAt: { x: number; y: number } | null = null;
/** When the pen's barrel button was last pressed; its context menu is suppressed. */
let penButtonAt = 0;
function local(e: PointerEvent | MouseEvent) { function local(e: PointerEvent | MouseEvent) {
const r = stage.getBoundingClientRect(); const r = stage.getBoundingClientRect();
@ -329,6 +357,227 @@
} }
const isEraserButton = (e: PointerEvent) => e.pointerType === 'pen' && (e.button === 5 || (e.buttons & 32) !== 0); const isEraserButton = (e: PointerEvent) => e.pointerType === 'pen' && (e.button === 5 || (e.buttons & 32) !== 0);
const isBarrelButton = (e: PointerEvent) => e.pointerType === 'pen' && (e.button === 2 || (e.buttons & 2) !== 0);
const isSelectButton = (e: PointerEvent) => settings.data.penButtonSelect && isBarrelButton(e);
// ---- selection -------------------------------------------------------
interface Selection {
pageId: string;
strokes: Set<string>;
images: Set<string>;
}
let selection = $state.raw<Selection | null>(null);
/** Transform of the selection while it is dragged or resized (committed on release). */
let selPreview = $state.raw<Transform | null>(null);
/** Lasso being drawn, in page-local points. */
let lasso = $state.raw<{ pageId: string; points: number[] } | null>(null);
const selected = $derived.by(() => {
const sel = selection;
const page = sel && doc.pages[sel.pageId];
if (!sel || !page) return null;
const strokes = page.strokes.filter((x) => sel.strokes.has(x.id));
const images = page.images.filter((x) => sel.images.has(x.id));
const box = objectsBounds(strokes, images);
return box ? { pageId: sel.pageId, strokes, images, box } : null;
});
const moving = $derived(
selection && selPreview ? { pageId: selection.pageId, ids: new Set([...selection.strokes, ...selection.images]), t: selPreview } : null
);
/** Selection box in world coordinates, following a drag/resize in progress. */
const selRect = $derived.by((): Rect | null => {
const r = selected && doc.rects.get(selected.pageId);
if (!selected || !r) return null;
const t = selPreview ?? IDENTITY;
const b = selected.box;
const pad = 6 / viewport.scale;
const x1 = b.x1 * t.k + t.tx;
const y1 = b.y1 * t.k + t.ty;
return { x: r.x + x1 - pad, y: r.y + y1 - pad, width: (b.x2 - b.x1) * t.k + 2 * pad, height: (b.y2 - b.y1) * t.k + 2 * pad };
});
/** Action bar above the selection (below it when there's no room), in screen coordinates. */
const selBar = $derived.by(() => {
if (!selRect || selPreview) return null;
const top = viewport.toScreen(selRect.x + selRect.width / 2, selRect.y);
const bottom = viewport.toScreen(selRect.x, selRect.y + selRect.height);
const x = Math.min(Math.max(top.x, 140), viewport.width - 140);
return top.y > 56 ? { x, y: top.y - 48 } : { x, y: Math.min(bottom.y + 8, viewport.height - 110) };
});
const CORNERS = ['nw', 'ne', 'se', 'sw'] as const;
// Switching tools drops the selection.
$effect(() => {
void tools.tool;
untrack(() => clearSelection());
});
function clearSelection() {
selection = null;
selPreview = null;
}
function select(pageId: string, strokes: string[], images: string[]) {
selection = strokes.length || images.length ? { pageId, strokes: new Set(strokes), images: new Set(images) } : null;
}
function commitTransform(t: Transform) {
const sel = selection;
if (!sel) return;
doc.setObjects(sel.pageId, (o) => ({
strokes: o.strokes.map((x) => (sel.strokes.has(x.id) ? transformStroke(x, t) : x)),
images: o.images.map((x) => (sel.images.has(x.id) ? transformImage(x, t) : x))
}));
}
function deleteSelection() {
const sel = selection;
if (!sel) return;
doc.setObjects(sel.pageId, (o) => ({
strokes: o.strokes.filter((x) => !sel.strokes.has(x.id)),
images: o.images.filter((x) => !sel.images.has(x.id))
}));
clearSelection();
}
function recolor(color: string) {
const sel = selection;
if (!sel) return;
doc.setObjects(sel.pageId, (o) => ({
strokes: o.strokes.map((x) => (sel.strokes.has(x.id) && x.color !== color ? { ...x, color } : x)),
images: o.images
}));
}
/** Add objects to a page as one undo step and select them. */
function addObjects(pageId: string, objs: { strokes: Stroke[]; images: PageImage[] }) {
doc.setObjects(pageId, (o) => ({ strokes: [...o.strokes, ...objs.strokes], images: [...o.images, ...objs.images] }));
doc.activeId = pageId;
select(pageId, objs.strokes.map((x) => x.id), objs.images.map((x) => x.id));
}
// ---- clipboard -------------------------------------------------------
// Copies keep a vector copy here and put a PNG on the system clipboard. Pasting prefers the
// vector copy while it is fresh: until the window loses focus or something else is copied.
let clip: Clip | null = null;
let clipFresh = false;
function copySelection() {
if (!selected) return false;
clip = makeClip(selected.strokes, selected.images);
clipFresh = true;
const c = clip;
if (c && navigator.clipboard?.write && typeof ClipboardItem !== 'undefined') {
// A promise inside the ClipboardItem keeps the user gesture alive while rendering (Safari).
const png = renderClipPng(c, (id) => assets.url(id));
navigator.clipboard.write([new ClipboardItem({ 'image/png': png })]).catch((err) => console.warn('Clipboard write failed', err));
}
return true;
}
function duplicateSelection() {
if (!selected) return;
const c = makeClip(selected.strokes, selected.images);
if (c) addObjects(selected.pageId, instantiate(c, selected.box.x1 + 12, selected.box.y1 + 12));
}
/** Where a paste lands: the pointer if it's over a page, else the middle of the visible part of the active page. */
function pasteTarget(at?: { x: number; y: number } | null) {
const p = at ?? pointerAt;
const over = p && pageAt(p.x, p.y);
if (p && over) return { pageId: over, ...pagePoint(over, p.x, p.y) };
const id = doc.activeId;
const r = id && doc.rects.get(id);
if (!id || !r) return null;
const w = viewport.world;
const x1 = Math.max(r.x, w.x), x2 = Math.min(r.x + r.width, w.x + w.width);
const y1 = Math.max(r.y, w.y), y2 = Math.min(r.y + r.height, w.y + w.height);
const cx = x2 > x1 ? (x1 + x2) / 2 : r.x + r.width / 2;
const cy = y2 > y1 ? (y1 + y2) / 2 : r.y + r.height / 2;
return { pageId: id, x: cx - r.x, y: cy - r.y };
}
function pasteClip(at?: { x: number; y: number } | null) {
const t = clip && pasteTarget(at);
const page = t && doc.pages[t.pageId];
if (!clip || !t || !page) return;
const pos = placeCentred(t.x, t.y, clip, page);
addObjects(t.pageId, instantiate(clip, pos.x, pos.y));
}
async function insertImages(files: Blob[], at?: { x: number; y: number } | null) {
const t = pasteTarget(at);
const page = t && doc.pages[t.pageId];
if (!t || !page) return;
const placed: PageImage[] = [];
for (const [i, f] of files.entries()) {
try {
const a = await assets.add(f);
if (a.bytes > 5_000_000) workspace.toast(`That image is ${(a.bytes / 1e6).toFixed(1)} MB; it will make the canvas file large`);
const size = imageSize(a, page);
const pos = placeCentred(t.x + i * 16, t.y + i * 16, size, page);
placed.push({ id: newId(), assetId: a.id, ...pos, ...size });
} catch (err) {
console.error(err);
workspace.toast(`Could not read ${f instanceof File ? f.name : 'that image'}`, 'error');
}
}
if (placed.length) addObjects(t.pageId, { strokes: [], images: placed });
}
async function pasteFromMenu(at?: { x: number; y: number }) {
if (clip && clipFresh) return pasteClip(at);
try {
for (const item of await navigator.clipboard.read()) {
const type = item.types.find((t) => t.startsWith('image/'));
if (type) return void (await insertImages([await item.getType(type)], at));
}
} catch {
/* no permission or no clipboard API */
}
if (clip) pasteClip(at);
else workspace.toast('No image or selection to paste');
}
function onPaste(e: ClipboardEvent) {
if (workspace.settingsOpen || sizing) return;
const dt = e.clipboardData;
const images = dt
? [...dt.items].filter((i) => i.kind === 'file' && i.type.startsWith('image/')).map((i) => i.getAsFile()).filter((f): f is File => !!f)
: [];
const inText = editable(e.target);
// Text goes to the editor; an image on its own is placed on the page.
if (inText && (!images.length || dt?.getData('text/plain'))) return;
if (clip && (clipFresh || (!images.length && !inText))) {
e.preventDefault();
return pasteClip();
}
if (images.length) {
e.preventDefault();
void insertImages(images);
}
}
function onDragOver(e: DragEvent) {
if (e.dataTransfer?.types.includes('Files')) e.preventDefault();
}
function onDrop(e: DragEvent) {
const files = [...(e.dataTransfer?.files ?? [])].filter((f) => f.type.startsWith('image/'));
if (!files.length) return;
e.preventDefault();
void insertImages(files, local(e));
}
function lassoPath(pts: number[]) {
let d = '';
for (let i = 0; i < pts.length; i += 2) d += `${i ? 'L' : 'M'}${pts[i].toFixed(1)},${pts[i + 1].toFixed(1)}`;
return d + 'Z';
}
function onPointerDown(e: PointerEvent) { function onPointerDown(e: PointerEvent) {
palm.track(e); palm.track(e);
@ -337,14 +586,18 @@
const target = e.target as Element; const target = e.target as Element;
if (target.closest('.no-stage')) return; if (target.closest('.no-stage')) return;
const p = local(e); const p = local(e);
pointerAt = p;
if (isBarrelButton(e)) penButtonAt = Date.now();
// Fingers ink only when enabled and no pen has been used; otherwise they pan/zoom. // Fingers ink only when enabled and no pen has been used; otherwise they pan/zoom.
const fingerInks = tools.inking && settings.data.fingerDraw && !palm.penSeen; const fingerInks = tools.inking && settings.data.fingerDraw && !palm.penSeen;
// Taps on an add-page button are palm-checked like navigation: still rejected for // Taps on an add-page button are palm-checked like navigation: still rejected for
// pen-down, palm-sized contacts and right after pen use, but not for the 5 s pen session. // pen-down, palm-sized contacts and right after pen use, but not for the 5 s pen session.
const plus = target.closest<HTMLElement>('.ghost, .offer-pill'); const plus = target.closest<HTMLElement>('.ghost, .offer-pill');
// The selection box and its handles are palm-checked like navigation too, so a finger can move it.
const selPart = selected ? target.closest<HTMLElement>('.sel-box, .sel-handle') : null;
if (e.pointerType === 'touch') { if (e.pointerType === 'touch') {
const decision = palm.evaluate(e, touchIntent(fingerInks, !!plus)); const decision = palm.evaluate(e, touchIntent(fingerInks, !!plus || !!selPart));
if (!decision.accept) return; // palm: ignore entirely if (!decision.accept) return; // palm: ignore entirely
touches.set(e.pointerId, p); touches.set(e.pointerId, p);
if (touches.size >= 2) { if (touches.size >= 2) {
@ -363,6 +616,26 @@
return; return;
} }
if (selPart && selected && (e.pointerType !== 'mouse' || e.button === 0) && !isEraserButton(e)) {
e.preventDefault();
capture(e.pointerId);
const { pageId, box: b } = selected;
const corner = selPart.dataset.corner;
const base = { pointerId: e.pointerId, pointerType: e.pointerType, pageId };
if (corner) {
// Uniform scale about the opposite corner.
const east = corner.includes('e');
const south = corner.includes('s');
const minK = 8 / Math.max(b.x2 - b.x1, b.y2 - b.y1, 1);
gesture = { kind: 'resize', ...base, ax: east ? b.x1 : b.x2, ay: south ? b.y1 : b.y2, cx: east ? b.x2 : b.x1, cy: south ? b.y2 : b.y1, minK };
} else {
const pt = pagePoint(pageId, p.x, p.y);
gesture = { kind: 'move', ...base, startX: pt.x, startY: pt.y };
}
selPreview = IDENTITY;
return;
}
const onPage = pageAt(p.x, p.y); const onPage = pageAt(p.x, p.y);
const inEditor = !!target.closest('.cm-editor'); const inEditor = !!target.closest('.cm-editor');
// Pressing anywhere outside the text leaves the editor (preventDefault // Pressing anywhere outside the text leaves the editor (preventDefault
@ -400,6 +673,18 @@
if (e.button !== 0 && e.pointerType === 'mouse') return; if (e.button !== 0 && e.pointerType === 'mouse') return;
const eraser = tools.tool === 'eraser' || isEraserButton(e); const eraser = tools.tool === 'eraser' || isEraserButton(e);
const lassoing = !eraser && (tools.tool === 'select' || isSelectButton(e));
// Pressing anywhere else drops the selection; Shift+lasso adds to it.
if (selection && !(lassoing && e.shiftKey)) clearSelection();
if (lassoing && onPage) {
e.preventDefault();
capture(e.pointerId);
const pt = pagePoint(onPage, p.x, p.y);
const points = [pt.x, pt.y];
gesture = { kind: 'lasso', pointerId: e.pointerId, pointerType: e.pointerType, pageId: onPage, points, additive: e.shiftKey, startX: p.x, startY: p.y, far: false };
lasso = { pageId: onPage, points };
return;
}
if ((tools.inking || isEraserButton(e)) && onPage) { if ((tools.inking || isEraserButton(e)) && onPage) {
e.preventDefault(); e.preventDefault();
capture(e.pointerId); capture(e.pointerId);
@ -422,6 +707,7 @@
function onPointerMove(e: PointerEvent) { function onPointerMove(e: PointerEvent) {
palm.track(e); palm.track(e);
const p = local(e); const p = local(e);
pointerAt = p;
if (tools.tool === 'eraser' || isEraserButton(e)) eraserAt = p; if (tools.tool === 'eraser' || isEraserButton(e)) eraserAt = p;
if (e.pointerType === 'touch' && touches.has(e.pointerId)) { if (e.pointerType === 'touch' && touches.has(e.pointerId)) {
@ -453,7 +739,8 @@
// A touch stroke is cut off as soon as the palm policy rejects it // A touch stroke is cut off as soon as the palm policy rejects it
// (e.g. the pen just came into range). // (e.g. the pen just came into range).
if (gesture.pointerType === 'touch' && !palm.evaluate(e, gesture.kind === 'add' ? 'navigate' : 'draw').accept) { const navigating = gesture.kind === 'add' || gesture.kind === 'move' || gesture.kind === 'resize';
if (gesture.pointerType === 'touch' && !palm.evaluate(e, navigating ? 'navigate' : 'draw').accept) {
cancelGesture(); cancelGesture();
return; return;
} }
@ -469,6 +756,35 @@
return; return;
} }
if (gesture.kind === 'lasso') {
const g = gesture;
if (Math.hypot(p.x - g.startX, p.y - g.startY) > 6) g.far = true;
const events = typeof e.getCoalescedEvents === 'function' ? e.getCoalescedEvents() : [];
for (const ev of events.length ? events : [e]) {
const q = local(ev);
const pt = pagePoint(g.pageId, q.x, q.y);
g.points.push(Math.round(pt.x * 10) / 10, Math.round(pt.y * 10) / 10);
}
lasso = { pageId: g.pageId, points: g.points };
return;
}
if (gesture.kind === 'move') {
const pt = pagePoint(gesture.pageId, p.x, p.y);
selPreview = translate(pt.x - gesture.startX, pt.y - gesture.startY);
return;
}
if (gesture.kind === 'resize') {
const g = gesture;
const pt = pagePoint(g.pageId, p.x, p.y);
const vx = g.cx - g.ax;
const vy = g.cy - g.ay;
const k = ((pt.x - g.ax) * vx + (pt.y - g.ay) * vy) / (vx * vx + vy * vy || 1);
selPreview = scaleAbout(Math.max(g.minK, k), g.ax, g.ay);
return;
}
const events = typeof e.getCoalescedEvents === 'function' ? e.getCoalescedEvents() : []; const events = typeof e.getCoalescedEvents === 'function' ? e.getCoalescedEvents() : [];
for (const ev of events.length ? events : [e]) { for (const ev of events.length ? events : [e]) {
const q = local(ev); const q = local(ev);
@ -491,7 +807,27 @@
if (!gesture || gesture.pointerId !== e.pointerId) return; if (!gesture || gesture.pointerId !== e.pointerId) return;
const g = gesture; const g = gesture;
gesture = null; gesture = null;
if (g.kind === 'pan') { if (isBarrelButton(e)) penButtonAt = Date.now();
if (g.kind === 'lasso') {
lasso = null;
const page = doc.pages[g.pageId];
if (e.type !== 'pointerup' || !page) return;
let hit: { strokes: string[]; images: string[] };
if (g.far) hit = lassoSelect(page.strokes, page.images, g.points);
else {
// A tap picks the object under it.
const q = local(e);
const pt = pagePoint(g.pageId, q.x, q.y);
const o = hitObject(page.strokes, page.images, pt.x, pt.y, 6 / viewport.scale);
hit = { strokes: o?.kind === 'stroke' ? [o.id] : [], images: o?.kind === 'image' ? [o.id] : [] };
}
const prev = g.additive && selection?.pageId === g.pageId ? selection : null;
select(g.pageId, [...(prev?.strokes ?? []), ...hit.strokes], [...(prev?.images ?? []), ...hit.images]);
} else if (g.kind === 'move' || g.kind === 'resize') {
const t = selPreview;
selPreview = null;
if (e.type === 'pointerup' && t && (t.k !== 1 || t.tx || t.ty)) commitTransform(t);
} else if (g.kind === 'pan') {
if (e.type === 'pointerup' && g.moved && g.pointerType === 'touch') { if (e.type === 'pointerup' && g.moved && g.pointerType === 'touch') {
pushSample(g.trail, { ...local(e), t: e.timeStamp }); pushSample(g.trail, { ...local(e), t: e.timeStamp });
offerAfterFling(g.trail); offerAfterFling(g.trail);
@ -511,6 +847,8 @@
function cancelGesture() { function cancelGesture() {
if (gesture?.kind === 'draw') live = null; if (gesture?.kind === 'draw') live = null;
if (gesture?.kind === 'erase') erasing = new Set(); if (gesture?.kind === 'erase') erasing = new Set();
if (gesture?.kind === 'lasso') lasso = null;
if (gesture?.kind === 'move' || gesture?.kind === 'resize') selPreview = null;
gesture = null; gesture = null;
} }
@ -553,11 +891,14 @@
} }
function onContextMenu(e: MouseEvent) { function onContextMenu(e: MouseEvent) {
// The pen's barrel button lassoes; it shouldn't also open a menu.
const pen = (e as PointerEvent).pointerType === 'pen' || Date.now() - penButtonAt < 1000;
if (pen && settings.data.penButtonSelect) return void e.preventDefault();
if ((e.target as Element).closest('.cm-editor') && !tools.inking) return; // native menu for text if ((e.target as Element).closest('.cm-editor') && !tools.inking) return; // native menu for text
e.preventDefault(); e.preventDefault();
const p = local(e); const p = local(e);
const id = pageAt(p.x, p.y); const id = pageAt(p.x, p.y);
if (id) pageMenu(e.clientX, e.clientY, id); if (id) pageMenu(e.clientX, e.clientY, id, p);
} }
// ---- keyboard -------------------------------------------------------- // ---- keyboard --------------------------------------------------------
@ -578,6 +919,27 @@
if (editable(e.target)) return; if (editable(e.target)) return;
if (selected) {
if (e.key === 'Escape') return clearSelection();
if (e.key === 'Delete' || e.key === 'Backspace') return void (e.preventDefault(), deleteSelection());
if (mod && k === 'c') return void (e.preventDefault(), copySelection());
if (mod && k === 'x') return void (e.preventDefault(), copySelection() && deleteSelection());
if (mod && k === 'd') return void (e.preventDefault(), duplicateSelection());
if (!mod && !e.altKey && e.key.startsWith('Arrow')) {
e.preventDefault();
const step = e.shiftKey ? 10 : 1;
const d = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[e.key];
if (d) commitTransform(translate(d[0], d[1]));
return;
}
}
if (mod && k === 'a' && tools.tool === 'select' && doc.activeId) {
e.preventDefault();
const page = doc.pages[doc.activeId];
if (page) select(page.id, page.strokes.map((x) => x.id), page.images.map((x) => x.id));
return;
}
if (mod && k === 'z' && !e.shiftKey) return void (e.preventDefault(), doc.undo()); 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 (mod && ((k === 'z' && e.shiftKey) || k === 'y')) return void (e.preventDefault(), doc.redo());
if (e.key === 'Escape') { if (e.key === 'Escape') {
@ -595,7 +957,7 @@
return; return;
} }
if (mod || e.altKey) return; if (mod || e.altKey) return;
const shortcuts: Record<string, typeof tools.tool> = { t: 'text', p: 'pen', h: 'highlighter', e: 'eraser' }; const shortcuts: Record<string, typeof tools.tool> = { t: 'text', s: 'select', p: 'pen', h: 'highlighter', e: 'eraser' };
if (shortcuts[k]) tools.tool = shortcuts[k]; if (shortcuts[k]) tools.tool = shortcuts[k];
} }
@ -606,7 +968,16 @@
const panning = $derived(spaceDown); const panning = $derived(spaceDown);
</script> </script>
<svelte:window onkeydown={onKeyDown} onkeyup={onKeyUp} onblur={() => (spaceDown = false)} /> <svelte:window
onkeydown={onKeyDown}
onkeyup={onKeyUp}
onblur={() => {
spaceDown = false;
clipFresh = false;
}}
oncopy={() => (clipFresh = false)}
onpaste={onPaste}
/>
<div class="view"> <div class="view">
<header class="titlebar"> <header class="titlebar">
@ -625,6 +996,7 @@
class:inking={tools.inking} class:inking={tools.inking}
class:panning class:panning
class:erasing={tools.tool === 'eraser'} class:erasing={tools.tool === 'eraser'}
class:moving={!!selPreview}
bind:this={stage} bind:this={stage}
style={gridStyle} style={gridStyle}
onpointerdown={onPointerDown} onpointerdown={onPointerDown}
@ -636,6 +1008,8 @@
eraserAt = null; eraserAt = null;
}} }}
oncontextmenu={onContextMenu} oncontextmenu={onContextMenu}
ondragover={onDragOver}
ondrop={onDrop}
> >
<div <div
class="world" class="world"
@ -654,12 +1028,31 @@
live={live?.pageId === id ? live.stroke : null} live={live?.pageId === id ? live.stroke : null}
{tick} {tick}
{erasing} {erasing}
moving={moving?.pageId === id ? moving : null}
onchange={() => doc.touch()} onchange={() => doc.touch()}
onactivate={() => (doc.activeId = id)} onactivate={() => (doc.activeId = id)}
/> />
{/if} {/if}
{/each} {/each}
{#if lasso && doc.rects.get(lasso.pageId)}
{@const r = doc.rects.get(lasso.pageId)!}
<svg class="lasso" style="left:{r.x}px; top:{r.y}px; width:{r.width}px; height:{r.height}px" viewBox="0 0 {r.width} {r.height}">
<path d={lassoPath(lasso.points)} />
</svg>
{/if}
{#if selRect}
<div class="sel-box" style="left:{selRect.x}px; top:{selRect.y}px; width:{selRect.width}px; height:{selRect.height}px"></div>
{#each CORNERS as c (c)}
<div
class="sel-handle"
data-corner={c}
style="left:{c.includes('e') ? selRect.x + selRect.width : selRect.x}px; top:{c.includes('s') ? selRect.y + selRect.height : selRect.y}px"
></div>
{/each}
{/if}
{#each ghostSlots as slot (slot.anchor + slot.dir)} {#each ghostSlots as slot (slot.anchor + slot.dir)}
{@const r = plusRect(slot)} {@const r = plusRect(slot)}
{#if r} {#if r}
@ -725,6 +1118,21 @@
</button> </button>
{/if} {/if}
{#if selBar && selected}
<div class="sel-bar no-stage" style="left:{selBar.x}px; top:{selBar.y}px" role="toolbar" aria-label="Selection">
<button class="icon-btn" title="Copy (Ctrl+C)" onclick={copySelection}><CopyIcon size={16} strokeWidth={1.75} /></button>
<button class="icon-btn" title="Cut (Ctrl+X)" onclick={() => copySelection() && deleteSelection()}><ScissorsIcon size={16} strokeWidth={1.75} /></button>
<button class="icon-btn" title="Duplicate (Ctrl+D)" onclick={duplicateSelection}><CopyPlusIcon size={16} strokeWidth={1.75} /></button>
<button class="icon-btn" title="Delete (Del)" onclick={deleteSelection}><TrashIcon size={16} strokeWidth={1.75} /></button>
{#if selected.strokes.length}
<span class="sep"></span>
{#each settings.data.penColors as c (c)}
<button class="swatch" style="--c: {c}" title="Recolour ink {c}" aria-label="Recolour ink {c}" onclick={() => recolor(c)}></button>
{/each}
{/if}
</div>
{/if}
{#if eraserAt && tools.tool === 'eraser'} {#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> <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}
@ -750,7 +1158,7 @@
/> />
{/if} {/if}
<Toolbar {doc} onfit={() => fitPage(doc.activeId)} onfitall={fitAll} /> <Toolbar {doc} onfit={() => fitPage(doc.activeId)} onfitall={fitAll} onimages={(files) => void insertImages(files)} />
</div> </div>
<style> <style>
@ -935,6 +1343,82 @@
background: var(--bg); background: var(--bg);
box-shadow: var(--shadow); box-shadow: var(--shadow);
} }
.lasso {
position: absolute;
overflow: visible;
pointer-events: none;
}
.lasso path {
fill: color-mix(in srgb, var(--accent) 8%, transparent);
stroke: var(--accent);
stroke-width: 1.25px;
stroke-dasharray: 5 4;
vector-effect: non-scaling-stroke;
}
.sel-box {
position: absolute;
border: calc(1.25px / var(--s)) dashed var(--accent);
border-radius: calc(3px / var(--s));
background: color-mix(in srgb, var(--accent) 5%, transparent);
cursor: move;
}
.sel-handle {
position: absolute;
/* 24 px touch target around a 10 px square. */
width: calc(24px / var(--s));
height: calc(24px / var(--s));
transform: translate(-50%, -50%);
cursor: nwse-resize;
}
.sel-handle[data-corner='ne'],
.sel-handle[data-corner='sw'] {
cursor: nesw-resize;
}
.sel-handle::after {
content: '';
position: absolute;
inset: calc(7px / var(--s));
background: var(--bg);
border: calc(1.5px / var(--s)) solid var(--accent);
border-radius: calc(2px / var(--s));
}
.stage.moving {
cursor: move;
}
.sel-bar {
position: absolute;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 2px;
padding: 3px;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 8px;
box-shadow: var(--shadow);
white-space: nowrap;
}
.sel-bar .icon-btn {
width: 30px;
height: 30px;
}
.sel-bar .sep {
width: 1px;
height: 18px;
background: var(--border);
margin: 0 3px;
}
.sel-bar .swatch {
width: 20px;
height: 20px;
margin: 0 1px;
padding: 0;
border-radius: 50%;
border: 0;
background: var(--c);
box-shadow: inset 0 0 0 1px rgba(128, 128, 128, 0.35);
cursor: pointer;
}
.eraser-ring { .eraser-ring {
position: absolute; position: absolute;
transform: translate(-50%, -50%); transform: translate(-50%, -50%);

View file

@ -0,0 +1,52 @@
<script lang="ts">
import { transformImage, type Transform } from '$lib/ink/select';
import type { PageImage } from '$lib/model/types';
import { assets } from '$lib/images/assets.svelte';
interface Props {
width: number;
height: number;
images: PageImage[];
/** Selected objects being dragged or resized, shown transformed until release. */
moving?: { ids: Set<string>; t: Transform } | null;
}
let { width, height, images, moving = null }: Props = $props();
const pct = (v: number, of: number) => `${(v / of) * 100}%`;
</script>
{#if images.length}
<div class="images" aria-hidden="true">
{#each images as img (img.id)}
{@const m = moving?.ids.has(img.id) ? transformImage(img, moving.t) : img}
{@const url = assets.url(img.assetId)}
<div
class="img"
style="left:{pct(m.x, width)}; top:{pct(m.y, height)}; width:{pct(m.width, width)}; height:{pct(m.height, height)}"
>
{#if url}<img src={url} alt="" draggable="false" />{/if}
</div>
{/each}
</div>
{/if}
<style>
.images {
position: absolute;
inset: 0;
pointer-events: none;
}
.img {
position: absolute;
background: color-mix(in srgb, currentColor 6%, transparent);
}
.img:has(img) {
background: none;
}
img {
display: block;
width: 100%;
height: 100%;
}
</style>

View file

@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import { svgPath, HIGHLIGHTER_OPACITY } from '$lib/ink/stroke'; import { svgPath, HIGHLIGHTER_OPACITY } from '$lib/ink/stroke';
import { matrix, type Transform } from '$lib/ink/select';
import type { Stroke } from '$lib/model/types'; import type { Stroke } from '$lib/model/types';
interface Props { interface Props {
@ -11,9 +12,11 @@
tick?: number; tick?: number;
/** Strokes hidden while an eraser gesture is in progress. */ /** Strokes hidden while an eraser gesture is in progress. */
erasing?: Set<string>; erasing?: Set<string>;
/** Selected objects being dragged or resized, shown transformed until release. */
moving?: { ids: Set<string>; t: Transform } | null;
} }
let { width, height, strokes, live = null, tick = 0, erasing }: Props = $props(); let { width, height, strokes, live = null, tick = 0, erasing, moving = null }: Props = $props();
const livePath = $derived.by(() => { const livePath = $derived.by(() => {
void tick; void tick;
@ -29,6 +32,7 @@
fill={s.color} fill={s.color}
fill-opacity={s.tool === 'highlighter' ? HIGHLIGHTER_OPACITY : 1} fill-opacity={s.tool === 'highlighter' ? HIGHLIGHTER_OPACITY : 1}
class:hl={s.tool === 'highlighter'} class:hl={s.tool === 'highlighter'}
transform={moving?.ids.has(s.id) ? matrix(moving.t) : undefined}
/> />
{/if} {/if}
{/each} {/each}

View file

@ -5,6 +5,8 @@
import MarkdownEditor from './MarkdownEditor.svelte'; import MarkdownEditor from './MarkdownEditor.svelte';
import PdfBackground from './PdfBackground.svelte'; import PdfBackground from './PdfBackground.svelte';
import InkLayer from './InkLayer.svelte'; import InkLayer from './InkLayer.svelte';
import ImageLayer from './ImageLayer.svelte';
import type { Transform } from '$lib/ink/select';
interface Props { interface Props {
page: PageModel; page: PageModel;
@ -15,11 +17,12 @@
live: Stroke | null; live: Stroke | null;
tick: number; tick: number;
erasing: Set<string>; erasing: Set<string>;
moving: { ids: Set<string>; t: Transform } | null;
onchange: () => void; onchange: () => void;
onactivate: () => void; onactivate: () => void;
} }
let { page, rect, active, invert, scale, live, tick, erasing, onchange, onactivate }: Props = $props(); let { page, rect, active, invert, scale, live, tick, erasing, moving, onchange, onactivate }: Props = $props();
</script> </script>
<div <div
@ -33,7 +36,8 @@
<PdfBackground origin={page.origin} width={page.width} height={page.height} {scale} /> <PdfBackground origin={page.origin} width={page.width} height={page.height} {scale} />
{/if} {/if}
<MarkdownEditor {page} {onchange} onfocus={onactivate} /> <MarkdownEditor {page} {onchange} onfocus={onactivate} />
<InkLayer width={page.width} height={page.height} strokes={page.strokes} {live} {tick} {erasing} /> <ImageLayer width={page.width} height={page.height} images={page.images} {moving} />
<InkLayer width={page.width} height={page.height} strokes={page.strokes} {live} {tick} {erasing} {moving} />
</div> </div>
{#if page.origin && active} {#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> <div class="origin" style="font-size:{11 / scale}px; top:{-18 / scale}px">{page.origin.name} · p. {page.origin.pageIndex + 1}</div>
@ -52,9 +56,18 @@
/* Crisp 1 screen-px outline, no blur. */ /* Crisp 1 screen-px outline, no blur. */
box-shadow: 0 0 0 calc(1px / var(--s)) var(--page-line); box-shadow: 0 0 0 calc(1px / var(--s)) var(--page-line);
} }
/* Dark pages: every layer but pasted images is colour-inverted, so images keep their colours.
The background is what white becomes under the filter. */
.paper.invert { .paper.invert {
background: #1f1f1f;
}
.paper.invert > :global(:not(.images)) {
filter: invert(0.88) hue-rotate(180deg); filter: invert(0.88) hue-rotate(180deg);
} }
/* Highlighter multiplies against the text in light mode; inverted, that is roughly a screen. */
.paper.invert > :global(.ink) {
mix-blend-mode: screen;
}
.page.active::after { .page.active::after {
content: ''; content: '';
position: absolute; position: absolute;

View file

@ -107,6 +107,10 @@
<div><div class="name">Swipe to add pages</div><div class="desc">A quick one-finger flick toward a free side of the active page offers to add a page there.</div></div> <div><div class="name">Swipe to add pages</div><div class="desc">A quick one-finger flick toward a free side of the active page offers to add a page there.</div></div>
<input type="checkbox" class="toggle" bind:checked={s.flingToAdd} onchange={save} /> <input type="checkbox" class="toggle" bind:checked={s.flingToAdd} onchange={save} />
</div> </div>
<div class="row">
<div><div class="name">Pen button selects</div><div class="desc">Hold the button on the side of the pen and draw a loop to select, whatever tool is active.</div></div>
<input type="checkbox" class="toggle" bind:checked={s.penButtonSelect} onchange={save} />
</div>
<h3>Palm rejection</h3> <h3>Palm rejection</h3>
<div class="row"> <div class="row">
<div><div class="name">Pen session lockout</div><div class="desc">Ignore touches while the pen is writing, and finger ink for 5 seconds after it was used.</div></div> <div><div class="name">Pen session lockout</div><div class="desc">Ignore touches while the pen is writing, and finger ink for 5 seconds after it was used.</div></div>

View file

@ -1,5 +1,7 @@
<script lang="ts"> <script lang="ts">
import TypeIcon from '@lucide/svelte/icons/type'; import TypeIcon from '@lucide/svelte/icons/type';
import LassoIcon from '@lucide/svelte/icons/lasso-select';
import ImagePlusIcon from '@lucide/svelte/icons/image-plus';
import PenIcon from '@lucide/svelte/icons/pen-line'; import PenIcon from '@lucide/svelte/icons/pen-line';
import HighlighterIcon from '@lucide/svelte/icons/highlighter'; import HighlighterIcon from '@lucide/svelte/icons/highlighter';
import EraserIcon from '@lucide/svelte/icons/eraser'; import EraserIcon from '@lucide/svelte/icons/eraser';
@ -18,13 +20,23 @@
import { vault } from '$lib/storage/vault.svelte'; import { vault } from '$lib/storage/vault.svelte';
import { pagesFromPdf } from '$lib/pdf/read'; import { pagesFromPdf } from '$lib/pdf/read';
let { doc, onfit, onfitall }: { doc: CanvasDoc; onfit: () => void; onfitall: () => void } = $props(); interface Props {
doc: CanvasDoc;
onfit: () => void;
onfitall: () => void;
/** Images picked with the "Insert image" button. */
onimages: (files: File[]) => void;
}
let { doc, onfit, onfitall, onimages }: Props = $props();
let fileInput: HTMLInputElement; let fileInput: HTMLInputElement;
let imageInput: HTMLInputElement;
let colorInput = $state<HTMLInputElement>(); let colorInput = $state<HTMLInputElement>();
const TOOLS: { id: Tool; label: string; key: string; icon: Component }[] = [ const TOOLS: { id: Tool; label: string; key: string; icon: Component }[] = [
{ id: 'text', label: 'Text', key: 'T', icon: TypeIcon }, { id: 'text', label: 'Text', key: 'T', icon: TypeIcon },
{ id: 'select', label: 'Select', key: 'S', icon: LassoIcon },
{ id: 'pen', label: 'Pen', key: 'P', icon: PenIcon }, { id: 'pen', label: 'Pen', key: 'P', icon: PenIcon },
{ id: 'highlighter', label: 'Highlighter', key: 'H', icon: HighlighterIcon }, { id: 'highlighter', label: 'Highlighter', key: 'H', icon: HighlighterIcon },
{ id: 'eraser', label: 'Eraser', key: 'E', icon: EraserIcon } { id: 'eraser', label: 'Eraser', key: 'E', icon: EraserIcon }
@ -106,6 +118,7 @@
<span class="sep"></span> <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="Import PDF" onclick={() => fileInput.click()}><FileUpIcon size={18} strokeWidth={1.75} /></button>
<button class="icon-btn" title="Insert image" onclick={() => imageInput.click()}><ImagePlusIcon 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="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> <button class="icon-btn" title="Redo (Ctrl+Shift+Z)" disabled={!doc.canRedo} onclick={() => doc.redo()}><RedoIcon size={18} strokeWidth={1.75} /></button>
@ -118,6 +131,18 @@
</div> </div>
<input bind:this={fileInput} type="file" accept="application/pdf,.pdf" hidden onchange={onFile} /> <input bind:this={fileInput} type="file" accept="application/pdf,.pdf" hidden onchange={onFile} />
<input
bind:this={imageInput}
type="file"
accept="image/*"
multiple
hidden
onchange={(e) => {
const files = [...(e.currentTarget.files ?? [])];
e.currentTarget.value = '';
if (files.length) onimages(files);
}}
/>
<style> <style>
.dock { .dock {

View file

@ -0,0 +1,40 @@
// Pasted images: storing them, and object URLs for showing them.
import { SvelteMap } from 'svelte/reactivity';
import { vault } from '$lib/storage/vault.svelte';
import { imageKind, sha256Hex } from '$lib/pdf/format';
import { prepareImage } from './normalize';
class Assets {
private urls = new SvelteMap<string, string>();
private loading = new Set<string>();
/** Object URL for an asset; undefined until its bytes are loaded (then reactive). */
url(id: string): string | undefined {
const u = this.urls.get(id);
if (u || this.loading.has(id)) return u;
this.loading.add(id);
void vault.getAsset(id).then((bytes) => {
if (bytes) this.prime(id, bytes);
else this.loading.delete(id);
});
return undefined;
}
private prime(id: string, bytes: Uint8Array) {
if (this.urls.has(id)) return;
const type = imageKind(bytes) === 'png' ? 'image/png' : 'image/jpeg';
this.urls.set(id, URL.createObjectURL(new Blob([bytes as BlobPart], { type })));
}
/** Normalise and store an image; returns its asset id and pixel size. */
async add(blob: Blob) {
const img = await prepareImage(blob);
const id = await sha256Hex(img.bytes);
await vault.putAsset(id, img.bytes);
this.prime(id, img.bytes);
return { id, width: img.width, height: img.height, bytes: img.bytes.length };
}
}
export const assets = new Assets();

View file

@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest';
import { imageKind } from '$lib/pdf/format';
import { candidateKinds, fitScale } from './normalize';
describe('image normalisation', () => {
it('caps the long edge', () => {
expect(fitScale(1200, 800)).toBe(1);
expect(fitScale(4800, 1200)).toBe(0.5);
expect(fitScale(1000, 9600)).toBe(0.25);
});
it('keeps transparency in PNG and JPEGs as JPEG', () => {
expect(candidateKinds('png', true)).toEqual(['png']);
expect(candidateKinds(null, true)).toEqual(['png']);
expect(candidateKinds('jpeg', false)).toEqual(['jpeg']);
expect(candidateKinds('png', false)).toEqual(['png', 'jpeg']);
expect(candidateKinds(null, false)).toEqual(['png', 'jpeg']); // e.g. WebP
});
it('sniffs PNG and JPEG', () => {
expect(imageKind(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 13, 10]))).toBe('png');
expect(imageKind(new Uint8Array([0xff, 0xd8, 0xff, 0xe0]))).toBe('jpeg');
expect(imageKind(new Uint8Array([0x52, 0x49, 0x46, 0x46]))).toBeNull(); // RIFF (WebP)
});
});

View file

@ -0,0 +1,75 @@
// Turn a pasted/dropped image into bytes a PDF can embed (PNG or JPEG), small
// enough to live in a git-synced canvas.
import { imageKind, type ImageKind } from '$lib/pdf/format';
/** Longest edge kept, in pixels. */
export const MAX_EDGE = 2400;
export const JPEG_QUALITY = 0.85;
export interface PreparedImage {
bytes: Uint8Array;
kind: ImageKind;
/** Pixel size of the stored image. */
width: number;
height: number;
}
export function fitScale(width: number, height: number, max = MAX_EDGE) {
return Math.min(1, max / Math.max(width, height));
}
/**
* Which encodings to try, given the source format and whether the pixels have transparency.
* JPEG sources stay JPEG; anything transparent must be PNG; other opaque images try both.
*/
export function candidateKinds(source: ImageKind | null, alpha: boolean): ImageKind[] {
if (alpha) return ['png'];
if (source === 'jpeg') return ['jpeg'];
return ['png', 'jpeg'];
}
export async function prepareImage(blob: Blob): Promise<PreparedImage> {
const original = new Uint8Array(await blob.arrayBuffer());
const source = imageKind(original);
// Applies EXIF orientation, so re-encoded JPEGs come out upright.
const bmp = await createImageBitmap(blob);
try {
const k = fitScale(bmp.width, bmp.height);
// A PNG that already fits is kept byte for byte.
if (k === 1 && source === 'png') return { bytes: original, kind: 'png', width: bmp.width, height: bmp.height };
const width = Math.max(1, Math.round(bmp.width * k));
const height = Math.max(1, Math.round(bmp.height * k));
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d', { willReadFrequently: true })!;
ctx.drawImage(bmp, 0, 0, width, height);
const alpha = source !== 'jpeg' && hasAlpha(ctx.getImageData(0, 0, width, height).data);
let best: { bytes: Uint8Array; kind: ImageKind } | null = null;
for (const kind of candidateKinds(source, alpha)) {
const bytes = await encode(canvas, kind);
if (!best || bytes.length < best.bytes.length) best = { bytes, kind };
}
return { ...best!, width, height };
} finally {
bmp.close();
}
}
function hasAlpha(px: Uint8ClampedArray) {
for (let i = 3; i < px.length; i += 4) if (px[i] < 255) return true;
return false;
}
function encode(canvas: HTMLCanvasElement, kind: ImageKind): Promise<Uint8Array> {
return new Promise((resolve, reject) =>
canvas.toBlob(
(b) => (b ? b.arrayBuffer().then((a) => resolve(new Uint8Array(a)), reject) : reject(new Error('encode failed'))),
kind === 'png' ? 'image/png' : 'image/jpeg',
JPEG_QUALITY
)
);
}

41
src/lib/images/png.ts Normal file
View file

@ -0,0 +1,41 @@
// Render page objects to a PNG, for the system clipboard.
import { HIGHLIGHTER_OPACITY, svgPath } from '$lib/ink/stroke';
import type { Clip } from '$lib/ink/clip';
/** Pixels per point: 2 = crisp on high-DPI screens and in other apps. */
const DENSITY = 2;
const MAX_PX = 4096;
export async function renderClipPng(clip: Clip, urlFor: (assetId: string) => string | undefined): Promise<Blob> {
const pad = 4;
const k = Math.min(DENSITY, MAX_PX / (clip.width + pad * 2), MAX_PX / (clip.height + pad * 2));
const canvas = document.createElement('canvas');
canvas.width = Math.max(1, Math.ceil((clip.width + pad * 2) * k));
canvas.height = Math.max(1, Math.ceil((clip.height + pad * 2) * k));
const ctx = canvas.getContext('2d')!;
ctx.scale(k, k);
ctx.translate(pad, pad);
for (const m of clip.images) {
const url = urlFor(m.assetId);
if (!url) continue;
const el = new Image();
el.src = url;
try {
await el.decode();
ctx.drawImage(el, m.x, m.y, m.width, m.height);
} catch {
/* skip an image that failed to load */
}
}
for (const s of clip.strokes) {
const hl = s.tool === 'highlighter';
ctx.globalAlpha = hl ? HIGHLIGHTER_OPACITY : 1;
ctx.globalCompositeOperation = hl ? 'multiply' : 'source-over';
ctx.fillStyle = s.color;
ctx.fill(new Path2D(svgPath(s)));
}
return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('encode failed'))), 'image/png'));
}

38
src/lib/ink/clip.test.ts Normal file
View file

@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest';
import type { PageImage, Stroke } from '$lib/model/types';
import { imageSize, instantiate, makeClip, placeCentred } from './clip';
const s: Stroke = { id: 's', tool: 'pen', color: '#000', width: 2, pressure: false, points: [110, 210, 0.5, 0, 0, 0, 150, 260, 0.5, 0, 0, 8] };
const img: PageImage = { id: 'i', assetId: 'a', x: 100, y: 200, width: 20, height: 10 };
const A4 = { width: 595.28, height: 841.89 };
describe('clip', () => {
it('normalises to the bounding box and pastes fresh copies', () => {
const clip = makeClip([s], [img])!;
expect(clip).toMatchObject({ width: 51, height: 61 });
expect(clip.images[0]).toMatchObject({ x: 0, y: 0 });
expect(clip.strokes[0].points.slice(0, 2)).toEqual([10, 10]);
const pasted = instantiate(clip, 300, 400);
expect(pasted.images[0]).toMatchObject({ x: 300, y: 400, assetId: 'a' });
expect(pasted.strokes[0].points.slice(6, 8)).toEqual([350, 460]);
expect(pasted.strokes[0].id).not.toBe('s');
expect(pasted.images[0].id).not.toBe('i');
expect(makeClip([], [])).toBeNull();
});
it('keeps pasted things on the page', () => {
expect(placeCentred(300, 400, { width: 100, height: 50 }, A4)).toEqual({ x: 250, y: 375 });
expect(placeCentred(10, 10, { width: 100, height: 50 }, A4)).toEqual({ x: 0, y: 0 });
expect(placeCentred(590, 840, { width: 100, height: 50 }, A4)).toEqual({ x: 495.28, y: 791.89 });
// Larger than the page: centred on it.
expect(placeCentred(0, 0, { width: 700, height: 50 }, A4).x).toBeCloseTo(-52.36);
});
it('sizes images at 96 dpi, at most 80 % of the page', () => {
expect(imageSize({ width: 400, height: 200 }, A4)).toEqual({ width: 300, height: 150 });
const big = imageSize({ width: 2400, height: 1200 }, A4);
expect(big.width).toBeCloseTo(476.22);
expect(big.height).toBeCloseTo(238.11);
});
});

52
src/lib/ink/clip.ts Normal file
View file

@ -0,0 +1,52 @@
// Copy/paste of page objects and placing new ones on a page.
import { newId, type PageImage, type Stroke } from '$lib/model/types';
import { objectsBounds, transformImage, transformStroke, translate } from './select';
/** Copied objects, moved so their bounding box starts at (0, 0). */
export interface Clip {
strokes: Stroke[];
images: PageImage[];
width: number;
height: number;
}
interface Size {
width: number;
height: number;
}
export function makeClip(strokes: Stroke[], images: PageImage[]): Clip | null {
const b = objectsBounds(strokes, images);
if (!b) return null;
const t = translate(-b.x1, -b.y1);
return {
strokes: strokes.map((s) => transformStroke(s, t)),
images: images.map((m) => transformImage(m, t)),
width: b.x2 - b.x1,
height: b.y2 - b.y1
};
}
/** Top-left for a box of `size` centred on (cx, cy), kept on the page where it fits. */
export function placeCentred(cx: number, cy: number, size: Size, page: Size) {
const clamp = (v: number, len: number, max: number) => (len >= max ? (max - len) / 2 : Math.min(Math.max(v, 0), max - len));
return { x: clamp(cx - size.width / 2, size.width, page.width), y: clamp(cy - size.height / 2, size.height, page.height) };
}
/** Fresh copies of a clip with its top-left at (x, y). */
export function instantiate(clip: Clip, x: number, y: number) {
const t = translate(x, y);
return {
strokes: clip.strokes.map((s) => ({ ...transformStroke(s, t), id: newId() })),
images: clip.images.map((m) => ({ ...transformImage(m, t), id: newId() }))
};
}
/** Size in points of a pasted image: 1 px = 0.75 pt (96 dpi), shrunk to 80 % of the page. */
export function imageSize(px: Size, page: Size): Size {
const w = px.width * 0.75;
const h = px.height * 0.75;
const k = Math.min(1, (page.width * 0.8) / w, (page.height * 0.8) / h);
return { width: Math.round(w * k * 100) / 100, height: Math.round(h * k * 100) / 100 };
}

View file

@ -0,0 +1,88 @@
import { describe, expect, it } from 'vitest';
import type { PageImage, Stroke } from '$lib/model/types';
import {
hitObject,
imageInLasso,
lassoSelect,
objectsBounds,
pointInPolygon,
scaleAbout,
strokeInLasso,
transformImage,
transformStroke,
translate
} from './select';
const square = [0, 0, 100, 0, 100, 100, 0, 100];
function stroke(id: string, xy: number[], width = 2): Stroke {
const points: number[] = [];
for (let i = 0; i < xy.length; i += 2) points.push(xy[i], xy[i + 1], 0.5, 0, 0, i * 8);
return { id, tool: 'pen', color: '#000', width, pressure: false, points };
}
const image = (id: string, x: number, y: number, w: number, h: number): PageImage => ({ id, assetId: 'a', x, y, width: w, height: h });
describe('lasso', () => {
it('tests points against the loop (even-odd)', () => {
expect(pointInPolygon(50, 50, square)).toBe(true);
expect(pointInPolygon(150, 50, square)).toBe(false);
// A "C" shape: the notch is outside.
const c = [0, 0, 100, 0, 100, 30, 30, 30, 30, 70, 100, 70, 100, 100, 0, 100];
expect(pointInPolygon(60, 50, c)).toBe(false);
expect(pointInPolygon(15, 50, c)).toBe(true);
});
it('selects a stroke only when all of it is inside', () => {
expect(strokeInLasso(stroke('in', [10, 10, 50, 50, 90, 20]), square)).toBe(true);
expect(strokeInLasso(stroke('out', [10, 10, 50, 50, 120, 20]), square)).toBe(false);
expect(strokeInLasso(stroke('in', [10, 10]), [0, 0, 100, 0])).toBe(false); // not a loop
});
it('selects an image only when all four corners are inside', () => {
expect(imageInLasso(image('i', 10, 10, 50, 50), square)).toBe(true);
expect(imageInLasso(image('i', 60, 60, 50, 50), square)).toBe(false);
});
it('returns the ids of everything fully inside', () => {
const sel = lassoSelect(
[stroke('a', [10, 10, 20, 20]), stroke('b', [10, 10, 200, 20])],
[image('x', 5, 5, 10, 10), image('y', 90, 90, 20, 20)],
square
);
expect(sel).toEqual({ strokes: ['a'], images: ['x'] });
});
});
describe('hit testing', () => {
it('prefers ink over images and later objects over earlier ones', () => {
const strokes = [stroke('a', [0, 50, 100, 50]), stroke('b', [0, 50, 100, 50])];
const images = [image('x', 0, 0, 100, 100)];
expect(hitObject(strokes, images, 50, 50, 3)).toEqual({ kind: 'stroke', id: 'b' });
expect(hitObject(strokes, images, 50, 10, 3)).toEqual({ kind: 'image', id: 'x' });
expect(hitObject(strokes, images, 150, 10, 3)).toBeNull();
});
});
describe('transforms', () => {
it('bounds strokes by their visible edge and images by their box', () => {
expect(objectsBounds([stroke('a', [10, 20, 30, 40], 4)], [image('x', 50, 0, 10, 10)])).toEqual({ x1: 8, y1: 0, x2: 60, y2: 42 });
expect(objectsBounds([], [])).toBeNull();
});
it('moves and scales strokes, keeping pressure/tilt/time', () => {
const s = stroke('a', [10, 10, 20, 30], 2);
const moved = transformStroke(s, translate(5, -5));
expect(moved.points).toEqual([15, 5, 0.5, 0, 0, 0, 25, 25, 0.5, 0, 0, 16]);
expect(moved.id).toBe('a');
const scaled = transformStroke(s, scaleAbout(2, 10, 10));
expect(scaled.points.slice(0, 2)).toEqual([10, 10]);
expect(scaled.points.slice(6, 8)).toEqual([30, 50]);
expect(scaled.width).toBe(4);
expect(s.points[6]).toBe(20); // original untouched
});
it('scales images about a fixed corner', () => {
expect(transformImage(image('x', 10, 10, 20, 10), scaleAbout(0.5, 30, 20))).toMatchObject({ x: 20, y: 15, width: 10, height: 5 });
});
});

124
src/lib/ink/select.ts Normal file
View file

@ -0,0 +1,124 @@
// Lasso selection, hit testing and transforms for page objects (strokes and images).
import { STRIDE, type PageImage, type Stroke } from '$lib/model/types';
import { hitStroke, strokeBounds } from './stroke';
export interface Box {
x1: number;
y1: number;
x2: number;
y2: number;
}
/** Uniform scale `k` about the origin, then a translation: p' = p·k + (tx, ty). */
export interface Transform {
k: number;
tx: number;
ty: number;
}
export const IDENTITY: Transform = { k: 1, tx: 0, ty: 0 };
/** Even-odd point-in-polygon; `poly` is flat [x0, y0, x1, y1, …] and closed implicitly. */
export function pointInPolygon(x: number, y: number, poly: number[]): boolean {
let inside = false;
const n = poly.length;
for (let i = 0, j = n - 2; i < n; j = i, i += 2) {
const xi = poly[i], yi = poly[i + 1], xj = poly[j], yj = poly[j + 1];
if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
}
return inside;
}
/** A stroke is lassoed only when every sample lies inside the loop. */
export function strokeInLasso(s: Stroke, poly: number[]): boolean {
if (poly.length < 6 || s.points.length === 0) return false;
for (let i = 0; i < s.points.length; i += STRIDE) {
if (!pointInPolygon(s.points[i], s.points[i + 1], poly)) return false;
}
return true;
}
/** An image is lassoed only when all four corners lie inside the loop. */
export function imageInLasso(img: PageImage, poly: number[]): boolean {
if (poly.length < 6) return false;
const { x, y, width: w, height: h } = img;
return [
[x, y],
[x + w, y],
[x + w, y + h],
[x, y + h]
].every(([px, py]) => pointInPolygon(px, py, poly));
}
export function lassoSelect(strokes: Stroke[], images: PageImage[], poly: number[]) {
return {
strokes: strokes.filter((s) => strokeInLasso(s, poly)).map((s) => s.id),
images: images.filter((i) => imageInLasso(i, poly)).map((i) => i.id)
};
}
/** Top-most object under a point: ink is drawn above images, later objects above earlier ones. */
export function hitObject(
strokes: Stroke[],
images: PageImage[],
x: number,
y: number,
r: number
): { kind: 'stroke' | 'image'; id: string } | null {
for (let i = strokes.length - 1; i >= 0; i--) {
if (hitStroke(strokes[i], x, y, r)) return { kind: 'stroke', id: strokes[i].id };
}
for (let i = images.length - 1; i >= 0; i--) {
const m = images[i];
if (x >= m.x && x <= m.x + m.width && y >= m.y && y <= m.y + m.height) return { kind: 'image', id: m.id };
}
return null;
}
export function objectsBounds(strokes: Stroke[], images: PageImage[]): Box | null {
let b: Box | null = null;
const grow = (x1: number, y1: number, x2: number, y2: number) => {
b = b
? { x1: Math.min(b.x1, x1), y1: Math.min(b.y1, y1), x2: Math.max(b.x2, x2), y2: Math.max(b.y2, y2) }
: { x1, y1, x2, y2 };
};
for (const s of strokes) {
if (s.points.length === 0) continue;
const sb = strokeBounds(s);
// strokeBounds pads by the full width; half of it is the visible edge.
const pad = s.width / 2;
grow(sb.x1 + pad, sb.y1 + pad, sb.x2 - pad, sb.y2 - pad);
}
for (const m of images) grow(m.x, m.y, m.x + m.width, m.y + m.height);
return b;
}
const r2 = (v: number) => Math.round(v * 100) / 100;
export function transformStroke(s: Stroke, t: Transform): Stroke {
const points = s.points.slice();
for (let i = 0; i < points.length; i += STRIDE) {
points[i] = r2(points[i] * t.k + t.tx);
points[i + 1] = r2(points[i + 1] * t.k + t.ty);
}
return { ...s, points, width: r2(s.width * t.k) };
}
export function transformImage(m: PageImage, t: Transform): PageImage {
return {
...m,
x: r2(m.x * t.k + t.tx),
y: r2(m.y * t.k + t.ty),
width: r2(m.width * t.k),
height: r2(m.height * t.k)
};
}
export const translate = (dx: number, dy: number): Transform => ({ k: 1, tx: dx, ty: dy });
/** Uniform scale by `k` keeping the point (ax, ay) fixed. */
export const scaleAbout = (k: number, ax: number, ay: number): Transform => ({ k, tx: ax - ax * k, ty: ay - ay * k });
/** SVG/CSS matrix for a transform in page-local points. */
export const matrix = (t: Transform) => `matrix(${t.k} 0 0 ${t.k} ${t.tx} ${t.ty})`;

View file

@ -42,12 +42,26 @@ export interface Origin {
name: string; name: string;
} }
/** A pasted image placed on a page, drawn above the markdown and under the ink. */
export interface PageImage {
id: string;
/** Content hash of the image bytes (key in the assets store). */
assetId: string;
/** Page-local points, origin top-left. */
x: number;
y: number;
width: number;
height: number;
}
export interface PageData { export interface PageData {
id: string; id: string;
width: number; width: number;
height: number; height: number;
markdown: string; markdown: string;
strokes: Stroke[]; strokes: Stroke[];
/** Missing on canvases saved before images existed. */
images?: PageImage[];
origin?: Origin; origin?: Origin;
} }

View file

@ -4,9 +4,20 @@ export const ATTACH = {
manifest: 'papure/manifest.json', manifest: 'papure/manifest.json',
markdown: (id: string) => `papure/pages/${id}.md`, markdown: (id: string) => `papure/pages/${id}.md`,
ink: (id: string) => `papure/pages/${id}.ink.json`, ink: (id: string) => `papure/pages/${id}.ink.json`,
source: (id: string) => `papure/sources/${id}.pdf` images: (id: string) => `papure/pages/${id}.images.json`,
source: (id: string) => `papure/sources/${id}.pdf`,
asset: (id: string, kind: ImageKind) => `papure/assets/${id}.${kind === 'png' ? 'png' : 'jpg'}`
}; };
export type ImageKind = 'png' | 'jpeg';
/** PNG or JPEG, by magic bytes (the only raster formats a PDF embeds directly). */
export function imageKind(bytes: Uint8Array): ImageKind | null {
if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return 'png';
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'jpeg';
return null;
}
export const FORMAT = 'papure'; export const FORMAT = 'papure';
export async function sha256Hex(bytes: Uint8Array, length = 24): Promise<string> { export async function sha256Hex(bytes: Uint8Array, length = 24): Promise<string> {

View file

@ -14,7 +14,7 @@ import {
decodePDFRawStream decodePDFRawStream
} from 'pdf-lib'; } from 'pdf-lib';
import { withTrunk, flatten, type Tree } from '$lib/model/tree'; import { withTrunk, flatten, type Tree } from '$lib/model/tree';
import { newId, type CanvasData, type Origin, type PageData, type Stroke } from '$lib/model/types'; import { newId, type CanvasData, type Origin, type PageData, type PageImage, type Stroke } from '$lib/model/types';
import { ATTACH, FORMAT, sha256Hex } from './format'; import { ATTACH, FORMAT, sha256Hex } from './format';
import { normRotation } from './write'; import { normRotation } from './write';
@ -22,6 +22,8 @@ export interface ReadResult {
data: CanvasData; data: CanvasData;
/** Source PDFs referenced by pages, keyed by source id. */ /** Source PDFs referenced by pages, keyed by source id. */
sources: Map<string, Uint8Array>; sources: Map<string, Uint8Array>;
/** Pasted images referenced by pages, keyed by asset id. */
assets: Map<string, Uint8Array>;
/** True when the file had no Papure layer and was imported as-is. */ /** True when the file had no Papure layer and was imported as-is. */
imported: boolean; imported: boolean;
} }
@ -56,13 +58,16 @@ function fromAttachments(files: Map<string, Uint8Array>, m: Manifest) {
if (!meta) continue; if (!meta) continue;
const md = files.get(ATTACH.markdown(id)); const md = files.get(ATTACH.markdown(id));
const ink = files.get(ATTACH.ink(id)); const ink = files.get(ATTACH.ink(id));
const imgs = files.get(ATTACH.images(id));
const images = imgs ? (JSON.parse(text(imgs)).images as PageImage[]) : [];
pages[id] = { pages[id] = {
id, id,
width: meta.width, width: meta.width,
height: meta.height, height: meta.height,
origin: meta.origin, origin: meta.origin,
markdown: md ? text(md) : '', markdown: md ? text(md) : '',
strokes: ink ? (JSON.parse(text(ink)).strokes as Stroke[]) : [] strokes: ink ? (JSON.parse(text(ink)).strokes as Stroke[]) : [],
...(images.length ? { images } : {})
}; };
} }
const sources = new Map<string, Uint8Array>(); const sources = new Map<string, Uint8Array>();
@ -71,8 +76,16 @@ function fromAttachments(files: Map<string, Uint8Array>, m: Manifest) {
const b = files.get(ATTACH.source(p.origin.sourceId)); const b = files.get(ATTACH.source(p.origin.sourceId));
if (b) sources.set(p.origin.sourceId, b); if (b) sources.set(p.origin.sourceId, b);
} }
const assets = new Map<string, Uint8Array>();
for (const p of Object.values(pages)) {
for (const img of p.images ?? []) {
if (assets.has(img.assetId)) continue;
const b = files.get(ATTACH.asset(img.assetId, 'png')) ?? files.get(ATTACH.asset(img.assetId, 'jpeg'));
if (b) assets.set(img.assetId, b);
}
}
const data: CanvasData = { version: 1, updatedAt: m.updatedAt, tree: m.tree, pages }; const data: CanvasData = { version: 1, updatedAt: m.updatedAt, tree: m.tree, pages };
return { data, sources }; return { data, sources, assets };
} }
/** Pages of a PDF as they appear on screen (CropBox, /Rotate applied). */ /** Pages of a PDF as they appear on screen (CropBox, /Rotate applied). */
@ -108,7 +121,7 @@ async function importPdf(bytes: Uint8Array, name: string, doc: PDFDocument): Pro
tree: withTrunk(pages.map((p) => p.id)), tree: withTrunk(pages.map((p) => p.id)),
pages: Object.fromEntries(pages.map((p) => [p.id, p])) pages: Object.fromEntries(pages.map((p) => [p.id, p]))
}; };
return { data, sources: new Map([[sourceId, bytes]]), imported: true }; return { data, sources: new Map([[sourceId, bytes]]), assets: new Map(), imported: true };
} }
const round = (v: number) => Math.round(v * 100) / 100; const round = (v: number) => Math.round(v * 100) / 100;

View file

@ -5,7 +5,7 @@ import { insert, withTrunk } from '$lib/model/tree';
import type { CanvasData, Stroke } from '$lib/model/types'; import type { CanvasData, Stroke } from '$lib/model/types';
import { setFontLoader } from './fonts'; import { setFontLoader } from './fonts';
import { canvasToPdf } from './write'; import { canvasToPdf } from './write';
import { readCanvasPdf } from './read'; import { readAttachments, readCanvasPdf } from './read';
beforeAll(() => { beforeAll(() => {
setFontLoader(async (f) => new Uint8Array(await readFile(`static/fonts/${f}`))); setFontLoader(async (f) => new Uint8Array(await readFile(`static/fonts/${f}`)));
@ -81,6 +81,33 @@ describe('pdf round trip', () => {
const doc = await PDFDocument.load(bytes); const doc = await PDFDocument.load(bytes);
expect(doc.getPage(1).getSize()).toEqual({ width: 200, height: 500 }); expect(doc.getPage(1).getSize()).toEqual({ width: 200, height: 500 });
}); });
it('draws pasted images and restores them with their bytes', async () => {
// 1×1 red PNG.
const png = Uint8Array.from(
atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=='),
(c) => c.charCodeAt(0)
);
const data = sample();
const img = { id: 'i1', assetId: 'png1', x: 20, y: 30, width: 100, height: 50 };
data.pages.a.images = [img];
data.pages.b.images = [{ ...img, id: 'i2', y: 200 }];
const bytes = await canvasToPdf(data, { title: 't', getSource: async () => undefined, getAsset: async (id) => (id === 'png1' ? png : undefined) });
const doc = await PDFDocument.load(bytes);
const xobjects = (i: number) => doc.getPage(i).node.Resources()?.lookup(PDFName.of('XObject'));
expect(xobjects(0)).toBeTruthy();
const back = await readCanvasPdf(bytes, 'x.pdf');
expect(back.data.pages.a.images).toEqual([img]);
expect(back.data.pages.b.images?.[0].id).toBe('i2');
expect(back.data.pages.r.images).toBeUndefined();
expect([...back.assets.keys()]).toEqual(['png1']);
expect(back.assets.get('png1')).toEqual(png);
// Stored once although placed twice.
const names = [...readAttachments(doc).keys()];
expect(names.filter((n) => n.startsWith('papure/assets/'))).toEqual(['papure/assets/png1.png']);
});
}); });
describe('imported pages', () => { describe('imported pages', () => {

View file

@ -15,6 +15,7 @@ import {
PDFString, PDFString,
degrees, degrees,
type PDFEmbeddedPage, type PDFEmbeddedPage,
type PDFImage,
type PDFPage type PDFPage
} from 'pdf-lib'; } from 'pdf-lib';
@ -27,13 +28,15 @@ interface EmbeddedSource {
import { flatten } from '$lib/model/tree'; import { flatten } from '$lib/model/tree';
import type { CanvasData, PageData, Stroke } from '$lib/model/types'; import type { CanvasData, PageData, Stroke } from '$lib/model/types';
import { HIGHLIGHTER_OPACITY, outline, samples } from '$lib/ink/stroke'; import { HIGHLIGHTER_OPACITY, outline, samples } from '$lib/ink/stroke';
import { ATTACH, FORMAT } from './format'; import { ATTACH, FORMAT, imageKind } from './format';
import { loadFonts } from './fonts'; import { loadFonts } from './fonts';
import { drawMarkdown, fontsNeeded, hex, type Fonts, type Metrics } from './text'; import { drawMarkdown, fontsNeeded, hex, type Fonts, type Metrics } from './text';
export interface WriteOptions { export interface WriteOptions {
title: string; title: string;
getSource: (id: string) => Promise<Uint8Array | undefined>; getSource: (id: string) => Promise<Uint8Array | undefined>;
/** Bytes of a pasted image (PNG or JPEG) by asset id. */
getAsset?: (id: string) => Promise<Uint8Array | undefined>;
} }
export async function canvasToPdf(data: CanvasData, opts: WriteOptions): Promise<Uint8Array> { export async function canvasToPdf(data: CanvasData, opts: WriteOptions): Promise<Uint8Array> {
@ -50,6 +53,7 @@ export async function canvasToPdf(data: CanvasData, opts: WriteOptions): Promise
const embedded = await embedSources(doc, pages, opts.getSource); const embedded = await embedSources(doc, pages, opts.getSource);
const hasText = pages.some((p) => p.markdown.trim()); const hasText = pages.some((p) => p.markdown.trim());
const text = hasText ? await embedFonts(doc, pages) : null; const text = hasText ? await embedFonts(doc, pages) : null;
const images = await embedImages(doc, pages, opts.getAsset);
for (const p of pages) { for (const p of pages) {
const page = doc.addPage([p.width, p.height]); const page = doc.addPage([p.width, p.height]);
@ -59,6 +63,10 @@ export async function canvasToPdf(data: CanvasData, opts: WriteOptions): Promise
copyMarkupAnnotations(doc, page, src); copyMarkupAnnotations(doc, page, src);
} }
if (text && p.markdown.trim()) drawMarkdown(page, p.markdown, text.fonts, text.metrics); if (text && p.markdown.trim()) drawMarkdown(page, p.markdown, text.fonts, text.metrics);
for (const m of p.images ?? []) {
const img = images.get(m.assetId);
if (img) page.drawImage(img.image, { x: m.x, y: p.height - m.y - m.height, width: m.width, height: m.height });
}
for (const s of p.strokes) addInkAnnotation(doc, page, s); for (const s of p.strokes) addInkAnnotation(doc, page, s);
} }
if (pages.length === 0) doc.addPage([595.28, 841.89]); if (pages.length === 0) doc.addPage([595.28, 841.89]);
@ -84,6 +92,10 @@ export async function canvasToPdf(data: CanvasData, opts: WriteOptions): Promise
for (const p of pages) { for (const p of pages) {
if (p.markdown) await attach(p.markdown, ATTACH.markdown(p.id), 'text/markdown'); if (p.markdown) await attach(p.markdown, ATTACH.markdown(p.id), 'text/markdown');
if (p.strokes.length) await attach(JSON.stringify({ strokes: p.strokes }), ATTACH.ink(p.id), 'application/json'); if (p.strokes.length) await attach(JSON.stringify({ strokes: p.strokes }), ATTACH.ink(p.id), 'application/json');
if (p.images?.length) await attach(JSON.stringify({ images: p.images }), ATTACH.images(p.id), 'application/json');
}
for (const [id, { bytes, kind }] of images) {
await attach(bytes, ATTACH.asset(id, kind), kind === 'png' ? 'image/png' : 'image/jpeg');
} }
const sourceIds = new Set(pages.flatMap((p) => (p.origin ? [p.origin.sourceId] : []))); const sourceIds = new Set(pages.flatMap((p) => (p.origin ? [p.origin.sourceId] : [])));
for (const id of sourceIds) { for (const id of sourceIds) {
@ -94,6 +106,27 @@ export async function canvasToPdf(data: CanvasData, opts: WriteOptions): Promise
return doc.save({ useObjectStreams: true }); return doc.save({ useObjectStreams: true });
} }
/** Each pasted image once, however many times it is placed. */
async function embedImages(doc: PDFDocument, pages: PageData[], getAsset: WriteOptions['getAsset']) {
const out = new Map<string, { image: PDFImage; bytes: Uint8Array; kind: 'png' | 'jpeg' }>();
if (!getAsset) return out;
for (const p of pages) {
for (const m of p.images ?? []) {
if (out.has(m.assetId)) continue;
const bytes = await getAsset(m.assetId);
const kind = bytes && imageKind(bytes);
if (!bytes || !kind) continue;
try {
const image = kind === 'png' ? await doc.embedPng(bytes) : await doc.embedJpg(bytes);
out.set(m.assetId, { image, bytes, kind });
} catch (err) {
console.warn('Could not embed image', m.assetId, err);
}
}
}
return out;
}
async function embedFonts(doc: PDFDocument, pages: PageData[]) { async function embedFonts(doc: PDFDocument, pages: PageData[]) {
const needed = new Set<keyof Fonts>(['regular']); const needed = new Set<keyof Fonts>(['regular']);
for (const p of pages) fontsNeeded(p.markdown, needed); for (const p of pages) fontsNeeded(p.markdown, needed);

View file

@ -2,7 +2,7 @@
import { layout, type Rect } from '$lib/model/layout'; import { layout, type Rect } from '$lib/model/layout';
import { insert, remove, canInsert, flatten, withTrunk, type Dir, type Tree } from '$lib/model/tree'; import { insert, remove, canInsert, flatten, withTrunk, type Dir, type Tree } from '$lib/model/tree';
import { A4, newId, type CanvasData, type Origin, type PageData, type Stroke } from '$lib/model/types'; import { A4, newId, type CanvasData, type Origin, type PageData, type PageImage, type Stroke } from '$lib/model/types';
export class PageModel { export class PageModel {
readonly id: string; readonly id: string;
@ -10,6 +10,7 @@ export class PageModel {
height = $state(A4.height); height = $state(A4.height);
markdown = $state(''); markdown = $state('');
strokes = $state.raw<Stroke[]>([]); strokes = $state.raw<Stroke[]>([]);
images = $state.raw<PageImage[]>([]);
readonly origin?: Origin; readonly origin?: Origin;
constructor(d: PageData) { constructor(d: PageData) {
@ -18,6 +19,7 @@ export class PageModel {
this.height = d.height; this.height = d.height;
this.markdown = d.markdown; this.markdown = d.markdown;
this.strokes = d.strokes; this.strokes = d.strokes;
this.images = d.images ?? [];
this.origin = d.origin; this.origin = d.origin;
} }
@ -28,11 +30,17 @@ export class PageModel {
height: this.height, height: this.height,
markdown: this.markdown, markdown: this.markdown,
strokes: this.strokes, strokes: this.strokes,
...(this.images.length ? { images: this.images } : {}),
...(this.origin ? { origin: this.origin } : {}) ...(this.origin ? { origin: this.origin } : {})
}; };
} }
} }
export interface PageObjects {
strokes: Stroke[];
images: PageImage[];
}
interface Command { interface Command {
undo(): void; undo(): void;
redo(): void; redo(): void;
@ -136,6 +144,21 @@ export class CanvasDoc {
}); });
} }
/** Replace a page's strokes and images together as one undoable step. */
setObjects(pageId: string, fn: (o: PageObjects) => PageObjects) {
const page = this.pages[pageId];
if (!page) return;
const before = { strokes: page.strokes, images: page.images };
const after = fn(before);
if (after.strokes === before.strokes && after.images === before.images) return;
const apply = (o: PageObjects) => {
const p = this.pages[pageId];
p.strokes = o.strokes;
p.images = o.images;
};
this.exec({ redo: () => apply(after), undo: () => apply(before) });
}
// ---- tree ------------------------------------------------------------ // ---- tree ------------------------------------------------------------
private treeCommand(nextTree: Tree, nextPages: Record<string, PageModel>, nextActive: string | null) { private treeCommand(nextTree: Tree, nextPages: Record<string, PageModel>, nextActive: string | null) {
@ -171,7 +194,7 @@ export class CanvasDoc {
get isBlank() { get isBlank() {
const ids = this.order; const ids = this.order;
const p = ids.length === 1 ? this.pages[ids[0]] : null; const p = ids.length === 1 ? this.pages[ids[0]] : null;
return !!p && !p.origin && !p.markdown.trim() && p.strokes.length === 0; return !!p && !p.origin && !p.markdown.trim() && p.strokes.length === 0 && p.images.length === 0;
} }
/** Replace every page with a new trunk (importing into a blank canvas). */ /** Replace every page with a new trunk (importing into a blank canvas). */

View file

@ -28,6 +28,8 @@ interface SettingsData {
fingerDraw: boolean; fingerDraw: boolean;
/** A finger fling toward a free side of the active page offers a new page there. */ /** A finger fling toward a free side of the active page offers a new page there. */
flingToAdd: boolean; flingToAdd: boolean;
/** Holding the pen's barrel button lassoes, whatever tool is active. */
penButtonSelect: boolean;
palm: PalmOptions; palm: PalmOptions;
github: GitHubSettings; github: GitHubSettings;
/** Minutes between automatic pushes (0 = manual only). */ /** Minutes between automatic pushes (0 = manual only). */
@ -42,6 +44,7 @@ const DEFAULTS: SettingsData = {
grid: { show: true, divisions: 1 }, grid: { show: true, divisions: 1 },
fingerDraw: true, fingerDraw: true,
flingToAdd: true, flingToAdd: true,
penButtonSelect: true,
palm: DEFAULT_PALM, palm: DEFAULT_PALM,
github: { token: '', owner: '', repo: '', branch: 'main', dir: '' }, github: { token: '', owner: '', repo: '', branch: 'main', dir: '' },
pushInterval: 5, pushInterval: 5,

View file

@ -1,7 +1,7 @@
import type { PageData } from '$lib/model/types'; import type { PageData } from '$lib/model/types';
import { settings } from './settings.svelte'; import { settings } from './settings.svelte';
export type Tool = 'text' | 'pen' | 'highlighter' | 'eraser'; export type Tool = 'text' | 'select' | 'pen' | 'highlighter' | 'eraser';
export const PEN_WIDTHS = [1.2, 2, 3.5]; export const PEN_WIDTHS = [1.2, 2, 3.5];
export const HIGHLIGHTER_WIDTHS = [10, 16, 24]; export const HIGHLIGHTER_WIDTHS = [10, 16, 24];
@ -17,6 +17,7 @@ class Tools {
/** Pages of an imported PDF waiting to be placed on the canvas. */ /** Pages of an imported PDF waiting to be placed on the canvas. */
placing = $state.raw<{ name: string; pages: PageData[] } | null>(null); placing = $state.raw<{ name: string; pages: PageData[] } | null>(null);
/** A pointer tool (select, ink, eraser) rather than typing: pages don't take text focus. */
get inking() { get inking() {
return this.tool !== 'text'; return this.tool !== 'text';
} }

View file

@ -25,6 +25,8 @@ interface Schema extends DBSchema {
files: { key: string; value: FileRecord }; files: { key: string; value: FileRecord };
docs: { key: string; value: CanvasData }; docs: { key: string; value: CanvasData };
sources: { key: string; value: Uint8Array }; sources: { key: string; value: Uint8Array };
/** Pasted image bytes (PNG or JPEG), keyed by content hash. */
assets: { key: string; value: Uint8Array };
search: { key: string; value: SearchRecord }; search: { key: string; value: SearchRecord };
kv: { key: string; value: unknown }; kv: { key: string; value: unknown };
} }
@ -32,13 +34,16 @@ interface Schema extends DBSchema {
let dbp: Promise<IDBPDatabase<Schema>> | null = null; let dbp: Promise<IDBPDatabase<Schema>> | null = null;
export function db() { export function db() {
dbp ??= openDB<Schema>('papure', 1, { dbp ??= openDB<Schema>('papure', 2, {
upgrade(d) { upgrade(d, oldVersion) {
d.createObjectStore('files', { keyPath: 'path' }); if (oldVersion < 1) {
d.createObjectStore('docs'); d.createObjectStore('files', { keyPath: 'path' });
d.createObjectStore('sources'); d.createObjectStore('docs');
d.createObjectStore('search', { keyPath: 'path' }); d.createObjectStore('sources');
d.createObjectStore('kv'); d.createObjectStore('search', { keyPath: 'path' });
d.createObjectStore('kv');
}
if (oldVersion < 2) d.createObjectStore('assets');
} }
}); });
return dbp; return dbp;

View file

@ -91,8 +91,9 @@ class Vault {
async importPdfAsCanvas(dir: string, file: File) { async importPdfAsCanvas(dir: string, file: File) {
const bytes = new Uint8Array(await file.arrayBuffer()); const bytes = new Uint8Array(await file.arrayBuffer());
const { data, sources } = await readCanvasPdf(bytes, file.name); const { data, sources, assets } = await readCanvasPdf(bytes, file.name);
for (const [id, b] of sources) await this.putSource(id, b); for (const [id, b] of sources) await this.putSource(id, b);
for (const [id, b] of assets) await this.putAsset(id, b);
return this.createCanvas(dir, file.name.replace(/\.pdf$/i, ''), data); return this.createCanvas(dir, file.name.replace(/\.pdf$/i, ''), data);
} }
@ -199,16 +200,29 @@ class Vault {
await (await db()).put('sources', bytes, id); await (await db()).put('sources', bytes, id);
} }
async getAsset(id: string) {
return (await db()).get('assets', id);
}
async putAsset(id: string, bytes: Uint8Array) {
await (await db()).put('assets', bytes, id);
}
async buildPdf(path: string): Promise<Uint8Array> { async buildPdf(path: string): Promise<Uint8Array> {
const data = await this.loadDoc(path); const data = await this.loadDoc(path);
if (!data) throw new Error(`No such canvas: ${path}`); if (!data) throw new Error(`No such canvas: ${path}`);
return canvasToPdf(data, { title: displayName(path), getSource: (id) => this.getSource(id) }); return canvasToPdf(data, {
title: displayName(path),
getSource: (id) => this.getSource(id),
getAsset: (id) => this.getAsset(id)
});
} }
/** Store a PDF pulled from the repo as the local working copy. */ /** Store a PDF pulled from the repo as the local working copy. */
async ingestPdf(path: string, bytes: Uint8Array, remoteSha: string) { async ingestPdf(path: string, bytes: Uint8Array, remoteSha: string) {
const { data, sources } = await readCanvasPdf(bytes, baseName(path)); const { data, sources, assets } = await readCanvasPdf(bytes, baseName(path));
for (const [id, b] of sources) await this.putSource(id, b); for (const [id, b] of sources) await this.putSource(id, b);
for (const [id, b] of assets) await this.putAsset(id, b);
await this.saveDoc(path, data, { remoteSha, clean: true }); await this.saveDoc(path, data, { remoteSha, clean: true });
return data; return data;
} }