From 4acb3a614c8fba9253e9082dbbed2214c7e64b00 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 27 Sep 2026 17:27:39 +0000 Subject: [PATCH 01/15] Replace page glow with a flat outline and add a canvas grid MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pages now get a crisp 1 screen-px outline instead of a blurred shadow, and the canvas background shows faint world-anchored grid lines that pan and zoom with the pages (spacing steps up ×4 when zoomed out). Co-Authored-By: Claude Opus 5.5 --- src/app.css | 6 ++++-- src/lib/components/CanvasView.svelte | 14 +++++++++++++- src/lib/components/PageView.svelte | 3 ++- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/app.css b/src/app.css index 8b7ba45..76440c5 100644 --- a/src/app.css +++ b/src/app.css @@ -59,7 +59,8 @@ --success: #2f9e5c; --warn: #d9901b; --shadow: 0 1px 2px rgba(0, 0, 0, 0.06), 0 4px 16px rgba(0, 0, 0, 0.08); - --page-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 0 0 1px rgba(0, 0, 0, 0.04); + --page-line: rgba(0, 0, 0, 0.18); + --grid-line: rgba(0, 0, 0, 0.05); --ghost: rgba(0, 0, 0, 0.045); --ghost-border: rgba(0, 0, 0, 0.12); --radius: 6px; @@ -85,7 +86,8 @@ --success: #44cf6e; --warn: #e9973f; --shadow: 0 1px 2px rgba(0, 0, 0, 0.3), 0 6px 20px rgba(0, 0, 0, 0.35); - --page-shadow: 0 0 0 1px rgba(255, 255, 255, 0.06), 0 2px 8px rgba(0, 0, 0, 0.5); + --page-line: rgba(255, 255, 255, 0.16); + --grid-line: rgba(255, 255, 255, 0.04); --ghost: rgba(255, 255, 255, 0.04); --ghost-border: rgba(255, 255, 255, 0.14); color-scheme: dark; diff --git a/src/lib/components/CanvasView.svelte b/src/lib/components/CanvasView.svelte index 4f05d39..d401e9b 100644 --- a/src/lib/components/CanvasView.svelte +++ b/src/lib/components/CanvasView.svelte @@ -28,6 +28,13 @@ let stage: HTMLDivElement; const cssVars = pageCssVars(); + // Background grid: world-anchored, stepping up ×4 when zoomed out so lines never get denser than ~12px. + const gridStep = $derived.by(() => { + let step = 24 * viewport.scale; + while (step < 12) step *= 4; + return step; + }); + // ---- autosave -------------------------------------------------------- $effect(() => { if (doc.version > 0) untrack(() => workspace.scheduleSave()); @@ -522,6 +529,7 @@ class:panning class:erasing={tools.tool === 'eraser'} bind:this={stage} + style="--grid: {gridStep}px; background-position: {viewport.x}px {viewport.y}px" onpointerdown={onPointerDown} onpointermove={onPointerMove} onpointerup={onPointerUp} @@ -660,7 +668,11 @@ touch-action: none; user-select: none; -webkit-user-select: none; - background: var(--bg-canvas); + background-color: var(--bg-canvas); + background-image: + linear-gradient(to right, var(--grid-line) 1px, transparent 1px), + linear-gradient(to bottom, var(--grid-line) 1px, transparent 1px); + background-size: var(--grid) var(--grid); } .stage :global(.cm-content) { user-select: text; diff --git a/src/lib/components/PageView.svelte b/src/lib/components/PageView.svelte index 51843b8..ad52f25 100644 --- a/src/lib/components/PageView.svelte +++ b/src/lib/components/PageView.svelte @@ -49,7 +49,8 @@ inset: 0; background: #ffffff; overflow: hidden; - box-shadow: var(--page-shadow); + /* Crisp 1 screen-px outline, no blur. */ + box-shadow: 0 0 0 calc(1px / var(--s)) var(--page-line); } .paper.invert { filter: invert(0.88) hue-rotate(180deg); From 138b7975061671224049842e1591467ded2e72fc Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 27 Sep 2026 17:34:28 +0000 Subject: [PATCH 02/15] Size the canvas grid to the active page Each grid cell is now the active page's size, aligned to its edges, so the grid marks where neighbouring pages would sit. Falls back to A4 at the origin when no page is active. Co-Authored-By: Claude Opus 5.5 --- src/lib/components/CanvasView.svelte | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/lib/components/CanvasView.svelte b/src/lib/components/CanvasView.svelte index d401e9b..0cfdd1f 100644 --- a/src/lib/components/CanvasView.svelte +++ b/src/lib/components/CanvasView.svelte @@ -28,11 +28,11 @@ let stage: HTMLDivElement; const cssVars = pageCssVars(); - // Background grid: world-anchored, stepping up ×4 when zoomed out so lines never get denser than ~12px. - const gridStep = $derived.by(() => { - let step = 24 * viewport.scale; - while (step < 12) step *= 4; - return step; + // Background grid: one cell per active page, aligned to its edges (A4 at the origin if none). + const grid = $derived.by(() => { + const r = (doc.activeId && doc.rects.get(doc.activeId)) || { x: 0, y: 0, ...A4 }; + const s = viewport.scale; + return { w: r.width * s, h: r.height * s, x: viewport.x + r.x * s, y: viewport.y + r.y * s }; }); // ---- autosave -------------------------------------------------------- @@ -529,7 +529,7 @@ class:panning class:erasing={tools.tool === 'eraser'} bind:this={stage} - style="--grid: {gridStep}px; background-position: {viewport.x}px {viewport.y}px" + style="background-size: {grid.w}px {grid.h}px; background-position: {grid.x}px {grid.y}px" onpointerdown={onPointerDown} onpointermove={onPointerMove} onpointerup={onPointerUp} @@ -672,7 +672,6 @@ background-image: linear-gradient(to right, var(--grid-line) 1px, transparent 1px), linear-gradient(to bottom, var(--grid-line) 1px, transparent 1px); - background-size: var(--grid) var(--grid); } .stage :global(.cm-content) { user-select: text; From 8295894b3216d7382632d6470d6618d6fe8efd46 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 27 Sep 2026 17:54:29 +0000 Subject: [PATCH 03/15] Show add-page indicator as a bar and palm-check its taps The add-page ghost is now a thin bar along the active page's free edge instead of a full page-sized block. Pointer taps on it go through the stage gesture handling, so touches are evaluated by the palm rejector with the same 'draw' policy as writing, including being cut off if the pen shows up mid-tap. The native click only handles keyboard activation. Co-Authored-By: Claude Opus 5.5 --- src/lib/components/CanvasView.svelte | 98 +++++++++++++++++++++++----- 1 file changed, 83 insertions(+), 15 deletions(-) diff --git a/src/lib/components/CanvasView.svelte b/src/lib/components/CanvasView.svelte index 0cfdd1f..f0ad3cb 100644 --- a/src/lib/components/CanvasView.svelte +++ b/src/lib/components/CanvasView.svelte @@ -1,6 +1,5 @@ + + e.key === 'Escape' && onclose()} /> + + +
e.target === e.currentTarget && onclose()}> +
{ + e.preventDefault(); + apply(); + }} + > +

