/** * Comment-thread composition — the conversation-plane view over the flat * annotation list. * * Where `buildThreads()` (relationships.ts) is the minimal, unopinionated * one-level composer, `buildCommentThreads()` is the opinionated one a * comments sidebar wants: * * - the whole `/IRT` subtree of a root is walked (cycle-safe), and its * non-state members flatten into one chronological reply list; * - ISO 32000 §12.5.6.3 state annotations (review status) are extracted * into `review` instead of appearing as replies; * - widgets, links, popups (a note's window, not a comment) and * unsupported blobs are excluded entirely; * - `/RT /Group` subordinates anywhere in the subtree fold into * `groupedParts`, never into `replies`. * * Tolerant-reader rules (foreign files are messy; none of this throws): * - empty-string `state` / `stateModel` count as absent — the engine * DTO is faithful (`''` = present-but-empty), tolerance lives here; * - a state annotation whose target cannot be resolved is dropped * (status metadata with no anchor has no meaning); * - an orphaned non-state reply is promoted to a thread root (matching * `buildThreads`), as is the first input-order member of an `/IRT` * cycle — the visited set breaks the loop, nothing is lost or hangs; * - a `/State` with no `/StateModel` infers its model from the known * vocabulary; a custom model with no derivable state is skipped. * * Ordering: threads appear in the input order of their roots; the * composer never sorts by page (display order is a layout concern — * callers join `pages.list()`). Replies sort chronologically by * `createdAt ?? modifiedAt`, entries without a date last, page z-order * (their place in `annotations`, bottom to top) as the final deterministic * tiebreak. */ import type { Annotation } from './kinds'; import type { KnownAnnotationState, KnownAnnotationStateModel } from './primitives'; import { classifyRelation } from './relationships'; import { annotationKey } from '../identity/annotationKey'; import type { AnnotationRef } from '../identity/AnnotationRef'; import type { PageRef } from '../identity/PageRef'; import { compareIsoDateTime, type IsoDateTime } from '../dto/IsoDateTime'; /** One reviewer's status, derived from an ISO §12.5.6.3 state annotation. */ export interface ReviewStatus { /** Wire-normalized when known (`'accepted'`, …); verbatim when custom. */ state: string; /** `'review'`, `'marked'`, or a custom model verbatim. */ stateModel: string; /** Reviewer key: `/EMBD_Metadata` userId, else `/T`, else null. */ by: string | null; /** `/M` ?? `/CreationDate` of the state annotation. */ at: IsoDateTime | null; /** The state annotation itself — for auditing or deletion. */ ref: AnnotationRef; } /** * Review state of one thread. The two ISO state models are independent * axes: `byReviewer` / `lastChange` cover review status (the standard * `Review` model plus custom models), while the personal-checkmark * `Marked` axis lives solely in `markedBy`. */ export interface CommentThreadReview { /** Latest review-axis status per reviewer key (unattributed skipped). */ byReviewer: Record; /** Latest review-axis change overall — a convenience, not a verdict. */ lastChange: ReviewStatus | null; /** Reviewer keys whose latest Marked-model status is `'marked'`. */ markedBy: string[]; /** * Every state annotation in the thread's subtree (both axes, all * reviewers, chronological) — thread membership, not status history: * deleting a whole thread must delete its state annotations too, and * the classified summaries above deliberately drop superseded refs. */ statusRefs: AnnotationRef[]; /** * `byReviewer[currentUserId]`: `null` when that reviewer has none, or when * no `currentUserId` was given. */ mine: ReviewStatus | null; } export interface CommentThread { root: T; page: PageRef; /** Whole-subtree replies, flattened chronologically; states excluded. */ replies: T[]; /** Every `/RT /Group` subordinate found in the subtree. */ groupedParts: T[]; review: CommentThreadReview; } export interface BuildCommentThreadsOptions { /** Compute `review.mine` against this reviewer key. */ currentUserId?: string; } /** Subtypes that never participate in comment threads: a popup is its * parent's window and an unsupported blob is unreadable, so neither makes * a comment card. */ const EXCLUDED_SUBTYPES: ReadonlySet = new Set(['widget', 'link', 'popup', 'unsupported']); const REVIEW_STATES: ReadonlySet = new Set([ 'accepted', 'rejected', 'cancelled', 'completed', 'none', ]); const MARKED_STATES: ReadonlySet = new Set(['marked', 'unmarked']); /** * The model a standard state belongs to (ISO 32000 §12.5.6.3, Table 174): * `'review'` for accepted, rejected, cancelled, completed and none, * `'marked'` for marked and unmarked; `null` for a custom state. */ export function standardStateModelOf(state: string): KnownAnnotationStateModel | null { if (REVIEW_STATES.has(state as KnownAnnotationState)) return 'review'; if (MARKED_STATES.has(state as KnownAnnotationState)) return 'marked'; return null; } const nonEmpty = (v: string | null | undefined): v is string => typeof v === 'string' && v !== ''; /** * An ISO 32000 §12.5.6.3 state annotation: a text annotation carrying a * non-empty `/State` or `/StateModel`. Classification never relies on * flags — producers disagree on how state annotations are flagged. */ export function isStateAnnotation(a: Annotation): boolean { return a.subtype === 'text' && (nonEmpty(a.state) || nonEmpty(a.stateModel)); } export function buildCommentThreads( annotations: readonly Annotation[], options: BuildCommentThreadsOptions = {}, ): CommentThread[] { const eligible = annotations.filter((a) => !EXCLUDED_SUBTYPES.has(a.subtype)); const byKey = new Map(eligible.map((a) => [annotationKey(a.ref), a])); const zOrder = new Map(eligible.map((a, at) => [annotationKey(a.ref), at])); const chronological = chronologicalIn(zOrder); // Children adjacency over resolvable /IRT edges. const children = new Map(); for (const a of eligible) { if (!a.reply) continue; const parent = byKey.get(annotationKey(a.reply.to)); if (!parent) continue; // orphan — handled in the promotion pass const parentKey = annotationKey(parent.ref); const list = children.get(parentKey); if (list) list.push(a); else children.set(parentKey, [a]); } const visited = new Set(); const threads: CommentThread[] = []; const walk = (root: Annotation): void => { const replies: Annotation[] = []; const groupedParts: Annotation[] = []; const states: Annotation[] = []; visited.add(annotationKey(root.ref)); const stack = [...(children.get(annotationKey(root.ref)) ?? [])]; while (stack.length > 0) { const a = stack.pop()!; const key = annotationKey(a.ref); if (visited.has(key)) continue; // cycle back-edge — skip visited.add(key); if (isStateAnnotation(a)) states.push(a); else if (classifyRelation(a) === 'grouped-subordinate') groupedParts.push(a); else replies.push(a); stack.push(...(children.get(key) ?? [])); } replies.sort(chronological); // Chronological order makes latest-wins deterministic for equal or // missing dates (the comparator's z-order tiebreak applies). states.sort(chronological); threads.push({ root, page: root.page, replies, groupedParts, review: computeReview(states, options), }); }; // Pass 1: real roots, in input order. for (const a of eligible) { if (!a.reply && !isStateAnnotation(a)) walk(a); } // Pass 2: promotion. Anything not reached from a root — an orphan whose // parent is missing, or a member of an /IRT cycle — promotes to its own // root in input order. State annotations never promote: a status with no // reachable target is dropped. for (const a of eligible) { if (visited.has(annotationKey(a.ref))) continue; if (isStateAnnotation(a)) continue; walk(a); } return threads; } /** `createdAt ?? modifiedAt` ascending; undated last; z-order tiebreak. */ function chronologicalIn(zOrder: ReadonlyMap) { return (a: Annotation, b: Annotation): number => { const at = a.createdAt ?? a.modifiedAt; const bt = b.createdAt ?? b.modifiedAt; const order = at !== null && bt !== null ? compareIsoDateTime(at, bt) : 0; if (order !== 0) return order; if (at !== null && bt === null) return -1; if (at === null && bt !== null) return 1; return zOrder.get(annotationKey(a.ref))! - zOrder.get(annotationKey(b.ref))!; }; } function computeReview( states: readonly Annotation[], opts: BuildCommentThreadsOptions, ): CommentThreadReview { const byReviewer: Record = {}; const markedLatest: Record = {}; let lastChange: ReviewStatus | null = null; for (const a of states) { const status = toReviewStatus(a); if (!status) continue; if (status.stateModel === 'marked') { if (status.by !== null && isNewer(status, markedLatest[status.by])) { markedLatest[status.by] = status; } continue; // the Marked axis never feeds byReviewer / lastChange } if (status.by !== null && isNewer(status, byReviewer[status.by])) { byReviewer[status.by] = status; } if (isNewer(status, lastChange)) lastChange = status; } const markedBy = Object.keys(markedLatest) .filter((key) => markedLatest[key]!.state === 'marked') .sort(); const review: CommentThreadReview = { byReviewer, lastChange, markedBy, statusRefs: states.map((a) => a.ref), mine: opts.currentUserId === undefined ? null : (byReviewer[opts.currentUserId] ?? null), }; return review; } /** * Derive a `ReviewStatus` from one state annotation, or null when nothing * classifiable can be derived. ISO defaulting happens here, not in the * engine reader: a known model with an absent state means `none` / * `unmarked`; an absent model infers from a known state; a custom model * with no state has no derivable status. */ function toReviewStatus(a: Annotation): ReviewStatus | null { if (a.subtype !== 'text') return null; const rawState = nonEmpty(a.state) ? a.state : null; const rawModel = nonEmpty(a.stateModel) ? a.stateModel : null; let stateModel = rawModel; if (stateModel === null && rawState !== null) { stateModel = standardStateModelOf(rawState); if (stateModel === null) return null; // custom state without a model: unclassifiable } let state = rawState; if (state === null) { if (stateModel === 'review') state = 'none'; else if (stateModel === 'marked') state = 'unmarked'; else return null; // custom model without a state: no default exists } if (stateModel === null) return null; // unreachable, kept for narrowing return { state, stateModel, by: a.userId ?? (nonEmpty(a.author) ? a.author : null), at: a.modifiedAt ?? a.createdAt ?? null, ref: a.ref, }; } /** `a` newer than (or supersedes) `b`. `at` decides; dated beats undated. * States arrive pre-sorted by `chronological` (date, then z-order), so on * equal or missing dates the later entry wins via `>=` / `true`. */ function isNewer(a: ReviewStatus, b: ReviewStatus | null | undefined): boolean { if (!b) return true; if (a.at !== null && b.at !== null) return compareIsoDateTime(a.at, b.at) >= 0; if (a.at !== null) return true; if (b.at !== null) return false; return true; // both undated: input order — later entry wins }