From 84b9d4469f26dea48177b2a596d0e2059559fd7b Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 29 Sep 2026 21:05:02 +0000 Subject: [PATCH] Add lasso selection and pasted images Select tool (S): lasso picks ink strokes and images that lie entirely inside the loop, a tap picks one object. Move, uniform resize, nudge, delete, recolour, copy/cut/paste/duplicate, each one undo step. Holding the pen's barrel button lassoes with any tool (Settings > Pen & touch). Copying also writes a PNG of the selection to the system clipboard. Images come in by paste, drop, the Insert image button or the page menu. They are capped at 2400 px, stored as PNG/JPEG by content hash in a new IndexedDB store, drawn between the markdown and the ink, and written to the PDF both visibly and as papure/assets + per-page images.json. Dark pages now invert each layer except images, so images keep their colours; the inverted ink layer is screen-blended so highlighted text stays bright. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UcbKnqfprs8hMkTVsYx1dh --- README.md | 9 +- spec.md | 29 +- src/lib/components/CanvasView.svelte | 502 +++++++++++++++++++++++- src/lib/components/ImageLayer.svelte | 52 +++ src/lib/components/InkLayer.svelte | 6 +- src/lib/components/PageView.svelte | 17 +- src/lib/components/SettingsModal.svelte | 4 + src/lib/components/Toolbar.svelte | 27 +- src/lib/images/assets.svelte.ts | 40 ++ src/lib/images/normalize.test.ts | 25 ++ src/lib/images/normalize.ts | 75 ++++ src/lib/images/png.ts | 41 ++ src/lib/ink/clip.test.ts | 38 ++ src/lib/ink/clip.ts | 52 +++ src/lib/ink/select.test.ts | 88 +++++ src/lib/ink/select.ts | 124 ++++++ src/lib/model/types.ts | 14 + src/lib/pdf/format.ts | 13 +- src/lib/pdf/read.ts | 21 +- src/lib/pdf/roundtrip.test.ts | 29 +- src/lib/pdf/write.ts | 35 +- src/lib/state/doc.svelte.ts | 27 +- src/lib/state/settings.svelte.ts | 3 + src/lib/state/tools.svelte.ts | 3 +- src/lib/storage/db.ts | 19 +- src/lib/storage/vault.svelte.ts | 20 +- 26 files changed, 1274 insertions(+), 39 deletions(-) create mode 100644 src/lib/components/ImageLayer.svelte create mode 100644 src/lib/images/assets.svelte.ts create mode 100644 src/lib/images/normalize.test.ts create mode 100644 src/lib/images/normalize.ts create mode 100644 src/lib/images/png.ts create mode 100644 src/lib/ink/clip.test.ts create mode 100644 src/lib/ink/clip.ts create mode 100644 src/lib/ink/select.test.ts create mode 100644 src/lib/ink/select.ts diff --git a/README.md b/README.md index 0cbf95a..d9136f2 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Lecture notes as a tree of pages ("comb") — live-preview markdown underneath, ```sh npm install 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 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 -- **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. - **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. @@ -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/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/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. Fonts in `static/fonts` are pre-subset (`scripts/subset-fonts.sh`) because pdf-lib's own subsetter drops glyphs. diff --git a/spec.md b/spec.md index c2f5235..ab8d018 100644 --- a/spec.md +++ b/spec.md @@ -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: -- **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. -- **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). +- **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), placed images per page (`papure/pages/.images.json`) with each image's bytes stored once (`papure/assets/.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. **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. - Full ink toolset: colors, highlighter, eraser. +- Lasso selection of ink and images; pasted images (§10). - Search across typed markdown text. - Pages remember their PDF-import origin, searchable. - 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. - 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. - [ ] 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. - [ ] Use recorded tilt for rendering. - [ ] GitLab sync. +- [ ] Selection: drag across pages, rotate; image crop; "paste as new page" for slide screenshots. diff --git a/src/lib/components/CanvasView.svelte b/src/lib/components/CanvasView.svelte index 6031c8a..b80c90d 100644 --- a/src/lib/components/CanvasView.svelte +++ b/src/lib/components/CanvasView.svelte @@ -6,6 +6,10 @@ import ArrowUpIcon from '@lucide/svelte/icons/arrow-up'; import TrashIcon from '@lucide/svelte/icons/trash-2'; 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 { viewport } from '$lib/state/viewport.svelte'; import { tools } from '$lib/state/tools.svelte'; @@ -15,10 +19,24 @@ 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 { 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 { flingDir, pushSample, type Sample } from '$lib/ink/fling'; 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 { downloadCanvas } from './download'; import PageSizeDialog from './PageSizeDialog.svelte'; @@ -231,10 +249,12 @@ } // ---- 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]; if (!page) return; doc.activeId = id; + const canRead = typeof navigator !== 'undefined' && !!navigator.clipboard?.read; const dirs: [Dir, string][] = [ ['up', 'Insert page above'], ['down', 'Insert page below'], @@ -259,6 +279,7 @@ } 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) }); menu.show(x, y, items); } @@ -286,6 +307,9 @@ | { kind: 'erase'; pointerId: number; pointerType: string; hits: Map> } | { 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: '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' }; let gesture: Gesture | null = null; @@ -298,6 +322,10 @@ let tick = $state(0); let erasing = $state.raw>(new Set()); 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) { const r = stage.getBoundingClientRect(); @@ -329,6 +357,227 @@ } 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; + images: Set; + } + + let selection = $state.raw(null); + /** Transform of the selection while it is dragged or resized (committed on release). */ + let selPreview = $state.raw(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) { palm.track(e); @@ -337,14 +586,18 @@ const target = e.target as Element; if (target.closest('.no-stage')) return; 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. const fingerInks = tools.inking && settings.data.fingerDraw && !palm.penSeen; // 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. const plus = target.closest('.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('.sel-box, .sel-handle') : null; 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 touches.set(e.pointerId, p); if (touches.size >= 2) { @@ -363,6 +616,26 @@ 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 inEditor = !!target.closest('.cm-editor'); // Pressing anywhere outside the text leaves the editor (preventDefault @@ -400,6 +673,18 @@ if (e.button !== 0 && e.pointerType === 'mouse') return; 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) { e.preventDefault(); capture(e.pointerId); @@ -422,6 +707,7 @@ function onPointerMove(e: PointerEvent) { palm.track(e); const p = local(e); + pointerAt = p; if (tools.tool === 'eraser' || isEraserButton(e)) eraserAt = p; 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 // (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(); return; } @@ -469,6 +756,35 @@ 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() : []; for (const ev of events.length ? events : [e]) { const q = local(ev); @@ -491,7 +807,27 @@ if (!gesture || gesture.pointerId !== e.pointerId) return; const g = gesture; 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') { pushSample(g.trail, { ...local(e), t: e.timeStamp }); offerAfterFling(g.trail); @@ -511,6 +847,8 @@ function cancelGesture() { if (gesture?.kind === 'draw') live = null; if (gesture?.kind === 'erase') erasing = new Set(); + if (gesture?.kind === 'lasso') lasso = null; + if (gesture?.kind === 'move' || gesture?.kind === 'resize') selPreview = null; gesture = null; } @@ -553,11 +891,14 @@ } 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 e.preventDefault(); const p = local(e); 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 -------------------------------------------------------- @@ -578,6 +919,27 @@ 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) || k === 'y')) return void (e.preventDefault(), doc.redo()); if (e.key === 'Escape') { @@ -595,7 +957,7 @@ return; } if (mod || e.altKey) return; - const shortcuts: Record = { t: 'text', p: 'pen', h: 'highlighter', e: 'eraser' }; + const shortcuts: Record = { t: 'text', s: 'select', p: 'pen', h: 'highlighter', e: 'eraser' }; if (shortcuts[k]) tools.tool = shortcuts[k]; } @@ -606,7 +968,16 @@ const panning = $derived(spaceDown); - (spaceDown = false)} /> + { + spaceDown = false; + clipFresh = false; + }} + oncopy={() => (clipFresh = false)} + onpaste={onPaste} +/>
@@ -625,6 +996,7 @@ class:inking={tools.inking} class:panning class:erasing={tools.tool === 'eraser'} + class:moving={!!selPreview} bind:this={stage} style={gridStyle} onpointerdown={onPointerDown} @@ -636,6 +1008,8 @@ eraserAt = null; }} oncontextmenu={onContextMenu} + ondragover={onDragOver} + ondrop={onDrop} >
doc.touch()} onactivate={() => (doc.activeId = id)} /> {/if} {/each} + {#if lasso && doc.rects.get(lasso.pageId)} + {@const r = doc.rects.get(lasso.pageId)!} + + + + {/if} + + {#if selRect} +
+ {#each CORNERS as c (c)} +
+ {/each} + {/if} + {#each ghostSlots as slot (slot.anchor + slot.dir)} {@const r = plusRect(slot)} {#if r} @@ -725,6 +1118,21 @@ {/if} + {#if selBar && selected} + + {/if} + {#if eraserAt && tools.tool === 'eraser'}
{/if} @@ -750,7 +1158,7 @@ /> {/if} - fitPage(doc.activeId)} onfitall={fitAll} /> + fitPage(doc.activeId)} onfitall={fitAll} onimages={(files) => void insertImages(files)} />
diff --git a/src/lib/components/InkLayer.svelte b/src/lib/components/InkLayer.svelte index a16e94c..a59e9fb 100644 --- a/src/lib/components/InkLayer.svelte +++ b/src/lib/components/InkLayer.svelte @@ -1,5 +1,6 @@
{/if} - + +
{#if page.origin && active}
{page.origin.name} · p. {page.origin.pageIndex + 1}
@@ -52,9 +56,18 @@ /* Crisp 1 screen-px outline, no blur. */ 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 { + background: #1f1f1f; + } + .paper.invert > :global(:not(.images)) { 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 { content: ''; position: absolute; diff --git a/src/lib/components/SettingsModal.svelte b/src/lib/components/SettingsModal.svelte index a6be752..fe45d40 100644 --- a/src/lib/components/SettingsModal.svelte +++ b/src/lib/components/SettingsModal.svelte @@ -107,6 +107,10 @@
Swipe to add pages
A quick one-finger flick toward a free side of the active page offers to add a page there.
+
+
Pen button selects
Hold the button on the side of the pen and draw a loop to select, whatever tool is active.
+ +

Palm rejection

Pen session lockout
Ignore touches while the pen is writing, and finger ink for 5 seconds after it was used.
diff --git a/src/lib/components/Toolbar.svelte b/src/lib/components/Toolbar.svelte index 7f5915a..2872fed 100644 --- a/src/lib/components/Toolbar.svelte +++ b/src/lib/components/Toolbar.svelte @@ -1,5 +1,7 @@