// The notebook editor: a page's strokes drawn from its `.rm` bytes, new // strokes from the pointer (pen, mouse or trackpad) written back in the // tablet's own format, an eraser that lifts whole strokes, undo and redo, // pages added and removed, and the page's template behind it all. The page // is parsed, rendered and written here in the browser; the sidecar only // moves bytes to and from the cloud. import { LitElement, html, svg, nothing } from 'lit'; import { unsafeSVG } from 'lit/directives/unsafe-svg.js'; import { repeat } from 'lit/directives/repeat.js'; import { PageEditor, pagePaint, lineSegments, SCREEN_WIDTH, SCREEN_HEIGHT, type Line, type PaintSegment } from '../../../lib/browser.js'; import { api } from '../api.ts'; import { confirm } from '../desktop.ts'; import { DEFAULT_PEN, PENS, PEN_KINDS, TEMPLATES, THICKNESSES, buildLine, colorsFor, simplify, strokesNear, templateSpec, type RawPoint, type TemplateSpec } from '../ink.ts'; import { msg, type DocInfo, type DocJson, type PenKind, type PenPrefs, type Thickness } from '../model.ts'; type Op = { kind: 'add' | 'remove'; key: string; line: Line }; type Tool = 'pen' | 'eraser'; const W = SCREEN_WIDTH; const H = SCREEN_HEIGHT; const VIEWBOX = `${-W / 2} 0 ${W} ${H}`; const THUMB = { w: 362, h: 482 }; const AUTOSAVE_MS = 4000; const ERASER_PX = 14; const ZOOMS = [0.25, 0.33, 0.5, 0.67, 0.75, 1, 1.25, 1.5, 2, 3]; const rgba = ([r, g, b, a]: [number, number, number, number]) => (a === 255 ? `rgb(${r},${g},${b})` : `rgba(${r},${g},${b},${(a / 255).toFixed(3)})`); const esc = (s: string) => s.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); function segmentMarkup(s: PaintSegment): string { if (s.points.length === 1) { const [x, y] = s.points[0]!; return ``; } const pts = s.points.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(' '); return ``; } function templateMarkup(spec: TemplateSpec, id: string): string { const ink = '#c8cdd8'; const x0 = -W / 2; switch (spec.kind) { case 'lines': { const lines: string[] = []; for (let y = spec.step; y < H; y += spec.step) lines.push(``); const margin = spec.margin ? `` : ''; return `${lines.join('')}${margin}`; } case 'grid': return ``; case 'dots': return ``; default: return ''; } } export class NbNotebook extends LitElement { static properties = { source: { attribute: false }, info: { state: true }, prefs: { attribute: false }, pageIndex: { state: true }, zoom: { state: true }, tool: { state: true }, dirty: { state: true }, busy: { state: true }, saving: { state: true }, error: { state: true }, rev: { state: true }, }; /** The document to edit, as the app fetched it. Once open, the editor keeps its own, fresher picture in `info`. */ declare source: DocInfo | null; declare info: DocInfo; declare prefs: PenPrefs; declare pageIndex: number; declare zoom: number | 'fit'; declare tool: Tool; declare dirty: boolean; declare busy: boolean; declare saving: boolean; declare error: string; /** Bumped whenever the ink changes, so the page redraws. */ declare rev: number; private editor: PageEditor | null = null; private loadedDoc: string | null = null; private pageId: string | null = null; private author = 1; private lines = new Map(); private markup = new Map(); private segments = new Map(); private textMarkup = ''; private inkCache: string | null = null; private flatCache: PaintSegment[] | null = null; private live: RawPoint[] | null = null; private pointerId: number | null = null; private undoStack: Op[] = []; private redoStack: Op[] = []; private thumbs = new Map(); private thumbQueue: Promise = Promise.resolve(); private autosave: ReturnType | null = null; private fitScale = 1; private resize: ResizeObserver | null = null; private observed: Element | null = null; private frame = 0; private seq = 0; private uid = `tpl-${Math.random().toString(36).slice(2, 8)}`; private onKey = (e: KeyboardEvent) => this.keydown(e); constructor() { super(); this.source = null; this.prefs = { ...DEFAULT_PEN }; this.pageIndex = 0; this.zoom = 'fit'; this.tool = 'pen'; this.dirty = false; this.busy = false; this.saving = false; this.error = ''; this.rev = 0; } protected override createRenderRoot() { return this; } override connectedCallback() { super.connectedCallback(); window.addEventListener('keydown', this.onKey); } override disconnectedCallback() { super.disconnectedCallback(); window.removeEventListener('keydown', this.onKey); this.resize?.disconnect(); if (this.autosave) clearTimeout(this.autosave); for (const url of this.thumbs.values()) URL.revokeObjectURL(url); } override updated(changed: Map) { // the canvas appears once a document is loaded; fit the page to it from then on const canvas = this.querySelector('.nb-canvas'); if (canvas && this.observed !== canvas) { this.resize?.disconnect(); this.resize = new ResizeObserver(() => this.measure()); this.resize.observe(canvas); this.observed = canvas; this.measure(); } if (changed.has('source') && this.source && this.source.doc.id !== this.loadedDoc) { this.info = this.source; this.loadedDoc = this.info.doc.id; const last = (this.info.content as { cPages?: { lastOpened?: { value?: string } } }).cPages?.lastOpened?.value; const i = Math.max(0, this.info.pages.findIndex((p) => p.id === last)); void this.openPage(i, true); void this.loadThumbs(); } } // ---- geometry ----------------------------------------------------------- private measure() { const canvas = this.querySelector('.nb-canvas') as HTMLElement | null; if (!canvas) return; const pad = 32; const s = Math.min((canvas.clientWidth - pad) / W, (canvas.clientHeight - pad) / H); if (s > 0 && Math.abs(s - this.fitScale) > 0.001) { // on the next frame, so the observer's own callback never changes layout requestAnimationFrame(() => { this.fitScale = s; this.rev++; }); } } get scale(): number { return this.zoom === 'fit' ? this.fitScale : this.zoom; } zoomIn() { const s = this.scale; this.zoom = ZOOMS.find((z) => z > s + 0.01) ?? ZOOMS[ZOOMS.length - 1]!; } zoomOut() { const s = this.scale; this.zoom = [...ZOOMS].reverse().find((z) => z < s - 0.01) ?? ZOOMS[0]!; } zoomFit() { this.zoom = 'fit'; } // ---- pages ---------------------------------------------------------------- get page() { return this.info?.pages[this.pageIndex] ?? null; } private emit(name: string, detail?: T) { this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true })); } /** Show page `index`, saving the current one first if it changed. */ async openPage(index: number, force = false) { const page = this.info?.pages[index]; if (!page) return; if (!force && index === this.pageIndex && this.pageId === page.id) return; await this.flush(); const seq = ++this.seq; this.pageIndex = index; this.pageId = page.id; this.busy = true; this.error = ''; this.live = null; try { const bytes = page.hasRm ? await api.page(this.info.doc.id, page.id) : null; if (seq !== this.seq) return; this.editor = bytes ? PageEditor.parse(bytes) : PageEditor.blank({ authorUuid: this.info.author.uuid }); this.author = this.editor.authorIndex(this.info.author.uuid, { preferred: this.info.author.index }); this.rebuild(); this.undoStack = []; this.redoStack = []; this.dirty = false; } catch (err) { if (seq !== this.seq) return; this.error = msg(err); this.editor = null; } finally { if (seq === this.seq) { this.busy = false; this.rev++; } } } nextPage() { void this.openPage(Math.min(this.info.pages.length - 1, this.pageIndex + 1)); } prevPage() { void this.openPage(Math.max(0, this.pageIndex - 1)); } private async reloadInfo(doc: DocJson) { this.info = await api.doc(this.info.doc.id); this.emit('doc-changed', doc); } async addPage() { if (this.busy) return; await this.flush(); this.busy = true; try { const { doc, pageId } = await api.addPage(this.info.doc.id, this.page?.id ?? null, this.page?.template ?? null); await this.reloadInfo(doc); const i = this.info.pages.findIndex((p) => p.id === pageId); await this.openPage(Math.max(0, i), true); } catch (err) { this.error = msg(err); } finally { this.busy = false; } } async removePage() { const page = this.page; if (!page || this.busy) return; if (this.info.pages.length <= 1) { this.error = 'A notebook keeps at least one page.'; return; } if (!(await confirm(`Delete page ${this.pageIndex + 1}?`, 'Its strokes go with it. This cannot be undone.', 'Delete', 'warning'))) return; this.busy = true; try { this.dirty = false; // whatever was drawn on it goes too if (this.autosave) clearTimeout(this.autosave); const { doc } = await api.removePage(this.info.doc.id, page.id); this.pageId = null; await this.reloadInfo(doc); await this.openPage(Math.min(this.pageIndex, this.info.pages.length - 1), true); } catch (err) { this.error = msg(err); } finally { this.busy = false; } } private async setTemplate(name: string) { const page = this.page; if (!page) return; try { const { doc } = await api.setTemplate(this.info.doc.id, page.id, name); const index = this.pageIndex; const id = this.pageId; this.info = await api.doc(this.info.doc.id); this.pageIndex = index; this.pageId = id; this.emit('doc-changed', doc); } catch (err) { this.error = msg(err); } } // ---- ink ------------------------------------------------------------------ /** Rebuild the drawn strokes from the editor's tree (after a load). */ private rebuild() { this.lines.clear(); this.markup.clear(); this.segments.clear(); this.textMarkup = ''; this.inkCache = null; this.flatCache = null; if (!this.editor) return; for (const s of this.editor.strokes) this.lines.set(s.key, s.line); const texts: string[] = []; for (const item of pagePaint(this.editor.tree).items) { if (item.kind === 'text') { const size = item.cls === 'heading' ? 44 : item.cls === 'bold' ? 28 : 26; texts.push(`${esc(item.content)}`); continue; } const key = item.item ?? '_'; const list = this.segments.get(key); if (list) list.push(item); else this.segments.set(key, [item]); } this.textMarkup = texts.join(''); for (const [key, segs] of this.segments) this.markup.set(key, segs.map(segmentMarkup).join('')); } private inkMarkup(): string { if (this.inkCache === null) this.inkCache = this.textMarkup + [...this.markup.values()].join(''); return this.inkCache; } private allSegments(): PaintSegment[] { if (!this.flatCache) this.flatCache = [...this.segments.values()].flat(); return this.flatCache; } private addDrawn(key: string, line: Line) { const segs = lineSegments(line); this.lines.set(key, line); this.segments.set(key, segs); this.markup.set(key, segs.map(segmentMarkup).join('')); this.inkCache = null; this.flatCache = null; } private forgetDrawn(key: string) { this.lines.delete(key); this.segments.delete(key); this.markup.delete(key); this.inkCache = null; this.flatCache = null; } private changed() { this.dirty = true; this.rev++; if (this.autosave) clearTimeout(this.autosave); this.autosave = setTimeout(() => void this.save(), AUTOSAVE_MS); } private toPage(e: PointerEvent): RawPoint { const el = this.querySelector('svg.page') as SVGSVGElement; const pt = new DOMPoint(e.clientX, e.clientY).matrixTransform(el.getScreenCTM()!.inverse()); return { x: pt.x, y: pt.y, pressure: e.pressure || (e.pointerType === 'mouse' ? 0.5 : 0.5), t: e.timeStamp, tiltX: e.tiltX ?? 0, tiltY: e.tiltY ?? 0 }; } private down(e: PointerEvent) { if (!this.editor || this.busy) return; if (e.pointerType === 'touch' || (e.button !== 0 && e.pointerType === 'mouse')) return; e.preventDefault(); const el = e.currentTarget as SVGSVGElement; try { el.setPointerCapture(e.pointerId); } catch { /* a synthetic pointer cannot be captured */ } this.pointerId = e.pointerId; const p = this.toPage(e); // the pen's eraser end, or the eraser tool if (this.tool === 'eraser' || e.buttons === 32 || e.button === 5) this.eraseAt(p); else this.live = [p]; } private move(e: PointerEvent) { if (this.pointerId !== e.pointerId) return; const events = typeof e.getCoalescedEvents === 'function' ? e.getCoalescedEvents() : [e]; for (const ev of events.length ? events : [e]) { const p = this.toPage(ev); if (this.live) this.live.push(p); else this.eraseAt(p); } if (!this.frame) this.frame = requestAnimationFrame(() => { this.frame = 0; this.rev++; }); } private up(e: PointerEvent) { if (this.pointerId !== e.pointerId) return; try { (e.currentTarget as SVGSVGElement).releasePointerCapture(e.pointerId); } catch { /* not captured */ } this.pointerId = null; if (this.live) { this.live.push(this.toPage(e)); this.commitStroke(); } this.live = null; this.rev++; } private commitStroke() { if (!this.editor || !this.live) return; const pts = simplify(this.live); if (pts.length === 1) pts.push({ ...pts[0]!, x: pts[0]!.x + 0.5, t: pts[0]!.t + 1 }); const line = buildLine(this.prefs, pts); const key = this.editor.addLine(line, { author: this.author }); this.addDrawn(key, line); this.undoStack.push({ kind: 'add', key, line }); this.redoStack = []; this.changed(); } private eraseAt(p: RawPoint) { if (!this.editor) return; const hits = strokesNear(this.allSegments(), p.x, p.y, ERASER_PX / this.scale); if (!hits.size) return; for (const key of hits) { const line = this.lines.get(key); if (!line || !this.editor.removeStroke(key)) continue; this.forgetDrawn(key); this.undoStack.push({ kind: 'remove', key, line }); } this.redoStack = []; this.changed(); } get canUndo() { return this.undoStack.length > 0; } get canRedo() { return this.redoStack.length > 0; } undo() { const op = this.undoStack.pop(); if (!op || !this.editor) return; if (op.kind === 'add') { this.editor.dropLine(op.key); this.forgetDrawn(op.key); } else { this.editor.restoreStroke(op.key, op.line); this.addDrawn(op.key, op.line); } this.redoStack.push(op); this.changed(); } redo() { const op = this.redoStack.pop(); if (!op || !this.editor) return; if (op.kind === 'add') { const key = this.editor.addLine(op.line, { author: this.author }); this.addDrawn(key, op.line); this.undoStack.push({ kind: 'add', key, line: op.line }); } else { this.editor.removeStroke(op.key); this.forgetDrawn(op.key); this.undoStack.push(op); } this.changed(); } // ---- saving ---------------------------------------------------------------- /** Save the page if it changed; waits for a save already under way. */ async flush() { if (this.autosave) { clearTimeout(this.autosave); this.autosave = null; } if (this.dirty) await this.save(); } async save() { if (!this.editor || !this.dirty || this.saving || !this.pageId) return; if (this.autosave) { clearTimeout(this.autosave); this.autosave = null; } const docId = this.info.doc.id; const pageId = this.pageId; const editor = this.editor; this.saving = true; this.error = ''; try { const bytes = editor.write(); const { doc } = await api.savePage(docId, pageId, bytes); if (this.pageId === pageId && this.editor === editor) this.dirty = false; this.emit('doc-changed', doc); const png = await this.thumbnail(); if (png) { const { doc: again } = await api.saveThumbnail(docId, pageId, png); const old = this.thumbs.get(pageId); if (old) URL.revokeObjectURL(old); this.thumbs.set(pageId, URL.createObjectURL(png)); this.emit('doc-changed', again); this.rev++; } } catch (err) { this.error = `Not saved: ${msg(err)}`; this.autosave = setTimeout(() => void this.save(), AUTOSAVE_MS * 3); } finally { this.saving = false; } } private pageMarkup(width: number, height: number): string { const spec = templateSpec(this.page?.template); return `${templateMarkup(spec, `${this.uid}-t`)}${this.inkMarkup()}`; } private async thumbnail(): Promise { try { const url = URL.createObjectURL(new Blob([this.pageMarkup(THUMB.w, THUMB.h)], { type: 'image/svg+xml' })); const img = new Image(); await new Promise((resolve, reject) => { img.onload = () => resolve(); img.onerror = () => reject(new Error('thumbnail did not render')); img.src = url; }); const canvas = document.createElement('canvas'); canvas.width = THUMB.w; canvas.height = THUMB.h; const ctx = canvas.getContext('2d')!; ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, THUMB.w, THUMB.h); ctx.drawImage(img, 0, 0, THUMB.w, THUMB.h); URL.revokeObjectURL(url); return await new Promise((resolve) => canvas.toBlob(resolve, 'image/png')); } catch { return null; } } private async loadThumbs() { const docId = this.info.doc.id; for (const p of this.info.pages) { if (!p.hasThumbnail || this.thumbs.has(p.id)) continue; this.thumbQueue = this.thumbQueue.then(async () => { if (this.loadedDoc !== docId || this.thumbs.has(p.id)) return; const bytes = await api.thumbnail(docId, p.id).catch(() => null); if (bytes && this.loadedDoc === docId) { this.thumbs.set(p.id, URL.createObjectURL(new Blob([bytes as BlobPart], { type: 'image/png' }))); this.rev++; } }); } } // ---- keys ------------------------------------------------------------------- private keydown(e: KeyboardEvent) { const t = e.target as HTMLElement | null; if (t && /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)) return; const meta = e.metaKey || e.ctrlKey; if (meta && e.key.toLowerCase() === 'z') { e.preventDefault(); if (e.shiftKey) this.redo(); else this.undo(); } else if (meta && e.key.toLowerCase() === 's') { e.preventDefault(); void this.save(); } else if (!meta && (e.key === 'e' || e.key === 'E')) this.tool = 'eraser'; else if (!meta && (e.key === 'p' || e.key === 'P' || e.key === 'Escape')) this.tool = 'pen'; else if (!meta && e.key === '[') this.prevPage(); else if (!meta && e.key === ']') this.nextPage(); else if (meta && (e.key === '=' || e.key === '+')) { e.preventDefault(); this.zoomIn(); } else if (meta && e.key === '-') { e.preventDefault(); this.zoomOut(); } else if (meta && e.key === '0') { e.preventDefault(); this.zoomFit(); } } private setPrefs(patch: Partial) { const next = { ...this.prefs, ...patch }; if (patch.kind && !colorsFor(next.kind).some((c) => c.id === next.color)) next.color = colorsFor(next.kind)[0]!.id; this.prefs = next; this.emit('prefs-changed', next); } // ---- render ----------------------------------------------------------------- private toolbar() { const pen = PENS[this.prefs.kind]; const colors = colorsFor(this.prefs.kind); return html` { this.tool = 'pen'; }}> Pen { this.tool = 'eraser'; }}> Eraser this.setPrefs({ kind: (e.target as HTMLSelectElement).value as PenKind })}> ${PEN_KINDS.map((k) => html`${PENS[k].label}`)} ${colors.map((c) => html` this.setPrefs({ color: c.id })}>`)} ${THICKNESSES.map((t) => html` this.setPrefs({ thickness: t.value as Thickness })}>`)} void this.setTemplate((e.target as HTMLSelectElement).value)}> ${TEMPLATES.map((t) => html`${t.label}`)} ${this.page?.template && !TEMPLATES.some((t) => t.name === this.page?.template) ? html`${this.page.template}` : nothing} ${Math.round(this.scale * 100)}% ${this.saving ? 'Saving…' : this.dirty ? 'Unsaved' : 'Saved'} void this.save()}> Save `; } private strip() { return html``; } private canvas() { const s = this.scale; const spec = templateSpec(this.page?.template); const live = this.live && this.live.length ? lineSegments(buildLine(this.prefs, this.live)) : []; return html` { if (e.metaKey || e.ctrlKey) { e.preventDefault(); if (e.deltaY < 0) this.zoomIn(); else this.zoomOut(); } }}> ${this.editor ? svg` ${unsafeSVG(templateMarkup(spec, this.uid))} ${unsafeSVG(this.inkMarkup())} ${live.map((seg) => (seg.points.length > 1 ? svg` `${x.toFixed(1)},${y.toFixed(1)}`).join(' ')} fill="none" stroke=${rgba(seg.color)} stroke-width=${seg.width} stroke-linecap=${seg.linecap} stroke-linejoin="round" opacity=${seg.opacity}/>` : nothing))} ` : this.busy ? html`Loading the page…` : nothing} `; } override render() { if (!this.info) return nothing; if (!this.info.pages.length) { return html`This document has no pages yet. Open it on the tablet once, then come back.`; } return html` ${this.toolbar()} ${this.error ? html`${this.error}` : nothing} ${this.strip()} ${this.canvas()} `; } } customElements.define('nb-notebook', NbNotebook);
Loading the page…
This document has no pages yet. Open it on the tablet once, then come back.
${this.error}