Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213// Editing a page in memory: start from a page's bytes (or blank; a version 3// or 5 page is taken in as the version 6 page it converts to), add// strokes, erase strokes, write the page back. Runs in a browser as well as// on Node, so an editor can keep the whole page client-side and only hand the// bytes to whatever stores them.//// The format is a log of CRDT blocks. A stroke is a SceneLineItemBlock whose// item sits in a layer's sequence (between `leftId` and `rightId`); erasing// one replaces the block with a tombstone carrying the same ids, which is how// the tablet records a deletion so that copies merge. Every id an author// makes is (authorIndex, counter), the author being registered in the page's// AuthorIdsBlock.import { CrdtId, LwwValue, randomUuid } from './tagged-block-common.js';import { CrdtSequenceItem, END_MARKER } from './crdt-sequence.js';import * as si from './scene-items.js';import { AuthorIdsBlock, MigrationInfoBlock, PageInfoBlock, SceneInfo, SceneTreeBlock, TreeNodeBlock, SceneGroupItemBlock, SceneLineItemBlock, SceneTombstoneItemBlock, SceneItemBlock, RootTextBlock, readBlocks, writeBlocks, buildTree,} from './scene-stream.js';import { SceneTree, ROOT_ID } from './scene-tree.js';import { SCREEN_WIDTH, SCREEN_HEIGHT } from './exporters/page-paint.js';
// The first layer of a page, as the tablet numbers it.export const LAYER_ID = new CrdtId(0, 11);
// The blocks of an empty page with one layer, laid out as the tablet writes them.export function blankPageBlocks ({ authorUuid = null } = {}) { const zero = new CrdtId(0, 0); const size = [SCREEN_WIDTH, SCREEN_HEIGHT]; return [ new AuthorIdsBlock(new Map([[1, authorUuid ?? randomUuid()]])), new MigrationInfoBlock(new CrdtId(1, 1), true), new PageInfoBlock(1, 0, 0, 0), new SceneInfo( new LwwValue(zero, zero), new LwwValue(zero, true), new LwwValue(zero, true), size, new LwwValue(zero, new Uint8Array(32)), size, new LwwValue(zero, size), new LwwValue(new CrdtId(0, 14), si.ColumnWidth.DEFAULT), ), new SceneTreeBlock(LAYER_ID, zero, true, ROOT_ID), new TreeNodeBlock(new si.Group({ nodeId: ROOT_ID })), new TreeNodeBlock(new si.Group({ nodeId: LAYER_ID, label: new LwwValue(new CrdtId(0, 12), 'Layer 1') })), new SceneGroupItemBlock(ROOT_ID, new CrdtSequenceItem(new CrdtId(0, 13), zero, zero, 0, LAYER_ID)), ];}
export function blankPage (options = {}) { return writeBlocks(blankPageBlocks(options));}
const u8 = (v) => Math.max(0, Math.min(255, Math.round(Number(v) || 0)));const u16 = (v) => Math.max(0, Math.min(65535, Math.round(Number(v) || 0)));
// A stroke from an editor's points. Each point is { x, y } in page units// (the page is 1404 wide, x from -702 to 702, y from 0 to 1872), with// optional `pressure` (0..255), `speed`, `direction` (0..255) and `width`// (the pen's size at that point, in the tablet's units; around 8 for a// medium pen), which the pens' rendering formulas read.export function makeLine ({ tool, color = si.PenColor.BLACK, colorRgba = null, thickness = 2, points }) { const pts = points.map(p => new si.Point( Number(p.x), Number(p.y), u16(p.speed ?? 0), u8(p.direction ?? 0), u16(p.width ?? 8), u8(p.pressure ?? 128), )); return new si.Line(color, tool, pts, thickness, 0, null, colorRgba);}
function* idsOf (value) { if (value instanceof CrdtId) yield value; else if (value instanceof LwwValue) { yield* idsOf(value.timestamp); yield* idsOf(value.value); } else if (value instanceof CrdtSequenceItem) { yield value.itemId; yield value.leftId; yield value.rightId; yield* idsOf(value.value); } else if (value instanceof si.Group) { yield value.nodeId; yield* idsOf(value.label); yield* idsOf(value.visible); yield* idsOf(value.anchorId); yield* idsOf(value.anchorType); yield* idsOf(value.anchorThreshold); yield* idsOf(value.anchorOriginX); } else if (value instanceof si.Line) yield* idsOf(value.moveId); else if (value instanceof si.Text) { for (const item of value.items.sequenceItems()) yield* idsOf(item); for (const [key, fmt] of value.styles) { yield CrdtId.fromKey(key); yield* idsOf(fmt); } }}
function* blockIds (block) { if (block instanceof SceneItemBlock) { yield block.parentId; yield* idsOf(block.item); } else if (block instanceof SceneTreeBlock) { yield block.treeId; yield block.nodeId; yield block.parentId; } else if (block instanceof TreeNodeBlock) yield* idsOf(block.group); else if (block instanceof RootTextBlock) { yield block.blockId; yield* idsOf(block.value); } else if (block instanceof MigrationInfoBlock) yield block.migrationId; else if (block instanceof SceneInfo) { for (const v of [block.currentLayer, block.backgroundVisible, block.rootDocumentVisible, block.customZoom, block.paperSizeFloatLww, block.columnWidth]) yield* idsOf(v); }}
export class PageEditor { constructor (blocks) { this.blocks = [...blocks]; this._tree = null; this._counters = new Map(); }
static parse (data) { return new PageEditor(readBlocks(data)); } static blank (options = {}) { return new PageEditor(blankPageBlocks(options)); }
// The scene tree of the current blocks (rebuilt after a change). get tree () { if (!this._tree) { this._tree = new SceneTree(); buildTree(this._tree, this.blocks); } return this._tree; }
get authorBlock () { return this.blocks.find(b => b instanceof AuthorIdsBlock) ?? null; }
// Map of author index → UUID, as the page records them. get authors () { return new Map(this.authorBlock?.authorUuids ?? []); }
// The index to write ids with for `uuid`: the one the page already has for // it, else `preferred` when that index is free, else the next free one. // Registers the author in the page when it is new. authorIndex (uuid, { preferred = null } = {}) { let block = this.authorBlock; if (!block) { block = new AuthorIdsBlock(new Map()); this.blocks.unshift(block); } for (const [index, id] of block.authorUuids) if (id === uuid) return index; const taken = new Set(block.authorUuids.keys()); let index = preferred != null && !taken.has(preferred) ? preferred : 1; while (taken.has(index)) index++; block.authorUuids.set(index, uuid); return index; }
// The top-level layers of the page, in order: [{ id, key, label, visible }]. get layers () { const out = []; for (const [, child] of this.tree.root.children.items()) { if (child instanceof si.Group) out.push({ id: child.nodeId, key: child.nodeId.toKey(), label: child.label?.value ?? '', visible: child.visible?.value ?? true }); } return out; }
// Every stroke, with the key of its item and of the layer holding it. get strokes () { const out = []; const walk = (group, layer) => { for (const [id, child] of group.children.items()) { if (child instanceof si.Group) walk(child, layer ?? child.nodeId.toKey()); else if (child instanceof si.Line) out.push({ key: id.toKey(), layer, line: child }); } }; walk(this.tree.root, null); return out; }
get isEmpty () { return this.strokes.length === 0 && !this.tree.rootText; }
// The next counter for `author`: one past every id the page holds for it. nextId (author) { if (!this._counters.has(author)) { let max = 0; for (const block of this.blocks) for (const id of blockIds(block)) if (id && id.part1 === author && id.part2 > max) max = id.part2; this._counters.set(author, max); } const next = this._counters.get(author) + 1; this._counters.set(author, next); return new CrdtId(author, next); }
// Append a stroke at the end of a layer (the first one by default). Returns the stroke's key. addLine (line, { author = 1, layer = null } = {}) { const layerId = layer ? (layer instanceof CrdtId ? layer : CrdtId.fromKey(layer)) : (this.layers[0]?.id ?? null); if (!layerId || !this.tree.has(layerId)) throw new Error('the page has no such layer'); const group = this.tree.get(layerId); const keys = group.children.keys(); const left = keys.length ? keys[keys.length - 1] : END_MARKER; const id = this.nextId(author); const item = new CrdtSequenceItem(id, left, END_MARKER, 0, line); this.blocks.push(new SceneLineItemBlock(layerId, item)); group.children.add(item); return id.toKey(); }
// Erase a stroke: its block becomes a tombstone. Returns whether it was there. removeStroke (key) { const i = this.blocks.findIndex(b => b instanceof SceneLineItemBlock && b.item.itemId.toKey() === key); if (i < 0) return false; const { parentId, item } = this.blocks[i]; this.blocks[i] = new SceneTombstoneItemBlock(parentId, new CrdtSequenceItem(item.itemId, item.leftId, item.rightId, 1, null)); this._tree = null; return true; }
// Take a stroke this editor added out of the page altogether, as if it had // never been drawn (an undo of the latest addition; nothing refers to it // yet). Returns whether it was there. dropLine (key) { const i = this.blocks.findIndex(b => b instanceof SceneLineItemBlock && b.item.itemId.toKey() === key); if (i < 0) return false; this.blocks.splice(i, 1); this._tree = null; return true; }
// Bring a stroke back after removeStroke (an undo). Returns whether it could. restoreStroke (key, line) { const i = this.blocks.findIndex(b => b instanceof SceneTombstoneItemBlock && b.item.itemId.toKey() === key); if (i < 0) return false; const { parentId, item } = this.blocks[i]; this.blocks[i] = new SceneLineItemBlock(parentId, new CrdtSequenceItem(item.itemId, item.leftId, item.rightId, 0, line)); this._tree = null; return true; }
write (options = {}) { return writeBlocks(this.blocks, options); }}