Page size

+
+ {#each PAGE_PRESETS as p (p.label)} + + {/each} +
+
+ + + + mm +
+ {#if !valid} +

Sizes must be between {toMm(MIN_PT)} and {toMm(MAX_PT)} mm.

+ {/if} +
+ + +
+
+
+ + From 3d29255d0c6f16e2ffd219dca9d2061fbd167758 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 27 Sep 2026 21:31:12 +0000 Subject: [PATCH 11/15] Add background grid settings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Appearance now has a toggle for the background grid and a choice of subdivisions (none, 2×2 up to 16×16) that split each page-sized cell into fainter lines. Subdivisions are left out when zoomed so far out that they would be under 8 px apart. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GaoZtJQZwLXkEgWs8twCia --- src/app.css | 2 ++ src/lib/components/CanvasView.svelte | 28 ++++++++++++++++++------- src/lib/components/SettingsModal.svelte | 14 +++++++++++++ src/lib/state/settings.svelte.ts | 9 ++++++++ 4 files changed, 46 insertions(+), 7 deletions(-) diff --git a/src/app.css b/src/app.css index 76440c5..912d602 100644 --- a/src/app.css +++ b/src/app.css @@ -61,6 +61,7 @@ --shadow: 0 1px 2px rgba(0, 0, 0, 0.06), 0 4px 16px rgba(0, 0, 0, 0.08); --page-line: rgba(0, 0, 0, 0.18); --grid-line: rgba(0, 0, 0, 0.05); + --grid-line-minor: rgba(0, 0, 0, 0.028); --ghost: rgba(0, 0, 0, 0.045); --ghost-border: rgba(0, 0, 0, 0.12); --radius: 6px; @@ -88,6 +89,7 @@ --shadow: 0 1px 2px rgba(0, 0, 0, 0.3), 0 6px 20px rgba(0, 0, 0, 0.35); --page-line: rgba(255, 255, 255, 0.16); --grid-line: rgba(255, 255, 255, 0.04); + --grid-line-minor: rgba(255, 255, 255, 0.022); --ghost: rgba(255, 255, 255, 0.04); --ghost-border: rgba(255, 255, 255, 0.14); color-scheme: dark; diff --git a/src/lib/components/CanvasView.svelte b/src/lib/components/CanvasView.svelte index 5b2b27f..4746268 100644 --- a/src/lib/components/CanvasView.svelte +++ b/src/lib/components/CanvasView.svelte @@ -30,11 +30,28 @@ let stage: HTMLDivElement; const cssVars = pageCssVars(); - // Background grid: one cell per active page, aligned to its edges (A4 at the origin if none). - const grid = $derived.by(() => { + // Background grid: one cell per active page, aligned to its edges (A4 at the origin if none), + // optionally split into fainter subdivisions. + const gridStyle = $derived.by(() => { + const g = settings.data.grid; + if (!g.show) return ''; const r = (doc.activeId && doc.rects.get(doc.activeId)) || { x: 0, y: 0, ...A4 }; const s = viewport.scale; - return { w: r.width * s, h: r.height * s, x: viewport.x + r.x * s, y: viewport.y + r.y * s }; + const w = r.width * s; + const h = r.height * s; + const lines = (color: string) => [ + `linear-gradient(to right, ${color} 1px, transparent 1px)`, + `linear-gradient(to bottom, ${color} 1px, transparent 1px)` + ]; + const images = lines('var(--grid-line)'); + const sizes = [`${w}px ${h}px`, `${w}px ${h}px`]; + // Leave out subdivisions once they'd be too dense to read. + const n = g.divisions; + if (n > 1 && Math.min(w, h) / n >= 8) { + images.push(...lines('var(--grid-line-minor)')); + sizes.push(`${w / n}px ${h / n}px`, `${w / n}px ${h / n}px`); + } + return `background-image: ${images.join(', ')}; background-size: ${sizes.join(', ')}; background-position: ${viewport.x + r.x * s}px ${viewport.y + r.y * s}px`; }); // ---- autosave -------------------------------------------------------- @@ -605,7 +622,7 @@ class:panning class:erasing={tools.tool === 'eraser'} bind:this={stage} - style="background-size: {grid.w}px {grid.h}px; background-position: {grid.x}px {grid.y}px" + style={gridStyle} onpointerdown={onPointerDown} onpointermove={onPointerMove} onpointerup={onPointerUp} @@ -760,9 +777,6 @@ user-select: none; -webkit-user-select: none; background-color: var(--bg-canvas); - background-image: - linear-gradient(to right, var(--grid-line) 1px, transparent 1px), - linear-gradient(to bottom, var(--grid-line) 1px, transparent 1px); } .stage :global(.cm-content) { user-select: text; diff --git a/src/lib/components/SettingsModal.svelte b/src/lib/components/SettingsModal.svelte index 6b92676..9c8f886 100644 --- a/src/lib/components/SettingsModal.svelte +++ b/src/lib/components/SettingsModal.svelte @@ -83,6 +83,20 @@ +
+
Background grid
Faint lines behind the pages, one cell per active page.
+ +
+
+
Grid subdivisions
Split each page-sized cell into a finer grid for sketching and lining things up.
+ +
{:else if tab === 'input'}

Pen & touch

diff --git a/src/lib/state/settings.svelte.ts b/src/lib/state/settings.svelte.ts index 4fa5724..92cee0b 100644 --- a/src/lib/state/settings.svelte.ts +++ b/src/lib/state/settings.svelte.ts @@ -6,6 +6,12 @@ import { DEFAULT_PALM, type PalmOptions } from '$lib/ink/palm'; export type ThemePref = 'system' | 'light' | 'dark'; export type PageStylePref = 'paper' | 'match'; +export interface GridSettings { + show: boolean; + /** Minor lines per page cell side (1 = page-sized cells only). */ + divisions: number; +} + export interface GitHubSettings { token: string; owner: string; @@ -18,6 +24,7 @@ export interface GitHubSettings { interface SettingsData { theme: ThemePref; pageStyle: PageStylePref; + grid: GridSettings; fingerDraw: boolean; palm: PalmOptions; github: GitHubSettings; @@ -30,6 +37,7 @@ interface SettingsData { const DEFAULTS: SettingsData = { theme: 'system', pageStyle: 'match', + grid: { show: true, divisions: 1 }, fingerDraw: true, palm: DEFAULT_PALM, github: { token: '', owner: '', repo: '', branch: 'main', dir: '' }, @@ -48,6 +56,7 @@ function load(): SettingsData { return { ...DEFAULTS, ...saved, + grid: { ...DEFAULTS.grid, ...saved.grid }, palm: { ...DEFAULTS.palm, ...saved.palm }, github: { ...DEFAULTS.github, ...saved.github } }; From 2df91b561de29a46d588d4e020144b4f5f09cd35 Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 27 Sep 2026 21:31:54 +0000 Subject: [PATCH 12/15] Bring spec and README up to date The spec still listed undo, the eraser, colours and smoothing as missing. Describe the ink engine and palm rejection as built (draw vs navigate intents, settings toggles, cancelled pointers), the plus buttons, fling offer, grid and page size dialog, note that sync is GitHub-only, and replace the stale open item with the real ones. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GaoZtJQZwLXkEgWs8twCia --- README.md | 3 ++- spec.md | 32 ++++++++++++++++++++++---------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 824eec3..a3149e3 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,8 @@ 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. -- **Pages**: the grey "+" tiles next to the active page add a page there; `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 fling past a free edge highlights that side's "+"); `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. - **View**: wheel/trackpad pans, `Ctrl`+wheel or pinch zooms, `Ctrl+0` fits the page, `Ctrl+9` shows the whole tree, space-drag or middle-drag pans. - **Sync**: Settings → Sync. Use a fine-grained token with *Contents: read & write* on the repo. Edits autosave locally; pushes happen every N minutes and on `Ctrl+S` / the sync button. Conflicts: newer wins. diff --git a/spec.md b/spec.md index 5125de1..aaedd63 100644 --- a/spec.md +++ b/spec.md @@ -9,10 +9,11 @@ One canvas = one tree = one `.pdf` file. - A branch can only ever continue in the direction it started (strictly linear — no sub-branches off a branch). - A trunk page can have at most one left branch and one right branch. - **PDF import**: creates a chain of pages in whatever direction you pick when placing it (up/down = extends the trunk, left/right = becomes a branch off the trunk page you clicked). Only one trunk exists per canvas — additional imported PDFs must attach as a branch off some trunk page, or extend an existing branch further outward in its established direction. -- Hidden/unopened neighbor pages render as a gray tile with a "+" in a circle; clicking (or a shortcut) instantiates them as real pages. +- Each free side of the active page shows a small "+" circle just off its edge; tapping it (or `Alt+Arrow`) adds a blank page there. A quick finger fling past a free edge highlights that side's "+" for a few seconds, but never adds a page by itself. +- The canvas background is a faint grid with one cell per active page, aligned to its edges; Settings can hide it or subdivide it. - Deleting a page removes it (undo via Ctrl+Z); no permanent trash. - Default zoom: one page fills the screen. Zoom out reveals the tree. -- Pages default to A4, or auto-match the aspect ratio of an imported PDF page; resizable manually otherwise. +- Pages default to A4, or auto-match the aspect ratio of an imported PDF page; resizable manually otherwise (page menu: presets, or a custom size in mm). ## 2. Flatten Algorithm (tree → linear page order, e.g. for PDF page order / print) @@ -45,7 +46,7 @@ Canvases (PDF files) live in a **file tree** you define, e.g. `school/english/le ## 5. Sync & Storage -- Repo-backed (GitHub/GitLab), one file per canvas. +- Repo-backed (GitHub for now; GitLab not implemented), one file per canvas. - PWA: offline-first, caches locally, explicit save/sync pushes to repo. - Multi-device: git pull/push is the sync mechanism (not real-time collab). @@ -54,7 +55,7 @@ Canvases (PDF files) live in a **file tree** you define, e.g. `school/english/le - **Frontend**: SvelteKit, deployed on your VPS, installable as PWA. - **Ink input**: Pointer Events + pressure (your existing artifact — pending). - **PDF read/write**: pdf.js + pdf-lib. -- **Storage**: Git repo via GitHub/GitLab API (or local backend proxy holding the token). +- **Storage**: IndexedDB locally; Git repo via the GitHub REST API (token in the browser, no proxy). ## 7. Confirmed Product Features @@ -79,12 +80,23 @@ Source: user-provided `palm-rejection-test.html` test harness. The acceptance po - A `touch` pointer is rejected if any of: a pen stroke is active or was active within the last ~5s, its contact ellipse (`width`/`height`) exceeds ~35px (palm heel vs. fingertip), it's within 150ms of the last pen activity, or a pen is currently hovering (armed lockout before it even touches down). - A touch stroke already in progress gets cut off mid-stroke if pen activity appears. -**Gaps before this is the real ink engine** (currently a raster test, not vector): -- `draw()` writes straight to canvas via `ctx.lineTo`/`stroke` with pressure-scaled line width, and throws points away. Needs to become `recordPoint()`: push `{x, y, pressure, tiltX, tiltY, t}` into a `Stroke.points[]` array per stroke; rendering = replaying that array. This is what makes strokes resizable/erasable/undoable and exportable to both the PDF Ink-annotation layer and the JSON attachment layer. -- `tiltX`/`tiltY` exist on the pen's `PointerEvent` but aren't read anywhere yet — needed for tilt support. -- No smoothing yet (raw straight segments) — fine as a v1, can layer in curve smoothing later without changing point storage. -- No undo/redo, multi-color, eraser yet — needs a `Stroke[]` array per page's ink layer with add/remove, which undo/redo just pops/pushes. +**How the app applies it** (`src/lib/ink/palm.ts`): +- Each touch is evaluated with an intent. `draw` (finger ink) gets the full policy above. `navigate` (pan, pinch, and taps on canvas buttons such as the add-page "+") skips the 5 s pen session and the hover lockout, so fingers can move around and tap between pen strokes; pen-down, wide contacts and the 150 ms window still reject it. +- Once a pen has been used, fingers only navigate. "Draw with finger" in Settings turns finger ink off entirely. +- Each rule (pen session, wide contact, timing, hover) can be switched off in Settings → Pen & touch. +- An interrupted pointer (`pointercancel`) drops the stroke or erase in progress instead of committing it. + +**Ink engine (implemented)**: +- `StrokeRecorder.recordPoint()` stores `x, y, pressure, tiltX, tiltY, t` per sample in a flat `Stroke.points` array (stride 6); rendering replays it. Tilt is recorded but not yet used for rendering. +- Outlines are smoothed with `perfect-freehand`; mouse and finger strokes simulate pressure. +- Pen, highlighter (translucent, no thinning) and stroke eraser, with configurable colour palettes; the pen's eraser end erases too. +- 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 -- [ ] Nothing blocking — ready to move into implementation planning (component breakdown, page-tree data structures in Svelte, PDF encode/decode module) +- [ ] 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. From 5fb11e49286c29149cf9b1bba7dcabce675ef47c Mon Sep 17 00:00:00 2001 From: agent Date: Sun, 27 Sep 2026 21:43:09 +0000 Subject: [PATCH 13/15] Let the page fling work anywhere, with a setting to turn it off MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A fling toward a free side of the active page now offers a page at any zoom or pan position, not only once that edge is on screen. If the side's plus is visible it pulses as before; otherwise an "Add page" button appears at that edge of the screen, tapped through the same palm-checked gesture as the plus. Settings → Pen & touch gets "Swipe to add pages" (on by default). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GaoZtJQZwLXkEgWs8twCia --- README.md | 2 +- spec.md | 2 +- src/lib/components/CanvasView.svelte | 71 +++++++++++++++++++++---- src/lib/components/SettingsModal.svelte | 4 ++ src/lib/state/settings.svelte.ts | 3 ++ 5 files changed, 71 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index a3149e3..0cbf95a 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ 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. -- **Pages**: the "+" circles beside the active page add a page there (a quick finger fling past a free edge highlights that side's "+"); `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. - **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. - **View**: wheel/trackpad pans, `Ctrl`+wheel or pinch zooms, `Ctrl+0` fits the page, `Ctrl+9` shows the whole tree, space-drag or middle-drag pans. diff --git a/spec.md b/spec.md index aaedd63..c2f5235 100644 --- a/spec.md +++ b/spec.md @@ -9,7 +9,7 @@ One canvas = one tree = one `.pdf` file. - A branch can only ever continue in the direction it started (strictly linear — no sub-branches off a branch). - A trunk page can have at most one left branch and one right branch. - **PDF import**: creates a chain of pages in whatever direction you pick when placing it (up/down = extends the trunk, left/right = becomes a branch off the trunk page you clicked). Only one trunk exists per canvas — additional imported PDFs must attach as a branch off some trunk page, or extend an existing branch further outward in its established direction. -- Each free side of the active page shows a small "+" circle just off its edge; tapping it (or `Alt+Arrow`) adds a blank page there. A quick finger fling past a free edge highlights that side's "+" for a few seconds, but never adds a page by itself. +- Each free side of the active page shows a small "+" circle just off its edge; tapping it (or `Alt+Arrow`) adds a blank page there. A quick finger fling toward a free side offers a page there for a few seconds: that side's "+" pulses, or, if it is off screen, an "Add page" button appears at that edge of the screen. The fling never adds a page by itself, and can be turned off in Settings. - The canvas background is a faint grid with one cell per active page, aligned to its edges; Settings can hide it or subdivide it. - Deleting a page removes it (undo via Ctrl+Z); no permanent trash. - Default zoom: one page fills the screen. Zoom out reveals the tree. diff --git a/src/lib/components/CanvasView.svelte b/src/lib/components/CanvasView.svelte index 4746268..6031c8a 100644 --- a/src/lib/components/CanvasView.svelte +++ b/src/lib/components/CanvasView.svelte @@ -119,7 +119,8 @@ const placeSlots = $derived(tools.placing ? freeSlots(doc.tree) : []); - // A finger fling past the active page's free edge highlights the plus on that side. + // A finger fling toward a free side of the active page offers a new page there: the plus + // pulses if it's on screen, otherwise a button appears at that edge of the screen. let offer = $state(null); let offerTimer: ReturnType | undefined; @@ -130,18 +131,21 @@ } function offerAfterFling(samples: Sample[]) { + if (!settings.data.flingToAdd) return; const dir = flingDir(samples); const id = doc.activeId; - const r = id && doc.rects.get(id); const slot = dir && ghostSlots.find((s) => s.anchor === id && s.dir === dir); - if (!r || !slot) return; - // Only once that edge has come into view, i.e. the fling went past the end. + if (slot) setOffer(slot); + } + + /** The offered plus is off screen, so the offer shows as an edge-of-screen button instead. */ + const offerOffscreen = $derived.by(() => { + const r = offer && plusRect(offer); + if (!r) return false; const a = viewport.toScreen(r.x, r.y); const b = viewport.toScreen(r.x + r.width, r.y + r.height); - const edge = { left: a.x, right: b.x, up: a.y, down: b.y }[slot.dir]; - const size = slot.dir === 'left' || slot.dir === 'right' ? viewport.width : viewport.height; - if (edge >= 0 && edge <= size) setOffer(slot); - } + return b.x < 0 || b.y < 0 || a.x > viewport.width || a.y > viewport.height; + }); // Show every possible spot when an imported PDF is waiting to be placed. $effect(() => { @@ -338,7 +342,7 @@ 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'); + const plus = target.closest('.ghost, .offer-pill'); if (e.pointerType === 'touch') { const decision = palm.evaluate(e, touchIntent(fingerInks, !!plus)); if (!decision.accept) return; // palm: ignore entirely @@ -707,6 +711,20 @@ {/if} + {#if offer && offerOffscreen} + + + {/if} + {#if eraserAt && tools.tool === 'eraser'}
{/if} @@ -834,6 +852,41 @@ transform: scale(1.3); } } + .offer-pill { + position: absolute; + display: flex; + align-items: center; + gap: 6px; + padding: 10px 16px 10px 12px; + border: 1px solid var(--accent); + border-radius: 999px; + background: var(--bg); + color: var(--accent); + box-shadow: var(--shadow); + cursor: pointer; + white-space: nowrap; + } + .offer-pill[data-side='right'] { + right: 12px; + top: 50%; + transform: translateY(-50%); + } + .offer-pill[data-side='left'] { + left: 12px; + top: 50%; + transform: translateY(-50%); + } + .offer-pill[data-side='up'] { + top: 12px; + left: 50%; + transform: translateX(-50%); + } + .offer-pill[data-side='down'] { + /* Clear of the toolbar. */ + bottom: 72px; + left: 50%; + transform: translateX(-50%); + } @media (prefers-reduced-motion: reduce) { .ghost.offer .plus { animation: none; diff --git a/src/lib/components/SettingsModal.svelte b/src/lib/components/SettingsModal.svelte index 9c8f886..a6be752 100644 --- a/src/lib/components/SettingsModal.svelte +++ b/src/lib/components/SettingsModal.svelte @@ -103,6 +103,10 @@
Draw with finger
When off, a single finger always pans; only pen and mouse draw. Once you use a pen, fingers only pan and zoom.
+
+
Swipe to add pages
A quick one-finger flick toward a free side of the active page offers to add a page there.
+ +

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/state/settings.svelte.ts b/src/lib/state/settings.svelte.ts index 92cee0b..ceb10c2 100644 --- a/src/lib/state/settings.svelte.ts +++ b/src/lib/state/settings.svelte.ts @@ -26,6 +26,8 @@ interface SettingsData { pageStyle: PageStylePref; grid: GridSettings; fingerDraw: boolean; + /** A finger fling toward a free side of the active page offers a new page there. */ + flingToAdd: boolean; palm: PalmOptions; github: GitHubSettings; /** Minutes between automatic pushes (0 = manual only). */ @@ -39,6 +41,7 @@ const DEFAULTS: SettingsData = { pageStyle: 'match', grid: { show: true, divisions: 1 }, fingerDraw: true, + flingToAdd: true, palm: DEFAULT_PALM, github: { token: '', owner: '', repo: '', branch: 'main', dir: '' }, pushInterval: 5, From 84b9d4469f26dea48177b2a596d0e2059559fd7b Mon Sep 17 00:00:00 2001 From: agent Date: Tue, 29 Sep 2026 21:05:02 +0000 Subject: [PATCH 14/15] 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 @@