Releasing a pan now lets the view glide on in the drag's direction, slowing under exponential drag (time constant GLIDE_TAU = 325 ms, so it coasts about 325 px per 1 px/ms of release speed). Only the position moves; the zoom is untouched. A drag that stops before lifting doesn't glide. Touching the canvas, wheel, zoom or fit stops a glide. Applies to finger, mouse (middle/space/background drag) and pen pans. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015cuSqnxerdvXU934U9DddL
1449 lines
48 KiB
Svelte
1449 lines
48 KiB
Svelte
<script lang="ts">
|
||
import { onMount, untrack } from 'svelte';
|
||
import CirclePlusIcon from '@lucide/svelte/icons/circle-plus';
|
||
import DownloadIcon from '@lucide/svelte/icons/download';
|
||
import EllipsisIcon from '@lucide/svelte/icons/ellipsis';
|
||
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';
|
||
import { settings } from '$lib/state/settings.svelte';
|
||
import { workspace } from '$lib/state/workspace.svelte';
|
||
import { menu, type MenuItem } from '$lib/state/menu.svelte';
|
||
import { dirName, displayName } from '$lib/storage/vault.svelte';
|
||
import { bounds, intersects, rectBeside, type Rect } from '$lib/model/layout';
|
||
import { canInsert, freeSlots, freeSlotsOf, neighbor, type Dir, type Slot } from '$lib/model/tree';
|
||
import { A4, PAGE_PRESETS, newId, type PageImage, type Stroke } from '$lib/model/types';
|
||
import { PalmRejector, touchIntent } from '$lib/ink/palm';
|
||
import { flingDir, pushSample, releaseVelocity, type Sample } from '$lib/ink/fling';
|
||
import { StrokeRecorder, hitStroke } from '$lib/ink/stroke';
|
||
import {
|
||
IDENTITY,
|
||
hitObject,
|
||
lassoSelect,
|
||
objectsBounds,
|
||
scaleAbout,
|
||
transformImage,
|
||
transformStroke,
|
||
translate,
|
||
type Transform
|
||
} from '$lib/ink/select';
|
||
import { imageSize, instantiate, makeClip, placeCentred, type Clip } from '$lib/ink/clip';
|
||
import { assets } from '$lib/images/assets.svelte';
|
||
import { renderClipPng } from '$lib/images/png';
|
||
import { pageCssVars } from '$lib/editor/pageStyle';
|
||
import { downloadCanvas } from './download';
|
||
import PageSizeDialog from './PageSizeDialog.svelte';
|
||
import PageView from './PageView.svelte';
|
||
import Toolbar from './Toolbar.svelte';
|
||
|
||
let { doc }: { doc: CanvasDoc } = $props();
|
||
|
||
let stage: HTMLDivElement;
|
||
const cssVars = pageCssVars();
|
||
|
||
// Background grid: one cell per active page, aligned to its edges (A4 at the origin if none),
|
||
// optionally split into fainter subdivisions.
|
||
const gridStyle = $derived.by(() => {
|
||
const g = settings.data.grid;
|
||
if (!g.show) return '';
|
||
const r = (doc.activeId && doc.rects.get(doc.activeId)) || { x: 0, y: 0, ...A4 };
|
||
const s = viewport.scale;
|
||
const w = r.width * s;
|
||
const h = r.height * s;
|
||
const lines = (color: string) => [
|
||
`linear-gradient(to right, ${color} 1px, transparent 1px)`,
|
||
`linear-gradient(to bottom, ${color} 1px, transparent 1px)`
|
||
];
|
||
const images = lines('var(--grid-line)');
|
||
const sizes = [`${w}px ${h}px`, `${w}px ${h}px`];
|
||
// Leave out subdivisions once they'd be too dense to read.
|
||
const n = g.divisions;
|
||
if (n > 1 && Math.min(w, h) / n >= 8) {
|
||
images.push(...lines('var(--grid-line-minor)'));
|
||
sizes.push(`${w / n}px ${h / n}px`, `${w / n}px ${h / n}px`);
|
||
}
|
||
return `background-image: ${images.join(', ')}; background-size: ${sizes.join(', ')}; background-position: ${viewport.x + r.x * s}px ${viewport.y + r.y * s}px`;
|
||
});
|
||
|
||
// ---- autosave --------------------------------------------------------
|
||
$effect(() => {
|
||
if (doc.version > 0) untrack(() => workspace.scheduleSave());
|
||
});
|
||
|
||
// ---- viewport --------------------------------------------------------
|
||
onMount(() => {
|
||
const ro = new ResizeObserver(() => {
|
||
const r = stage.getBoundingClientRect();
|
||
const first = viewport.width === 0;
|
||
viewport.width = r.width;
|
||
viewport.height = r.height;
|
||
if (first) fitPage(workspace.focusPage ?? doc.activeId);
|
||
});
|
||
viewport.width = 0;
|
||
ro.observe(stage);
|
||
stage.addEventListener('wheel', onWheel, { passive: false });
|
||
return () => {
|
||
ro.disconnect();
|
||
stage.removeEventListener('wheel', onWheel);
|
||
clearTimeout(offerTimer);
|
||
};
|
||
});
|
||
|
||
// Search hits etc. ask for a page to be revealed.
|
||
$effect(() => {
|
||
const id = workspace.focusPage;
|
||
if (!id || !viewport.width) return;
|
||
untrack(() => {
|
||
if (doc.pages[id]) {
|
||
doc.activeId = id;
|
||
fitPage(id);
|
||
}
|
||
workspace.focusPage = null;
|
||
});
|
||
});
|
||
|
||
function fitPage(id: string | null) {
|
||
const r = (id && doc.rectOf(id)) || doc.rectOf(doc.order[0]);
|
||
if (r) viewport.fit(r);
|
||
}
|
||
|
||
function fitAll() {
|
||
const b = bounds(doc.rects.values());
|
||
if (b) viewport.fit(b, 48);
|
||
}
|
||
|
||
const visible = $derived.by(() => {
|
||
const w = viewport.world;
|
||
// One extra screen of margin around the view so panning doesn't pop.
|
||
const area = { x: w.x - w.width, y: w.y - w.height, width: w.width * 3, height: w.height * 3 };
|
||
return doc.order.filter((id) => {
|
||
const r = doc.rects.get(id);
|
||
return r && intersects(r, area);
|
||
});
|
||
});
|
||
|
||
// ---- adding pages ----------------------------------------------------
|
||
const ghostSlots = $derived.by((): Slot[] => {
|
||
if (tools.placing || !doc.activeId) return [];
|
||
return freeSlotsOf(doc.tree, doc.activeId);
|
||
});
|
||
|
||
const placeSlots = $derived(tools.placing ? freeSlots(doc.tree) : []);
|
||
|
||
// A finger fling toward a free side of the active page offers a new page there: the plus
|
||
// pulses if it's on screen, otherwise a button appears at that edge of the screen.
|
||
let offer = $state<Slot | null>(null);
|
||
let offerTimer: ReturnType<typeof setTimeout> | undefined;
|
||
|
||
function setOffer(slot: Slot | null) {
|
||
clearTimeout(offerTimer);
|
||
offer = slot;
|
||
if (slot) offerTimer = setTimeout(() => (offer = null), 3000);
|
||
}
|
||
|
||
function offerAfterFling(samples: Sample[]) {
|
||
if (!settings.data.flingToAdd) return;
|
||
const dir = flingDir(samples);
|
||
const id = doc.activeId;
|
||
const slot = dir && ghostSlots.find((s) => s.anchor === id && s.dir === dir);
|
||
if (slot) setOffer(slot);
|
||
}
|
||
|
||
/** The offered plus is off screen, so the offer shows as an edge-of-screen button instead. */
|
||
const offerOffscreen = $derived.by(() => {
|
||
const r = offer && plusRect(offer);
|
||
if (!r) return false;
|
||
const a = viewport.toScreen(r.x, r.y);
|
||
const b = viewport.toScreen(r.x + r.width, r.y + r.height);
|
||
return b.x < 0 || b.y < 0 || a.x > viewport.width || a.y > viewport.height;
|
||
});
|
||
|
||
// Show every possible spot when an imported PDF is waiting to be placed.
|
||
$effect(() => {
|
||
if (!tools.placing) return;
|
||
untrack(() => {
|
||
const size = tools.placing!.pages[0];
|
||
const rects = [...doc.rects.values(), ...placeSlots.map((s) => slotRect(s, size)).filter((r): r is Rect => !!r)];
|
||
const b = bounds(rects);
|
||
if (b) viewport.fit(b, 48);
|
||
});
|
||
});
|
||
|
||
function slotRect(slot: Slot, size?: { width: number; height: number }): Rect | null {
|
||
const a = doc.rectOf(slot.anchor);
|
||
if (!a) return null;
|
||
const page = doc.pages[slot.anchor];
|
||
const s = size ?? (page ? { width: page.width, height: page.height } : A4);
|
||
return rectBeside(a, slot.dir, s);
|
||
}
|
||
|
||
/**
|
||
* Hit area of the add-page button: 48 px square touching the middle of the anchor's
|
||
* free edge. The visible 32 px circle sits centred in it, 8 px off the page.
|
||
*/
|
||
function plusRect(slot: Slot): Rect | null {
|
||
const a = doc.rectOf(slot.anchor);
|
||
if (!a) return null;
|
||
const d = 48 / viewport.scale;
|
||
const cx = a.x + (a.width - d) / 2;
|
||
const cy = a.y + (a.height - d) / 2;
|
||
if (slot.dir === 'right') return { x: a.x + a.width, y: cy, width: d, height: d };
|
||
if (slot.dir === 'left') return { x: a.x - d, y: cy, width: d, height: d };
|
||
if (slot.dir === 'down') return { x: cx, y: a.y + a.height, width: d, height: d };
|
||
return { x: cx, y: a.y - d, width: d, height: d };
|
||
}
|
||
|
||
/** Run a tree change without the anchor page jumping on screen. */
|
||
function keepAnchor(anchor: string, fn: () => void) {
|
||
const before = doc.rectOf(anchor);
|
||
fn();
|
||
const after = doc.rectOf(anchor);
|
||
if (before && after) viewport.panBy(-(after.x - before.x) * viewport.scale, -(after.y - before.y) * viewport.scale);
|
||
}
|
||
|
||
function revealPage(id: string) {
|
||
const r = doc.rectOf(id);
|
||
if (!r) return;
|
||
const w = viewport.world;
|
||
const inView = r.x >= w.x && r.y >= w.y && r.x + r.width <= w.x + w.width && r.y + r.height <= w.y + w.height;
|
||
if (!inView) {
|
||
const fits = r.width * viewport.scale <= viewport.width && r.height * viewport.scale <= viewport.height;
|
||
if (fits) viewport.center(r);
|
||
else viewport.fit(r);
|
||
}
|
||
}
|
||
|
||
function addPage(anchor: string, dir: Dir) {
|
||
let id: string | null = null;
|
||
keepAnchor(anchor, () => (id = doc.addBlankPage(anchor, dir)));
|
||
if (id) revealPage(id);
|
||
}
|
||
|
||
function place(slot: Slot) {
|
||
const p = tools.placing;
|
||
if (!p) return;
|
||
let ok = false;
|
||
keepAnchor(slot.anchor, () => (ok = doc.insertPages(slot.anchor, slot.dir, p.pages)));
|
||
if (ok) {
|
||
tools.placing = null;
|
||
revealPage(p.pages[0].id);
|
||
workspace.toast(`Placed ${p.pages.length} page${p.pages.length === 1 ? '' : 's'} from ${p.name}`);
|
||
}
|
||
}
|
||
|
||
function go(dir: Dir) {
|
||
const id = doc.activeId;
|
||
if (!id) return;
|
||
const next = neighbor(doc.tree, id, dir);
|
||
if (next) {
|
||
doc.activeId = next;
|
||
revealPage(next);
|
||
} else if (canInsert(doc.tree, id, dir)) addPage(id, dir);
|
||
}
|
||
|
||
// ---- page menu -------------------------------------------------------
|
||
/** `at`: stage-local point to paste at (the right-click position). */
|
||
function pageMenu(x: number, y: number, id: string, at?: { x: number; y: number }) {
|
||
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'],
|
||
['left', 'Insert page left'],
|
||
['right', 'Insert page right']
|
||
];
|
||
const items: MenuItem[] = dirs.map(([dir, label]) => ({
|
||
label,
|
||
disabled: !canInsert(doc.tree, id, dir),
|
||
action: () => addPage(id, dir)
|
||
}));
|
||
if (!page.origin) {
|
||
items.push('separator');
|
||
for (const p of PAGE_PRESETS) {
|
||
const current = Math.abs(p.width - page.width) < 0.5 && Math.abs(p.height - page.height) < 0.5;
|
||
items.push({
|
||
label: p.label,
|
||
icon: current ? CheckIcon : undefined,
|
||
hint: `${Math.round(p.width)}×${Math.round(p.height)}`,
|
||
action: () => keepAnchor(id, () => doc.resizePage(id, p.width, p.height))
|
||
});
|
||
}
|
||
items.push({ label: 'Custom size…', action: () => customSize(id) });
|
||
}
|
||
items.push('separator', { label: 'Paste', icon: ClipboardPasteIcon, disabled: !clip && !canRead, action: () => void pasteFromMenu(at) });
|
||
items.push('separator', { label: 'Delete page', icon: TrashIcon, danger: true, action: () => doc.deletePage(id) });
|
||
menu.show(x, y, items);
|
||
}
|
||
|
||
/** Page whose custom-size dialog is open. */
|
||
let sizing = $state<string | null>(null);
|
||
const customSize = (id: string) => (sizing = id);
|
||
|
||
const activeMenuPos = $derived.by(() => {
|
||
const id = doc.activeId;
|
||
const r = id && doc.rects.get(id);
|
||
if (!r || tools.placing) return null;
|
||
const p = viewport.toScreen(r.x + r.width, r.y);
|
||
return { x: p.x + 6, y: p.y };
|
||
});
|
||
|
||
// ---- input -----------------------------------------------------------
|
||
const palm = new PalmRejector(settings.data.palm);
|
||
$effect(() => {
|
||
palm.options = settings.data.palm;
|
||
});
|
||
|
||
type Gesture =
|
||
| { kind: 'draw'; pointerId: number; pointerType: string; pageId: string; rec: StrokeRecorder }
|
||
| { kind: 'erase'; pointerId: number; pointerType: string; hits: Map<string, Set<string>> }
|
||
| { kind: 'pan'; pointerId: number; pointerType: string; lastX: number; lastY: number; startX: number; startY: number; moved: boolean; tap: boolean; trail: Sample[] }
|
||
| { kind: '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;
|
||
const touches = new Map<number, { x: number; y: number }>();
|
||
let pinchLast: { dist: number; mx: number; my: number } | null = null;
|
||
let spaceDown = $state(false);
|
||
|
||
// Reactive bits for rendering in-progress ink.
|
||
let live = $state.raw<{ pageId: string; stroke: Stroke } | null>(null);
|
||
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();
|
||
return { x: e.clientX - r.left, y: e.clientY - r.top };
|
||
}
|
||
|
||
function pageAt(sx: number, sy: number): string | null {
|
||
const w = viewport.toWorld(sx, sy);
|
||
for (const id of visible) {
|
||
const r = doc.rects.get(id)!;
|
||
if (w.x >= r.x && w.x <= r.x + r.width && w.y >= r.y && w.y <= r.y + r.height) return id;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function pagePoint(pageId: string, sx: number, sy: number) {
|
||
const r = doc.rects.get(pageId)!;
|
||
const w = viewport.toWorld(sx, sy);
|
||
return { x: w.x - r.x, y: w.y - r.y };
|
||
}
|
||
|
||
/** Pointer capture can throw if the pointer is already gone; drawing still works without it. */
|
||
function capture(id: number) {
|
||
try {
|
||
stage.setPointerCapture(id);
|
||
} catch {
|
||
/* ignore */
|
||
}
|
||
}
|
||
|
||
const isEraserButton = (e: PointerEvent) => e.pointerType === 'pen' && (e.button === 5 || (e.buttons & 32) !== 0);
|
||
const isBarrelButton = (e: PointerEvent) => e.pointerType === 'pen' && (e.button === 2 || (e.buttons & 2) !== 0);
|
||
const isSelectButton = (e: PointerEvent) => settings.data.penButtonSelect && isBarrelButton(e);
|
||
|
||
// ---- selection -------------------------------------------------------
|
||
interface Selection {
|
||
pageId: string;
|
||
strokes: Set<string>;
|
||
images: Set<string>;
|
||
}
|
||
|
||
let selection = $state.raw<Selection | null>(null);
|
||
/** Transform of the selection while it is dragged or resized (committed on release). */
|
||
let selPreview = $state.raw<Transform | null>(null);
|
||
/** Lasso being drawn, in page-local points. */
|
||
let lasso = $state.raw<{ pageId: string; points: number[] } | null>(null);
|
||
|
||
const selected = $derived.by(() => {
|
||
const sel = selection;
|
||
const page = sel && doc.pages[sel.pageId];
|
||
if (!sel || !page) return null;
|
||
const strokes = page.strokes.filter((x) => sel.strokes.has(x.id));
|
||
const images = page.images.filter((x) => sel.images.has(x.id));
|
||
const box = objectsBounds(strokes, images);
|
||
return box ? { pageId: sel.pageId, strokes, images, box } : null;
|
||
});
|
||
|
||
const moving = $derived(
|
||
selection && selPreview ? { pageId: selection.pageId, ids: new Set([...selection.strokes, ...selection.images]), t: selPreview } : null
|
||
);
|
||
|
||
/** Selection box in world coordinates, following a drag/resize in progress. */
|
||
const selRect = $derived.by((): Rect | null => {
|
||
const r = selected && doc.rects.get(selected.pageId);
|
||
if (!selected || !r) return null;
|
||
const t = selPreview ?? IDENTITY;
|
||
const b = selected.box;
|
||
const pad = 6 / viewport.scale;
|
||
const x1 = b.x1 * t.k + t.tx;
|
||
const y1 = b.y1 * t.k + t.ty;
|
||
return { x: r.x + x1 - pad, y: r.y + y1 - pad, width: (b.x2 - b.x1) * t.k + 2 * pad, height: (b.y2 - b.y1) * t.k + 2 * pad };
|
||
});
|
||
|
||
/** Action bar above the selection (below it when there's no room), in screen coordinates. */
|
||
const selBar = $derived.by(() => {
|
||
if (!selRect || selPreview) return null;
|
||
const top = viewport.toScreen(selRect.x + selRect.width / 2, selRect.y);
|
||
const bottom = viewport.toScreen(selRect.x, selRect.y + selRect.height);
|
||
const x = Math.min(Math.max(top.x, 140), viewport.width - 140);
|
||
return top.y > 56 ? { x, y: top.y - 48 } : { x, y: Math.min(bottom.y + 8, viewport.height - 110) };
|
||
});
|
||
|
||
const CORNERS = ['nw', 'ne', 'se', 'sw'] as const;
|
||
|
||
// Switching tools drops the selection.
|
||
$effect(() => {
|
||
void tools.tool;
|
||
untrack(() => clearSelection());
|
||
});
|
||
|
||
function clearSelection() {
|
||
selection = null;
|
||
selPreview = null;
|
||
}
|
||
|
||
function select(pageId: string, strokes: string[], images: string[]) {
|
||
selection = strokes.length || images.length ? { pageId, strokes: new Set(strokes), images: new Set(images) } : null;
|
||
}
|
||
|
||
function commitTransform(t: Transform) {
|
||
const sel = selection;
|
||
if (!sel) return;
|
||
doc.setObjects(sel.pageId, (o) => ({
|
||
strokes: o.strokes.map((x) => (sel.strokes.has(x.id) ? transformStroke(x, t) : x)),
|
||
images: o.images.map((x) => (sel.images.has(x.id) ? transformImage(x, t) : x))
|
||
}));
|
||
}
|
||
|
||
function deleteSelection() {
|
||
const sel = selection;
|
||
if (!sel) return;
|
||
doc.setObjects(sel.pageId, (o) => ({
|
||
strokes: o.strokes.filter((x) => !sel.strokes.has(x.id)),
|
||
images: o.images.filter((x) => !sel.images.has(x.id))
|
||
}));
|
||
clearSelection();
|
||
}
|
||
|
||
function recolor(color: string) {
|
||
const sel = selection;
|
||
if (!sel) return;
|
||
doc.setObjects(sel.pageId, (o) => ({
|
||
strokes: o.strokes.map((x) => (sel.strokes.has(x.id) && x.color !== color ? { ...x, color } : x)),
|
||
images: o.images
|
||
}));
|
||
}
|
||
|
||
/** Add objects to a page as one undo step and select them. */
|
||
function addObjects(pageId: string, objs: { strokes: Stroke[]; images: PageImage[] }) {
|
||
doc.setObjects(pageId, (o) => ({ strokes: [...o.strokes, ...objs.strokes], images: [...o.images, ...objs.images] }));
|
||
doc.activeId = pageId;
|
||
select(pageId, objs.strokes.map((x) => x.id), objs.images.map((x) => x.id));
|
||
}
|
||
|
||
// ---- clipboard -------------------------------------------------------
|
||
// Copies keep a vector copy here and put a PNG on the system clipboard. Pasting prefers the
|
||
// vector copy while it is fresh: until the window loses focus or something else is copied.
|
||
let clip: Clip | null = null;
|
||
let clipFresh = false;
|
||
|
||
function copySelection() {
|
||
if (!selected) return false;
|
||
clip = makeClip(selected.strokes, selected.images);
|
||
clipFresh = true;
|
||
const c = clip;
|
||
if (c && navigator.clipboard?.write && typeof ClipboardItem !== 'undefined') {
|
||
// A promise inside the ClipboardItem keeps the user gesture alive while rendering (Safari).
|
||
const png = renderClipPng(c, (id) => assets.url(id));
|
||
navigator.clipboard.write([new ClipboardItem({ 'image/png': png })]).catch((err) => console.warn('Clipboard write failed', err));
|
||
}
|
||
return true;
|
||
}
|
||
|
||
function duplicateSelection() {
|
||
if (!selected) return;
|
||
const c = makeClip(selected.strokes, selected.images);
|
||
if (c) addObjects(selected.pageId, instantiate(c, selected.box.x1 + 12, selected.box.y1 + 12));
|
||
}
|
||
|
||
/** Where a paste lands: the pointer if it's over a page, else the middle of the visible part of the active page. */
|
||
function pasteTarget(at?: { x: number; y: number } | null) {
|
||
const p = at ?? pointerAt;
|
||
const over = p && pageAt(p.x, p.y);
|
||
if (p && over) return { pageId: over, ...pagePoint(over, p.x, p.y) };
|
||
const id = doc.activeId;
|
||
const r = id && doc.rects.get(id);
|
||
if (!id || !r) return null;
|
||
const w = viewport.world;
|
||
const x1 = Math.max(r.x, w.x), x2 = Math.min(r.x + r.width, w.x + w.width);
|
||
const y1 = Math.max(r.y, w.y), y2 = Math.min(r.y + r.height, w.y + w.height);
|
||
const cx = x2 > x1 ? (x1 + x2) / 2 : r.x + r.width / 2;
|
||
const cy = y2 > y1 ? (y1 + y2) / 2 : r.y + r.height / 2;
|
||
return { pageId: id, x: cx - r.x, y: cy - r.y };
|
||
}
|
||
|
||
function pasteClip(at?: { x: number; y: number } | null) {
|
||
const t = clip && pasteTarget(at);
|
||
const page = t && doc.pages[t.pageId];
|
||
if (!clip || !t || !page) return;
|
||
const pos = placeCentred(t.x, t.y, clip, page);
|
||
addObjects(t.pageId, instantiate(clip, pos.x, pos.y));
|
||
}
|
||
|
||
async function insertImages(files: Blob[], at?: { x: number; y: number } | null) {
|
||
const t = pasteTarget(at);
|
||
const page = t && doc.pages[t.pageId];
|
||
if (!t || !page) return;
|
||
const placed: PageImage[] = [];
|
||
for (const [i, f] of files.entries()) {
|
||
try {
|
||
const a = await assets.add(f);
|
||
if (a.bytes > 5_000_000) workspace.toast(`That image is ${(a.bytes / 1e6).toFixed(1)} MB; it will make the canvas file large`);
|
||
const size = imageSize(a, page);
|
||
const pos = placeCentred(t.x + i * 16, t.y + i * 16, size, page);
|
||
placed.push({ id: newId(), assetId: a.id, ...pos, ...size });
|
||
} catch (err) {
|
||
console.error(err);
|
||
workspace.toast(`Could not read ${f instanceof File ? f.name : 'that image'}`, 'error');
|
||
}
|
||
}
|
||
if (placed.length) addObjects(t.pageId, { strokes: [], images: placed });
|
||
}
|
||
|
||
async function pasteFromMenu(at?: { x: number; y: number }) {
|
||
if (clip && clipFresh) return pasteClip(at);
|
||
try {
|
||
for (const item of await navigator.clipboard.read()) {
|
||
const type = item.types.find((t) => t.startsWith('image/'));
|
||
if (type) return void (await insertImages([await item.getType(type)], at));
|
||
}
|
||
} catch {
|
||
/* no permission or no clipboard API */
|
||
}
|
||
if (clip) pasteClip(at);
|
||
else workspace.toast('No image or selection to paste');
|
||
}
|
||
|
||
function onPaste(e: ClipboardEvent) {
|
||
if (workspace.settingsOpen || sizing) return;
|
||
const dt = e.clipboardData;
|
||
const images = dt
|
||
? [...dt.items].filter((i) => i.kind === 'file' && i.type.startsWith('image/')).map((i) => i.getAsFile()).filter((f): f is File => !!f)
|
||
: [];
|
||
const inText = editable(e.target);
|
||
// Text goes to the editor; an image on its own is placed on the page.
|
||
if (inText && (!images.length || dt?.getData('text/plain'))) return;
|
||
if (clip && (clipFresh || (!images.length && !inText))) {
|
||
e.preventDefault();
|
||
return pasteClip();
|
||
}
|
||
if (images.length) {
|
||
e.preventDefault();
|
||
void insertImages(images);
|
||
}
|
||
}
|
||
|
||
function onDragOver(e: DragEvent) {
|
||
if (e.dataTransfer?.types.includes('Files')) e.preventDefault();
|
||
}
|
||
|
||
function onDrop(e: DragEvent) {
|
||
const files = [...(e.dataTransfer?.files ?? [])].filter((f) => f.type.startsWith('image/'));
|
||
if (!files.length) return;
|
||
e.preventDefault();
|
||
void insertImages(files, local(e));
|
||
}
|
||
|
||
function lassoPath(pts: number[]) {
|
||
let d = '';
|
||
for (let i = 0; i < pts.length; i += 2) d += `${i ? 'L' : 'M'}${pts[i].toFixed(1)},${pts[i + 1].toFixed(1)}`;
|
||
return d + 'Z';
|
||
}
|
||
|
||
function onPointerDown(e: PointerEvent) {
|
||
palm.track(e);
|
||
if (menu.open) menu.close();
|
||
if (offer) setOffer(null);
|
||
const target = e.target as Element;
|
||
if (target.closest('.no-stage')) return;
|
||
const p = local(e);
|
||
pointerAt = p;
|
||
if (isBarrelButton(e)) penButtonAt = Date.now();
|
||
|
||
// Fingers ink only when enabled and no pen has been used; otherwise they pan/zoom.
|
||
const fingerInks = tools.inking && settings.data.fingerDraw && !palm.penSeen;
|
||
// Taps on an add-page button are palm-checked like navigation: still rejected for
|
||
// pen-down, palm-sized contacts and right after pen use, but not for the 5 s pen session.
|
||
const plus = target.closest<HTMLElement>('.ghost, .offer-pill');
|
||
// The selection box and its handles are palm-checked like navigation too, so a finger can move it.
|
||
const selPart = selected ? target.closest<HTMLElement>('.sel-box, .sel-handle') : null;
|
||
if (e.pointerType === 'touch') {
|
||
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) {
|
||
cancelGesture();
|
||
gesture = { kind: 'pinch' };
|
||
pinchLast = pinchState();
|
||
return;
|
||
}
|
||
}
|
||
// Touching the canvas catches a gliding view.
|
||
viewport.stopGlide();
|
||
|
||
if (plus && e.button === 0) {
|
||
e.preventDefault();
|
||
const slot = { anchor: plus.dataset.anchor!, dir: plus.dataset.dir as Dir };
|
||
gesture = { kind: 'add', pointerId: e.pointerId, pointerType: e.pointerType, startX: p.x, startY: p.y, slot };
|
||
capture(e.pointerId);
|
||
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
|
||
// below would otherwise keep focus in it).
|
||
if (!inEditor) (document.activeElement as HTMLElement | null)?.blur?.();
|
||
|
||
// Panning: middle mouse, space+drag, or background drags.
|
||
const wantsPan =
|
||
e.button === 1 ||
|
||
spaceDown ||
|
||
(e.pointerType === 'touch' && (!fingerInks || !onPage)) ||
|
||
(e.pointerType === 'mouse' && e.button === 0 && !onPage && !target.closest('.slot'));
|
||
if (wantsPan) {
|
||
if (onPage && !inEditor) doc.activeId = onPage;
|
||
gesture = {
|
||
kind: 'pan',
|
||
pointerId: e.pointerId,
|
||
pointerType: e.pointerType,
|
||
lastX: p.x,
|
||
lastY: p.y,
|
||
startX: p.x,
|
||
startY: p.y,
|
||
moved: false,
|
||
tap: inEditor || !!target.closest('.slot'),
|
||
trail: [{ ...p, t: e.timeStamp }]
|
||
};
|
||
if (e.pointerType !== 'touch' || !gesture.tap) {
|
||
if (e.pointerType !== 'touch') e.preventDefault();
|
||
capture(e.pointerId);
|
||
}
|
||
return;
|
||
}
|
||
|
||
if (onPage) doc.activeId = onPage;
|
||
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);
|
||
if (eraser) {
|
||
gesture = { kind: 'erase', pointerId: e.pointerId, pointerType: e.pointerType, hits: new Map() };
|
||
erasing = new Set();
|
||
eraseAt(e);
|
||
} else {
|
||
const tool = tools.tool === 'highlighter' ? 'highlighter' : 'pen';
|
||
const rec = new StrokeRecorder(tool, tools.color, tools.width, e.pointerType === 'pen');
|
||
const pt = pagePoint(onPage, p.x, p.y);
|
||
rec.recordPoint(pt.x, pt.y, e);
|
||
gesture = { kind: 'draw', pointerId: e.pointerId, pointerType: e.pointerType, pageId: onPage, rec };
|
||
live = { pageId: onPage, stroke: rec.stroke };
|
||
tick++;
|
||
}
|
||
}
|
||
}
|
||
|
||
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)) {
|
||
touches.set(e.pointerId, p);
|
||
if (gesture?.kind === 'pinch') {
|
||
const s = pinchState();
|
||
if (s && pinchLast) {
|
||
viewport.zoomAt(s.dist / pinchLast.dist, s.mx, s.my);
|
||
viewport.panBy(s.mx - pinchLast.mx, s.my - pinchLast.my);
|
||
}
|
||
pinchLast = s;
|
||
return;
|
||
}
|
||
}
|
||
if (!gesture || gesture.kind === 'pinch' || gesture.pointerId !== e.pointerId) return;
|
||
|
||
if (gesture.kind === 'pan') {
|
||
const dx = p.x - gesture.lastX;
|
||
const dy = p.y - gesture.lastY;
|
||
if (!gesture.moved && Math.hypot(p.x - gesture.startX, p.y - gesture.startY) < 8) return;
|
||
if (!gesture.moved && gesture.tap) capture(e.pointerId);
|
||
gesture.moved = true;
|
||
viewport.panBy(dx, dy);
|
||
gesture.lastX = p.x;
|
||
gesture.lastY = p.y;
|
||
pushSample(gesture.trail, { ...p, t: e.timeStamp });
|
||
return;
|
||
}
|
||
|
||
// A touch stroke is cut off as soon as the palm policy rejects it
|
||
// (e.g. the pen just came into range).
|
||
const navigating = gesture.kind === 'add' || gesture.kind === 'move' || gesture.kind === 'resize';
|
||
if (gesture.pointerType === 'touch' && !palm.evaluate(e, navigating ? 'navigate' : 'draw').accept) {
|
||
cancelGesture();
|
||
return;
|
||
}
|
||
|
||
if (gesture.kind === 'add') {
|
||
// Dragging off the button is not a tap.
|
||
if (Math.hypot(p.x - gesture.startX, p.y - gesture.startY) > 12) gesture = null;
|
||
return;
|
||
}
|
||
|
||
if (gesture.kind === 'erase') {
|
||
eraseAt(e);
|
||
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);
|
||
const pt = pagePoint(gesture.pageId, q.x, q.y);
|
||
gesture.rec.recordPoint(pt.x, pt.y, ev);
|
||
}
|
||
tick++;
|
||
}
|
||
|
||
function onPointerUp(e: PointerEvent) {
|
||
palm.track(e);
|
||
touches.delete(e.pointerId);
|
||
if (gesture?.kind === 'pinch') {
|
||
if (touches.size < 2) {
|
||
gesture = null;
|
||
pinchLast = null;
|
||
}
|
||
return;
|
||
}
|
||
if (!gesture || gesture.pointerId !== e.pointerId) return;
|
||
const g = gesture;
|
||
gesture = null;
|
||
if (isBarrelButton(e)) penButtonAt = Date.now();
|
||
if (g.kind === 'lasso') {
|
||
lasso = null;
|
||
const page = doc.pages[g.pageId];
|
||
if (e.type !== 'pointerup' || !page) return;
|
||
let hit: { strokes: string[]; images: string[] };
|
||
if (g.far) hit = lassoSelect(page.strokes, page.images, g.points);
|
||
else {
|
||
// A tap picks the object under it.
|
||
const q = local(e);
|
||
const pt = pagePoint(g.pageId, q.x, q.y);
|
||
const o = hitObject(page.strokes, page.images, pt.x, pt.y, 6 / viewport.scale);
|
||
hit = { strokes: o?.kind === 'stroke' ? [o.id] : [], images: o?.kind === 'image' ? [o.id] : [] };
|
||
}
|
||
const prev = g.additive && selection?.pageId === g.pageId ? selection : null;
|
||
select(g.pageId, [...(prev?.strokes ?? []), ...hit.strokes], [...(prev?.images ?? []), ...hit.images]);
|
||
} else if (g.kind === 'move' || g.kind === 'resize') {
|
||
const t = selPreview;
|
||
selPreview = null;
|
||
if (e.type === 'pointerup' && t && (t.k !== 1 || t.tx || t.ty)) commitTransform(t);
|
||
} else if (g.kind === 'pan') {
|
||
if (e.type === 'pointerup' && g.moved) {
|
||
pushSample(g.trail, { ...local(e), t: e.timeStamp });
|
||
// The view coasts on in the direction of the drag (a drag that stopped before lifting has ~no velocity).
|
||
const v = releaseVelocity(g.trail);
|
||
if (v) viewport.glide(v.vx, v.vy);
|
||
if (g.pointerType === 'touch') offerAfterFling(g.trail);
|
||
}
|
||
} else if (g.kind === 'add') {
|
||
if (e.type === 'pointerup' && (g.pointerType !== 'touch' || palm.evaluate(e, 'navigate').accept)) addPage(g.slot.anchor, g.slot.dir);
|
||
} else if (g.kind === 'draw') {
|
||
live = null;
|
||
if (e.type === 'pointerup') doc.addStroke(g.pageId, g.rec.stroke);
|
||
} else if (g.kind === 'erase') {
|
||
// Like ink, an interrupted (pointercancel) erase is dropped.
|
||
if (e.type === 'pointerup') for (const [pageId, ids] of g.hits) doc.setStrokes(pageId, (s) => s.filter((x) => !ids.has(x.id)));
|
||
erasing = new Set();
|
||
}
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
function eraseAt(e: PointerEvent) {
|
||
if (gesture?.kind !== 'erase') return;
|
||
const p = local(e);
|
||
const pageId = pageAt(p.x, p.y);
|
||
if (!pageId) return;
|
||
const pt = pagePoint(pageId, p.x, p.y);
|
||
const r = tools.eraserRadius / viewport.scale;
|
||
let set = gesture.hits.get(pageId);
|
||
let changed = false;
|
||
for (const s of doc.pages[pageId].strokes) {
|
||
if (set?.has(s.id) || !hitStroke(s, pt.x, pt.y, r)) continue;
|
||
if (!set) gesture.hits.set(pageId, (set = new Set()));
|
||
set.add(s.id);
|
||
changed = true;
|
||
}
|
||
if (changed) erasing = new Set([...gesture.hits.values()].flatMap((x) => [...x]));
|
||
}
|
||
|
||
function pinchState() {
|
||
const pts = [...touches.values()];
|
||
if (pts.length < 2) return null;
|
||
const [a, b] = pts;
|
||
return { dist: Math.max(1, Math.hypot(a.x - b.x, a.y - b.y)), mx: (a.x + b.x) / 2, my: (a.y + b.y) / 2 };
|
||
}
|
||
|
||
function onWheel(e: WheelEvent) {
|
||
e.preventDefault();
|
||
const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? viewport.height : 1;
|
||
const p = local(e);
|
||
if (e.ctrlKey || e.metaKey) {
|
||
viewport.zoomAt(Math.exp(-e.deltaY * unit * 0.0025), p.x, p.y);
|
||
} else if (e.shiftKey && !e.deltaX) {
|
||
viewport.panBy(-e.deltaY * unit, 0);
|
||
} else {
|
||
viewport.panBy(-e.deltaX * unit, -e.deltaY * unit);
|
||
}
|
||
}
|
||
|
||
function onContextMenu(e: MouseEvent) {
|
||
// The pen's barrel button lassoes; it shouldn't also open a menu.
|
||
const pen = (e as PointerEvent).pointerType === 'pen' || Date.now() - penButtonAt < 1000;
|
||
if (pen && settings.data.penButtonSelect) return void e.preventDefault();
|
||
if ((e.target as Element).closest('.cm-editor') && !tools.inking) return; // native menu for text
|
||
e.preventDefault();
|
||
const p = local(e);
|
||
const id = pageAt(p.x, p.y);
|
||
if (id) pageMenu(e.clientX, e.clientY, id, p);
|
||
}
|
||
|
||
// ---- keyboard --------------------------------------------------------
|
||
function editable(t: EventTarget | null) {
|
||
const el = t as HTMLElement | null;
|
||
return !!el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName));
|
||
}
|
||
|
||
function onKeyDown(e: KeyboardEvent) {
|
||
if (workspace.settingsOpen || sizing) return;
|
||
const mod = e.ctrlKey || e.metaKey;
|
||
const k = e.key.toLowerCase();
|
||
|
||
if (mod && (k === '=' || k === '+')) return void (e.preventDefault(), viewport.zoomAt(1.25));
|
||
if (mod && k === '-') return void (e.preventDefault(), viewport.zoomAt(0.8));
|
||
if (mod && k === '0') return void (e.preventDefault(), fitPage(doc.activeId));
|
||
if (mod && k === '9') return void (e.preventDefault(), fitAll());
|
||
|
||
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') {
|
||
if (tools.placing) tools.placing = null;
|
||
return;
|
||
}
|
||
if (e.altKey && e.key.startsWith('Arrow')) {
|
||
e.preventDefault();
|
||
go(e.key.slice(5).toLowerCase() as Dir);
|
||
return;
|
||
}
|
||
if (e.key === ' ' && !e.repeat) {
|
||
spaceDown = true;
|
||
e.preventDefault();
|
||
return;
|
||
}
|
||
if (mod || e.altKey) return;
|
||
const shortcuts: Record<string, typeof tools.tool> = { t: 'text', s: 'select', p: 'pen', h: 'highlighter', e: 'eraser' };
|
||
if (shortcuts[k]) tools.tool = shortcuts[k];
|
||
}
|
||
|
||
function onKeyUp(e: KeyboardEvent) {
|
||
if (e.key === ' ') spaceDown = false;
|
||
}
|
||
|
||
const panning = $derived(spaceDown);
|
||
</script>
|
||
|
||
<svelte:window
|
||
onkeydown={onKeyDown}
|
||
onkeyup={onKeyUp}
|
||
onblur={() => {
|
||
spaceDown = false;
|
||
clipFresh = false;
|
||
}}
|
||
oncopy={() => (clipFresh = false)}
|
||
onpaste={onPaste}
|
||
/>
|
||
|
||
<div class="view">
|
||
<header class="titlebar">
|
||
<div class="crumbs">
|
||
{#if dirName(doc.path)}<span class="dir">{dirName(doc.path).replaceAll('/', ' / ')} /</span>{/if}
|
||
<span class="name">{displayName(doc.path)}</span>
|
||
</div>
|
||
<button class="icon-btn" title="Download PDF" onclick={() => downloadCanvas(doc.path)}>
|
||
<DownloadIcon size={16} strokeWidth={1.75} />
|
||
</button>
|
||
</header>
|
||
|
||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||
<div
|
||
class="stage"
|
||
class:inking={tools.inking}
|
||
class:panning
|
||
class:erasing={tools.tool === 'eraser'}
|
||
class:moving={!!selPreview}
|
||
bind:this={stage}
|
||
style={gridStyle}
|
||
onpointerdown={onPointerDown}
|
||
onpointermove={onPointerMove}
|
||
onpointerup={onPointerUp}
|
||
onpointercancel={onPointerUp}
|
||
onpointerleave={(e) => {
|
||
palm.track(e);
|
||
eraserAt = null;
|
||
}}
|
||
oncontextmenu={onContextMenu}
|
||
ondragover={onDragOver}
|
||
ondrop={onDrop}
|
||
>
|
||
<div
|
||
class="world"
|
||
style="transform: translate({viewport.x}px, {viewport.y}px) scale({viewport.scale}); --s: {viewport.scale}; {cssVars}"
|
||
>
|
||
{#each visible as id (id)}
|
||
{@const page = doc.pages[id]}
|
||
{@const rect = doc.rects.get(id)}
|
||
{#if page && rect}
|
||
<PageView
|
||
{page}
|
||
{rect}
|
||
active={doc.activeId === id}
|
||
invert={settings.dark && settings.data.pageStyle === 'match'}
|
||
scale={viewport.scale}
|
||
live={live?.pageId === id ? live.stroke : null}
|
||
{tick}
|
||
{erasing}
|
||
moving={moving?.pageId === id ? moving : null}
|
||
onchange={() => doc.touch()}
|
||
onactivate={() => (doc.activeId = id)}
|
||
/>
|
||
{/if}
|
||
{/each}
|
||
|
||
{#if lasso && doc.rects.get(lasso.pageId)}
|
||
{@const r = doc.rects.get(lasso.pageId)!}
|
||
<svg class="lasso" style="left:{r.x}px; top:{r.y}px; width:{r.width}px; height:{r.height}px" viewBox="0 0 {r.width} {r.height}">
|
||
<path d={lassoPath(lasso.points)} />
|
||
</svg>
|
||
{/if}
|
||
|
||
{#if selRect}
|
||
<div class="sel-box" style="left:{selRect.x}px; top:{selRect.y}px; width:{selRect.width}px; height:{selRect.height}px"></div>
|
||
{#each CORNERS as c (c)}
|
||
<div
|
||
class="sel-handle"
|
||
data-corner={c}
|
||
style="left:{c.includes('e') ? selRect.x + selRect.width : selRect.x}px; top:{c.includes('s') ? selRect.y + selRect.height : selRect.y}px"
|
||
></div>
|
||
{/each}
|
||
{/if}
|
||
|
||
{#each ghostSlots as slot (slot.anchor + slot.dir)}
|
||
{@const r = plusRect(slot)}
|
||
{#if r}
|
||
<!-- Pointer taps go through the palm-checked gesture; onclick only serves the keyboard. -->
|
||
<button
|
||
class="ghost"
|
||
class:offer={offer?.anchor === slot.anchor && offer.dir === slot.dir}
|
||
data-anchor={slot.anchor}
|
||
data-dir={slot.dir}
|
||
style="left:{r.x}px; top:{r.y}px; width:{r.width}px; height:{r.height}px"
|
||
title="Add page ({slot.dir})"
|
||
onclick={(e) => e.detail === 0 && addPage(slot.anchor, slot.dir)}
|
||
>
|
||
<span class="plus"><CirclePlusIcon size="100%" strokeWidth={1.5} /></span>
|
||
</button>
|
||
{/if}
|
||
{/each}
|
||
|
||
{#if tools.placing}
|
||
{#each placeSlots as slot (slot.anchor + slot.dir)}
|
||
{@const first = tools.placing.pages[0]}
|
||
{@const r = slotRect(slot, first)}
|
||
{#if r}
|
||
<button
|
||
class="slot"
|
||
style="left:{r.x}px; top:{r.y}px; width:{r.width}px; height:{r.height}px"
|
||
onclick={() => place(slot)}
|
||
>
|
||
<span class="arrow" data-dir={slot.dir} style="--icon: {Math.min(r.width, r.height) * 0.16}px">
|
||
<ArrowUpIcon size="100%" strokeWidth={1.25} />
|
||
</span>
|
||
</button>
|
||
{/if}
|
||
{/each}
|
||
{/if}
|
||
</div>
|
||
|
||
{#if activeMenuPos && doc.activeId}
|
||
<button
|
||
class="icon-btn page-menu no-stage"
|
||
style="left:{activeMenuPos.x}px; top:{activeMenuPos.y}px"
|
||
title="Page options"
|
||
onclick={(e) => {
|
||
const r = e.currentTarget.getBoundingClientRect();
|
||
pageMenu(r.left, r.bottom + 4, doc.activeId!);
|
||
}}
|
||
>
|
||
<EllipsisIcon size={16} />
|
||
</button>
|
||
{/if}
|
||
|
||
{#if offer && offerOffscreen}
|
||
<!-- Like the plus buttons, taps go through the palm-checked gesture. -->
|
||
<button
|
||
class="offer-pill"
|
||
data-anchor={offer.anchor}
|
||
data-dir={offer.dir}
|
||
data-side={offer.dir}
|
||
onclick={(e) => e.detail === 0 && offer && addPage(offer.anchor, offer.dir)}
|
||
>
|
||
<CirclePlusIcon size={18} strokeWidth={1.75} />
|
||
Add page
|
||
</button>
|
||
{/if}
|
||
|
||
{#if selBar && selected}
|
||
<div class="sel-bar no-stage" style="left:{selBar.x}px; top:{selBar.y}px" role="toolbar" aria-label="Selection">
|
||
<button class="icon-btn" title="Copy (Ctrl+C)" onclick={copySelection}><CopyIcon size={16} strokeWidth={1.75} /></button>
|
||
<button class="icon-btn" title="Cut (Ctrl+X)" onclick={() => copySelection() && deleteSelection()}><ScissorsIcon size={16} strokeWidth={1.75} /></button>
|
||
<button class="icon-btn" title="Duplicate (Ctrl+D)" onclick={duplicateSelection}><CopyPlusIcon size={16} strokeWidth={1.75} /></button>
|
||
<button class="icon-btn" title="Delete (Del)" onclick={deleteSelection}><TrashIcon size={16} strokeWidth={1.75} /></button>
|
||
{#if selected.strokes.length}
|
||
<span class="sep"></span>
|
||
{#each settings.data.penColors as c (c)}
|
||
<button class="swatch" style="--c: {c}" title="Recolour ink {c}" aria-label="Recolour ink {c}" onclick={() => recolor(c)}></button>
|
||
{/each}
|
||
{/if}
|
||
</div>
|
||
{/if}
|
||
|
||
{#if eraserAt && tools.tool === 'eraser'}
|
||
<div class="eraser-ring" style="left:{eraserAt.x}px; top:{eraserAt.y}px; width:{tools.eraserRadius * 2}px; height:{tools.eraserRadius * 2}px"></div>
|
||
{/if}
|
||
|
||
{#if tools.placing}
|
||
<div class="banner no-stage">
|
||
Choose where to place <b>{tools.placing.name}</b> ({tools.placing.pages.length} page{tools.placing.pages.length === 1 ? '' : 's'})
|
||
<button class="btn" onclick={() => (tools.placing = null)}>Cancel</button>
|
||
</div>
|
||
{/if}
|
||
</div>
|
||
|
||
{#if sizing && doc.pages[sizing]}
|
||
{@const id = sizing}
|
||
<PageSizeDialog
|
||
width={doc.pages[id].width}
|
||
height={doc.pages[id].height}
|
||
onclose={() => (sizing = null)}
|
||
onapply={(w, h) => {
|
||
sizing = null;
|
||
keepAnchor(id, () => doc.resizePage(id, w, h));
|
||
}}
|
||
/>
|
||
{/if}
|
||
|
||
<Toolbar {doc} onfit={() => fitPage(doc.activeId)} onfitall={fitAll} onimages={(files) => void insertImages(files)} />
|
||
</div>
|
||
|
||
<style>
|
||
.view {
|
||
position: absolute;
|
||
inset: 0;
|
||
display: flex;
|
||
flex-direction: column;
|
||
}
|
||
.titlebar {
|
||
height: 38px;
|
||
flex: none;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
position: relative;
|
||
background: var(--bg);
|
||
border-bottom: 1px solid var(--border);
|
||
padding: 0 8px;
|
||
}
|
||
.crumbs {
|
||
display: flex;
|
||
gap: 6px;
|
||
min-width: 0;
|
||
white-space: nowrap;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
color: var(--text);
|
||
}
|
||
.crumbs .dir {
|
||
color: var(--faint);
|
||
}
|
||
.titlebar .icon-btn {
|
||
position: absolute;
|
||
right: 8px;
|
||
}
|
||
.stage {
|
||
position: relative;
|
||
flex: 1;
|
||
overflow: hidden;
|
||
touch-action: none;
|
||
user-select: none;
|
||
-webkit-user-select: none;
|
||
background-color: var(--bg-canvas);
|
||
}
|
||
.stage :global(.cm-content) {
|
||
user-select: text;
|
||
-webkit-user-select: text;
|
||
}
|
||
.stage.inking {
|
||
cursor: crosshair;
|
||
}
|
||
.stage.erasing {
|
||
cursor: none;
|
||
}
|
||
.stage.inking :global(.page .md),
|
||
.stage.panning :global(.page .md) {
|
||
pointer-events: none;
|
||
}
|
||
.stage.panning {
|
||
cursor: grab;
|
||
}
|
||
.world {
|
||
position: absolute;
|
||
left: 0;
|
||
top: 0;
|
||
transform-origin: 0 0;
|
||
}
|
||
.ghost {
|
||
position: absolute;
|
||
display: grid;
|
||
place-items: center;
|
||
background: none;
|
||
border: 0;
|
||
padding: 0;
|
||
color: var(--faint);
|
||
cursor: pointer;
|
||
transition: color 0.12s;
|
||
}
|
||
.ghost:hover,
|
||
.ghost:focus-visible {
|
||
color: var(--accent);
|
||
}
|
||
.ghost .plus {
|
||
display: grid;
|
||
width: calc(32px / var(--s));
|
||
height: calc(32px / var(--s));
|
||
border-radius: 50%;
|
||
background: var(--bg-canvas);
|
||
}
|
||
.ghost.offer {
|
||
color: var(--accent);
|
||
}
|
||
.ghost.offer .plus {
|
||
animation: offer 1s ease-in-out infinite;
|
||
}
|
||
@keyframes offer {
|
||
50% {
|
||
transform: scale(1.3);
|
||
}
|
||
}
|
||
.offer-pill {
|
||
position: absolute;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
padding: 10px 16px 10px 12px;
|
||
border: 1px solid var(--accent);
|
||
border-radius: 999px;
|
||
background: var(--bg);
|
||
color: var(--accent);
|
||
box-shadow: var(--shadow);
|
||
cursor: pointer;
|
||
white-space: nowrap;
|
||
}
|
||
.offer-pill[data-side='right'] {
|
||
right: 12px;
|
||
top: 50%;
|
||
transform: translateY(-50%);
|
||
}
|
||
.offer-pill[data-side='left'] {
|
||
left: 12px;
|
||
top: 50%;
|
||
transform: translateY(-50%);
|
||
}
|
||
.offer-pill[data-side='up'] {
|
||
top: 12px;
|
||
left: 50%;
|
||
transform: translateX(-50%);
|
||
}
|
||
.offer-pill[data-side='down'] {
|
||
/* Clear of the toolbar. */
|
||
bottom: 72px;
|
||
left: 50%;
|
||
transform: translateX(-50%);
|
||
}
|
||
@media (prefers-reduced-motion: reduce) {
|
||
.ghost.offer .plus {
|
||
animation: none;
|
||
}
|
||
}
|
||
.slot {
|
||
position: absolute;
|
||
display: grid;
|
||
place-items: center;
|
||
background: var(--ghost);
|
||
border: calc(1px / var(--s)) dashed var(--ghost-border);
|
||
border-radius: calc(4px / var(--s));
|
||
color: var(--faint);
|
||
cursor: pointer;
|
||
padding: 0;
|
||
transition: background 0.12s, color 0.12s;
|
||
}
|
||
.slot:hover {
|
||
background: var(--accent-soft);
|
||
color: var(--accent);
|
||
border-color: var(--accent);
|
||
}
|
||
.slot {
|
||
border-style: solid;
|
||
color: var(--accent);
|
||
border-color: color-mix(in srgb, var(--accent) 50%, transparent);
|
||
}
|
||
.arrow {
|
||
display: grid;
|
||
width: var(--icon);
|
||
height: var(--icon);
|
||
}
|
||
.arrow[data-dir='down'] {
|
||
transform: rotate(180deg);
|
||
}
|
||
.arrow[data-dir='left'] {
|
||
transform: rotate(-90deg);
|
||
}
|
||
.arrow[data-dir='right'] {
|
||
transform: rotate(90deg);
|
||
}
|
||
.page-menu {
|
||
position: absolute;
|
||
width: 26px;
|
||
height: 26px;
|
||
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%);
|
||
border: 1.5px solid var(--muted);
|
||
border-radius: 50%;
|
||
pointer-events: none;
|
||
}
|
||
.banner {
|
||
position: absolute;
|
||
top: 12px;
|
||
left: 50%;
|
||
transform: translateX(-50%);
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 12px;
|
||
padding: 6px 6px 6px 14px;
|
||
background: var(--bg);
|
||
border: 1px solid var(--border);
|
||
border-radius: 8px;
|
||
box-shadow: var(--shadow);
|
||
white-space: nowrap;
|
||
}
|
||
</style>
|