Compare commits
No commits in common. "main" and "sw-bypass-http-cache" have entirely different histories.
main
...
sw-bypass-
36 changed files with 80 additions and 2032 deletions
|
|
@ -1,8 +1,4 @@
|
|||
# Keep just enough of .git for the build to read the current commit.
|
||||
.git/*
|
||||
!.git/HEAD
|
||||
!.git/refs
|
||||
!.git/packed-refs
|
||||
.git
|
||||
.claude
|
||||
node_modules
|
||||
.svelte-kit
|
||||
|
|
|
|||
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)
|
||||
|
|
|
|||
|
|
@ -59,9 +59,7 @@
|
|||
--success: #2f9e5c;
|
||||
--warn: #d9901b;
|
||||
--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);
|
||||
--page-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 0 0 1px rgba(0, 0, 0, 0.04);
|
||||
--ghost: rgba(0, 0, 0, 0.045);
|
||||
--ghost-border: rgba(0, 0, 0, 0.12);
|
||||
--radius: 6px;
|
||||
|
|
@ -87,9 +85,7 @@
|
|||
--success: #44cf6e;
|
||||
--warn: #e9973f;
|
||||
--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);
|
||||
--page-shadow: 0 0 0 1px rgba(255, 255, 255, 0.06), 0 2px 8px rgba(0, 0, 0, 0.5);
|
||||
--ghost: rgba(255, 255, 255, 0.04);
|
||||
--ghost-border: rgba(255, 255, 255, 0.14);
|
||||
color-scheme: dark;
|
||||
|
|
|
|||
3
src/app.d.ts
vendored
3
src/app.d.ts
vendored
|
|
@ -1,9 +1,6 @@
|
|||
// See https://svelte.dev/docs/kit/types#app.d.ts
|
||||
declare global {
|
||||
namespace App {}
|
||||
|
||||
/** Stamped in by vite.config.ts at build time. */
|
||||
const __BUILD__: { version: string; commit: string; dirty: boolean; time: string };
|
||||
}
|
||||
|
||||
export {};
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -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>
|
||||
|
|
@ -53,21 +49,11 @@
|
|||
inset: 0;
|
||||
background: #ffffff;
|
||||
overflow: hidden;
|
||||
/* Crisp 1 screen-px outline, no blur. */
|
||||
box-shadow: 0 0 0 calc(1px / var(--s)) var(--page-line);
|
||||
box-shadow: var(--page-shadow);
|
||||
}
|
||||
/* 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;
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@
|
|||
type Tab = 'appearance' | 'input' | 'sync';
|
||||
let tab = $state<Tab>('appearance');
|
||||
const s = settings.data;
|
||||
const build = __BUILD__;
|
||||
|
||||
let testing = $state(false);
|
||||
let testResult = $state<{ ok: boolean; text: string } | null>(null);
|
||||
|
|
@ -56,9 +55,6 @@
|
|||
<button class:active={tab === 'appearance'} onclick={() => (tab = 'appearance')}>Appearance</button>
|
||||
<button class:active={tab === 'input'} onclick={() => (tab = 'input')}>Pen & touch</button>
|
||||
<button class:active={tab === 'sync'} onclick={() => (tab = 'sync')}>Sync</button>
|
||||
<div class="build" title={`Commit ${build.commit}\nBuilt ${new Date(build.time).toLocaleString()}`}>
|
||||
v{build.version} · {build.commit.slice(0, 7)}{build.dirty ? '-dirty' : ''}
|
||||
</div>
|
||||
</nav>
|
||||
<section>
|
||||
<button class="icon-btn close" title="Close" onclick={close}><XIcon size={18} /></button>
|
||||
|
|
@ -83,34 +79,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>
|
||||
|
|
@ -213,14 +187,6 @@
|
|||
color: var(--faint);
|
||||
padding: 0 10px 8px;
|
||||
}
|
||||
.build {
|
||||
margin-top: auto;
|
||||
padding: 0 10px;
|
||||
font-family: var(--mono-font);
|
||||
font-size: 11px;
|
||||
color: var(--faint);
|
||||
user-select: text;
|
||||
}
|
||||
nav button {
|
||||
text-align: left;
|
||||
border: 0;
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,40 +1,8 @@
|
|||
import { execSync } from 'node:child_process';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { sveltekit } from '@sveltejs/kit/vite';
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
/** Current commit. Uses git when available, else reads .git directly (the Docker build has no git binary). */
|
||||
function gitCommit(): { commit: string; dirty: boolean } {
|
||||
if (process.env.GIT_COMMIT) return { commit: process.env.GIT_COMMIT, dirty: false };
|
||||
try {
|
||||
const commit = execSync('git rev-parse HEAD', { stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
|
||||
const dirty = execSync('git status --porcelain --untracked-files=no', { stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim() !== '';
|
||||
return { commit, dirty };
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
try {
|
||||
const head = readFileSync('.git/HEAD', 'utf8').trim();
|
||||
if (!head.startsWith('ref: ')) return { commit: head, dirty: false };
|
||||
const ref = head.slice(5);
|
||||
if (existsSync(`.git/${ref}`)) return { commit: readFileSync(`.git/${ref}`, 'utf8').trim(), dirty: false };
|
||||
const packed = readFileSync('.git/packed-refs', 'utf8').split('\n').find((l) => l.endsWith(` ${ref}`));
|
||||
if (packed) return { commit: packed.split(' ')[0], dirty: false };
|
||||
} catch {
|
||||
/* no repository */
|
||||
}
|
||||
return { commit: 'unknown', dirty: false };
|
||||
}
|
||||
|
||||
const build = {
|
||||
version: JSON.parse(readFileSync('package.json', 'utf8')).version as string,
|
||||
...gitCommit(),
|
||||
time: new Date().toISOString()
|
||||
};
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [sveltekit()],
|
||||
define: { __BUILD__: JSON.stringify(build) },
|
||||
test: {
|
||||
include: ['src/**/*.test.ts'],
|
||||
environment: 'node'
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue