Add lasso selection and pasted images

Select tool (S): lasso picks ink strokes and images that lie entirely
inside the loop, a tap picks one object. Move, uniform resize, nudge,
delete, recolour, copy/cut/paste/duplicate, each one undo step. Holding
the pen's barrel button lassoes with any tool (Settings > Pen & touch).
Copying also writes a PNG of the selection to the system clipboard.

Images come in by paste, drop, the Insert image button or the page menu.
They are capped at 2400 px, stored as PNG/JPEG by content hash in a new
IndexedDB store, drawn between the markdown and the ink, and written to
the PDF both visibly and as papure/assets + per-page images.json.

Dark pages now invert each layer except images, so images keep their
colours; the inverted ink layer is screen-blended so highlighted text
stays bright.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UcbKnqfprs8hMkTVsYx1dh
This commit is contained in:
agent 2026-09-29 21:05:02 +00:00
parent 894291df7f
commit 84b9d4469f
26 changed files with 1274 additions and 39 deletions

View file

@ -6,6 +6,10 @@
import ArrowUpIcon from '@lucide/svelte/icons/arrow-up';
import TrashIcon from '@lucide/svelte/icons/trash-2';
import CheckIcon from '@lucide/svelte/icons/check';
import CopyIcon from '@lucide/svelte/icons/copy';
import CopyPlusIcon from '@lucide/svelte/icons/copy-plus';
import ScissorsIcon from '@lucide/svelte/icons/scissors';
import ClipboardPasteIcon from '@lucide/svelte/icons/clipboard-paste';
import type { CanvasDoc } from '$lib/state/doc.svelte';
import { viewport } from '$lib/state/viewport.svelte';
import { tools } from '$lib/state/tools.svelte';
@ -15,10 +19,24 @@
import { dirName, displayName } from '$lib/storage/vault.svelte';
import { bounds, intersects, rectBeside, type Rect } from '$lib/model/layout';
import { canInsert, freeSlots, freeSlotsOf, neighbor, type Dir, type Slot } from '$lib/model/tree';
import { A4, PAGE_PRESETS, type Stroke } from '$lib/model/types';
import { A4, PAGE_PRESETS, newId, type PageImage, type Stroke } from '$lib/model/types';
import { PalmRejector, touchIntent } from '$lib/ink/palm';
import { flingDir, pushSample, type Sample } from '$lib/ink/fling';
import { StrokeRecorder, hitStroke } from '$lib/ink/stroke';
import {
IDENTITY,
hitObject,
lassoSelect,
objectsBounds,
scaleAbout,
transformImage,
transformStroke,
translate,
type Transform
} from '$lib/ink/select';
import { imageSize, instantiate, makeClip, placeCentred, type Clip } from '$lib/ink/clip';
import { assets } from '$lib/images/assets.svelte';
import { renderClipPng } from '$lib/images/png';
import { pageCssVars } from '$lib/editor/pageStyle';
import { downloadCanvas } from './download';
import PageSizeDialog from './PageSizeDialog.svelte';
@ -231,10 +249,12 @@
}
// ---- page menu -------------------------------------------------------
function pageMenu(x: number, y: number, id: string) {
/** `at`: stage-local point to paste at (the right-click position). */
function pageMenu(x: number, y: number, id: string, at?: { x: number; y: number }) {
const page = doc.pages[id];
if (!page) return;
doc.activeId = id;
const canRead = typeof navigator !== 'undefined' && !!navigator.clipboard?.read;
const dirs: [Dir, string][] = [
['up', 'Insert page above'],
['down', 'Insert page below'],
@ -259,6 +279,7 @@
}
items.push({ label: 'Custom size…', action: () => customSize(id) });
}
items.push('separator', { label: 'Paste', icon: ClipboardPasteIcon, disabled: !clip && !canRead, action: () => void pasteFromMenu(at) });
items.push('separator', { label: 'Delete page', icon: TrashIcon, danger: true, action: () => doc.deletePage(id) });
menu.show(x, y, items);
}
@ -286,6 +307,9 @@
| { kind: 'erase'; pointerId: number; pointerType: string; hits: Map<string, Set<string>> }
| { kind: 'pan'; pointerId: number; pointerType: string; lastX: number; lastY: number; startX: number; startY: number; moved: boolean; tap: boolean; trail: Sample[] }
| { kind: 'add'; pointerId: number; pointerType: string; startX: number; startY: number; slot: Slot }
| { kind: 'lasso'; pointerId: number; pointerType: string; pageId: string; points: number[]; additive: boolean; startX: number; startY: number; far: boolean }
| { kind: 'move'; pointerId: number; pointerType: string; pageId: string; startX: number; startY: number }
| { kind: 'resize'; pointerId: number; pointerType: string; pageId: string; ax: number; ay: number; cx: number; cy: number; minK: number }
| { kind: 'pinch' };
let gesture: Gesture | null = null;
@ -298,6 +322,10 @@
let tick = $state(0);
let erasing = $state.raw<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();
@ -329,6 +357,227 @@
}
const isEraserButton = (e: PointerEvent) => e.pointerType === 'pen' && (e.button === 5 || (e.buttons & 32) !== 0);
const isBarrelButton = (e: PointerEvent) => e.pointerType === 'pen' && (e.button === 2 || (e.buttons & 2) !== 0);
const isSelectButton = (e: PointerEvent) => settings.data.penButtonSelect && isBarrelButton(e);
// ---- selection -------------------------------------------------------
interface Selection {
pageId: string;
strokes: Set<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);
@ -337,14 +586,18 @@
const target = e.target as Element;
if (target.closest('.no-stage')) return;
const p = local(e);
pointerAt = p;
if (isBarrelButton(e)) penButtonAt = Date.now();
// Fingers ink only when enabled and no pen has been used; otherwise they pan/zoom.
const fingerInks = tools.inking && settings.data.fingerDraw && !palm.penSeen;
// Taps on an add-page button are palm-checked like navigation: still rejected for
// pen-down, palm-sized contacts and right after pen use, but not for the 5 s pen session.
const plus = target.closest<HTMLElement>('.ghost, .offer-pill');
// The selection box and its handles are palm-checked like navigation too, so a finger can move it.
const selPart = selected ? target.closest<HTMLElement>('.sel-box, .sel-handle') : null;
if (e.pointerType === 'touch') {
const decision = palm.evaluate(e, touchIntent(fingerInks, !!plus));
const decision = palm.evaluate(e, touchIntent(fingerInks, !!plus || !!selPart));
if (!decision.accept) return; // palm: ignore entirely
touches.set(e.pointerId, p);
if (touches.size >= 2) {
@ -363,6 +616,26 @@
return;
}
if (selPart && selected && (e.pointerType !== 'mouse' || e.button === 0) && !isEraserButton(e)) {
e.preventDefault();
capture(e.pointerId);
const { pageId, box: b } = selected;
const corner = selPart.dataset.corner;
const base = { pointerId: e.pointerId, pointerType: e.pointerType, pageId };
if (corner) {
// Uniform scale about the opposite corner.
const east = corner.includes('e');
const south = corner.includes('s');
const minK = 8 / Math.max(b.x2 - b.x1, b.y2 - b.y1, 1);
gesture = { kind: 'resize', ...base, ax: east ? b.x1 : b.x2, ay: south ? b.y1 : b.y2, cx: east ? b.x2 : b.x1, cy: south ? b.y2 : b.y1, minK };
} else {
const pt = pagePoint(pageId, p.x, p.y);
gesture = { kind: 'move', ...base, startX: pt.x, startY: pt.y };
}
selPreview = IDENTITY;
return;
}
const onPage = pageAt(p.x, p.y);
const inEditor = !!target.closest('.cm-editor');
// Pressing anywhere outside the text leaves the editor (preventDefault
@ -400,6 +673,18 @@
if (e.button !== 0 && e.pointerType === 'mouse') return;
const eraser = tools.tool === 'eraser' || isEraserButton(e);
const lassoing = !eraser && (tools.tool === 'select' || isSelectButton(e));
// Pressing anywhere else drops the selection; Shift+lasso adds to it.
if (selection && !(lassoing && e.shiftKey)) clearSelection();
if (lassoing && onPage) {
e.preventDefault();
capture(e.pointerId);
const pt = pagePoint(onPage, p.x, p.y);
const points = [pt.x, pt.y];
gesture = { kind: 'lasso', pointerId: e.pointerId, pointerType: e.pointerType, pageId: onPage, points, additive: e.shiftKey, startX: p.x, startY: p.y, far: false };
lasso = { pageId: onPage, points };
return;
}
if ((tools.inking || isEraserButton(e)) && onPage) {
e.preventDefault();
capture(e.pointerId);
@ -422,6 +707,7 @@
function onPointerMove(e: PointerEvent) {
palm.track(e);
const p = local(e);
pointerAt = p;
if (tools.tool === 'eraser' || isEraserButton(e)) eraserAt = p;
if (e.pointerType === 'touch' && touches.has(e.pointerId)) {
@ -453,7 +739,8 @@
// A touch stroke is cut off as soon as the palm policy rejects it
// (e.g. the pen just came into range).
if (gesture.pointerType === 'touch' && !palm.evaluate(e, gesture.kind === 'add' ? 'navigate' : 'draw').accept) {
const navigating = gesture.kind === 'add' || gesture.kind === 'move' || gesture.kind === 'resize';
if (gesture.pointerType === 'touch' && !palm.evaluate(e, navigating ? 'navigate' : 'draw').accept) {
cancelGesture();
return;
}
@ -469,6 +756,35 @@
return;
}
if (gesture.kind === 'lasso') {
const g = gesture;
if (Math.hypot(p.x - g.startX, p.y - g.startY) > 6) g.far = true;
const events = typeof e.getCoalescedEvents === 'function' ? e.getCoalescedEvents() : [];
for (const ev of events.length ? events : [e]) {
const q = local(ev);
const pt = pagePoint(g.pageId, q.x, q.y);
g.points.push(Math.round(pt.x * 10) / 10, Math.round(pt.y * 10) / 10);
}
lasso = { pageId: g.pageId, points: g.points };
return;
}
if (gesture.kind === 'move') {
const pt = pagePoint(gesture.pageId, p.x, p.y);
selPreview = translate(pt.x - gesture.startX, pt.y - gesture.startY);
return;
}
if (gesture.kind === 'resize') {
const g = gesture;
const pt = pagePoint(g.pageId, p.x, p.y);
const vx = g.cx - g.ax;
const vy = g.cy - g.ay;
const k = ((pt.x - g.ax) * vx + (pt.y - g.ay) * vy) / (vx * vx + vy * vy || 1);
selPreview = scaleAbout(Math.max(g.minK, k), g.ax, g.ay);
return;
}
const events = typeof e.getCoalescedEvents === 'function' ? e.getCoalescedEvents() : [];
for (const ev of events.length ? events : [e]) {
const q = local(ev);
@ -491,7 +807,27 @@
if (!gesture || gesture.pointerId !== e.pointerId) return;
const g = gesture;
gesture = null;
if (g.kind === 'pan') {
if (isBarrelButton(e)) penButtonAt = Date.now();
if (g.kind === 'lasso') {
lasso = null;
const page = doc.pages[g.pageId];
if (e.type !== 'pointerup' || !page) return;
let hit: { strokes: string[]; images: string[] };
if (g.far) hit = lassoSelect(page.strokes, page.images, g.points);
else {
// A tap picks the object under it.
const q = local(e);
const pt = pagePoint(g.pageId, q.x, q.y);
const o = hitObject(page.strokes, page.images, pt.x, pt.y, 6 / viewport.scale);
hit = { strokes: o?.kind === 'stroke' ? [o.id] : [], images: o?.kind === 'image' ? [o.id] : [] };
}
const prev = g.additive && selection?.pageId === g.pageId ? selection : null;
select(g.pageId, [...(prev?.strokes ?? []), ...hit.strokes], [...(prev?.images ?? []), ...hit.images]);
} else if (g.kind === 'move' || g.kind === 'resize') {
const t = selPreview;
selPreview = null;
if (e.type === 'pointerup' && t && (t.k !== 1 || t.tx || t.ty)) commitTransform(t);
} else if (g.kind === 'pan') {
if (e.type === 'pointerup' && g.moved && g.pointerType === 'touch') {
pushSample(g.trail, { ...local(e), t: e.timeStamp });
offerAfterFling(g.trail);
@ -511,6 +847,8 @@
function cancelGesture() {
if (gesture?.kind === 'draw') live = null;
if (gesture?.kind === 'erase') erasing = new Set();
if (gesture?.kind === 'lasso') lasso = null;
if (gesture?.kind === 'move' || gesture?.kind === 'resize') selPreview = null;
gesture = null;
}
@ -553,11 +891,14 @@
}
function onContextMenu(e: MouseEvent) {
// The pen's barrel button lassoes; it shouldn't also open a menu.
const pen = (e as PointerEvent).pointerType === 'pen' || Date.now() - penButtonAt < 1000;
if (pen && settings.data.penButtonSelect) return void e.preventDefault();
if ((e.target as Element).closest('.cm-editor') && !tools.inking) return; // native menu for text
e.preventDefault();
const p = local(e);
const id = pageAt(p.x, p.y);
if (id) pageMenu(e.clientX, e.clientY, id);
if (id) pageMenu(e.clientX, e.clientY, id, p);
}
// ---- keyboard --------------------------------------------------------
@ -578,6 +919,27 @@
if (editable(e.target)) return;
if (selected) {
if (e.key === 'Escape') return clearSelection();
if (e.key === 'Delete' || e.key === 'Backspace') return void (e.preventDefault(), deleteSelection());
if (mod && k === 'c') return void (e.preventDefault(), copySelection());
if (mod && k === 'x') return void (e.preventDefault(), copySelection() && deleteSelection());
if (mod && k === 'd') return void (e.preventDefault(), duplicateSelection());
if (!mod && !e.altKey && e.key.startsWith('Arrow')) {
e.preventDefault();
const step = e.shiftKey ? 10 : 1;
const d = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[e.key];
if (d) commitTransform(translate(d[0], d[1]));
return;
}
}
if (mod && k === 'a' && tools.tool === 'select' && doc.activeId) {
e.preventDefault();
const page = doc.pages[doc.activeId];
if (page) select(page.id, page.strokes.map((x) => x.id), page.images.map((x) => x.id));
return;
}
if (mod && k === 'z' && !e.shiftKey) return void (e.preventDefault(), doc.undo());
if (mod && ((k === 'z' && e.shiftKey) || k === 'y')) return void (e.preventDefault(), doc.redo());
if (e.key === 'Escape') {
@ -595,7 +957,7 @@
return;
}
if (mod || e.altKey) return;
const shortcuts: Record<string, typeof tools.tool> = { t: 'text', p: 'pen', h: 'highlighter', e: 'eraser' };
const shortcuts: Record<string, typeof tools.tool> = { t: 'text', s: 'select', p: 'pen', h: 'highlighter', e: 'eraser' };
if (shortcuts[k]) tools.tool = shortcuts[k];
}
@ -606,7 +968,16 @@
const panning = $derived(spaceDown);
</script>
<svelte:window onkeydown={onKeyDown} onkeyup={onKeyUp} onblur={() => (spaceDown = false)} />
<svelte:window
onkeydown={onKeyDown}
onkeyup={onKeyUp}
onblur={() => {
spaceDown = false;
clipFresh = false;
}}
oncopy={() => (clipFresh = false)}
onpaste={onPaste}
/>
<div class="view">
<header class="titlebar">
@ -625,6 +996,7 @@
class:inking={tools.inking}
class:panning
class:erasing={tools.tool === 'eraser'}
class:moving={!!selPreview}
bind:this={stage}
style={gridStyle}
onpointerdown={onPointerDown}
@ -636,6 +1008,8 @@
eraserAt = null;
}}
oncontextmenu={onContextMenu}
ondragover={onDragOver}
ondrop={onDrop}
>
<div
class="world"
@ -654,12 +1028,31 @@
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}
@ -725,6 +1118,21 @@
</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}
@ -750,7 +1158,7 @@
/>
{/if}
<Toolbar {doc} onfit={() => fitPage(doc.activeId)} onfitall={fitAll} />
<Toolbar {doc} onfit={() => fitPage(doc.activeId)} onfitall={fitAll} onimages={(files) => void insertImages(files)} />
</div>
<style>
@ -935,6 +1343,82 @@
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%);

View file

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

View file

@ -1,5 +1,6 @@
<script lang="ts">
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 {
@ -11,9 +12,11 @@
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 }: Props = $props();
let { width, height, strokes, live = null, tick = 0, erasing, moving = null }: Props = $props();
const livePath = $derived.by(() => {
void tick;
@ -29,6 +32,7 @@
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}

View file

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

View file

@ -107,6 +107,10 @@
<div><div class="name">Swipe to add pages</div><div class="desc">A quick one-finger flick toward a free side of the active page offers to add a page there.</div></div>
<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>

View file

@ -1,5 +1,7 @@
<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';
@ -18,13 +20,23 @@
import { vault } from '$lib/storage/vault.svelte';
import { pagesFromPdf } from '$lib/pdf/read';
let { doc, onfit, onfitall }: { doc: CanvasDoc; onfit: () => void; onfitall: () => void } = $props();
interface Props {
doc: CanvasDoc;
onfit: () => void;
onfitall: () => void;
/** Images picked with the "Insert image" button. */
onimages: (files: File[]) => void;
}
let { doc, onfit, onfitall, onimages }: Props = $props();
let fileInput: HTMLInputElement;
let 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 }
@ -106,6 +118,7 @@
<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>
@ -118,6 +131,18 @@
</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 {