Compare commits
No commits in common. "main" and "add-page-plus" have entirely different histories.
main
...
add-page-p
33 changed files with 74 additions and 1905 deletions
14
README.md
14
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, selection, PDF round trip, sync against a fake GitHub)
|
||||
npm test # unit tests (tree, markdown, 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,13 +22,10 @@ The image builds the PWA and serves it with nginx. Put an HTTPS reverse proxy in
|
|||
|
||||
## Using it
|
||||
|
||||
- **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.
|
||||
- **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.
|
||||
- **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. A drag keeps gliding for a moment after you let go and slows to a stop (the zoom never changes); touching the canvas catches it. The drag strength is `GLIDE_TAU` in `src/lib/ink/fling.ts`.
|
||||
- **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.
|
||||
|
||||
## Layout
|
||||
|
|
@ -36,8 +33,7 @@ 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, 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/ink` — stroke recording/outlines and palm rejection (ported from `palm-rejection-test.html`).
|
||||
- `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.
|
||||
|
|
|
|||
61
spec.md
61
spec.md
|
|
@ -9,11 +9,10 @@ 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 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.
|
||||
- Hidden/unopened neighbor pages render as a gray tile with a "+" in a circle; clicking (or a shortcut) instantiates them as real pages.
|
||||
- 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 (page menu: presets, or a custom size in mm).
|
||||
- Pages default to A4, or auto-match the aspect ratio of an imported PDF page; resizable manually otherwise.
|
||||
|
||||
## 2. Flatten Algorithm (tree → linear page order, e.g. for PDF page order / print)
|
||||
|
||||
|
|
@ -32,8 +31,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, 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/<id>.images.json`) with each image's bytes stored once (`papure/assets/<hash>.png|jpg`), and grid metadata (each page's tree position, size, and which PDF import it originated from, for provenance search).
|
||||
- **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).
|
||||
- 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).
|
||||
|
|
@ -46,7 +45,7 @@ Canvases (PDF files) live in a **file tree** you define, e.g. `school/english/le
|
|||
|
||||
## 5. Sync & Storage
|
||||
|
||||
- Repo-backed (GitHub for now; GitLab not implemented), one file per canvas.
|
||||
- Repo-backed (GitHub/GitLab), 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).
|
||||
|
||||
|
|
@ -55,13 +54,12 @@ 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**: IndexedDB locally; Git repo via the GitHub REST API (token in the browser, no proxy).
|
||||
- **Storage**: Git repo via GitHub/GitLab API (or local backend proxy holding the token).
|
||||
|
||||
## 7. Confirmed Product Features
|
||||
|
||||
- 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).
|
||||
|
|
@ -81,45 +79,12 @@ 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.
|
||||
|
||||
**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.
|
||||
**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.
|
||||
|
||||
**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
|
||||
|
||||
## 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.
|
||||
- [ ] Nothing blocking — ready to move into implementation planning (component breakdown, page-tree data structures in Svelte, PDF encode/decode module)
|
||||
|
|
|
|||
|
|
@ -61,7 +61,6 @@
|
|||
--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;
|
||||
|
|
@ -89,7 +88,6 @@
|
|||
--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;
|
||||
|
|
|
|||
|
|
@ -6,10 +6,6 @@
|
|||
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';
|
||||
|
|
@ -19,27 +15,11 @@
|
|||
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, newId, type PageImage, type Stroke } from '$lib/model/types';
|
||||
import { PalmRejector, touchIntent } from '$lib/ink/palm';
|
||||
import { flingDir, pushSample, releaseVelocity, type Sample } from '$lib/ink/fling';
|
||||
import { A4, PAGE_PRESETS, type Stroke } from '$lib/model/types';
|
||||
import { PalmRejector } from '$lib/ink/palm';
|
||||
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';
|
||||
import PageView from './PageView.svelte';
|
||||
import Toolbar from './Toolbar.svelte';
|
||||
|
||||
|
|
@ -48,28 +28,11 @@
|
|||
let stage: HTMLDivElement;
|
||||
const cssVars = pageCssVars();
|
||||
|
||||
// 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 '';
|
||||
// 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;
|
||||
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`;
|
||||
return { w: r.width * s, h: r.height * s, x: viewport.x + r.x * s, y: viewport.y + r.y * s };
|
||||
});
|
||||
|
||||
// ---- autosave --------------------------------------------------------
|
||||
|
|
@ -92,7 +55,6 @@
|
|||
return () => {
|
||||
ro.disconnect();
|
||||
stage.removeEventListener('wheel', onWheel);
|
||||
clearTimeout(offerTimer);
|
||||
};
|
||||
});
|
||||
|
||||
|
|
@ -137,34 +99,6 @@
|
|||
|
||||
const placeSlots = $derived(tools.placing ? freeSlots(doc.tree) : []);
|
||||
|
||||
// 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<Slot | null>(null);
|
||||
let offerTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
function setOffer(slot: Slot | null) {
|
||||
clearTimeout(offerTimer);
|
||||
offer = slot;
|
||||
if (slot) offerTimer = setTimeout(() => (offer = null), 3000);
|
||||
}
|
||||
|
||||
function offerAfterFling(samples: Sample[]) {
|
||||
if (!settings.data.flingToAdd) return;
|
||||
const dir = flingDir(samples);
|
||||
const id = doc.activeId;
|
||||
const slot = dir && ghostSlots.find((s) => s.anchor === id && s.dir === dir);
|
||||
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);
|
||||
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(() => {
|
||||
if (!tools.placing) return;
|
||||
|
|
@ -249,12 +183,10 @@
|
|||
}
|
||||
|
||||
// ---- page menu -------------------------------------------------------
|
||||
/** `at`: stage-local point to paste at (the right-click position). */
|
||||
function pageMenu(x: number, y: number, id: string, at?: { x: number; y: number }) {
|
||||
function pageMenu(x: number, y: number, id: string) {
|
||||
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'],
|
||||
|
|
@ -279,14 +211,19 @@
|
|||
}
|
||||
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);
|
||||
}
|
||||
|
||||
/** Page whose custom-size dialog is open. */
|
||||
let sizing = $state<string | null>(null);
|
||||
const customSize = (id: string) => (sizing = id);
|
||||
function customSize(id: string) {
|
||||
const page = doc.pages[id];
|
||||
const mm = (pt: number) => Math.round((pt / 72) * 25.4);
|
||||
const answer = prompt('Page size in millimetres (width × height)', `${mm(page.width)} × ${mm(page.height)}`);
|
||||
const m = answer && /^\s*(\d+(?:\.\d+)?)\s*[x×*,\s]\s*(\d+(?:\.\d+)?)\s*$/i.exec(answer);
|
||||
if (!m) return;
|
||||
const pt = (v: string) => Math.min(5000, Math.max(50, (parseFloat(v) / 25.4) * 72));
|
||||
keepAnchor(id, () => doc.resizePage(id, pt(m[1]), pt(m[2])));
|
||||
}
|
||||
|
||||
const activeMenuPos = $derived.by(() => {
|
||||
const id = doc.activeId;
|
||||
|
|
@ -305,11 +242,8 @@
|
|||
type Gesture =
|
||||
| { kind: 'draw'; pointerId: number; pointerType: string; pageId: string; rec: StrokeRecorder }
|
||||
| { kind: 'erase'; pointerId: number; pointerType: string; hits: Map<string, Set<string>> }
|
||||
| { kind: 'pan'; pointerId: number; pointerType: string; lastX: number; lastY: number; startX: number; startY: number; moved: boolean; tap: boolean; trail: Sample[] }
|
||||
| { kind: 'pan'; pointerId: number; lastX: number; lastY: number; startX: number; startY: number; moved: boolean; tap: boolean }
|
||||
| { 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;
|
||||
|
|
@ -322,10 +256,6 @@
|
|||
let tick = $state(0);
|
||||
let erasing = $state.raw<Set<string>>(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();
|
||||
|
|
@ -357,247 +287,21 @@
|
|||
}
|
||||
|
||||
const isEraserButton = (e: PointerEvent) => e.pointerType === 'pen' && (e.button === 5 || (e.buttons & 32) !== 0);
|
||||
const isBarrelButton = (e: PointerEvent) => e.pointerType === 'pen' && (e.button === 2 || (e.buttons & 2) !== 0);
|
||||
const isSelectButton = (e: PointerEvent) => settings.data.penButtonSelect && isBarrelButton(e);
|
||||
|
||||
// ---- selection -------------------------------------------------------
|
||||
interface Selection {
|
||||
pageId: string;
|
||||
strokes: Set<string>;
|
||||
images: Set<string>;
|
||||
}
|
||||
|
||||
let selection = $state.raw<Selection | null>(null);
|
||||
/** Transform of the selection while it is dragged or resized (committed on release). */
|
||||
let selPreview = $state.raw<Transform | null>(null);
|
||||
/** Lasso being drawn, in page-local points. */
|
||||
let lasso = $state.raw<{ pageId: string; points: number[] } | null>(null);
|
||||
|
||||
const selected = $derived.by(() => {
|
||||
const sel = selection;
|
||||
const page = sel && doc.pages[sel.pageId];
|
||||
if (!sel || !page) return null;
|
||||
const strokes = page.strokes.filter((x) => sel.strokes.has(x.id));
|
||||
const images = page.images.filter((x) => sel.images.has(x.id));
|
||||
const box = objectsBounds(strokes, images);
|
||||
return box ? { pageId: sel.pageId, strokes, images, box } : null;
|
||||
});
|
||||
|
||||
const moving = $derived(
|
||||
selection && selPreview ? { pageId: selection.pageId, ids: new Set([...selection.strokes, ...selection.images]), t: selPreview } : null
|
||||
);
|
||||
|
||||
/** Selection box in world coordinates, following a drag/resize in progress. */
|
||||
const selRect = $derived.by((): Rect | null => {
|
||||
const r = selected && doc.rects.get(selected.pageId);
|
||||
if (!selected || !r) return null;
|
||||
const t = selPreview ?? IDENTITY;
|
||||
const b = selected.box;
|
||||
const pad = 6 / viewport.scale;
|
||||
const x1 = b.x1 * t.k + t.tx;
|
||||
const y1 = b.y1 * t.k + t.ty;
|
||||
return { x: r.x + x1 - pad, y: r.y + y1 - pad, width: (b.x2 - b.x1) * t.k + 2 * pad, height: (b.y2 - b.y1) * t.k + 2 * pad };
|
||||
});
|
||||
|
||||
/** Action bar above the selection (below it when there's no room), in screen coordinates. */
|
||||
const selBar = $derived.by(() => {
|
||||
if (!selRect || selPreview) return null;
|
||||
const top = viewport.toScreen(selRect.x + selRect.width / 2, selRect.y);
|
||||
const bottom = viewport.toScreen(selRect.x, selRect.y + selRect.height);
|
||||
const x = Math.min(Math.max(top.x, 140), viewport.width - 140);
|
||||
return top.y > 56 ? { x, y: top.y - 48 } : { x, y: Math.min(bottom.y + 8, viewport.height - 110) };
|
||||
});
|
||||
|
||||
const CORNERS = ['nw', 'ne', 'se', 'sw'] as const;
|
||||
|
||||
// Switching tools drops the selection.
|
||||
$effect(() => {
|
||||
void tools.tool;
|
||||
untrack(() => clearSelection());
|
||||
});
|
||||
|
||||
function clearSelection() {
|
||||
selection = null;
|
||||
selPreview = null;
|
||||
}
|
||||
|
||||
function select(pageId: string, strokes: string[], images: string[]) {
|
||||
selection = strokes.length || images.length ? { pageId, strokes: new Set(strokes), images: new Set(images) } : null;
|
||||
}
|
||||
|
||||
function commitTransform(t: Transform) {
|
||||
const sel = selection;
|
||||
if (!sel) return;
|
||||
doc.setObjects(sel.pageId, (o) => ({
|
||||
strokes: o.strokes.map((x) => (sel.strokes.has(x.id) ? transformStroke(x, t) : x)),
|
||||
images: o.images.map((x) => (sel.images.has(x.id) ? transformImage(x, t) : x))
|
||||
}));
|
||||
}
|
||||
|
||||
function deleteSelection() {
|
||||
const sel = selection;
|
||||
if (!sel) return;
|
||||
doc.setObjects(sel.pageId, (o) => ({
|
||||
strokes: o.strokes.filter((x) => !sel.strokes.has(x.id)),
|
||||
images: o.images.filter((x) => !sel.images.has(x.id))
|
||||
}));
|
||||
clearSelection();
|
||||
}
|
||||
|
||||
function recolor(color: string) {
|
||||
const sel = selection;
|
||||
if (!sel) return;
|
||||
doc.setObjects(sel.pageId, (o) => ({
|
||||
strokes: o.strokes.map((x) => (sel.strokes.has(x.id) && x.color !== color ? { ...x, color } : x)),
|
||||
images: o.images
|
||||
}));
|
||||
}
|
||||
|
||||
/** Add objects to a page as one undo step and select them. */
|
||||
function addObjects(pageId: string, objs: { strokes: Stroke[]; images: PageImage[] }) {
|
||||
doc.setObjects(pageId, (o) => ({ strokes: [...o.strokes, ...objs.strokes], images: [...o.images, ...objs.images] }));
|
||||
doc.activeId = pageId;
|
||||
select(pageId, objs.strokes.map((x) => x.id), objs.images.map((x) => x.id));
|
||||
}
|
||||
|
||||
// ---- clipboard -------------------------------------------------------
|
||||
// Copies keep a vector copy here and put a PNG on the system clipboard. Pasting prefers the
|
||||
// vector copy while it is fresh: until the window loses focus or something else is copied.
|
||||
let clip: Clip | null = null;
|
||||
let clipFresh = false;
|
||||
|
||||
function copySelection() {
|
||||
if (!selected) return false;
|
||||
clip = makeClip(selected.strokes, selected.images);
|
||||
clipFresh = true;
|
||||
const c = clip;
|
||||
if (c && navigator.clipboard?.write && typeof ClipboardItem !== 'undefined') {
|
||||
// A promise inside the ClipboardItem keeps the user gesture alive while rendering (Safari).
|
||||
const png = renderClipPng(c, (id) => assets.url(id));
|
||||
navigator.clipboard.write([new ClipboardItem({ 'image/png': png })]).catch((err) => console.warn('Clipboard write failed', err));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function duplicateSelection() {
|
||||
if (!selected) return;
|
||||
const c = makeClip(selected.strokes, selected.images);
|
||||
if (c) addObjects(selected.pageId, instantiate(c, selected.box.x1 + 12, selected.box.y1 + 12));
|
||||
}
|
||||
|
||||
/** Where a paste lands: the pointer if it's over a page, else the middle of the visible part of the active page. */
|
||||
function pasteTarget(at?: { x: number; y: number } | null) {
|
||||
const p = at ?? pointerAt;
|
||||
const over = p && pageAt(p.x, p.y);
|
||||
if (p && over) return { pageId: over, ...pagePoint(over, p.x, p.y) };
|
||||
const id = doc.activeId;
|
||||
const r = id && doc.rects.get(id);
|
||||
if (!id || !r) return null;
|
||||
const w = viewport.world;
|
||||
const x1 = Math.max(r.x, w.x), x2 = Math.min(r.x + r.width, w.x + w.width);
|
||||
const y1 = Math.max(r.y, w.y), y2 = Math.min(r.y + r.height, w.y + w.height);
|
||||
const cx = x2 > x1 ? (x1 + x2) / 2 : r.x + r.width / 2;
|
||||
const cy = y2 > y1 ? (y1 + y2) / 2 : r.y + r.height / 2;
|
||||
return { pageId: id, x: cx - r.x, y: cy - r.y };
|
||||
}
|
||||
|
||||
function pasteClip(at?: { x: number; y: number } | null) {
|
||||
const t = clip && pasteTarget(at);
|
||||
const page = t && doc.pages[t.pageId];
|
||||
if (!clip || !t || !page) return;
|
||||
const pos = placeCentred(t.x, t.y, clip, page);
|
||||
addObjects(t.pageId, instantiate(clip, pos.x, pos.y));
|
||||
}
|
||||
|
||||
async function insertImages(files: Blob[], at?: { x: number; y: number } | null) {
|
||||
const t = pasteTarget(at);
|
||||
const page = t && doc.pages[t.pageId];
|
||||
if (!t || !page) return;
|
||||
const placed: PageImage[] = [];
|
||||
for (const [i, f] of files.entries()) {
|
||||
try {
|
||||
const a = await assets.add(f);
|
||||
if (a.bytes > 5_000_000) workspace.toast(`That image is ${(a.bytes / 1e6).toFixed(1)} MB; it will make the canvas file large`);
|
||||
const size = imageSize(a, page);
|
||||
const pos = placeCentred(t.x + i * 16, t.y + i * 16, size, page);
|
||||
placed.push({ id: newId(), assetId: a.id, ...pos, ...size });
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
workspace.toast(`Could not read ${f instanceof File ? f.name : 'that image'}`, 'error');
|
||||
}
|
||||
}
|
||||
if (placed.length) addObjects(t.pageId, { strokes: [], images: placed });
|
||||
}
|
||||
|
||||
async function pasteFromMenu(at?: { x: number; y: number }) {
|
||||
if (clip && clipFresh) return pasteClip(at);
|
||||
try {
|
||||
for (const item of await navigator.clipboard.read()) {
|
||||
const type = item.types.find((t) => t.startsWith('image/'));
|
||||
if (type) return void (await insertImages([await item.getType(type)], at));
|
||||
}
|
||||
} catch {
|
||||
/* no permission or no clipboard API */
|
||||
}
|
||||
if (clip) pasteClip(at);
|
||||
else workspace.toast('No image or selection to paste');
|
||||
}
|
||||
|
||||
function onPaste(e: ClipboardEvent) {
|
||||
if (workspace.settingsOpen || sizing) return;
|
||||
const dt = e.clipboardData;
|
||||
const images = dt
|
||||
? [...dt.items].filter((i) => i.kind === 'file' && i.type.startsWith('image/')).map((i) => i.getAsFile()).filter((f): f is File => !!f)
|
||||
: [];
|
||||
const inText = editable(e.target);
|
||||
// Text goes to the editor; an image on its own is placed on the page.
|
||||
if (inText && (!images.length || dt?.getData('text/plain'))) return;
|
||||
if (clip && (clipFresh || (!images.length && !inText))) {
|
||||
e.preventDefault();
|
||||
return pasteClip();
|
||||
}
|
||||
if (images.length) {
|
||||
e.preventDefault();
|
||||
void insertImages(images);
|
||||
}
|
||||
}
|
||||
|
||||
function onDragOver(e: DragEvent) {
|
||||
if (e.dataTransfer?.types.includes('Files')) e.preventDefault();
|
||||
}
|
||||
|
||||
function onDrop(e: DragEvent) {
|
||||
const files = [...(e.dataTransfer?.files ?? [])].filter((f) => f.type.startsWith('image/'));
|
||||
if (!files.length) return;
|
||||
e.preventDefault();
|
||||
void insertImages(files, local(e));
|
||||
}
|
||||
|
||||
function lassoPath(pts: number[]) {
|
||||
let d = '';
|
||||
for (let i = 0; i < pts.length; i += 2) d += `${i ? 'L' : 'M'}${pts[i].toFixed(1)},${pts[i + 1].toFixed(1)}`;
|
||||
return d + 'Z';
|
||||
}
|
||||
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
palm.track(e);
|
||||
if (menu.open) menu.close();
|
||||
if (offer) setOffer(null);
|
||||
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<HTMLElement>('.ghost, .offer-pill');
|
||||
// The selection box and its handles are palm-checked like navigation too, so a finger can move it.
|
||||
const selPart = selected ? target.closest<HTMLElement>('.sel-box, .sel-handle') : null;
|
||||
const plus = target.closest<HTMLElement>('.ghost');
|
||||
if (e.pointerType === 'touch') {
|
||||
const decision = palm.evaluate(e, touchIntent(fingerInks, !!plus || !!selPart));
|
||||
const decision = palm.evaluate(e, fingerInks && !plus ? 'draw' : 'navigate');
|
||||
if (!decision.accept) return; // palm: ignore entirely
|
||||
touches.set(e.pointerId, p);
|
||||
if (touches.size >= 2) {
|
||||
|
|
@ -607,8 +311,6 @@
|
|||
return;
|
||||
}
|
||||
}
|
||||
// Touching the canvas catches a gliding view.
|
||||
viewport.stopGlide();
|
||||
|
||||
if (plus && e.button === 0) {
|
||||
e.preventDefault();
|
||||
|
|
@ -618,26 +320,6 @@
|
|||
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
|
||||
|
|
@ -652,18 +334,7 @@
|
|||
(e.pointerType === 'mouse' && e.button === 0 && !onPage && !target.closest('.slot'));
|
||||
if (wantsPan) {
|
||||
if (onPage && !inEditor) doc.activeId = onPage;
|
||||
gesture = {
|
||||
kind: 'pan',
|
||||
pointerId: e.pointerId,
|
||||
pointerType: e.pointerType,
|
||||
lastX: p.x,
|
||||
lastY: p.y,
|
||||
startX: p.x,
|
||||
startY: p.y,
|
||||
moved: false,
|
||||
tap: inEditor || !!target.closest('.slot'),
|
||||
trail: [{ ...p, t: e.timeStamp }]
|
||||
};
|
||||
gesture = { kind: 'pan', pointerId: e.pointerId, lastX: p.x, lastY: p.y, startX: p.x, startY: p.y, moved: false, tap: inEditor || !!target.closest('.slot') };
|
||||
if (e.pointerType !== 'touch' || !gesture.tap) {
|
||||
if (e.pointerType !== 'touch') e.preventDefault();
|
||||
capture(e.pointerId);
|
||||
|
|
@ -675,18 +346,6 @@
|
|||
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);
|
||||
|
|
@ -709,7 +368,6 @@
|
|||
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)) {
|
||||
|
|
@ -735,14 +393,12 @@
|
|||
viewport.panBy(dx, dy);
|
||||
gesture.lastX = p.x;
|
||||
gesture.lastY = p.y;
|
||||
pushSample(gesture.trail, { ...p, t: e.timeStamp });
|
||||
return;
|
||||
}
|
||||
|
||||
// A touch stroke is cut off as soon as the palm policy rejects it
|
||||
// (e.g. the pen just came into range).
|
||||
const navigating = gesture.kind === 'add' || gesture.kind === 'move' || gesture.kind === 'resize';
|
||||
if (gesture.pointerType === 'touch' && !palm.evaluate(e, navigating ? 'navigate' : 'draw').accept) {
|
||||
if (gesture.pointerType === 'touch' && !palm.evaluate(e, gesture.kind === 'add' ? 'navigate' : 'draw').accept) {
|
||||
cancelGesture();
|
||||
return;
|
||||
}
|
||||
|
|
@ -758,35 +414,6 @@
|
|||
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);
|
||||
|
|
@ -809,42 +436,13 @@
|
|||
if (!gesture || gesture.pointerId !== e.pointerId) return;
|
||||
const g = gesture;
|
||||
gesture = null;
|
||||
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) {
|
||||
pushSample(g.trail, { ...local(e), t: e.timeStamp });
|
||||
// The view coasts on in the direction of the drag (a drag that stopped before lifting has ~no velocity).
|
||||
const v = releaseVelocity(g.trail);
|
||||
if (v) viewport.glide(v.vx, v.vy);
|
||||
if (g.pointerType === 'touch') offerAfterFling(g.trail);
|
||||
}
|
||||
} else if (g.kind === 'add') {
|
||||
if (g.kind === 'add') {
|
||||
if (e.type === 'pointerup' && (g.pointerType !== 'touch' || palm.evaluate(e, 'navigate').accept)) addPage(g.slot.anchor, g.slot.dir);
|
||||
} else if (g.kind === 'draw') {
|
||||
live = null;
|
||||
if (e.type === 'pointerup') doc.addStroke(g.pageId, g.rec.stroke);
|
||||
} else if (g.kind === 'erase') {
|
||||
// Like ink, an interrupted (pointercancel) erase is dropped.
|
||||
if (e.type === 'pointerup') for (const [pageId, ids] of g.hits) doc.setStrokes(pageId, (s) => s.filter((x) => !ids.has(x.id)));
|
||||
for (const [pageId, ids] of g.hits) doc.setStrokes(pageId, (s) => s.filter((x) => !ids.has(x.id)));
|
||||
erasing = new Set();
|
||||
}
|
||||
}
|
||||
|
|
@ -852,8 +450,6 @@
|
|||
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;
|
||||
}
|
||||
|
||||
|
|
@ -896,14 +492,11 @@
|
|||
}
|
||||
|
||||
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, p);
|
||||
if (id) pageMenu(e.clientX, e.clientY, id);
|
||||
}
|
||||
|
||||
// ---- keyboard --------------------------------------------------------
|
||||
|
|
@ -913,7 +506,7 @@
|
|||
}
|
||||
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (workspace.settingsOpen || sizing) return;
|
||||
if (workspace.settingsOpen) return;
|
||||
const mod = e.ctrlKey || e.metaKey;
|
||||
const k = e.key.toLowerCase();
|
||||
|
||||
|
|
@ -924,27 +517,6 @@
|
|||
|
||||
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') {
|
||||
|
|
@ -962,7 +534,7 @@
|
|||
return;
|
||||
}
|
||||
if (mod || e.altKey) return;
|
||||
const shortcuts: Record<string, typeof tools.tool> = { t: 'text', s: 'select', p: 'pen', h: 'highlighter', e: 'eraser' };
|
||||
const shortcuts: Record<string, typeof tools.tool> = { t: 'text', p: 'pen', h: 'highlighter', e: 'eraser' };
|
||||
if (shortcuts[k]) tools.tool = shortcuts[k];
|
||||
}
|
||||
|
||||
|
|
@ -973,16 +545,7 @@
|
|||
const panning = $derived(spaceDown);
|
||||
</script>
|
||||
|
||||
<svelte:window
|
||||
onkeydown={onKeyDown}
|
||||
onkeyup={onKeyUp}
|
||||
onblur={() => {
|
||||
spaceDown = false;
|
||||
clipFresh = false;
|
||||
}}
|
||||
oncopy={() => (clipFresh = false)}
|
||||
onpaste={onPaste}
|
||||
/>
|
||||
<svelte:window onkeydown={onKeyDown} onkeyup={onKeyUp} onblur={() => (spaceDown = false)} />
|
||||
|
||||
<div class="view">
|
||||
<header class="titlebar">
|
||||
|
|
@ -1001,9 +564,8 @@
|
|||
class:inking={tools.inking}
|
||||
class:panning
|
||||
class:erasing={tools.tool === 'eraser'}
|
||||
class:moving={!!selPreview}
|
||||
bind:this={stage}
|
||||
style={gridStyle}
|
||||
style="background-size: {grid.w}px {grid.h}px; background-position: {grid.x}px {grid.y}px"
|
||||
onpointerdown={onPointerDown}
|
||||
onpointermove={onPointerMove}
|
||||
onpointerup={onPointerUp}
|
||||
|
|
@ -1013,8 +575,6 @@
|
|||
eraserAt = null;
|
||||
}}
|
||||
oncontextmenu={onContextMenu}
|
||||
ondragover={onDragOver}
|
||||
ondrop={onDrop}
|
||||
>
|
||||
<div
|
||||
class="world"
|
||||
|
|
@ -1033,38 +593,18 @@
|
|||
live={live?.pageId === id ? live.stroke : null}
|
||||
{tick}
|
||||
{erasing}
|
||||
moving={moving?.pageId === id ? moving : null}
|
||||
onchange={() => doc.touch()}
|
||||
onactivate={() => (doc.activeId = id)}
|
||||
/>
|
||||
{/if}
|
||||
{/each}
|
||||
|
||||
{#if lasso && doc.rects.get(lasso.pageId)}
|
||||
{@const r = doc.rects.get(lasso.pageId)!}
|
||||
<svg class="lasso" style="left:{r.x}px; top:{r.y}px; width:{r.width}px; height:{r.height}px" viewBox="0 0 {r.width} {r.height}">
|
||||
<path d={lassoPath(lasso.points)} />
|
||||
</svg>
|
||||
{/if}
|
||||
|
||||
{#if selRect}
|
||||
<div class="sel-box" style="left:{selRect.x}px; top:{selRect.y}px; width:{selRect.width}px; height:{selRect.height}px"></div>
|
||||
{#each CORNERS as c (c)}
|
||||
<div
|
||||
class="sel-handle"
|
||||
data-corner={c}
|
||||
style="left:{c.includes('e') ? selRect.x + selRect.width : selRect.x}px; top:{c.includes('s') ? selRect.y + selRect.height : selRect.y}px"
|
||||
></div>
|
||||
{/each}
|
||||
{/if}
|
||||
|
||||
{#each ghostSlots as slot (slot.anchor + slot.dir)}
|
||||
{@const r = plusRect(slot)}
|
||||
{#if r}
|
||||
<!-- Pointer taps go through the palm-checked gesture; onclick only serves the keyboard. -->
|
||||
<button
|
||||
class="ghost"
|
||||
class:offer={offer?.anchor === slot.anchor && offer.dir === slot.dir}
|
||||
data-anchor={slot.anchor}
|
||||
data-dir={slot.dir}
|
||||
style="left:{r.x}px; top:{r.y}px; width:{r.width}px; height:{r.height}px"
|
||||
|
|
@ -1109,35 +649,6 @@
|
|||
</button>
|
||||
{/if}
|
||||
|
||||
{#if offer && offerOffscreen}
|
||||
<!-- Like the plus buttons, taps go through the palm-checked gesture. -->
|
||||
<button
|
||||
class="offer-pill"
|
||||
data-anchor={offer.anchor}
|
||||
data-dir={offer.dir}
|
||||
data-side={offer.dir}
|
||||
onclick={(e) => e.detail === 0 && offer && addPage(offer.anchor, offer.dir)}
|
||||
>
|
||||
<CirclePlusIcon size={18} strokeWidth={1.75} />
|
||||
Add page
|
||||
</button>
|
||||
{/if}
|
||||
|
||||
{#if selBar && selected}
|
||||
<div class="sel-bar no-stage" style="left:{selBar.x}px; top:{selBar.y}px" role="toolbar" aria-label="Selection">
|
||||
<button class="icon-btn" title="Copy (Ctrl+C)" onclick={copySelection}><CopyIcon size={16} strokeWidth={1.75} /></button>
|
||||
<button class="icon-btn" title="Cut (Ctrl+X)" onclick={() => copySelection() && deleteSelection()}><ScissorsIcon size={16} strokeWidth={1.75} /></button>
|
||||
<button class="icon-btn" title="Duplicate (Ctrl+D)" onclick={duplicateSelection}><CopyPlusIcon size={16} strokeWidth={1.75} /></button>
|
||||
<button class="icon-btn" title="Delete (Del)" onclick={deleteSelection}><TrashIcon size={16} strokeWidth={1.75} /></button>
|
||||
{#if selected.strokes.length}
|
||||
<span class="sep"></span>
|
||||
{#each settings.data.penColors as c (c)}
|
||||
<button class="swatch" style="--c: {c}" title="Recolour ink {c}" aria-label="Recolour ink {c}" onclick={() => recolor(c)}></button>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if eraserAt && tools.tool === 'eraser'}
|
||||
<div class="eraser-ring" style="left:{eraserAt.x}px; top:{eraserAt.y}px; width:{tools.eraserRadius * 2}px; height:{tools.eraserRadius * 2}px"></div>
|
||||
{/if}
|
||||
|
|
@ -1150,20 +661,7 @@
|
|||
{/if}
|
||||
</div>
|
||||
|
||||
{#if sizing && doc.pages[sizing]}
|
||||
{@const id = sizing}
|
||||
<PageSizeDialog
|
||||
width={doc.pages[id].width}
|
||||
height={doc.pages[id].height}
|
||||
onclose={() => (sizing = null)}
|
||||
onapply={(w, h) => {
|
||||
sizing = null;
|
||||
keepAnchor(id, () => doc.resizePage(id, w, h));
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<Toolbar {doc} onfit={() => fitPage(doc.activeId)} onfitall={fitAll} onimages={(files) => void insertImages(files)} />
|
||||
<Toolbar {doc} onfit={() => fitPage(doc.activeId)} onfitall={fitAll} />
|
||||
</div>
|
||||
|
||||
<style>
|
||||
|
|
@ -1208,6 +706,9 @@
|
|||
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;
|
||||
|
|
@ -1254,57 +755,6 @@
|
|||
border-radius: 50%;
|
||||
background: var(--bg-canvas);
|
||||
}
|
||||
.ghost.offer {
|
||||
color: var(--accent);
|
||||
}
|
||||
.ghost.offer .plus {
|
||||
animation: offer 1s ease-in-out infinite;
|
||||
}
|
||||
@keyframes offer {
|
||||
50% {
|
||||
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;
|
||||
}
|
||||
}
|
||||
.slot {
|
||||
position: absolute;
|
||||
display: grid;
|
||||
|
|
@ -1348,82 +798,6 @@
|
|||
background: var(--bg);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.lasso {
|
||||
position: absolute;
|
||||
overflow: visible;
|
||||
pointer-events: none;
|
||||
}
|
||||
.lasso path {
|
||||
fill: color-mix(in srgb, var(--accent) 8%, transparent);
|
||||
stroke: var(--accent);
|
||||
stroke-width: 1.25px;
|
||||
stroke-dasharray: 5 4;
|
||||
vector-effect: non-scaling-stroke;
|
||||
}
|
||||
.sel-box {
|
||||
position: absolute;
|
||||
border: calc(1.25px / var(--s)) dashed var(--accent);
|
||||
border-radius: calc(3px / var(--s));
|
||||
background: color-mix(in srgb, var(--accent) 5%, transparent);
|
||||
cursor: move;
|
||||
}
|
||||
.sel-handle {
|
||||
position: absolute;
|
||||
/* 24 px touch target around a 10 px square. */
|
||||
width: calc(24px / var(--s));
|
||||
height: calc(24px / var(--s));
|
||||
transform: translate(-50%, -50%);
|
||||
cursor: nwse-resize;
|
||||
}
|
||||
.sel-handle[data-corner='ne'],
|
||||
.sel-handle[data-corner='sw'] {
|
||||
cursor: nesw-resize;
|
||||
}
|
||||
.sel-handle::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: calc(7px / var(--s));
|
||||
background: var(--bg);
|
||||
border: calc(1.5px / var(--s)) solid var(--accent);
|
||||
border-radius: calc(2px / var(--s));
|
||||
}
|
||||
.stage.moving {
|
||||
cursor: move;
|
||||
}
|
||||
.sel-bar {
|
||||
position: absolute;
|
||||
transform: translateX(-50%);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
padding: 3px;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
box-shadow: var(--shadow);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.sel-bar .icon-btn {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
}
|
||||
.sel-bar .sep {
|
||||
width: 1px;
|
||||
height: 18px;
|
||||
background: var(--border);
|
||||
margin: 0 3px;
|
||||
}
|
||||
.sel-bar .swatch {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
margin: 0 1px;
|
||||
padding: 0;
|
||||
border-radius: 50%;
|
||||
border: 0;
|
||||
background: var(--c);
|
||||
box-shadow: inset 0 0 0 1px rgba(128, 128, 128, 0.35);
|
||||
cursor: pointer;
|
||||
}
|
||||
.eraser-ring {
|
||||
position: absolute;
|
||||
transform: translate(-50%, -50%);
|
||||
|
|
|
|||
|
|
@ -1,52 +0,0 @@
|
|||
<script lang="ts">
|
||||
import { transformImage, type Transform } from '$lib/ink/select';
|
||||
import type { PageImage } from '$lib/model/types';
|
||||
import { assets } from '$lib/images/assets.svelte';
|
||||
|
||||
interface Props {
|
||||
width: number;
|
||||
height: number;
|
||||
images: PageImage[];
|
||||
/** Selected objects being dragged or resized, shown transformed until release. */
|
||||
moving?: { ids: Set<string>; t: Transform } | null;
|
||||
}
|
||||
|
||||
let { width, height, images, moving = null }: Props = $props();
|
||||
|
||||
const pct = (v: number, of: number) => `${(v / of) * 100}%`;
|
||||
</script>
|
||||
|
||||
{#if images.length}
|
||||
<div class="images" aria-hidden="true">
|
||||
{#each images as img (img.id)}
|
||||
{@const m = moving?.ids.has(img.id) ? transformImage(img, moving.t) : img}
|
||||
{@const url = assets.url(img.assetId)}
|
||||
<div
|
||||
class="img"
|
||||
style="left:{pct(m.x, width)}; top:{pct(m.y, height)}; width:{pct(m.width, width)}; height:{pct(m.height, height)}"
|
||||
>
|
||||
{#if url}<img src={url} alt="" draggable="false" />{/if}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.images {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
.img {
|
||||
position: absolute;
|
||||
background: color-mix(in srgb, currentColor 6%, transparent);
|
||||
}
|
||||
.img:has(img) {
|
||||
background: none;
|
||||
}
|
||||
img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
<script lang="ts">
|
||||
import { svgPath, HIGHLIGHTER_OPACITY } from '$lib/ink/stroke';
|
||||
import { matrix, type Transform } from '$lib/ink/select';
|
||||
import type { Stroke } from '$lib/model/types';
|
||||
|
||||
interface Props {
|
||||
|
|
@ -12,11 +11,9 @@
|
|||
tick?: number;
|
||||
/** Strokes hidden while an eraser gesture is in progress. */
|
||||
erasing?: Set<string>;
|
||||
/** Selected objects being dragged or resized, shown transformed until release. */
|
||||
moving?: { ids: Set<string>; t: Transform } | null;
|
||||
}
|
||||
|
||||
let { width, height, strokes, live = null, tick = 0, erasing, moving = null }: Props = $props();
|
||||
let { width, height, strokes, live = null, tick = 0, erasing }: Props = $props();
|
||||
|
||||
const livePath = $derived.by(() => {
|
||||
void tick;
|
||||
|
|
@ -32,7 +29,6 @@
|
|||
fill={s.color}
|
||||
fill-opacity={s.tool === 'highlighter' ? HIGHLIGHTER_OPACITY : 1}
|
||||
class:hl={s.tool === 'highlighter'}
|
||||
transform={moving?.ids.has(s.id) ? matrix(moving.t) : undefined}
|
||||
/>
|
||||
{/if}
|
||||
{/each}
|
||||
|
|
|
|||
|
|
@ -1,173 +0,0 @@
|
|||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import ArrowLeftRightIcon from '@lucide/svelte/icons/arrow-left-right';
|
||||
import { PAGE_PRESETS } from '$lib/model/types';
|
||||
|
||||
let {
|
||||
width,
|
||||
height,
|
||||
onapply,
|
||||
onclose
|
||||
}: { width: number; height: number; onapply: (width: number, height: number) => void; onclose: () => void } = $props();
|
||||
|
||||
// Sizes are stored in points; people think in millimetres.
|
||||
const MIN_PT = 50;
|
||||
const MAX_PT = 5000;
|
||||
const toMm = (pt: number) => Math.round((pt / 72) * 25.4);
|
||||
const toPt = (mm: number) => (mm / 25.4) * 72;
|
||||
|
||||
// Start from the page's current size; edits are local until Apply.
|
||||
let w = $state(untrack(() => toMm(width)));
|
||||
let h = $state(untrack(() => toMm(height)));
|
||||
let first: HTMLInputElement;
|
||||
|
||||
const valid = $derived([w, h].every((v) => Number.isFinite(v) && toPt(v) >= MIN_PT && toPt(v) <= MAX_PT));
|
||||
|
||||
$effect(() => {
|
||||
first.focus();
|
||||
first.select();
|
||||
});
|
||||
|
||||
function apply() {
|
||||
if (!valid) return;
|
||||
// Whole millimetres would nudge exact sizes (A4 is 595.28 pt), so keep those as they are.
|
||||
const exact = [{ width, height }, ...PAGE_PRESETS].find((p) => toMm(p.width) === w && toMm(p.height) === h);
|
||||
if (exact) onapply(exact.width, exact.height);
|
||||
else onapply(toPt(w), toPt(h));
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={(e) => e.key === 'Escape' && onclose()} />
|
||||
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
|
||||
<div class="backdrop" onclick={(e) => e.target === e.currentTarget && onclose()}>
|
||||
<form
|
||||
class="dialog"
|
||||
aria-label="Page size"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
apply();
|
||||
}}
|
||||
>
|
||||
<h2>Page size</h2>
|
||||
<div class="presets">
|
||||
{#each PAGE_PRESETS as p (p.label)}
|
||||
<button
|
||||
type="button"
|
||||
class="chip"
|
||||
class:active={toMm(p.width) === w && toMm(p.height) === h}
|
||||
onclick={() => ((w = toMm(p.width)), (h = toMm(p.height)))}>{p.label}</button
|
||||
>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="fields">
|
||||
<label>
|
||||
<span>Width</span>
|
||||
<input type="number" inputmode="decimal" min={toMm(MIN_PT)} max={toMm(MAX_PT)} step="1" bind:value={w} bind:this={first} />
|
||||
</label>
|
||||
<button type="button" class="icon-btn" title="Swap width and height" onclick={() => ([w, h] = [h, w])}>
|
||||
<ArrowLeftRightIcon size={16} />
|
||||
</button>
|
||||
<label>
|
||||
<span>Height</span>
|
||||
<input type="number" inputmode="decimal" min={toMm(MIN_PT)} max={toMm(MAX_PT)} step="1" bind:value={h} />
|
||||
</label>
|
||||
<span class="unit">mm</span>
|
||||
</div>
|
||||
{#if !valid}
|
||||
<p class="hint">Sizes must be between {toMm(MIN_PT)} and {toMm(MAX_PT)} mm.</p>
|
||||
{/if}
|
||||
<div class="actions">
|
||||
<button type="button" class="btn" onclick={onclose}>Cancel</button>
|
||||
<button type="submit" class="btn primary" disabled={!valid}>Apply</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 50;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: rgba(0, 0, 0, 0.45);
|
||||
padding: 16px;
|
||||
}
|
||||
.dialog {
|
||||
width: min(400px, 100%);
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
box-shadow: var(--shadow);
|
||||
padding: 18px 20px 20px;
|
||||
}
|
||||
h2 {
|
||||
font-size: 16px;
|
||||
margin: 0 0 14px;
|
||||
}
|
||||
.presets {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.chip {
|
||||
border: 1px solid var(--border);
|
||||
background: none;
|
||||
color: var(--muted);
|
||||
border-radius: 14px;
|
||||
padding: 4px 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.chip:hover {
|
||||
color: var(--text);
|
||||
background: var(--hover);
|
||||
}
|
||||
.chip.active {
|
||||
color: var(--text);
|
||||
border-color: var(--accent);
|
||||
background: var(--accent-soft);
|
||||
}
|
||||
.fields {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
label span {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
input {
|
||||
width: 100%;
|
||||
}
|
||||
.fields .icon-btn {
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
.unit {
|
||||
color: var(--faint);
|
||||
padding-bottom: 7px;
|
||||
}
|
||||
.hint {
|
||||
color: var(--danger);
|
||||
font-size: 12px;
|
||||
margin: 8px 0 0;
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
.btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -5,8 +5,6 @@
|
|||
import MarkdownEditor from './MarkdownEditor.svelte';
|
||||
import PdfBackground from './PdfBackground.svelte';
|
||||
import InkLayer from './InkLayer.svelte';
|
||||
import ImageLayer from './ImageLayer.svelte';
|
||||
import type { Transform } from '$lib/ink/select';
|
||||
|
||||
interface Props {
|
||||
page: PageModel;
|
||||
|
|
@ -17,12 +15,11 @@
|
|||
live: Stroke | null;
|
||||
tick: number;
|
||||
erasing: Set<string>;
|
||||
moving: { ids: Set<string>; t: Transform } | null;
|
||||
onchange: () => void;
|
||||
onactivate: () => void;
|
||||
}
|
||||
|
||||
let { page, rect, active, invert, scale, live, tick, erasing, moving, onchange, onactivate }: Props = $props();
|
||||
let { page, rect, active, invert, scale, live, tick, erasing, onchange, onactivate }: Props = $props();
|
||||
</script>
|
||||
|
||||
<div
|
||||
|
|
@ -36,8 +33,7 @@
|
|||
<PdfBackground origin={page.origin} width={page.width} height={page.height} {scale} />
|
||||
{/if}
|
||||
<MarkdownEditor {page} {onchange} onfocus={onactivate} />
|
||||
<ImageLayer width={page.width} height={page.height} images={page.images} {moving} />
|
||||
<InkLayer width={page.width} height={page.height} strokes={page.strokes} {live} {tick} {erasing} {moving} />
|
||||
<InkLayer width={page.width} height={page.height} strokes={page.strokes} {live} {tick} {erasing} />
|
||||
</div>
|
||||
{#if page.origin && active}
|
||||
<div class="origin" style="font-size:{11 / scale}px; top:{-18 / scale}px">{page.origin.name} · p. {page.origin.pageIndex + 1}</div>
|
||||
|
|
@ -56,18 +52,9 @@
|
|||
/* 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;
|
||||
|
|
|
|||
|
|
@ -83,34 +83,12 @@
|
|||
<option value="paper">Paper</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div><div class="name">Background grid</div><div class="desc">Faint lines behind the pages, one cell per active page.</div></div>
|
||||
<input type="checkbox" class="toggle" bind:checked={s.grid.show} onchange={save} />
|
||||
</div>
|
||||
<div class="row">
|
||||
<div><div class="name">Grid subdivisions</div><div class="desc">Split each page-sized cell into a finer grid for sketching and lining things up.</div></div>
|
||||
<select bind:value={s.grid.divisions} onchange={save} disabled={!s.grid.show}>
|
||||
<option value={1}>None</option>
|
||||
<option value={2}>2 × 2</option>
|
||||
<option value={4}>4 × 4</option>
|
||||
<option value={8}>8 × 8</option>
|
||||
<option value={16}>16 × 16</option>
|
||||
</select>
|
||||
</div>
|
||||
{:else if tab === 'input'}
|
||||
<h2>Pen & touch</h2>
|
||||
<div class="row">
|
||||
<div><div class="name">Draw with finger</div><div class="desc">When off, a single finger always pans; only pen and mouse draw. Once you use a pen, fingers only pan and zoom.</div></div>
|
||||
<input type="checkbox" class="toggle" bind:checked={s.fingerDraw} onchange={save} />
|
||||
</div>
|
||||
<div class="row">
|
||||
<div><div class="name">Swipe to add pages</div><div class="desc">A quick one-finger flick toward a free side of the active page offers to add a page there.</div></div>
|
||||
<input type="checkbox" class="toggle" bind:checked={s.flingToAdd} onchange={save} />
|
||||
</div>
|
||||
<div class="row">
|
||||
<div><div class="name">Pen button selects</div><div class="desc">Hold the button on the side of the pen and draw a loop to select, whatever tool is active.</div></div>
|
||||
<input type="checkbox" class="toggle" bind:checked={s.penButtonSelect} onchange={save} />
|
||||
</div>
|
||||
<h3>Palm rejection</h3>
|
||||
<div class="row">
|
||||
<div><div class="name">Pen session lockout</div><div class="desc">Ignore touches while the pen is writing, and finger ink for 5 seconds after it was used.</div></div>
|
||||
|
|
|
|||
|
|
@ -1,7 +1,5 @@
|
|||
<script lang="ts">
|
||||
import TypeIcon from '@lucide/svelte/icons/type';
|
||||
import LassoIcon from '@lucide/svelte/icons/lasso-select';
|
||||
import ImagePlusIcon from '@lucide/svelte/icons/image-plus';
|
||||
import PenIcon from '@lucide/svelte/icons/pen-line';
|
||||
import HighlighterIcon from '@lucide/svelte/icons/highlighter';
|
||||
import EraserIcon from '@lucide/svelte/icons/eraser';
|
||||
|
|
@ -20,23 +18,13 @@
|
|||
import { vault } from '$lib/storage/vault.svelte';
|
||||
import { pagesFromPdf } from '$lib/pdf/read';
|
||||
|
||||
interface Props {
|
||||
doc: CanvasDoc;
|
||||
onfit: () => void;
|
||||
onfitall: () => void;
|
||||
/** Images picked with the "Insert image" button. */
|
||||
onimages: (files: File[]) => void;
|
||||
}
|
||||
|
||||
let { doc, onfit, onfitall, onimages }: Props = $props();
|
||||
let { doc, onfit, onfitall }: { doc: CanvasDoc; onfit: () => void; onfitall: () => void } = $props();
|
||||
|
||||
let fileInput: HTMLInputElement;
|
||||
let imageInput: HTMLInputElement;
|
||||
let colorInput = $state<HTMLInputElement>();
|
||||
|
||||
const TOOLS: { id: Tool; label: string; key: string; icon: Component }[] = [
|
||||
{ id: 'text', label: 'Text', key: 'T', icon: TypeIcon },
|
||||
{ id: 'select', label: 'Select', key: 'S', icon: LassoIcon },
|
||||
{ id: 'pen', label: 'Pen', key: 'P', icon: PenIcon },
|
||||
{ id: 'highlighter', label: 'Highlighter', key: 'H', icon: HighlighterIcon },
|
||||
{ id: 'eraser', label: 'Eraser', key: 'E', icon: EraserIcon }
|
||||
|
|
@ -118,7 +106,6 @@
|
|||
|
||||
<span class="sep"></span>
|
||||
<button class="icon-btn" title="Import PDF" onclick={() => fileInput.click()}><FileUpIcon size={18} strokeWidth={1.75} /></button>
|
||||
<button class="icon-btn" title="Insert image" onclick={() => imageInput.click()}><ImagePlusIcon size={18} strokeWidth={1.75} /></button>
|
||||
<button class="icon-btn" title="Undo (Ctrl+Z)" disabled={!doc.canUndo} onclick={() => doc.undo()}><UndoIcon size={18} strokeWidth={1.75} /></button>
|
||||
<button class="icon-btn" title="Redo (Ctrl+Shift+Z)" disabled={!doc.canRedo} onclick={() => doc.redo()}><RedoIcon size={18} strokeWidth={1.75} /></button>
|
||||
|
||||
|
|
@ -131,18 +118,6 @@
|
|||
</div>
|
||||
|
||||
<input bind:this={fileInput} type="file" accept="application/pdf,.pdf" hidden onchange={onFile} />
|
||||
<input
|
||||
bind:this={imageInput}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
hidden
|
||||
onchange={(e) => {
|
||||
const files = [...(e.currentTarget.files ?? [])];
|
||||
e.currentTarget.value = '';
|
||||
if (files.length) onimages(files);
|
||||
}}
|
||||
/>
|
||||
|
||||
<style>
|
||||
.dock {
|
||||
|
|
|
|||
|
|
@ -1,40 +0,0 @@
|
|||
// Pasted images: storing them, and object URLs for showing them.
|
||||
|
||||
import { SvelteMap } from 'svelte/reactivity';
|
||||
import { vault } from '$lib/storage/vault.svelte';
|
||||
import { imageKind, sha256Hex } from '$lib/pdf/format';
|
||||
import { prepareImage } from './normalize';
|
||||
|
||||
class Assets {
|
||||
private urls = new SvelteMap<string, string>();
|
||||
private loading = new Set<string>();
|
||||
|
||||
/** Object URL for an asset; undefined until its bytes are loaded (then reactive). */
|
||||
url(id: string): string | undefined {
|
||||
const u = this.urls.get(id);
|
||||
if (u || this.loading.has(id)) return u;
|
||||
this.loading.add(id);
|
||||
void vault.getAsset(id).then((bytes) => {
|
||||
if (bytes) this.prime(id, bytes);
|
||||
else this.loading.delete(id);
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private prime(id: string, bytes: Uint8Array) {
|
||||
if (this.urls.has(id)) return;
|
||||
const type = imageKind(bytes) === 'png' ? 'image/png' : 'image/jpeg';
|
||||
this.urls.set(id, URL.createObjectURL(new Blob([bytes as BlobPart], { type })));
|
||||
}
|
||||
|
||||
/** Normalise and store an image; returns its asset id and pixel size. */
|
||||
async add(blob: Blob) {
|
||||
const img = await prepareImage(blob);
|
||||
const id = await sha256Hex(img.bytes);
|
||||
await vault.putAsset(id, img.bytes);
|
||||
this.prime(id, img.bytes);
|
||||
return { id, width: img.width, height: img.height, bytes: img.bytes.length };
|
||||
}
|
||||
}
|
||||
|
||||
export const assets = new Assets();
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { imageKind } from '$lib/pdf/format';
|
||||
import { candidateKinds, fitScale } from './normalize';
|
||||
|
||||
describe('image normalisation', () => {
|
||||
it('caps the long edge', () => {
|
||||
expect(fitScale(1200, 800)).toBe(1);
|
||||
expect(fitScale(4800, 1200)).toBe(0.5);
|
||||
expect(fitScale(1000, 9600)).toBe(0.25);
|
||||
});
|
||||
|
||||
it('keeps transparency in PNG and JPEGs as JPEG', () => {
|
||||
expect(candidateKinds('png', true)).toEqual(['png']);
|
||||
expect(candidateKinds(null, true)).toEqual(['png']);
|
||||
expect(candidateKinds('jpeg', false)).toEqual(['jpeg']);
|
||||
expect(candidateKinds('png', false)).toEqual(['png', 'jpeg']);
|
||||
expect(candidateKinds(null, false)).toEqual(['png', 'jpeg']); // e.g. WebP
|
||||
});
|
||||
|
||||
it('sniffs PNG and JPEG', () => {
|
||||
expect(imageKind(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 13, 10]))).toBe('png');
|
||||
expect(imageKind(new Uint8Array([0xff, 0xd8, 0xff, 0xe0]))).toBe('jpeg');
|
||||
expect(imageKind(new Uint8Array([0x52, 0x49, 0x46, 0x46]))).toBeNull(); // RIFF (WebP)
|
||||
});
|
||||
});
|
||||
|
|
@ -1,75 +0,0 @@
|
|||
// Turn a pasted/dropped image into bytes a PDF can embed (PNG or JPEG), small
|
||||
// enough to live in a git-synced canvas.
|
||||
|
||||
import { imageKind, type ImageKind } from '$lib/pdf/format';
|
||||
|
||||
/** Longest edge kept, in pixels. */
|
||||
export const MAX_EDGE = 2400;
|
||||
export const JPEG_QUALITY = 0.85;
|
||||
|
||||
export interface PreparedImage {
|
||||
bytes: Uint8Array;
|
||||
kind: ImageKind;
|
||||
/** Pixel size of the stored image. */
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export function fitScale(width: number, height: number, max = MAX_EDGE) {
|
||||
return Math.min(1, max / Math.max(width, height));
|
||||
}
|
||||
|
||||
/**
|
||||
* Which encodings to try, given the source format and whether the pixels have transparency.
|
||||
* JPEG sources stay JPEG; anything transparent must be PNG; other opaque images try both.
|
||||
*/
|
||||
export function candidateKinds(source: ImageKind | null, alpha: boolean): ImageKind[] {
|
||||
if (alpha) return ['png'];
|
||||
if (source === 'jpeg') return ['jpeg'];
|
||||
return ['png', 'jpeg'];
|
||||
}
|
||||
|
||||
export async function prepareImage(blob: Blob): Promise<PreparedImage> {
|
||||
const original = new Uint8Array(await blob.arrayBuffer());
|
||||
const source = imageKind(original);
|
||||
// Applies EXIF orientation, so re-encoded JPEGs come out upright.
|
||||
const bmp = await createImageBitmap(blob);
|
||||
try {
|
||||
const k = fitScale(bmp.width, bmp.height);
|
||||
// A PNG that already fits is kept byte for byte.
|
||||
if (k === 1 && source === 'png') return { bytes: original, kind: 'png', width: bmp.width, height: bmp.height };
|
||||
|
||||
const width = Math.max(1, Math.round(bmp.width * k));
|
||||
const height = Math.max(1, Math.round(bmp.height * k));
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true })!;
|
||||
ctx.drawImage(bmp, 0, 0, width, height);
|
||||
const alpha = source !== 'jpeg' && hasAlpha(ctx.getImageData(0, 0, width, height).data);
|
||||
|
||||
let best: { bytes: Uint8Array; kind: ImageKind } | null = null;
|
||||
for (const kind of candidateKinds(source, alpha)) {
|
||||
const bytes = await encode(canvas, kind);
|
||||
if (!best || bytes.length < best.bytes.length) best = { bytes, kind };
|
||||
}
|
||||
return { ...best!, width, height };
|
||||
} finally {
|
||||
bmp.close();
|
||||
}
|
||||
}
|
||||
|
||||
function hasAlpha(px: Uint8ClampedArray) {
|
||||
for (let i = 3; i < px.length; i += 4) if (px[i] < 255) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function encode(canvas: HTMLCanvasElement, kind: ImageKind): Promise<Uint8Array> {
|
||||
return new Promise((resolve, reject) =>
|
||||
canvas.toBlob(
|
||||
(b) => (b ? b.arrayBuffer().then((a) => resolve(new Uint8Array(a)), reject) : reject(new Error('encode failed'))),
|
||||
kind === 'png' ? 'image/png' : 'image/jpeg',
|
||||
JPEG_QUALITY
|
||||
)
|
||||
);
|
||||
}
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
// Render page objects to a PNG, for the system clipboard.
|
||||
|
||||
import { HIGHLIGHTER_OPACITY, svgPath } from '$lib/ink/stroke';
|
||||
import type { Clip } from '$lib/ink/clip';
|
||||
|
||||
/** Pixels per point: 2 = crisp on high-DPI screens and in other apps. */
|
||||
const DENSITY = 2;
|
||||
const MAX_PX = 4096;
|
||||
|
||||
export async function renderClipPng(clip: Clip, urlFor: (assetId: string) => string | undefined): Promise<Blob> {
|
||||
const pad = 4;
|
||||
const k = Math.min(DENSITY, MAX_PX / (clip.width + pad * 2), MAX_PX / (clip.height + pad * 2));
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = Math.max(1, Math.ceil((clip.width + pad * 2) * k));
|
||||
canvas.height = Math.max(1, Math.ceil((clip.height + pad * 2) * k));
|
||||
const ctx = canvas.getContext('2d')!;
|
||||
ctx.scale(k, k);
|
||||
ctx.translate(pad, pad);
|
||||
|
||||
for (const m of clip.images) {
|
||||
const url = urlFor(m.assetId);
|
||||
if (!url) continue;
|
||||
const el = new Image();
|
||||
el.src = url;
|
||||
try {
|
||||
await el.decode();
|
||||
ctx.drawImage(el, m.x, m.y, m.width, m.height);
|
||||
} catch {
|
||||
/* skip an image that failed to load */
|
||||
}
|
||||
}
|
||||
for (const s of clip.strokes) {
|
||||
const hl = s.tool === 'highlighter';
|
||||
ctx.globalAlpha = hl ? HIGHLIGHTER_OPACITY : 1;
|
||||
ctx.globalCompositeOperation = hl ? 'multiply' : 'source-over';
|
||||
ctx.fillStyle = s.color;
|
||||
ctx.fill(new Path2D(svgPath(s)));
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('encode failed'))), 'image/png'));
|
||||
}
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import type { PageImage, Stroke } from '$lib/model/types';
|
||||
import { imageSize, instantiate, makeClip, placeCentred } from './clip';
|
||||
|
||||
const s: Stroke = { id: 's', tool: 'pen', color: '#000', width: 2, pressure: false, points: [110, 210, 0.5, 0, 0, 0, 150, 260, 0.5, 0, 0, 8] };
|
||||
const img: PageImage = { id: 'i', assetId: 'a', x: 100, y: 200, width: 20, height: 10 };
|
||||
const A4 = { width: 595.28, height: 841.89 };
|
||||
|
||||
describe('clip', () => {
|
||||
it('normalises to the bounding box and pastes fresh copies', () => {
|
||||
const clip = makeClip([s], [img])!;
|
||||
expect(clip).toMatchObject({ width: 51, height: 61 });
|
||||
expect(clip.images[0]).toMatchObject({ x: 0, y: 0 });
|
||||
expect(clip.strokes[0].points.slice(0, 2)).toEqual([10, 10]);
|
||||
|
||||
const pasted = instantiate(clip, 300, 400);
|
||||
expect(pasted.images[0]).toMatchObject({ x: 300, y: 400, assetId: 'a' });
|
||||
expect(pasted.strokes[0].points.slice(6, 8)).toEqual([350, 460]);
|
||||
expect(pasted.strokes[0].id).not.toBe('s');
|
||||
expect(pasted.images[0].id).not.toBe('i');
|
||||
expect(makeClip([], [])).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps pasted things on the page', () => {
|
||||
expect(placeCentred(300, 400, { width: 100, height: 50 }, A4)).toEqual({ x: 250, y: 375 });
|
||||
expect(placeCentred(10, 10, { width: 100, height: 50 }, A4)).toEqual({ x: 0, y: 0 });
|
||||
expect(placeCentred(590, 840, { width: 100, height: 50 }, A4)).toEqual({ x: 495.28, y: 791.89 });
|
||||
// Larger than the page: centred on it.
|
||||
expect(placeCentred(0, 0, { width: 700, height: 50 }, A4).x).toBeCloseTo(-52.36);
|
||||
});
|
||||
|
||||
it('sizes images at 96 dpi, at most 80 % of the page', () => {
|
||||
expect(imageSize({ width: 400, height: 200 }, A4)).toEqual({ width: 300, height: 150 });
|
||||
const big = imageSize({ width: 2400, height: 1200 }, A4);
|
||||
expect(big.width).toBeCloseTo(476.22);
|
||||
expect(big.height).toBeCloseTo(238.11);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
// Copy/paste of page objects and placing new ones on a page.
|
||||
|
||||
import { newId, type PageImage, type Stroke } from '$lib/model/types';
|
||||
import { objectsBounds, transformImage, transformStroke, translate } from './select';
|
||||
|
||||
/** Copied objects, moved so their bounding box starts at (0, 0). */
|
||||
export interface Clip {
|
||||
strokes: Stroke[];
|
||||
images: PageImage[];
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
interface Size {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export function makeClip(strokes: Stroke[], images: PageImage[]): Clip | null {
|
||||
const b = objectsBounds(strokes, images);
|
||||
if (!b) return null;
|
||||
const t = translate(-b.x1, -b.y1);
|
||||
return {
|
||||
strokes: strokes.map((s) => transformStroke(s, t)),
|
||||
images: images.map((m) => transformImage(m, t)),
|
||||
width: b.x2 - b.x1,
|
||||
height: b.y2 - b.y1
|
||||
};
|
||||
}
|
||||
|
||||
/** Top-left for a box of `size` centred on (cx, cy), kept on the page where it fits. */
|
||||
export function placeCentred(cx: number, cy: number, size: Size, page: Size) {
|
||||
const clamp = (v: number, len: number, max: number) => (len >= max ? (max - len) / 2 : Math.min(Math.max(v, 0), max - len));
|
||||
return { x: clamp(cx - size.width / 2, size.width, page.width), y: clamp(cy - size.height / 2, size.height, page.height) };
|
||||
}
|
||||
|
||||
/** Fresh copies of a clip with its top-left at (x, y). */
|
||||
export function instantiate(clip: Clip, x: number, y: number) {
|
||||
const t = translate(x, y);
|
||||
return {
|
||||
strokes: clip.strokes.map((s) => ({ ...transformStroke(s, t), id: newId() })),
|
||||
images: clip.images.map((m) => ({ ...transformImage(m, t), id: newId() }))
|
||||
};
|
||||
}
|
||||
|
||||
/** Size in points of a pasted image: 1 px = 0.75 pt (96 dpi), shrunk to 80 % of the page. */
|
||||
export function imageSize(px: Size, page: Size): Size {
|
||||
const w = px.width * 0.75;
|
||||
const h = px.height * 0.75;
|
||||
const k = Math.min(1, (page.width * 0.8) / w, (page.height * 0.8) / h);
|
||||
return { width: Math.round(w * k * 100) / 100, height: Math.round(h * k * 100) / 100 };
|
||||
}
|
||||
|
|
@ -1,93 +0,0 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { flingDir, GLIDE_TAU, glideStep, pushSample, releaseVelocity, type Sample } from './fling';
|
||||
|
||||
/** A straight drag from (0,0) by (dx,dy) over `ms`, sampled every 16 ms. */
|
||||
function drag(dx: number, dy: number, ms: number): Sample[] {
|
||||
const out: Sample[] = [];
|
||||
for (let t = 0; t <= ms; t += 16) pushSample(out, { x: (dx * t) / ms, y: (dy * t) / ms, t });
|
||||
return out;
|
||||
}
|
||||
|
||||
describe('flingDir', () => {
|
||||
it('maps a flick to the side it reveals', () => {
|
||||
expect(flingDir(drag(-200, 0, 96))).toBe('right');
|
||||
expect(flingDir(drag(200, 0, 96))).toBe('left');
|
||||
expect(flingDir(drag(0, -200, 96))).toBe('down');
|
||||
expect(flingDir(drag(0, 200, 96))).toBe('up');
|
||||
});
|
||||
|
||||
it('ignores slow drags', () => {
|
||||
expect(flingDir(drag(-200, 0, 800))).toBeNull();
|
||||
});
|
||||
|
||||
it('ignores diagonal flicks', () => {
|
||||
expect(flingDir(drag(-200, -150, 96))).toBeNull();
|
||||
});
|
||||
|
||||
it('ignores a drag that stops before lifting', () => {
|
||||
const s = drag(-300, 0, 96);
|
||||
const end = s.at(-1)!;
|
||||
for (let t = 16; t <= 160; t += 16) pushSample(s, { ...end, t: end.t + t });
|
||||
expect(flingDir(s)).toBeNull();
|
||||
});
|
||||
|
||||
it('needs at least two samples', () => {
|
||||
expect(flingDir([])).toBeNull();
|
||||
expect(flingDir([{ x: 0, y: 0, t: 0 }])).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the trail short', () => {
|
||||
const s = drag(-2000, 0, 2000);
|
||||
expect(s.at(-1)!.t - s[0].t).toBeLessThanOrEqual(216);
|
||||
});
|
||||
});
|
||||
|
||||
describe('releaseVelocity', () => {
|
||||
it('measures the speed and direction at release', () => {
|
||||
const v = releaseVelocity(drag(-200, 100, 96))!;
|
||||
expect(v.vx).toBeCloseTo(-200 / 96);
|
||||
expect(v.vy).toBeCloseTo(100 / 96);
|
||||
});
|
||||
|
||||
it('is zero for a drag that stops before lifting', () => {
|
||||
const s = drag(-300, 0, 96);
|
||||
const end = s.at(-1)!;
|
||||
for (let t = 16; t <= 160; t += 16) pushSample(s, { ...end, t: end.t + t });
|
||||
expect(releaseVelocity(s)).toEqual({ vx: 0, vy: 0 });
|
||||
});
|
||||
|
||||
it('needs at least two samples', () => {
|
||||
expect(releaseVelocity([{ x: 0, y: 0, t: 0 }])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('glideStep', () => {
|
||||
it('slows down and coasts GLIDE_TAU × speed in total', () => {
|
||||
let vx = 2;
|
||||
let vy = -1;
|
||||
let x = 0;
|
||||
let y = 0;
|
||||
for (let i = 0; i < 1000; i++) {
|
||||
const s = glideStep(vx, vy, 16);
|
||||
expect(Math.abs(s.vx)).toBeLessThan(Math.abs(vx));
|
||||
({ vx, vy } = s);
|
||||
x += s.dx;
|
||||
y += s.dy;
|
||||
}
|
||||
expect(x).toBeCloseTo(2 * GLIDE_TAU);
|
||||
expect(y).toBeCloseTo(-GLIDE_TAU);
|
||||
});
|
||||
|
||||
it('does not depend on the frame rate', () => {
|
||||
const once = glideStep(1, 0, 64);
|
||||
let v = 1;
|
||||
let x = 0;
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const s = glideStep(v, 0, 16);
|
||||
v = s.vx;
|
||||
x += s.dx;
|
||||
}
|
||||
expect(x).toBeCloseTo(once.dx);
|
||||
expect(v).toBeCloseTo(once.vx);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
// Fling detection and momentum for pans: a quick flick that ends the drag.
|
||||
|
||||
import type { Dir } from '$lib/model/tree';
|
||||
|
||||
export interface Sample {
|
||||
x: number;
|
||||
y: number;
|
||||
t: number;
|
||||
}
|
||||
|
||||
/** Only the last stretch of the drag counts. */
|
||||
const WINDOW_MS = 100;
|
||||
/** px/ms; a slow drag that stops is not a fling. */
|
||||
const MIN_SPEED = 0.6;
|
||||
/** The main axis must dominate by this much. */
|
||||
const MIN_RATIO = 2;
|
||||
|
||||
/** Pointer velocity at release in px/ms, from the last stretch of the drag; null if there is too little trail to tell. */
|
||||
export function releaseVelocity(samples: readonly Sample[]): { vx: number; vy: number } | null {
|
||||
const last = samples.at(-1);
|
||||
if (!last) return null;
|
||||
const first = samples.find((s) => last.t - s.t <= WINDOW_MS);
|
||||
if (!first || first === last) return null;
|
||||
const dt = last.t - first.t;
|
||||
if (dt <= 0) return null;
|
||||
return { vx: (last.x - first.x) / dt, vy: (last.y - first.y) / dt };
|
||||
}
|
||||
|
||||
/**
|
||||
* Side of the canvas a fling heads for, or null. Moving the finger left pulls in
|
||||
* what's on the right, so a leftward flick returns 'right'.
|
||||
*/
|
||||
export function flingDir(samples: readonly Sample[]): Dir | null {
|
||||
const v = releaseVelocity(samples);
|
||||
if (!v || Math.hypot(v.vx, v.vy) < MIN_SPEED) return null;
|
||||
const { vx: dx, vy: dy } = v;
|
||||
if (Math.abs(dx) >= Math.abs(dy) * MIN_RATIO) return dx < 0 ? 'right' : 'left';
|
||||
if (Math.abs(dy) >= Math.abs(dx) * MIN_RATIO) return dy < 0 ? 'down' : 'up';
|
||||
return null;
|
||||
}
|
||||
|
||||
// Momentum: after release the view keeps moving and slows under drag, with
|
||||
// velocity decaying exponentially (v' = -v / GLIDE_TAU). It coasts
|
||||
// GLIDE_TAU × release speed in total, e.g. 325 px after a 1 px/ms flick.
|
||||
|
||||
/** Decay time constant, ms. Larger = less drag, longer glide. */
|
||||
export const GLIDE_TAU = 325;
|
||||
/** px/ms; releases slower than this don't glide, and a glide stops once it drops below it. */
|
||||
export const GLIDE_MIN_SPEED = 0.02;
|
||||
/** px/ms; caps a wild flick so it can't throw the view miles away. */
|
||||
export const GLIDE_MAX_SPEED = 6;
|
||||
|
||||
/** Advances a glide by `dt` ms: how far it moves and the velocity left afterwards. */
|
||||
export function glideStep(vx: number, vy: number, dt: number) {
|
||||
const decay = Math.exp(-dt / GLIDE_TAU);
|
||||
const travel = GLIDE_TAU * (1 - decay);
|
||||
return { dx: vx * travel, dy: vy * travel, vx: vx * decay, vy: vy * decay };
|
||||
}
|
||||
|
||||
/** Keeps a short trail of pointer samples for flingDir. */
|
||||
export function pushSample(samples: Sample[], s: Sample) {
|
||||
samples.push(s);
|
||||
while (samples.length > 2 && s.t - samples[0].t > WINDOW_MS * 2) samples.shift();
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { PalmRejector, touchIntent } from './palm';
|
||||
import { PalmRejector } from './palm';
|
||||
|
||||
const ev = (type: string, pointerType: string, extra: Partial<PointerEvent> = {}) =>
|
||||
({ type, pointerType, pointerId: pointerType === 'pen' ? 1 : 2, width: 10, height: 10, ...extra }) as PointerEvent;
|
||||
|
|
@ -53,37 +53,4 @@ describe('palm rejection', () => {
|
|||
it('allows finger ink again once the pen session ends', () => {
|
||||
expect(afterPen(5100).evaluate(touch(), 'draw').accept).toBe(true);
|
||||
});
|
||||
|
||||
describe('add-page button taps', () => {
|
||||
// With a pen in use fingers don't ink, but finger ink may still be on (before any pen).
|
||||
const tap = (palm: PalmRejector, extra: Partial<PointerEvent> = {}, fingerInks = false) =>
|
||||
palm.evaluate(touch(extra), touchIntent(fingerInks, true));
|
||||
|
||||
it('are handled as navigation even when fingers ink', () => {
|
||||
expect(touchIntent(true, true)).toBe('navigate');
|
||||
expect(touchIntent(false, true)).toBe('navigate');
|
||||
expect(touchIntent(true, false)).toBe('draw');
|
||||
expect(touchIntent(false, false)).toBe('navigate');
|
||||
});
|
||||
|
||||
it('are accepted a couple of seconds after writing', () => {
|
||||
expect(tap(afterPen(2000)).accept).toBe(true);
|
||||
expect(tap(afterPen(2000), {}, true).accept).toBe(true);
|
||||
});
|
||||
|
||||
it('are accepted while the pen hovers', () => {
|
||||
expect(tap(afterPen(2000, { leave: false })).accept).toBe(true);
|
||||
});
|
||||
|
||||
it('are rejected while the pen is down', () => {
|
||||
const palm = new PalmRejector();
|
||||
palm.track(ev('pointerdown', 'pen'));
|
||||
expect(tap(palm).accept).toBe(false);
|
||||
});
|
||||
|
||||
it('are rejected for a palm or right after the pen', () => {
|
||||
expect(tap(afterPen(2000), { width: 60, height: 40 }).accept).toBe(false);
|
||||
expect(tap(afterPen(50)).accept).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -27,15 +27,6 @@ const PALM_CONTACT_PX = 35;
|
|||
/** What an accepted touch would do: ink (draw/erase) or pan/zoom. */
|
||||
export type TouchIntent = 'draw' | 'navigate';
|
||||
|
||||
/**
|
||||
* Which policy a touch falls under. It only draws when finger ink is on and it
|
||||
* didn't land on a button; taps on buttons (e.g. add page) navigate, so they keep
|
||||
* working between pen strokes.
|
||||
*/
|
||||
export function touchIntent(fingerInks: boolean, onButton: boolean): TouchIntent {
|
||||
return fingerInks && !onButton ? 'draw' : 'navigate';
|
||||
}
|
||||
|
||||
export interface Decision {
|
||||
accept: boolean;
|
||||
reason: string;
|
||||
|
|
|
|||
|
|
@ -1,88 +0,0 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import type { PageImage, Stroke } from '$lib/model/types';
|
||||
import {
|
||||
hitObject,
|
||||
imageInLasso,
|
||||
lassoSelect,
|
||||
objectsBounds,
|
||||
pointInPolygon,
|
||||
scaleAbout,
|
||||
strokeInLasso,
|
||||
transformImage,
|
||||
transformStroke,
|
||||
translate
|
||||
} from './select';
|
||||
|
||||
const square = [0, 0, 100, 0, 100, 100, 0, 100];
|
||||
|
||||
function stroke(id: string, xy: number[], width = 2): Stroke {
|
||||
const points: number[] = [];
|
||||
for (let i = 0; i < xy.length; i += 2) points.push(xy[i], xy[i + 1], 0.5, 0, 0, i * 8);
|
||||
return { id, tool: 'pen', color: '#000', width, pressure: false, points };
|
||||
}
|
||||
|
||||
const image = (id: string, x: number, y: number, w: number, h: number): PageImage => ({ id, assetId: 'a', x, y, width: w, height: h });
|
||||
|
||||
describe('lasso', () => {
|
||||
it('tests points against the loop (even-odd)', () => {
|
||||
expect(pointInPolygon(50, 50, square)).toBe(true);
|
||||
expect(pointInPolygon(150, 50, square)).toBe(false);
|
||||
// A "C" shape: the notch is outside.
|
||||
const c = [0, 0, 100, 0, 100, 30, 30, 30, 30, 70, 100, 70, 100, 100, 0, 100];
|
||||
expect(pointInPolygon(60, 50, c)).toBe(false);
|
||||
expect(pointInPolygon(15, 50, c)).toBe(true);
|
||||
});
|
||||
|
||||
it('selects a stroke only when all of it is inside', () => {
|
||||
expect(strokeInLasso(stroke('in', [10, 10, 50, 50, 90, 20]), square)).toBe(true);
|
||||
expect(strokeInLasso(stroke('out', [10, 10, 50, 50, 120, 20]), square)).toBe(false);
|
||||
expect(strokeInLasso(stroke('in', [10, 10]), [0, 0, 100, 0])).toBe(false); // not a loop
|
||||
});
|
||||
|
||||
it('selects an image only when all four corners are inside', () => {
|
||||
expect(imageInLasso(image('i', 10, 10, 50, 50), square)).toBe(true);
|
||||
expect(imageInLasso(image('i', 60, 60, 50, 50), square)).toBe(false);
|
||||
});
|
||||
|
||||
it('returns the ids of everything fully inside', () => {
|
||||
const sel = lassoSelect(
|
||||
[stroke('a', [10, 10, 20, 20]), stroke('b', [10, 10, 200, 20])],
|
||||
[image('x', 5, 5, 10, 10), image('y', 90, 90, 20, 20)],
|
||||
square
|
||||
);
|
||||
expect(sel).toEqual({ strokes: ['a'], images: ['x'] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('hit testing', () => {
|
||||
it('prefers ink over images and later objects over earlier ones', () => {
|
||||
const strokes = [stroke('a', [0, 50, 100, 50]), stroke('b', [0, 50, 100, 50])];
|
||||
const images = [image('x', 0, 0, 100, 100)];
|
||||
expect(hitObject(strokes, images, 50, 50, 3)).toEqual({ kind: 'stroke', id: 'b' });
|
||||
expect(hitObject(strokes, images, 50, 10, 3)).toEqual({ kind: 'image', id: 'x' });
|
||||
expect(hitObject(strokes, images, 150, 10, 3)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('transforms', () => {
|
||||
it('bounds strokes by their visible edge and images by their box', () => {
|
||||
expect(objectsBounds([stroke('a', [10, 20, 30, 40], 4)], [image('x', 50, 0, 10, 10)])).toEqual({ x1: 8, y1: 0, x2: 60, y2: 42 });
|
||||
expect(objectsBounds([], [])).toBeNull();
|
||||
});
|
||||
|
||||
it('moves and scales strokes, keeping pressure/tilt/time', () => {
|
||||
const s = stroke('a', [10, 10, 20, 30], 2);
|
||||
const moved = transformStroke(s, translate(5, -5));
|
||||
expect(moved.points).toEqual([15, 5, 0.5, 0, 0, 0, 25, 25, 0.5, 0, 0, 16]);
|
||||
expect(moved.id).toBe('a');
|
||||
const scaled = transformStroke(s, scaleAbout(2, 10, 10));
|
||||
expect(scaled.points.slice(0, 2)).toEqual([10, 10]);
|
||||
expect(scaled.points.slice(6, 8)).toEqual([30, 50]);
|
||||
expect(scaled.width).toBe(4);
|
||||
expect(s.points[6]).toBe(20); // original untouched
|
||||
});
|
||||
|
||||
it('scales images about a fixed corner', () => {
|
||||
expect(transformImage(image('x', 10, 10, 20, 10), scaleAbout(0.5, 30, 20))).toMatchObject({ x: 20, y: 15, width: 10, height: 5 });
|
||||
});
|
||||
});
|
||||
|
|
@ -1,124 +0,0 @@
|
|||
// Lasso selection, hit testing and transforms for page objects (strokes and images).
|
||||
|
||||
import { STRIDE, type PageImage, type Stroke } from '$lib/model/types';
|
||||
import { hitStroke, strokeBounds } from './stroke';
|
||||
|
||||
export interface Box {
|
||||
x1: number;
|
||||
y1: number;
|
||||
x2: number;
|
||||
y2: number;
|
||||
}
|
||||
|
||||
/** Uniform scale `k` about the origin, then a translation: p' = p·k + (tx, ty). */
|
||||
export interface Transform {
|
||||
k: number;
|
||||
tx: number;
|
||||
ty: number;
|
||||
}
|
||||
|
||||
export const IDENTITY: Transform = { k: 1, tx: 0, ty: 0 };
|
||||
|
||||
/** Even-odd point-in-polygon; `poly` is flat [x0, y0, x1, y1, …] and closed implicitly. */
|
||||
export function pointInPolygon(x: number, y: number, poly: number[]): boolean {
|
||||
let inside = false;
|
||||
const n = poly.length;
|
||||
for (let i = 0, j = n - 2; i < n; j = i, i += 2) {
|
||||
const xi = poly[i], yi = poly[i + 1], xj = poly[j], yj = poly[j + 1];
|
||||
if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
|
||||
}
|
||||
return inside;
|
||||
}
|
||||
|
||||
/** A stroke is lassoed only when every sample lies inside the loop. */
|
||||
export function strokeInLasso(s: Stroke, poly: number[]): boolean {
|
||||
if (poly.length < 6 || s.points.length === 0) return false;
|
||||
for (let i = 0; i < s.points.length; i += STRIDE) {
|
||||
if (!pointInPolygon(s.points[i], s.points[i + 1], poly)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** An image is lassoed only when all four corners lie inside the loop. */
|
||||
export function imageInLasso(img: PageImage, poly: number[]): boolean {
|
||||
if (poly.length < 6) return false;
|
||||
const { x, y, width: w, height: h } = img;
|
||||
return [
|
||||
[x, y],
|
||||
[x + w, y],
|
||||
[x + w, y + h],
|
||||
[x, y + h]
|
||||
].every(([px, py]) => pointInPolygon(px, py, poly));
|
||||
}
|
||||
|
||||
export function lassoSelect(strokes: Stroke[], images: PageImage[], poly: number[]) {
|
||||
return {
|
||||
strokes: strokes.filter((s) => strokeInLasso(s, poly)).map((s) => s.id),
|
||||
images: images.filter((i) => imageInLasso(i, poly)).map((i) => i.id)
|
||||
};
|
||||
}
|
||||
|
||||
/** Top-most object under a point: ink is drawn above images, later objects above earlier ones. */
|
||||
export function hitObject(
|
||||
strokes: Stroke[],
|
||||
images: PageImage[],
|
||||
x: number,
|
||||
y: number,
|
||||
r: number
|
||||
): { kind: 'stroke' | 'image'; id: string } | null {
|
||||
for (let i = strokes.length - 1; i >= 0; i--) {
|
||||
if (hitStroke(strokes[i], x, y, r)) return { kind: 'stroke', id: strokes[i].id };
|
||||
}
|
||||
for (let i = images.length - 1; i >= 0; i--) {
|
||||
const m = images[i];
|
||||
if (x >= m.x && x <= m.x + m.width && y >= m.y && y <= m.y + m.height) return { kind: 'image', id: m.id };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function objectsBounds(strokes: Stroke[], images: PageImage[]): Box | null {
|
||||
let b: Box | null = null;
|
||||
const grow = (x1: number, y1: number, x2: number, y2: number) => {
|
||||
b = b
|
||||
? { x1: Math.min(b.x1, x1), y1: Math.min(b.y1, y1), x2: Math.max(b.x2, x2), y2: Math.max(b.y2, y2) }
|
||||
: { x1, y1, x2, y2 };
|
||||
};
|
||||
for (const s of strokes) {
|
||||
if (s.points.length === 0) continue;
|
||||
const sb = strokeBounds(s);
|
||||
// strokeBounds pads by the full width; half of it is the visible edge.
|
||||
const pad = s.width / 2;
|
||||
grow(sb.x1 + pad, sb.y1 + pad, sb.x2 - pad, sb.y2 - pad);
|
||||
}
|
||||
for (const m of images) grow(m.x, m.y, m.x + m.width, m.y + m.height);
|
||||
return b;
|
||||
}
|
||||
|
||||
const r2 = (v: number) => Math.round(v * 100) / 100;
|
||||
|
||||
export function transformStroke(s: Stroke, t: Transform): Stroke {
|
||||
const points = s.points.slice();
|
||||
for (let i = 0; i < points.length; i += STRIDE) {
|
||||
points[i] = r2(points[i] * t.k + t.tx);
|
||||
points[i + 1] = r2(points[i + 1] * t.k + t.ty);
|
||||
}
|
||||
return { ...s, points, width: r2(s.width * t.k) };
|
||||
}
|
||||
|
||||
export function transformImage(m: PageImage, t: Transform): PageImage {
|
||||
return {
|
||||
...m,
|
||||
x: r2(m.x * t.k + t.tx),
|
||||
y: r2(m.y * t.k + t.ty),
|
||||
width: r2(m.width * t.k),
|
||||
height: r2(m.height * t.k)
|
||||
};
|
||||
}
|
||||
|
||||
export const translate = (dx: number, dy: number): Transform => ({ k: 1, tx: dx, ty: dy });
|
||||
|
||||
/** Uniform scale by `k` keeping the point (ax, ay) fixed. */
|
||||
export const scaleAbout = (k: number, ax: number, ay: number): Transform => ({ k, tx: ax - ax * k, ty: ay - ay * k });
|
||||
|
||||
/** SVG/CSS matrix for a transform in page-local points. */
|
||||
export const matrix = (t: Transform) => `matrix(${t.k} 0 0 ${t.k} ${t.tx} ${t.ty})`;
|
||||
|
|
@ -42,26 +42,12 @@ export interface Origin {
|
|||
name: string;
|
||||
}
|
||||
|
||||
/** A pasted image placed on a page, drawn above the markdown and under the ink. */
|
||||
export interface PageImage {
|
||||
id: string;
|
||||
/** Content hash of the image bytes (key in the assets store). */
|
||||
assetId: string;
|
||||
/** Page-local points, origin top-left. */
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface PageData {
|
||||
id: string;
|
||||
width: number;
|
||||
height: number;
|
||||
markdown: string;
|
||||
strokes: Stroke[];
|
||||
/** Missing on canvases saved before images existed. */
|
||||
images?: PageImage[];
|
||||
origin?: Origin;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,20 +4,9 @@ export const ATTACH = {
|
|||
manifest: 'papure/manifest.json',
|
||||
markdown: (id: string) => `papure/pages/${id}.md`,
|
||||
ink: (id: string) => `papure/pages/${id}.ink.json`,
|
||||
images: (id: string) => `papure/pages/${id}.images.json`,
|
||||
source: (id: string) => `papure/sources/${id}.pdf`,
|
||||
asset: (id: string, kind: ImageKind) => `papure/assets/${id}.${kind === 'png' ? 'png' : 'jpg'}`
|
||||
source: (id: string) => `papure/sources/${id}.pdf`
|
||||
};
|
||||
|
||||
export type ImageKind = 'png' | 'jpeg';
|
||||
|
||||
/** PNG or JPEG, by magic bytes (the only raster formats a PDF embeds directly). */
|
||||
export function imageKind(bytes: Uint8Array): ImageKind | null {
|
||||
if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return 'png';
|
||||
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'jpeg';
|
||||
return null;
|
||||
}
|
||||
|
||||
export const FORMAT = 'papure';
|
||||
|
||||
export async function sha256Hex(bytes: Uint8Array, length = 24): Promise<string> {
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import {
|
|||
decodePDFRawStream
|
||||
} from 'pdf-lib';
|
||||
import { withTrunk, flatten, type Tree } from '$lib/model/tree';
|
||||
import { newId, type CanvasData, type Origin, type PageData, type PageImage, type Stroke } from '$lib/model/types';
|
||||
import { newId, type CanvasData, type Origin, type PageData, type Stroke } from '$lib/model/types';
|
||||
import { ATTACH, FORMAT, sha256Hex } from './format';
|
||||
import { normRotation } from './write';
|
||||
|
||||
|
|
@ -22,8 +22,6 @@ export interface ReadResult {
|
|||
data: CanvasData;
|
||||
/** Source PDFs referenced by pages, keyed by source id. */
|
||||
sources: Map<string, Uint8Array>;
|
||||
/** Pasted images referenced by pages, keyed by asset id. */
|
||||
assets: Map<string, Uint8Array>;
|
||||
/** True when the file had no Papure layer and was imported as-is. */
|
||||
imported: boolean;
|
||||
}
|
||||
|
|
@ -58,16 +56,13 @@ function fromAttachments(files: Map<string, Uint8Array>, m: Manifest) {
|
|||
if (!meta) continue;
|
||||
const md = files.get(ATTACH.markdown(id));
|
||||
const ink = files.get(ATTACH.ink(id));
|
||||
const imgs = files.get(ATTACH.images(id));
|
||||
const images = imgs ? (JSON.parse(text(imgs)).images as PageImage[]) : [];
|
||||
pages[id] = {
|
||||
id,
|
||||
width: meta.width,
|
||||
height: meta.height,
|
||||
origin: meta.origin,
|
||||
markdown: md ? text(md) : '',
|
||||
strokes: ink ? (JSON.parse(text(ink)).strokes as Stroke[]) : [],
|
||||
...(images.length ? { images } : {})
|
||||
strokes: ink ? (JSON.parse(text(ink)).strokes as Stroke[]) : []
|
||||
};
|
||||
}
|
||||
const sources = new Map<string, Uint8Array>();
|
||||
|
|
@ -76,16 +71,8 @@ function fromAttachments(files: Map<string, Uint8Array>, m: Manifest) {
|
|||
const b = files.get(ATTACH.source(p.origin.sourceId));
|
||||
if (b) sources.set(p.origin.sourceId, b);
|
||||
}
|
||||
const assets = new Map<string, Uint8Array>();
|
||||
for (const p of Object.values(pages)) {
|
||||
for (const img of p.images ?? []) {
|
||||
if (assets.has(img.assetId)) continue;
|
||||
const b = files.get(ATTACH.asset(img.assetId, 'png')) ?? files.get(ATTACH.asset(img.assetId, 'jpeg'));
|
||||
if (b) assets.set(img.assetId, b);
|
||||
}
|
||||
}
|
||||
const data: CanvasData = { version: 1, updatedAt: m.updatedAt, tree: m.tree, pages };
|
||||
return { data, sources, assets };
|
||||
return { data, sources };
|
||||
}
|
||||
|
||||
/** Pages of a PDF as they appear on screen (CropBox, /Rotate applied). */
|
||||
|
|
@ -121,7 +108,7 @@ async function importPdf(bytes: Uint8Array, name: string, doc: PDFDocument): Pro
|
|||
tree: withTrunk(pages.map((p) => p.id)),
|
||||
pages: Object.fromEntries(pages.map((p) => [p.id, p]))
|
||||
};
|
||||
return { data, sources: new Map([[sourceId, bytes]]), assets: new Map(), imported: true };
|
||||
return { data, sources: new Map([[sourceId, bytes]]), imported: true };
|
||||
}
|
||||
|
||||
const round = (v: number) => Math.round(v * 100) / 100;
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { insert, withTrunk } from '$lib/model/tree';
|
|||
import type { CanvasData, Stroke } from '$lib/model/types';
|
||||
import { setFontLoader } from './fonts';
|
||||
import { canvasToPdf } from './write';
|
||||
import { readAttachments, readCanvasPdf } from './read';
|
||||
import { readCanvasPdf } from './read';
|
||||
|
||||
beforeAll(() => {
|
||||
setFontLoader(async (f) => new Uint8Array(await readFile(`static/fonts/${f}`)));
|
||||
|
|
@ -81,33 +81,6 @@ describe('pdf round trip', () => {
|
|||
const doc = await PDFDocument.load(bytes);
|
||||
expect(doc.getPage(1).getSize()).toEqual({ width: 200, height: 500 });
|
||||
});
|
||||
|
||||
it('draws pasted images and restores them with their bytes', async () => {
|
||||
// 1×1 red PNG.
|
||||
const png = Uint8Array.from(
|
||||
atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=='),
|
||||
(c) => c.charCodeAt(0)
|
||||
);
|
||||
const data = sample();
|
||||
const img = { id: 'i1', assetId: 'png1', x: 20, y: 30, width: 100, height: 50 };
|
||||
data.pages.a.images = [img];
|
||||
data.pages.b.images = [{ ...img, id: 'i2', y: 200 }];
|
||||
const bytes = await canvasToPdf(data, { title: 't', getSource: async () => undefined, getAsset: async (id) => (id === 'png1' ? png : undefined) });
|
||||
|
||||
const doc = await PDFDocument.load(bytes);
|
||||
const xobjects = (i: number) => doc.getPage(i).node.Resources()?.lookup(PDFName.of('XObject'));
|
||||
expect(xobjects(0)).toBeTruthy();
|
||||
|
||||
const back = await readCanvasPdf(bytes, 'x.pdf');
|
||||
expect(back.data.pages.a.images).toEqual([img]);
|
||||
expect(back.data.pages.b.images?.[0].id).toBe('i2');
|
||||
expect(back.data.pages.r.images).toBeUndefined();
|
||||
expect([...back.assets.keys()]).toEqual(['png1']);
|
||||
expect(back.assets.get('png1')).toEqual(png);
|
||||
// Stored once although placed twice.
|
||||
const names = [...readAttachments(doc).keys()];
|
||||
expect(names.filter((n) => n.startsWith('papure/assets/'))).toEqual(['papure/assets/png1.png']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('imported pages', () => {
|
||||
|
|
|
|||
|
|
@ -15,7 +15,6 @@ import {
|
|||
PDFString,
|
||||
degrees,
|
||||
type PDFEmbeddedPage,
|
||||
type PDFImage,
|
||||
type PDFPage
|
||||
} from 'pdf-lib';
|
||||
|
||||
|
|
@ -28,15 +27,13 @@ interface EmbeddedSource {
|
|||
import { flatten } from '$lib/model/tree';
|
||||
import type { CanvasData, PageData, Stroke } from '$lib/model/types';
|
||||
import { HIGHLIGHTER_OPACITY, outline, samples } from '$lib/ink/stroke';
|
||||
import { ATTACH, FORMAT, imageKind } from './format';
|
||||
import { ATTACH, FORMAT } from './format';
|
||||
import { loadFonts } from './fonts';
|
||||
import { drawMarkdown, fontsNeeded, hex, type Fonts, type Metrics } from './text';
|
||||
|
||||
export interface WriteOptions {
|
||||
title: string;
|
||||
getSource: (id: string) => Promise<Uint8Array | undefined>;
|
||||
/** Bytes of a pasted image (PNG or JPEG) by asset id. */
|
||||
getAsset?: (id: string) => Promise<Uint8Array | undefined>;
|
||||
}
|
||||
|
||||
export async function canvasToPdf(data: CanvasData, opts: WriteOptions): Promise<Uint8Array> {
|
||||
|
|
@ -53,7 +50,6 @@ export async function canvasToPdf(data: CanvasData, opts: WriteOptions): Promise
|
|||
const embedded = await embedSources(doc, pages, opts.getSource);
|
||||
const hasText = pages.some((p) => p.markdown.trim());
|
||||
const text = hasText ? await embedFonts(doc, pages) : null;
|
||||
const images = await embedImages(doc, pages, opts.getAsset);
|
||||
|
||||
for (const p of pages) {
|
||||
const page = doc.addPage([p.width, p.height]);
|
||||
|
|
@ -63,10 +59,6 @@ export async function canvasToPdf(data: CanvasData, opts: WriteOptions): Promise
|
|||
copyMarkupAnnotations(doc, page, src);
|
||||
}
|
||||
if (text && p.markdown.trim()) drawMarkdown(page, p.markdown, text.fonts, text.metrics);
|
||||
for (const m of p.images ?? []) {
|
||||
const img = images.get(m.assetId);
|
||||
if (img) page.drawImage(img.image, { x: m.x, y: p.height - m.y - m.height, width: m.width, height: m.height });
|
||||
}
|
||||
for (const s of p.strokes) addInkAnnotation(doc, page, s);
|
||||
}
|
||||
if (pages.length === 0) doc.addPage([595.28, 841.89]);
|
||||
|
|
@ -92,10 +84,6 @@ export async function canvasToPdf(data: CanvasData, opts: WriteOptions): Promise
|
|||
for (const p of pages) {
|
||||
if (p.markdown) await attach(p.markdown, ATTACH.markdown(p.id), 'text/markdown');
|
||||
if (p.strokes.length) await attach(JSON.stringify({ strokes: p.strokes }), ATTACH.ink(p.id), 'application/json');
|
||||
if (p.images?.length) await attach(JSON.stringify({ images: p.images }), ATTACH.images(p.id), 'application/json');
|
||||
}
|
||||
for (const [id, { bytes, kind }] of images) {
|
||||
await attach(bytes, ATTACH.asset(id, kind), kind === 'png' ? 'image/png' : 'image/jpeg');
|
||||
}
|
||||
const sourceIds = new Set(pages.flatMap((p) => (p.origin ? [p.origin.sourceId] : [])));
|
||||
for (const id of sourceIds) {
|
||||
|
|
@ -106,27 +94,6 @@ export async function canvasToPdf(data: CanvasData, opts: WriteOptions): Promise
|
|||
return doc.save({ useObjectStreams: true });
|
||||
}
|
||||
|
||||
/** Each pasted image once, however many times it is placed. */
|
||||
async function embedImages(doc: PDFDocument, pages: PageData[], getAsset: WriteOptions['getAsset']) {
|
||||
const out = new Map<string, { image: PDFImage; bytes: Uint8Array; kind: 'png' | 'jpeg' }>();
|
||||
if (!getAsset) return out;
|
||||
for (const p of pages) {
|
||||
for (const m of p.images ?? []) {
|
||||
if (out.has(m.assetId)) continue;
|
||||
const bytes = await getAsset(m.assetId);
|
||||
const kind = bytes && imageKind(bytes);
|
||||
if (!bytes || !kind) continue;
|
||||
try {
|
||||
const image = kind === 'png' ? await doc.embedPng(bytes) : await doc.embedJpg(bytes);
|
||||
out.set(m.assetId, { image, bytes, kind });
|
||||
} catch (err) {
|
||||
console.warn('Could not embed image', m.assetId, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function embedFonts(doc: PDFDocument, pages: PageData[]) {
|
||||
const needed = new Set<keyof Fonts>(['regular']);
|
||||
for (const p of pages) fontsNeeded(p.markdown, needed);
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
import { layout, type Rect } from '$lib/model/layout';
|
||||
import { insert, remove, canInsert, flatten, withTrunk, type Dir, type Tree } from '$lib/model/tree';
|
||||
import { A4, newId, type CanvasData, type Origin, type PageData, type PageImage, type Stroke } from '$lib/model/types';
|
||||
import { A4, newId, type CanvasData, type Origin, type PageData, type Stroke } from '$lib/model/types';
|
||||
|
||||
export class PageModel {
|
||||
readonly id: string;
|
||||
|
|
@ -10,7 +10,6 @@ export class PageModel {
|
|||
height = $state(A4.height);
|
||||
markdown = $state('');
|
||||
strokes = $state.raw<Stroke[]>([]);
|
||||
images = $state.raw<PageImage[]>([]);
|
||||
readonly origin?: Origin;
|
||||
|
||||
constructor(d: PageData) {
|
||||
|
|
@ -19,7 +18,6 @@ export class PageModel {
|
|||
this.height = d.height;
|
||||
this.markdown = d.markdown;
|
||||
this.strokes = d.strokes;
|
||||
this.images = d.images ?? [];
|
||||
this.origin = d.origin;
|
||||
}
|
||||
|
||||
|
|
@ -30,17 +28,11 @@ export class PageModel {
|
|||
height: this.height,
|
||||
markdown: this.markdown,
|
||||
strokes: this.strokes,
|
||||
...(this.images.length ? { images: this.images } : {}),
|
||||
...(this.origin ? { origin: this.origin } : {})
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export interface PageObjects {
|
||||
strokes: Stroke[];
|
||||
images: PageImage[];
|
||||
}
|
||||
|
||||
interface Command {
|
||||
undo(): void;
|
||||
redo(): void;
|
||||
|
|
@ -144,21 +136,6 @@ export class CanvasDoc {
|
|||
});
|
||||
}
|
||||
|
||||
/** Replace a page's strokes and images together as one undoable step. */
|
||||
setObjects(pageId: string, fn: (o: PageObjects) => PageObjects) {
|
||||
const page = this.pages[pageId];
|
||||
if (!page) return;
|
||||
const before = { strokes: page.strokes, images: page.images };
|
||||
const after = fn(before);
|
||||
if (after.strokes === before.strokes && after.images === before.images) return;
|
||||
const apply = (o: PageObjects) => {
|
||||
const p = this.pages[pageId];
|
||||
p.strokes = o.strokes;
|
||||
p.images = o.images;
|
||||
};
|
||||
this.exec({ redo: () => apply(after), undo: () => apply(before) });
|
||||
}
|
||||
|
||||
// ---- tree ------------------------------------------------------------
|
||||
|
||||
private treeCommand(nextTree: Tree, nextPages: Record<string, PageModel>, nextActive: string | null) {
|
||||
|
|
@ -194,7 +171,7 @@ export class CanvasDoc {
|
|||
get isBlank() {
|
||||
const ids = this.order;
|
||||
const p = ids.length === 1 ? this.pages[ids[0]] : null;
|
||||
return !!p && !p.origin && !p.markdown.trim() && p.strokes.length === 0 && p.images.length === 0;
|
||||
return !!p && !p.origin && !p.markdown.trim() && p.strokes.length === 0;
|
||||
}
|
||||
|
||||
/** Replace every page with a new trunk (importing into a blank canvas). */
|
||||
|
|
|
|||
|
|
@ -6,12 +6,6 @@ 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;
|
||||
|
|
@ -24,12 +18,7 @@ export interface GitHubSettings {
|
|||
interface SettingsData {
|
||||
theme: ThemePref;
|
||||
pageStyle: PageStylePref;
|
||||
grid: GridSettings;
|
||||
fingerDraw: boolean;
|
||||
/** A finger fling toward a free side of the active page offers a new page there. */
|
||||
flingToAdd: boolean;
|
||||
/** Holding the pen's barrel button lassoes, whatever tool is active. */
|
||||
penButtonSelect: boolean;
|
||||
palm: PalmOptions;
|
||||
github: GitHubSettings;
|
||||
/** Minutes between automatic pushes (0 = manual only). */
|
||||
|
|
@ -41,10 +30,7 @@ interface SettingsData {
|
|||
const DEFAULTS: SettingsData = {
|
||||
theme: 'system',
|
||||
pageStyle: 'match',
|
||||
grid: { show: true, divisions: 1 },
|
||||
fingerDraw: true,
|
||||
flingToAdd: true,
|
||||
penButtonSelect: true,
|
||||
palm: DEFAULT_PALM,
|
||||
github: { token: '', owner: '', repo: '', branch: 'main', dir: '' },
|
||||
pushInterval: 5,
|
||||
|
|
@ -62,7 +48,6 @@ function load(): SettingsData {
|
|||
return {
|
||||
...DEFAULTS,
|
||||
...saved,
|
||||
grid: { ...DEFAULTS.grid, ...saved.grid },
|
||||
palm: { ...DEFAULTS.palm, ...saved.palm },
|
||||
github: { ...DEFAULTS.github, ...saved.github }
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import type { PageData } from '$lib/model/types';
|
||||
import { settings } from './settings.svelte';
|
||||
|
||||
export type Tool = 'text' | 'select' | 'pen' | 'highlighter' | 'eraser';
|
||||
export type Tool = 'text' | 'pen' | 'highlighter' | 'eraser';
|
||||
|
||||
export const PEN_WIDTHS = [1.2, 2, 3.5];
|
||||
export const HIGHLIGHTER_WIDTHS = [10, 16, 24];
|
||||
|
|
@ -17,7 +17,6 @@ class Tools {
|
|||
/** Pages of an imported PDF waiting to be placed on the canvas. */
|
||||
placing = $state.raw<{ name: string; pages: PageData[] } | null>(null);
|
||||
|
||||
/** A pointer tool (select, ink, eraser) rather than typing: pages don't take text focus. */
|
||||
get inking() {
|
||||
return this.tool !== 'text';
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
// Pan/zoom of the canvas view. World units are PDF points.
|
||||
|
||||
import type { Rect } from '$lib/model/layout';
|
||||
import { GLIDE_MAX_SPEED, GLIDE_MIN_SPEED, glideStep } from '$lib/ink/fling';
|
||||
|
||||
export const MIN_SCALE = 0.04;
|
||||
export const MAX_SCALE = 8;
|
||||
|
|
@ -14,8 +13,6 @@ class Viewport {
|
|||
/** Size of the stage element. */
|
||||
width = $state(0);
|
||||
height = $state(0);
|
||||
/** Pending animation frame of a momentum glide, 0 when still. */
|
||||
private glideFrame = 0;
|
||||
|
||||
toWorld(sx: number, sy: number) {
|
||||
return { x: (sx - this.x) / this.scale, y: (sy - this.y) / this.scale };
|
||||
|
|
@ -31,7 +28,6 @@ class Viewport {
|
|||
}
|
||||
|
||||
zoomAt(factor: number, sx = this.width / 2, sy = this.height / 2) {
|
||||
this.stopGlide();
|
||||
const next = Math.min(MAX_SCALE, Math.max(MIN_SCALE, this.scale * factor));
|
||||
const w = this.toWorld(sx, sy);
|
||||
this.scale = next;
|
||||
|
|
@ -40,44 +36,12 @@ class Viewport {
|
|||
}
|
||||
|
||||
panBy(dx: number, dy: number) {
|
||||
this.stopGlide();
|
||||
this.x += dx;
|
||||
this.y += dy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep panning after a drag is released, at velocity (vx, vy) px/ms, slowing to
|
||||
* a stop. Only the position moves; the zoom stays as it is. Any other view change
|
||||
* (pan, zoom, fit) stops it.
|
||||
*/
|
||||
glide(vx: number, vy: number) {
|
||||
this.stopGlide();
|
||||
const speed = Math.hypot(vx, vy);
|
||||
if (speed < GLIDE_MIN_SPEED) return;
|
||||
if (speed > GLIDE_MAX_SPEED) {
|
||||
vx *= GLIDE_MAX_SPEED / speed;
|
||||
vy *= GLIDE_MAX_SPEED / speed;
|
||||
}
|
||||
let last = performance.now();
|
||||
const frame = (now: number) => {
|
||||
const s = glideStep(vx, vy, Math.max(0, now - last));
|
||||
last = now;
|
||||
this.x += s.dx;
|
||||
this.y += s.dy;
|
||||
({ vx, vy } = s);
|
||||
this.glideFrame = Math.hypot(vx, vy) < GLIDE_MIN_SPEED ? 0 : requestAnimationFrame(frame);
|
||||
};
|
||||
this.glideFrame = requestAnimationFrame(frame);
|
||||
}
|
||||
|
||||
stopGlide() {
|
||||
if (this.glideFrame) cancelAnimationFrame(this.glideFrame);
|
||||
this.glideFrame = 0;
|
||||
}
|
||||
|
||||
/** Fit a world rectangle into the stage with some padding. */
|
||||
fit(r: Rect, pad = 24) {
|
||||
this.stopGlide();
|
||||
if (!this.width || !this.height) return;
|
||||
const s = Math.min((this.width - 2 * pad) / r.width, (this.height - 2 * pad) / r.height);
|
||||
this.scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, s));
|
||||
|
|
@ -87,7 +51,6 @@ class Viewport {
|
|||
|
||||
/** Pan so the rectangle is centred, keeping the zoom. */
|
||||
center(r: Rect) {
|
||||
this.stopGlide();
|
||||
this.x = this.width / 2 - (r.x + r.width / 2) * this.scale;
|
||||
this.y = this.height / 2 - (r.y + r.height / 2) * this.scale;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,8 +25,6 @@ interface Schema extends DBSchema {
|
|||
files: { key: string; value: FileRecord };
|
||||
docs: { key: string; value: CanvasData };
|
||||
sources: { key: string; value: Uint8Array };
|
||||
/** Pasted image bytes (PNG or JPEG), keyed by content hash. */
|
||||
assets: { key: string; value: Uint8Array };
|
||||
search: { key: string; value: SearchRecord };
|
||||
kv: { key: string; value: unknown };
|
||||
}
|
||||
|
|
@ -34,16 +32,13 @@ interface Schema extends DBSchema {
|
|||
let dbp: Promise<IDBPDatabase<Schema>> | null = null;
|
||||
|
||||
export function db() {
|
||||
dbp ??= openDB<Schema>('papure', 2, {
|
||||
upgrade(d, oldVersion) {
|
||||
if (oldVersion < 1) {
|
||||
d.createObjectStore('files', { keyPath: 'path' });
|
||||
d.createObjectStore('docs');
|
||||
d.createObjectStore('sources');
|
||||
d.createObjectStore('search', { keyPath: 'path' });
|
||||
d.createObjectStore('kv');
|
||||
}
|
||||
if (oldVersion < 2) d.createObjectStore('assets');
|
||||
dbp ??= openDB<Schema>('papure', 1, {
|
||||
upgrade(d) {
|
||||
d.createObjectStore('files', { keyPath: 'path' });
|
||||
d.createObjectStore('docs');
|
||||
d.createObjectStore('sources');
|
||||
d.createObjectStore('search', { keyPath: 'path' });
|
||||
d.createObjectStore('kv');
|
||||
}
|
||||
});
|
||||
return dbp;
|
||||
|
|
|
|||
|
|
@ -91,9 +91,8 @@ class Vault {
|
|||
|
||||
async importPdfAsCanvas(dir: string, file: File) {
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
const { data, sources, assets } = await readCanvasPdf(bytes, file.name);
|
||||
const { data, sources } = await readCanvasPdf(bytes, file.name);
|
||||
for (const [id, b] of sources) await this.putSource(id, b);
|
||||
for (const [id, b] of assets) await this.putAsset(id, b);
|
||||
return this.createCanvas(dir, file.name.replace(/\.pdf$/i, ''), data);
|
||||
}
|
||||
|
||||
|
|
@ -200,29 +199,16 @@ class Vault {
|
|||
await (await db()).put('sources', bytes, id);
|
||||
}
|
||||
|
||||
async getAsset(id: string) {
|
||||
return (await db()).get('assets', id);
|
||||
}
|
||||
|
||||
async putAsset(id: string, bytes: Uint8Array) {
|
||||
await (await db()).put('assets', bytes, id);
|
||||
}
|
||||
|
||||
async buildPdf(path: string): Promise<Uint8Array> {
|
||||
const data = await this.loadDoc(path);
|
||||
if (!data) throw new Error(`No such canvas: ${path}`);
|
||||
return canvasToPdf(data, {
|
||||
title: displayName(path),
|
||||
getSource: (id) => this.getSource(id),
|
||||
getAsset: (id) => this.getAsset(id)
|
||||
});
|
||||
return canvasToPdf(data, { title: displayName(path), getSource: (id) => this.getSource(id) });
|
||||
}
|
||||
|
||||
/** Store a PDF pulled from the repo as the local working copy. */
|
||||
async ingestPdf(path: string, bytes: Uint8Array, remoteSha: string) {
|
||||
const { data, sources, assets } = await readCanvasPdf(bytes, baseName(path));
|
||||
const { data, sources } = await readCanvasPdf(bytes, baseName(path));
|
||||
for (const [id, b] of sources) await this.putSource(id, b);
|
||||
for (const [id, b] of assets) await this.putAsset(id, b);
|
||||
await this.saveDoc(path, data, { remoteSha, clean: true });
|
||||
return data;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue