import { type Anchor, type Editor, ElementApi, PointApi, type Range, RangeApi, TextApi, } from 'platejs'; import { AuthoredPlugin } from 'platejs/authored'; import { BaseCommentsPlugin, type CommentData } from 'platejs/comments'; import { BaseInkPlugin, type InkMark, type InkPassage } from 'platejs/ink'; import { type InkPassageImages, InkPlugin } from 'platejs/ink/react'; import type { InkDigitizeCorrection, InkDigitizeEdit, InkDigitizeMeaning, InkDigitizeReading, InkDigitizeRequest, } from '@/registry/app/api/ai/ink-digitize/ink-digitize-route'; export const INK_DIGITIZE_MAX_WORDS = 1000; export const INK_DIGITIZE_MAX_SIDE = 2048; const VOID_CHAR = String.fromCodePoint(0xff_fc); const ATTACHED_PUNCT_RE = /^[.,!?;:)\]}]+$/; const PUNCT_ONLY_RE = /^[\p{P}\p{S}]+$/u; const requestCounters = new WeakMap(); const latestRequests = new WeakMap(); export const nextInkDigitizeRequestId = (view: Editor): string => { const next = (requestCounters.get(view) ?? 0) + 1; requestCounters.set(view, next); const id = `r${next}`; latestRequests.set(view, id); return id; }; export const latestInkDigitizeRequestId = (view: Editor): string | undefined => latestRequests.get(view); export const canDigitizeInk = (view: Editor): boolean => { if (view.read.view.isReadOnly()) return false; if (view.plugin(AuthoredPlugin).installed) { const authoredView = view.plugin(AuthoredPlugin).read.view(); if ('preview' in authoredView) return false; } return true; }; export type PreparedPassageMeta = Readonly<{ blockId: string; copy: string; id: string; passage: InkPassage; words: readonly string[]; }>; export type PreparedInkDigitize = Readonly<{ blockOrder: readonly string[]; blockSnapshots: ReadonlyMap; extraMarkIds: readonly string[]; lassoedMarkIds: readonly string[]; markIdByKey: ReadonlyMap; markKeyById: ReadonlyMap; passages: readonly PreparedPassageMeta[]; request: Omit< InkDigitizeRequest, 'apiKey' | 'correction' | 'instruction' | 'model' >; shownByBlock: ReadonlyMap; }>; export type PrepareInkDigitizeResult = | Readonly<{ kind: 'blocked'; reason: 'no-marks' | 'read-only-or-preview' }> | Readonly<{ canRetryLassoOnly: boolean; kind: 'too-many-words'; wordCount: number; }> | Readonly<{ kind: 'passage-too-large'; markIds: readonly string[]; }> | Readonly<{ kind: 'ready'; prepared: PreparedInkDigitize; }>; const blockIdsBetween = ( view: Editor, targetBlockIds: ReadonlySet ): readonly string[] => { const allBlocks: string[] = []; for (const [node] of view.read.nodes.blocks({ at: [], mode: 'lowest', })) { if (ElementApi.isElement(node) && typeof node.id === 'string') { allBlocks.push(node.id); } } let first = -1; let last = -1; for (const [index, id] of allBlocks.entries()) { if (targetBlockIds.has(id)) { if (first === -1) first = index; last = index; } } if (first === -1) return []; return allBlocks.slice(first, last + 1); }; const liveBlockInkText = (view: Editor, blockId: string): string | null => { const entry = view.read.nodes.byId(blockId); if (!entry) return null; const { schema } = view.read; let text = ''; const walk = (node: unknown) => { if (TextApi.isText(node)) { text += node.text; return; } if (!ElementApi.isElement(node)) return; for (const child of node.children) { if ( ElementApi.isElement(child) && schema.isInline(child) && schema.isVoid(child) ) { text += VOID_CHAR; } else { walk(child); } } }; walk(entry.node); return text; }; const passageTextForEdit = ( view: Editor, read: Readonly<{ copy: (id: string) => Readonly<{ text: string }> | undefined; }>, meta: PreparedPassageMeta ): string | null => meta.passage.block ? liveBlockInkText(view, meta.passage.block) : (read.copy(meta.copy)?.text ?? null); const shownMarkIdsByBlock = ( view: Editor, blockIds: ReadonlySet ): Map => { const { read } = view.plugin(BaseInkPlugin); const byBlock = new Map(); for (const blockId of blockIds) byBlock.set(blockId, []); for (const mark of read.liveMarks()) { const seen = new Set(); for (const block of mark.blocks) { const copy = read.copy(block.copy); if (!copy || !blockIds.has(copy.block) || seen.has(copy.block)) continue; seen.add(copy.block); byBlock.get(copy.block)?.push(mark.id); } } for (const list of byBlock.values()) list.sort(); return byBlock; }; const totalWordsOf = (passages: readonly InkPassage[]) => passages.reduce((sum, passage) => sum + passage.words.length, 0); export const prepareInkDigitizeRequest = async ( view: Editor, pickedIds: readonly string[], options: Readonly<{ lassoOnly?: boolean; maxSide?: number; maxWords?: number; renderImages?: ( passages: readonly InkPassage[], options: Readonly<{ maxSide: number }> ) => Promise>; }> = {} ): Promise => { if (!canDigitizeInk(view)) { return { kind: 'blocked', reason: 'read-only-or-preview' }; } const maxSide = options.maxSide ?? INK_DIGITIZE_MAX_SIDE; const maxWords = options.maxWords ?? INK_DIGITIZE_MAX_WORDS; const ink = view.plugin(InkPlugin); const liveMarks = ink.read.liveMarks(); const liveById = new Map(liveMarks.map((mark) => [mark.id, mark])); const pickedMarks = [...new Set(pickedIds)] .map((id) => liveById.get(id)) .filter((mark): mark is InkMark => mark !== undefined); if (pickedMarks.length === 0) { return { kind: 'blocked', reason: 'no-marks' }; } const lassoedSet = new Set(pickedMarks.map((mark) => mark.id)); const touchedBlocks = new Set(); for (const mark of pickedMarks) { for (const block of mark.blocks) { const copy = ink.read.copy(block.copy); if (copy) touchedBlocks.add(copy.block); } } const widenedMarks = liveMarks.filter((mark) => mark.blocks.some((block) => { const copy = ink.read.copy(block.copy); return copy !== undefined && touchedBlocks.has(copy.block); }) ); const extraMarkIds = widenedMarks .filter((mark) => !lassoedSet.has(mark.id)) .map((mark) => mark.id); const targetIds = options.lassoOnly ? pickedMarks.map((mark) => mark.id) : widenedMarks.map((mark) => mark.id); const passages = ink.read.passages(targetIds); if (passages.length === 0) { return { kind: 'blocked', reason: 'no-marks' }; } const wordCount = totalWordsOf(passages); if (wordCount > maxWords) { const lassoOnlyWords = options.lassoOnly ? wordCount : totalWordsOf(ink.read.passages(pickedMarks.map((mark) => mark.id))); return { canRetryLassoOnly: !options.lassoOnly && extraMarkIds.length > 0 && lassoOnlyWords <= maxWords, kind: 'too-many-words', wordCount, }; } // Reserve the request ID and snapshot live block state BEFORE asynchronous // image rendering so mid-capture edits cannot pass stale checks at confirm. const requestId = nextInkDigitizeRequestId(view); const passageBlocks = new Set(); for (const passage of passages) { const blockId = passage.block ?? ink.read.copy(passage.copy)?.block; if (blockId) passageBlocks.add(blockId); } const blockOrder = blockIdsBetween(view, passageBlocks); const shownByBlock = shownMarkIdsByBlock(view, passageBlocks); const blockSnapshots = new Map(); for (const blockId of passageBlocks) { blockSnapshots.set( blockId, canonicalBlocksSnapshot(view.read.nodes, [blockId]) ); } const pictures = await (options.renderImages ? options.renderImages(passages, { maxSide }) : ink.api.images(passages, { maxSide })); const oversizedIndex = pictures.indexOf(null); if (oversizedIndex !== -1) { return { kind: 'passage-too-large', markIds: passages[oversizedIndex].marks.map((mark) => mark.id), }; } const markKeyById = new Map(); const markIdByKey = new Map(); const keyOf = (markId: string) => { let key = markKeyById.get(markId); if (!key) { key = `k${markKeyById.size}`; markKeyById.set(markId, key); markIdByKey.set(key, markId); } return key; }; const passageMetas: PreparedPassageMeta[] = []; const requestPassages: InkDigitizeRequest['passages'] = []; for (const [index, passage] of passages.entries()) { const pic = pictures[index] as InkPassageImages; const blockId = passage.block ?? ink.read.copy(passage.copy)?.block; if (!blockId) continue; const id = `p${index}`; const words = passage.words.map(({ end, start }) => { const raw = passage.text.slice( start - passage.start, end - passage.start ); return raw === VOID_CHAR ? (pic.voids[start] ?? '') : raw; }); passageMetas.push({ blockId, copy: passage.copy, id, passage, words, }); requestPassages.push({ id, images: { inkAlone: pic.inkAlone, inkOnText: pic.inkOnText, }, marks: passage.marks.map((mark) => { const [left, top, right, bottom] = pic.boxes[mark.id] ?? [0, 0, 0, 0]; return { box: [left, top, right, bottom], ...(mark.gaps.length > 0 ? { gaps: [...mark.gaps] } : {}), id: keyOf(mark.id), ...(mark.margin ? { margin: mark.margin } : {}), ...(mark.words.length > 0 ? { words: [...mark.words] } : {}), }; }), words, }); } return { kind: 'ready', prepared: { blockOrder, blockSnapshots, extraMarkIds: options.lassoOnly ? [] : extraMarkIds, lassoedMarkIds: [...lassoedSet], markIdByKey, markKeyById, passages: passageMetas, request: { passages: requestPassages, request: requestId, }, shownByBlock, }, }; }; export type ValidatedCorrection = Readonly<{ defaultKept: boolean; markIds: readonly string[]; markKeys: readonly string[]; meanings: readonly InkDigitizeMeaning[]; }>; export type ValidatedDigitizeReading = | Readonly<{ corrections: readonly ValidatedCorrection[]; ok: true; request: string; }> | Readonly<{ ok: false; reason: | 'cross-passage-order' | 'duplicate-mark' | 'interleaved-corrections' | 'overlapping-edits' | 'stale-request' | 'unknown-reference'; }>; const isCommentEdit = ( edit: InkDigitizeEdit ): edit is Extract => edit.kind === 'comment' || edit.kind === 'answer'; const editsOverlap = (a: InkDigitizeEdit, b: InkDigitizeEdit): boolean => { if (a.passage !== b.passage) return false; if (isCommentEdit(a) || isCommentEdit(b)) return false; if (a.kind === 'insert') { if (b.kind === 'insert') return a.gap === b.gap; return b.words[0] < a.gap && a.gap <= b.words[1]; } if (b.kind === 'insert') { return a.words[0] < b.gap && b.gap <= a.words[1]; } return a.words[0] <= b.words[1] && b.words[0] <= a.words[1]; }; const editPos = (edit: InkDigitizeEdit): number => edit.kind === 'insert' ? edit.gap * 2 : edit.words[0] * 2 + 1; const editEndPos = (edit: InkDigitizeEdit): number => edit.kind === 'insert' ? edit.gap * 2 : edit.words[1] * 2 + 1; const quoteMatches = ( meta: PreparedPassageMeta, start: number, end: number, quote: string ): boolean => { if (start > end || end >= meta.words.length) return false; const joined = meta.words.slice(start, end + 1).join(' '); if (quote === joined) return true; const wStart = meta.passage.words[start].start - meta.passage.start; const wEnd = meta.passage.words[end].end - meta.passage.start; let compact = ''; let cursor = wStart; for (let i = start; i <= end; i += 1) { const ws = meta.passage.words[i].start - meta.passage.start; const we = meta.passage.words[i].end - meta.passage.start; compact += meta.passage.text.slice(cursor, ws); compact += meta.words[i]; cursor = we; } compact += meta.passage.text.slice(cursor, wEnd); return quote === compact; }; const editTouchesCorrectionMarks = ( edit: InkDigitizeEdit, passage: InkDigitizeRequest['passages'][number], markKeySet: ReadonlySet ): boolean => { const relevantMarks = passage.marks.filter((mark) => markKeySet.has(mark.id)); if (relevantMarks.length === 0) return false; if (edit.kind === 'insert') { return relevantMarks.some( (mark) => (mark.gaps ?? []).includes(edit.gap) || (mark.words ?? []).some((w) => w === edit.gap - 1 || w === edit.gap) ); } const [start, end] = edit.words; if ( (edit.kind === 'comment' || edit.kind === 'answer') && relevantMarks.some( (mark) => mark.margin !== undefined || ((mark.words?.length ?? 0) === 0 && (mark.gaps?.length ?? 0) === 0) ) ) { return true; } return relevantMarks.some( (mark) => (mark.words ?? []).some((w) => w >= start && w <= end) || (mark.gaps ?? []).some((g) => g >= start && g <= end + 1) ); }; const checkCorrectionsOrderAndOverlap = ( corrections: readonly InkDigitizeCorrection[] ): | null | 'cross-passage-order' | 'interleaved-corrections' | 'overlapping-edits' => { const spansByPassage = new Map< string, Array<{ correction: number; max: number; min: number }> >(); for (const [cIndex, correction] of corrections.entries()) { const primary = correction.meanings[0]; if (!primary) continue; for (const meaning of correction.meanings) { for (let i = 0; i < meaning.edits.length; i += 1) { for (let j = i + 1; j < meaning.edits.length; j += 1) { if (editsOverlap(meaning.edits[i], meaning.edits[j])) { return 'overlapping-edits'; } } } } const perPassage = new Map(); for (const edit of primary.edits) { if (isCommentEdit(edit)) continue; const edits = perPassage.get(edit.passage) ?? []; edits.push(edit); perPassage.set(edit.passage, edits); } for (const [passageId, edits] of perPassage) { const list = spansByPassage.get(passageId) ?? []; list.push({ correction: cIndex, max: Math.max(...edits.map(editEndPos)), min: Math.min(...edits.map(editPos)), }); spansByPassage.set(passageId, list); } } for (let i = 0; i < corrections.length; i += 1) { for (let j = i + 1; j < corrections.length; j += 1) { for (const meaningA of corrections[i].meanings) { for (const meaningB of corrections[j].meanings) { for (const a of meaningA.edits) { for (const b of meaningB.edits) { if (editsOverlap(a, b)) return 'overlapping-edits'; } } } } } } const pairOrder = new Map(); for (const spans of spansByPassage.values()) { for (let i = 0; i < spans.length; i += 1) { for (let j = i + 1; j < spans.length; j += 1) { const a = spans[i]; const b = spans[j]; if (a.min < b.max && b.min < a.max) { return 'interleaved-corrections'; } const dir = a.max <= b.min ? -1 : 1; const pairKey = a.correction < b.correction ? `${a.correction}:${b.correction}` : `${b.correction}:${a.correction}`; const normalizedDir = a.correction < b.correction ? dir : -dir; const prev = pairOrder.get(pairKey); if (prev !== undefined && prev !== normalizedDir) { return 'cross-passage-order'; } pairOrder.set(pairKey, normalizedDir); } } } return null; }; export const validateInkDigitizeReading = ( prepared: PreparedInkDigitize, reading: InkDigitizeReading, latestRequestId: string | undefined ): ValidatedDigitizeReading => { if ( reading.request !== prepared.request.request || (latestRequestId !== undefined && reading.request !== latestRequestId) ) { return { ok: false, reason: 'stale-request' }; } const metaById = new Map(prepared.passages.map((meta) => [meta.id, meta])); const reqPassageById = new Map( prepared.request.passages.map((passage) => [passage.id, passage]) ); const lassoedSet = new Set(prepared.lassoedMarkIds); const usedMarks = new Set(); const keptRaw: InkDigitizeCorrection[] = []; const validated: ValidatedCorrection[] = []; for (const correction of reading.corrections) { const markIds: string[] = []; for (const key of correction.marks) { const markId = prepared.markIdByKey.get(key); if (!markId) return { ok: false, reason: 'unknown-reference' }; if (usedMarks.has(key)) return { ok: false, reason: 'duplicate-mark' }; usedMarks.add(key); markIds.push(markId); } const keySet = new Set(correction.marks); const validMeanings: InkDigitizeMeaning[] = []; for (const meaning of correction.meanings) { let ok = true; for (const edit of meaning.edits) { const meta = metaById.get(edit.passage); const reqPassage = reqPassageById.get(edit.passage); if (!meta || !reqPassage) { return { ok: false, reason: 'unknown-reference' }; } if (!editTouchesCorrectionMarks(edit, reqPassage, keySet)) { ok = false; break; } if (edit.kind === 'insert') { if (edit.gap > meta.words.length) { return { ok: false, reason: 'unknown-reference' }; } const expectedBefore = meta.words[edit.gap - 1] ?? ''; const expectedAfter = meta.words[edit.gap] ?? ''; if ( edit.between[0] !== expectedBefore || edit.between[1] !== expectedAfter ) { ok = false; break; } } else if ( !quoteMatches(meta, edit.words[0], edit.words[1], edit.quote) ) { ok = false; break; } } if (ok) validMeanings.push(meaning); } if (validMeanings.length === 0) continue; keptRaw.push({ marks: correction.marks, meanings: validMeanings }); validated.push({ defaultKept: markIds.some((id) => lassoedSet.has(id)), markIds, markKeys: correction.marks, meanings: validMeanings, }); } const orderIssue = checkCorrectionsOrderAndOverlap(keptRaw); if (orderIssue) return { ok: false, reason: orderIssue }; return { corrections: validated, ok: true, request: reading.request, }; }; type ResolvedEdit = Readonly<{ charEnd: number; charStart: number; copy: string; edit: InkDigitizeEdit; insertText?: string; passageIndex: number; range: Range; }>; const resolveEditSpan = ( copyText: string, meta: PreparedPassageMeta, edit: InkDigitizeEdit ): { charEnd: number; charStart: number; insertText?: string } => { if (edit.kind === 'insert') { const prev = edit.gap > 0 ? meta.passage.words[edit.gap - 1] : undefined; const next = edit.gap < meta.passage.words.length ? meta.passage.words[edit.gap] : undefined; const atOffset = prev ? prev.end : (next?.start ?? meta.passage.start); const trimmed = edit.text.trim(); if (trimmed.length === 0) { return { charEnd: atOffset, charStart: atOffset, insertText: '' }; } const leftCh = atOffset > 0 ? copyText[atOffset - 1] : ''; const rightCh = atOffset < copyText.length ? copyText[atOffset] : ''; const startsWithAttachedPunct = ATTACHED_PUNCT_RE.test(trimmed[0]); const endsWithSpaceOrOpen = /[\s([{]$/.test(trimmed); const leftIsWord = leftCh !== '' && !/\s/.test(leftCh); const rightIsWord = rightCh !== '' && !/\s/.test(rightCh) && !ATTACHED_PUNCT_RE.test(rightCh); const needLead = leftIsWord && !startsWithAttachedPunct; const needTrail = rightIsWord && !endsWithSpaceOrOpen; return { charEnd: atOffset, charStart: atOffset, insertText: `${needLead ? ' ' : ''}${trimmed}${needTrail ? ' ' : ''}`, }; } const charStart = meta.passage.words[edit.words[0]].start; const charEnd = meta.passage.words[edit.words[1]].end; if (edit.kind === 'delete') { const deletedSlice = copyText.slice(charStart, charEnd); let afterSpaceEnd = charEnd; while ( afterSpaceEnd < copyText.length && /\s/.test(copyText[afterSpaceEnd]) ) { afterSpaceEnd += 1; } let beforeSpaceStart = charStart; while (beforeSpaceStart > 0 && /\s/.test(copyText[beforeSpaceStart - 1])) { beforeSpaceStart -= 1; } const hasSpaceAfter = afterSpaceEnd > charEnd; const hasSpaceBefore = beforeSpaceStart < charStart; const charAfterSpaces = copyText[afterSpaceEnd] ?? ''; const followsPunctOrEnd = afterSpaceEnd === copyText.length || ATTACHED_PUNCT_RE.test(charAfterSpaces); const deletingPunctAfterWord = PUNCT_ONLY_RE.test(deletedSlice) && !hasSpaceBefore && charStart > 0 && !/\s/.test(copyText[charStart - 1]); if (deletingPunctAfterWord) { return { charEnd, charStart }; } if (!followsPunctOrEnd && hasSpaceAfter) { return { charEnd: afterSpaceEnd, charStart }; } if (hasSpaceBefore) { return { charEnd, charStart: beforeSpaceStart }; } return { charEnd, charStart }; } return { charEnd, charStart }; }; const rangesOverlapPending = ( at: Range, pending: readonly Range[] ): boolean => { const [aStart, aEnd] = RangeApi.edges(at); const collapsed = PointApi.equals(aStart, aEnd); for (const range of pending) { const [bStart, bEnd] = RangeApi.edges(range); if (collapsed) { if ( PointApi.compare(bStart, aStart) < 0 && PointApi.compare(aStart, bEnd) < 0 ) { return true; } } else if ( PointApi.compare(aStart, bEnd) < 0 && PointApi.compare(bStart, aEnd) < 0 ) { return true; } } return false; }; export type ConfirmChoice = Readonly<{ correctionIndex: number; meaningIndex: number; }>; export type ConfirmSkipReason = | 'no-comments-plugin' | 'no-op' | 'pending-suggestion' | 'refused' | 'save-failed' | 'save-rejected'; export type ConfirmInkDigitizeResult = | Readonly<{ applied: ReadonlyArray<{ correctionIndex: number; markIds: readonly string[]; threadIds?: readonly string[]; }>; skipped: ReadonlyArray<{ correctionIndex: number; markIds: readonly string[]; reason: ConfirmSkipReason; }>; status: 'applied'; }> | Readonly<{ reason: 'read-only-or-preview' | 'stale-request'; status: 'blocked'; }> | Readonly<{ status: 'stale'; }>; class NoOpRollbackError extends Error { override name = 'NoOpRollbackError'; } const sameTextMarks = ( a: Record, b: Record ): boolean => { const keysA = Object.keys(a).filter((k) => k !== 'text'); const keysB = Object.keys(b).filter((k) => k !== 'text'); if (keysA.length !== keysB.length) return false; return keysA.every((k) => JSON.stringify(a[k]) === JSON.stringify(b[k])); }; const canonicalizeNode = (node: unknown): unknown => { if (!ElementApi.isElement(node)) return node; const rawChildren = node.children.map(canonicalizeNode); const merged: unknown[] = []; for (const child of rawChildren) { if (TextApi.isText(child)) { const prev = merged.at(-1); if (prev && TextApi.isText(prev)) { if (child.text === '') continue; if (prev.text === '') { merged[merged.length - 1] = child; continue; } if (sameTextMarks(prev, child)) { merged[merged.length - 1] = { ...prev, text: prev.text + child.text, }; continue; } } } merged.push(child); } return { ...node, children: merged }; }; const canonicalBlocksSnapshot = ( nodes: Readonly<{ byId: (id: string) => Readonly<{ node: unknown }> | null; }>, blockIds: readonly string[] ): string => JSON.stringify( blockIds.map((blockId) => { const entry = nodes.byId(blockId); return entry ? canonicalizeNode(entry.node) : null; }) ); const isStalePick = (view: Editor, prepared: PreparedInkDigitize): boolean => { const { read } = view.plugin(BaseInkPlugin); const blockIds = new Set(); const liveIds = new Set(read.liveMarks().map((mark) => mark.id)); for (const meta of prepared.passages) { if (meta.passage.block) { if (meta.passage.marks.some((mark) => !liveIds.has(mark.id))) { return true; } } else if (read.place(meta.copy)?.kind !== 'live') { return true; } blockIds.add(meta.blockId); } for (const [blockId, snapshot] of prepared.blockSnapshots) { if (canonicalBlocksSnapshot(view.read.nodes, [blockId]) !== snapshot) { return true; } } const currentOrder = blockIdsBetween(view, blockIds); if ( currentOrder.length !== prepared.blockOrder.length || currentOrder.some((id, index) => id !== prepared.blockOrder[index]) ) { return true; } const currentShown = shownMarkIdsByBlock(view, blockIds); for (const [blockId, expected] of prepared.shownByBlock) { const actual = currentShown.get(blockId) ?? []; if ( actual.length !== expected.length || actual.some((id, index) => id !== expected[index]) ) { return true; } } return false; }; const liveRangesOverlap = (a: Range, b: Range): boolean => { const [aStart, aEnd] = RangeApi.edges(a); const [bStart, bEnd] = RangeApi.edges(b); const aCollapsed = PointApi.equals(aStart, aEnd); const bCollapsed = PointApi.equals(bStart, bEnd); if (aCollapsed && bCollapsed) return PointApi.equals(aStart, bStart); if (aCollapsed) { return ( PointApi.compare(aStart, bStart) >= 0 && PointApi.compare(aStart, bEnd) <= 0 ); } if (bCollapsed) { return ( PointApi.compare(bStart, aStart) >= 0 && PointApi.compare(bStart, aEnd) <= 0 ); } return ( PointApi.compare(aStart, bEnd) < 0 && PointApi.compare(bStart, aEnd) < 0 ); }; const compareRangesReverse = (a: Range, b: Range): number => { const [aStart, aEnd] = RangeApi.edges(a); const [bStart, bEnd] = RangeApi.edges(b); return PointApi.compare(bEnd, aEnd) || PointApi.compare(bStart, aStart); }; export const confirmInkDigitize = ( view: Editor, prepared: PreparedInkDigitize, validated: Extract, choices: readonly ConfirmChoice[], latestRequestId: string | undefined = latestInkDigitizeRequestId(view), options?: Readonly<{ skipDigitize?: ReadonlySet }> ): ConfirmInkDigitizeResult => { if (!canDigitizeInk(view)) { return { reason: 'read-only-or-preview', status: 'blocked' }; } if ( validated.request !== prepared.request.request || (latestRequestId !== undefined && validated.request !== latestRequestId) ) { return { reason: 'stale-request', status: 'blocked' }; } if (isStalePick(view, prepared)) { return { status: 'stale' }; } const { read } = view.plugin(BaseInkPlugin); const metaIndexById = new Map( prepared.passages.map((meta, index) => [meta.id, { index, meta }]) ); const pendingRanges: Range[] = []; const authored = view.plugin(AuthoredPlugin); if (authored.installed) { for (let cursor: string | undefined; ;) { const page = authored.read.changes({ cursor, limit: 200 }); for (const item of page.items) { pendingRanges.push(...item.ranges); } if (!page.cursor) break; ({ cursor } = page); } } type PlannedCorrection = { correctionIndex: number; edits: ResolvedEdit[]; headRange: Range; markIds: readonly string[]; }; const planned: PlannedCorrection[] = []; for (const choice of choices) { const correction = validated.corrections[choice.correctionIndex]; const meaning = correction?.meanings[choice.meaningIndex]; if (!correction || !meaning) continue; const resolvedEdits: ResolvedEdit[] = []; for (const edit of meaning.edits) { if (isCommentEdit(edit)) continue; const entry = metaIndexById.get(edit.passage); if (!entry) return { status: 'stale' }; const baseText = passageTextForEdit(view, read, entry.meta); if (baseText === null) return { status: 'stale' }; const span = resolveEditSpan(baseText, entry.meta, edit); const range = read.range( entry.meta.passage.block ? { block: entry.meta.passage.block, end: span.charEnd, start: span.charStart, } : { copy: entry.meta.copy, end: span.charEnd, start: span.charStart, } ); if (!range) return { status: 'stale' }; resolvedEdits.push({ charEnd: span.charEnd, charStart: span.charStart, copy: entry.meta.copy, edit, insertText: span.insertText, passageIndex: entry.index, range, }); } if (resolvedEdits.length === 0) continue; resolvedEdits.sort((a, b) => compareRangesReverse(a.range, b.range)); planned.push({ correctionIndex: choice.correctionIndex, edits: resolvedEdits, headRange: resolvedEdits[0].range, markIds: correction.markIds, }); } planned.sort((a, b) => compareRangesReverse(a.headRange, b.headRange)); const applied: Array<{ correctionIndex: number; markIds: readonly string[]; }> = []; const skipped: Array<{ correctionIndex: number; markIds: readonly string[]; reason: ConfirmSkipReason; }> = []; let committedCount = 0; const claimedLiveRanges: Range[] = []; for (const item of planned) { if ( item.edits.some((resolved) => claimedLiveRanges.some((claimed) => liveRangesOverlap(resolved.range, claimed) ) ) ) { skipped.push({ correctionIndex: item.correctionIndex, markIds: item.markIds, reason: 'refused', }); continue; } if ( item.edits.some((resolved) => rangesOverlapPending(resolved.range, pendingRanges) ) ) { skipped.push({ correctionIndex: item.correctionIndex, markIds: item.markIds, reason: 'pending-suggestion', }); continue; } const isNoOpInput = item.edits.some((resolved) => { if (resolved.edit.kind === 'insert') { return (resolved.insertText ?? '').length === 0; } if (resolved.edit.kind === 'replace') { const meta = prepared.passages[resolved.passageIndex]; const baseText = passageTextForEdit(view, read, meta); return ( baseText?.slice(resolved.charStart, resolved.charEnd) === resolved.edit.text ); } return false; }); if (isNoOpInput) { skipped.push({ correctionIndex: item.correctionIndex, markIds: item.markIds, reason: 'no-op', }); continue; } let noOp = false; let threw = false; const deferDigitize = options?.skipDigitize?.has(item.correctionIndex) ?? false; const touchedBlockIds = [ ...new Set( item.edits.map( (resolved) => prepared.passages[resolved.passageIndex].blockId ) ), ]; try { view.update((tx) => { if (committedCount === 0) tx.history.newBatch(); else tx.history.merge(); const before = canonicalBlocksSnapshot(tx.nodes, touchedBlockIds); for (const resolved of item.edits) { const { edit, range } = resolved; if (edit.kind === 'delete') { tx.text.delete({ at: range }); } else if (edit.kind === 'insert') { tx.text.insert(resolved.insertText ?? '', { at: range.anchor }); } else if (edit.kind === 'replace') { tx.text.delete({ at: range }); tx.text.insert(edit.text, { at: range.anchor }); } else { tx.nodes.set( { highlight: true }, { at: range, marks: true, split: true } ); } } if (before === canonicalBlocksSnapshot(tx.nodes, touchedBlockIds)) { throw new NoOpRollbackError(); } if (!deferDigitize) { tx.plugin(BaseInkPlugin).setDigitized(item.markIds, true); } }); } catch (error) { if (error instanceof NoOpRollbackError) noOp = true; else threw = true; } if (noOp) { skipped.push({ correctionIndex: item.correctionIndex, markIds: item.markIds, reason: 'no-op', }); continue; } if (threw) { skipped.push({ correctionIndex: item.correctionIndex, markIds: item.markIds, reason: 'refused', }); continue; } const shownAfter = new Set(read.shownMarks().map((mark) => mark.id)); const digitized = deferDigitize || item.markIds.every((id) => !shownAfter.has(id)); if (!digitized) { skipped.push({ correctionIndex: item.correctionIndex, markIds: item.markIds, reason: 'refused', }); } else { committedCount += 1; for (const resolved of item.edits) claimedLiveRanges.push(resolved.range); applied.push({ correctionIndex: item.correctionIndex, markIds: item.markIds, }); } } view.plugin(InkPlugin).api.setPicked([]); return { applied, skipped, status: 'applied', }; }; export const confirmInkDigitizeWithComments = async ( view: Editor, prepared: PreparedInkDigitize, validated: Extract, choices: readonly ConfirmChoice[], latestRequestId: string | undefined = latestInkDigitizeRequestId(view) ): Promise => { if (!canDigitizeInk(view)) { return { reason: 'read-only-or-preview', status: 'blocked' }; } if ( validated.request !== prepared.request.request || (latestRequestId !== undefined && validated.request !== latestRequestId) ) { return { reason: 'stale-request', status: 'blocked' }; } if (isStalePick(view, prepared)) { return { status: 'stale' }; } const textChoices: ConfirmChoice[] = []; const commentChoices: ConfirmChoice[] = []; const mixedChoiceIndices = new Set(); for (const choice of choices) { const correction = validated.corrections[choice.correctionIndex]; const meaning = correction?.meanings[choice.meaningIndex]; if (!correction || !meaning) continue; const hasComment = meaning.edits.some(isCommentEdit); const hasText = meaning.edits.some((edit) => !isCommentEdit(edit)); if (hasComment) commentChoices.push(choice); if (hasText) textChoices.push(choice); if (hasComment && hasText) mixedChoiceIndices.add(choice.correctionIndex); } if (commentChoices.length === 0) { return confirmInkDigitize( view, prepared, validated, textChoices, latestRequestId ); } const { read } = view.plugin(BaseInkPlugin); const metaById = new Map(prepared.passages.map((meta) => [meta.id, meta])); type PinnedCommentEdit = Readonly<{ anchor: Anchor; edit: Extract; excerpt: string; }>; type PlannedCommentCorrection = Readonly<{ correctionIndex: number; edits: readonly PinnedCommentEdit[]; markIds: readonly string[]; }>; const pinnedCorrections: PlannedCommentCorrection[] = []; const allAnchors: Array> = []; const releaseAllAnchors = () => { for (const anchor of allAnchors) anchor.release(); allAnchors.length = 0; }; try { for (const choice of commentChoices) { const correction = validated.corrections[choice.correctionIndex]; const meaning = correction.meanings[choice.meaningIndex]; const pinnedEdits: PinnedCommentEdit[] = []; for (const edit of meaning.edits) { if (!isCommentEdit(edit)) continue; const meta = metaById.get(edit.passage); if (!meta) return { status: 'stale' }; const baseText = passageTextForEdit(view, read, meta); if (baseText === null) return { status: 'stale' }; const span = resolveEditSpan(baseText, meta, edit); const range = read.range( meta.passage.block ? { block: meta.passage.block, end: span.charEnd, start: span.charStart, } : { copy: meta.copy, end: span.charEnd, start: span.charStart, } ); if (!range) return { status: 'stale' }; const anchor = view.anchor(range, { association: 'inward', deletion: 'nearest', }); allAnchors.push(anchor); pinnedEdits.push({ anchor, edit, excerpt: baseText.slice(span.charStart, span.charEnd), }); } if (pinnedEdits.length > 0) { pinnedCorrections.push({ correctionIndex: choice.correctionIndex, edits: pinnedEdits, markIds: correction.markIds, }); } } const applied: Array<{ correctionIndex: number; markIds: readonly string[]; threadIds?: readonly string[]; }> = []; const skipped: Array<{ correctionIndex: number; markIds: readonly string[]; reason: ConfirmSkipReason; }> = []; if (textChoices.length > 0) { const textResult = confirmInkDigitize( view, prepared, validated, textChoices, latestRequestId, mixedChoiceIndices.size > 0 ? { skipDigitize: mixedChoiceIndices } : undefined ); if (textResult.status !== 'applied') { return textResult; } for (const entry of textResult.applied) { if (!mixedChoiceIndices.has(entry.correctionIndex)) { applied.push(entry); } } for (const entry of textResult.skipped) { if (!mixedChoiceIndices.has(entry.correctionIndex)) { skipped.push(entry); } } } const commentsPlugin = view.plugin(BaseCommentsPlugin); if (!commentsPlugin.installed) { for (const item of pinnedCorrections) { skipped.push({ correctionIndex: item.correctionIndex, markIds: item.markIds, reason: 'no-comments-plugin', }); } return { applied, skipped, status: 'applied' }; } for (const item of pinnedCorrections) { const threadIds: string[] = []; let failureReason: ConfirmSkipReason | null = null; for (const [editIndex, pinned] of item.edits.entries()) { const range = pinned.anchor.resolve(view); if (!range || view.read.ranges.isEmpty(range)) { failureReason = 'refused'; break; } const isLastEdit = editIndex === item.edits.length - 1; const body = [ { children: [{ text: pinned.edit.text }], type: 'paragraph', }, ]; const data: CommentData = pinned.edit.kind === 'answer' ? { kind: 'answer', question: pinned.edit.question } : { kind: 'comment' }; try { const created = await commentsPlugin.api.createThread({ body, data, excerpt: pinned.excerpt, target: { range, type: 'range' }, ...(isLastEdit ? { withHistory: (tx) => { const shownNow = new Set( view .plugin(BaseInkPlugin) .read.shownMarks() .map((mark) => mark.id) ); const stillShown = item.markIds.filter((id) => shownNow.has(id) ); if (stillShown.length > 0) { tx.plugin(BaseInkPlugin).setDigitized(stillShown, true); } }, } : {}), }); if (created.status === 'applied') { threadIds.push(created.value); } else { failureReason = created.status === 'rejected' ? 'save-rejected' : 'refused'; break; } } catch { failureReason = 'save-failed'; break; } } if (failureReason) { skipped.push({ correctionIndex: item.correctionIndex, markIds: item.markIds, reason: failureReason, }); } else { applied.push({ correctionIndex: item.correctionIndex, markIds: item.markIds, threadIds, }); } } if (view.plugin(InkPlugin).installed) { if (skipped.length === 0) { view.plugin(InkPlugin).api.setPicked([]); } else { const digitizedSet = new Set(applied.flatMap((entry) => entry.markIds)); const remaining = view .plugin(InkPlugin) .viewStore.get() .picked.filter((id) => !digitizedSet.has(id)); view.plugin(InkPlugin).api.setPicked(remaining); } } return { applied, skipped, status: 'applied' }; } finally { releaseAllAnchors(); } }; export const INK_DIGITIZE_KIND_LABELS: Readonly< Record > = { answer: 'Answer', comment: 'Comment', delete: 'Delete', highlight: 'Highlight', insert: 'Insert', replace: 'Replace', }; export const correctionPrimaryKind = ( correction: ValidatedCorrection, meaningIndex = 0 ): InkDigitizeEdit['kind'] | null => { const meaning = correction.meanings[meaningIndex] ?? correction.meanings[0]; return meaning?.edits[0]?.kind ?? null; }; type MarkBounds = Readonly<{ bottom: number; left: number; right: number; top: number; }>; const markBounds = (mark: InkMark): MarkBounds | null => { let left = Number.POSITIVE_INFINITY; let top = Number.POSITIVE_INFINITY; let right = Number.NEGATIVE_INFINITY; let bottom = Number.NEGATIVE_INFINITY; for (const sample of mark.samples) { const [x, y] = sample; if (x < left) left = x; if (x > right) right = x; if (y < top) top = y; if (y > bottom) bottom = y; } return Number.isFinite(left) ? { bottom, left, right, top } : null; }; const boxesWithin = (a: MarkBounds, b: MarkBounds, maxDistance: number) => { const dx = Math.max(0, Math.max(a.left - b.right, b.left - a.right)); const dy = Math.max(0, Math.max(a.top - b.bottom, b.top - a.bottom)); return Math.hypot(dx, dy) <= maxDistance; }; export type GroupInkMarksOptions = Readonly<{ maxDistancePx?: number; maxGapMs?: number; }>; export const groupInkMarksByDistanceAndTime = ( marks: readonly InkMark[], options: GroupInkMarksOptions = {} ): ReadonlyArray => { if (marks.length === 0) return []; const maxDistancePx = options.maxDistancePx ?? 48; const maxGapMs = options.maxGapMs ?? 30_000; const parent = marks.map((_, index) => index); const find = (index: number): number => { let cur = index; while (parent[cur] !== cur) { parent[cur] = parent[parent[cur]]; cur = parent[cur]; } return cur; }; const unite = (a: number, b: number) => { const ra = find(a); const rb = find(b); if (ra !== rb) parent[Math.max(ra, rb)] = Math.min(ra, rb); }; const bounds = marks.map(markBounds); const byCopy = new Map(); for (const [index, mark] of marks.entries()) { const seen = new Set(); for (const block of mark.blocks) { if (seen.has(block.copy)) continue; seen.add(block.copy); const bucket = byCopy.get(block.copy) ?? []; bucket.push(index); byCopy.set(block.copy, bucket); } } for (const indices of byCopy.values()) { for (let a = 0; a < indices.length; a += 1) { const i = indices[a]; for (let b = a + 1; b < indices.length; b += 1) { const j = indices[b]; const closeInTime = Math.abs(marks[i].at - marks[j].at) <= maxGapMs; const bi = bounds[i]; const bj = bounds[j]; const closeInSpace = bi !== null && bj !== null && boxesWithin(bi, bj, maxDistancePx); if (closeInTime || closeInSpace) { unite(i, j); } } } } const buckets = new Map(); for (const [index, mark] of marks.entries()) { const root = find(index); const list = buckets.get(root) ?? []; list.push(mark); buckets.set(root, list); } return [...buckets.values()]; }; export const liveShownInkMarkIds = (view: Editor): readonly string[] => view .plugin(BaseInkPlugin) .read.liveMarks() .map((mark) => mark.id); export const planInkDigitizeAllBatches = ( view: Editor, options: GroupInkMarksOptions & Readonly<{ maxWords?: number }> = {} ): ReadonlyArray => { const { read } = view.plugin(BaseInkPlugin); const maxWords = options.maxWords ?? INK_DIGITIZE_MAX_WORDS; const liveMarks = read.liveMarks(); if (liveMarks.length === 0) return []; const clusters = groupInkMarksByDistanceAndTime(liveMarks, options); const clusterEntries = clusters .map((cluster) => { const ids = cluster.map((mark) => mark.id); const passages = read.passages(ids); const words = passages.reduce( (sum, passage) => sum + passage.words.length, 0 ); const firstPassage = passages[0]; const blockId = firstPassage ? (firstPassage.block ?? read.copy(firstPassage.copy)?.block) : null; return { blockId, ids, words }; }) .filter((entry) => entry.words > 0); if (clusterEntries.length === 0) return []; const blockRank = new Map(); let rank = 0; for (const [node] of view.read.nodes.blocks({ at: [], mode: 'lowest' })) { if (ElementApi.isElement(node) && typeof node.id === 'string') { blockRank.set(node.id, rank); rank += 1; } } clusterEntries.sort((a, b) => { const ra = a.blockId ? (blockRank.get(a.blockId) ?? rank) : rank; const rb = b.blockId ? (blockRank.get(b.blockId) ?? rank) : rank; return ra - rb; }); const batches: string[][] = []; let current: string[] = []; let currentWords = 0; for (const entry of clusterEntries) { if (current.length > 0 && currentWords + entry.words > maxWords) { batches.push(current); current = [...entry.ids]; currentWords = entry.words; } else { current.push(...entry.ids); currentWords += entry.words; } } if (current.length > 0) batches.push(current); return batches; };