Something went wrong. Try again.
a tool for shared writing and social publishing
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284import { v7 } from "uuid";import type { Replicache } from "replicache";import type { ReplicacheMutators } from "src/replicache";import { scanIndex } from "src/replicache/utils";import type { UndoManager } from "src/undoManager";import { useUIState } from "src/useUIState";import { DRAWING_PADDING, DrawingLayout, INK_PRESSURE_SCALE, INK_UNITS_PER_PX, InkStroke, ViewBox, canvasToDrawing, drawingScale, inkSamples, loopAt, refitLayout, simplifySamples, strokeBounds, unionBounds,} from "./ink";import { useInkSession } from "./useInkSession";
type Rep = Replicache<ReplicacheMutators>;
export type DrawingState = { layout: DrawingLayout; positionFactID: string; strokes: { id: string; stroke: InkStroke }[];};
export async function readDrawing( rep: Rep, page: string, entity: string,): Promise<DrawingState | null> { return rep.query(async (tx) => { let scan = scanIndex(tx); let placed = (await scan.eav(page, "canvas/block")).find( (f) => f.data.value === entity, ); let [viewBox] = await scan.eav(entity, "drawing/view-box"); if (!placed || !viewBox) return null; let [width] = await scan.eav(entity, "canvas/block/width"); let [rotation] = await scan.eav(entity, "canvas/block/rotation"); let strokes = await scan.eav(entity, "drawing/stroke"); return { positionFactID: placed.id, layout: { position: placed.data.position, width: width?.data.value || 360, rotation: Math.round(rotation?.data.value || 0), viewBox: viewBox.data.value, }, strokes: strokes.map((s) => ({ id: s.id, stroke: s.data.value })), }; });}
// Drawings placed directly on the page, the session's target first.async function readDrawings(rep: Rep, page: string) { let target = useInkSession.getState().target; let entities = await rep.query(async (tx) => { let scan = scanIndex(tx); let drawings: string[] = []; for (let placed of await scan.eav(page, "canvas/block")) { let [type] = await scan.eav(placed.data.value, "block/type"); if (type?.data.value === "drawing") drawings.push(placed.data.value); } return drawings; }); entities.sort((a, b) => Number(b === target) - Number(a === target)); let drawings: (DrawingState & { entity: string })[] = []; for (let entity of entities) { let drawing = await readDrawing(rep, page, entity); if (drawing) drawings.push({ ...drawing, entity }); } return drawings;}
// Fills the closed stroke around a canvas point, if there is one.export async function fillAt( rep: Rep, undoManager: UndoManager, args: { page: string; point: { x: number; y: number }; color: string },) { for (let drawing of await readDrawings(rep, args.page)) { let hit = loopAt( drawing.strokes, canvasToDrawing(drawing.layout, args.point), ); if (!hit) continue; let { id, stroke } = hit.stroke; if (stroke.fill?.color === args.color) return; await undoManager.withUndoGroup(() => rep.mutate.assertFact({ id, entity: drawing.entity, attribute: "drawing/stroke", data: { type: "ink-stroke", value: { ...stroke, points: [...stroke.points], fill: { points: hit.loop, color: args.color }, }, }, }), ); return; }}
// Canvas px the stored points may stray from the drawn stroke.const SIMPLIFY_TOLERANCE_PX = 0.25;const SIMPLIFY_PRESSURE_TOLERANCE = 0.03;
// Canvas px points in, drawing-space stroke out.function toStroke( canvasPoints: number[], layout: DrawingLayout, args: { color: string; size: number; simulatePressure: boolean },) { let samples = simplifySamples( inkSamples(canvasPoints, args.size), SIMPLIFY_TOLERANCE_PX, SIMPLIFY_PRESSURE_TOLERANCE, ); let points: number[] = []; for (let [cx, cy, pressure] of samples) { let d = canvasToDrawing(layout, { x: cx, y: cy }); let x = Math.round(d.x), y = Math.round(d.y); let n = points.length; if (n >= 3 && points[n - 3] === x && points[n - 2] === y) continue; points.push(x, y, Math.round(pressure * INK_PRESSURE_SCALE)); } return { points, color: args.color, size: Math.max(1, Math.round(args.size / drawingScale(layout))), ...(args.simulatePressure && { simulatePressure: true }), };}
// A new drawing's frame: drawing units are INK_UNITS_PER_PX per canvas px, with// the origin at canvas (0, 0). Its view box is empty, so the first stroke// always refits it.const NEW_DRAWING: DrawingLayout = { position: { x: -DRAWING_PADDING, y: -DRAWING_PADDING }, width: 2 * DRAWING_PADDING + 1, rotation: 0, viewBox: { x: 0, y: 0, width: INK_UNITS_PER_PX, height: 0 },};
// Refits the drawing's frame to a new view box, if it changed.async function fitViewBox( rep: Rep, page: string, entity: string, drawing: Omit<DrawingState, "strokes">, viewBox: ViewBox | null,) { let old = drawing.layout.viewBox; if ( !viewBox || (["x", "y", "width", "height"] as const).every((k) => viewBox[k] === old[k]) ) return; let layout = refitLayout(drawing.layout, viewBox); await rep.mutate.assertFact([ { entity, attribute: "drawing/view-box", data: { type: "view-box", value: layout.viewBox }, }, { entity, attribute: "canvas/block/width", data: { type: "number", value: layout.width }, }, { id: drawing.positionFactID, entity: page, attribute: "canvas/block", data: { type: "spatial-reference", value: entity, position: layout.position, }, }, ]);}
export async function commitStroke( rep: Rep, undoManager: UndoManager, args: { page: string; permission_set: string; canvasPoints: number[]; color: string; // Canvas px. size: number; simulatePressure: boolean; },) { let target = useInkSession.getState().target; let existing = target ? await readDrawing(rep, args.page, target) : null; let drawing = existing ?? { layout: NEW_DRAWING, positionFactID: v7() }; let stroke = toStroke(args.canvasPoints, drawing.layout, args); let bounds = strokeBounds(stroke); if (!bounds) return; await undoManager.withUndoGroup(async () => { let entity = (existing && target) || v7(); if (!existing) { await rep.mutate.addCanvasBlock({ parent: args.page, permission_set: args.permission_set, factID: drawing.positionFactID, newEntityID: entity, type: "drawing", position: drawing.layout.position, }); useInkSession.setState({ target: entity }); } await rep.mutate.assertFact({ id: v7(), entity, attribute: "drawing/stroke", data: { type: "ink-stroke", value: stroke }, }); await fitViewBox( rep, args.page, entity, drawing, unionBounds([existing?.layout.viewBox ?? null, bounds]), ); });}
export async function eraseStrokes( rep: Rep, undoManager: UndoManager, args: { page: string; target: string; strokeIDs: string[] },) { let existing = await readDrawing(rep, args.page, args.target); if (!existing) return; let remaining = existing.strokes.filter( (s) => !args.strokeIDs.includes(s.id), ); await undoManager.withUndoGroup(async () => { for (let factID of args.strokeIDs) await rep.mutate.retractFact({ factID }); await fitViewBox( rep, args.page, args.target, existing, unionBounds(remaining.map((s) => strokeBounds(s.stroke))), ); });}
// Leaves draw mode with the drawing selected, or removes it if every stroke// was erased.export async function stopInk(rep: Rep | null, undoManager: UndoManager) { let { page, target } = useInkSession.getState(); useInkSession.setState({ page: null, target: null, erasing: [] }); if (!rep || !page || !target) return; let drawing = await readDrawing(rep, page, target); if (!drawing) return; if (drawing.strokes.length === 0) { await undoManager.withUndoGroup(() => rep.mutate.removeBlock({ blockEntity: target, parent: page }), ); return; } let ui = useUIState.getState(); ui.setSelectedBlocks([{ entityID: target, parent: page }]); ui.setFocusedBlock({ entityType: "block", entityID: target, parent: page });}