/** * Suggestions feature — public type surface for v1. * * Source contract: docs/suggestions-api-contract.md * Source flows: docs/suggestions-implementation-flows.md * * Types are exported from the SDK's public barrel. Customer code interacts * with these via Snippyly.getSuggestionElement(); the SDK constructs all * Suggestion objects internally and customers do not build them directly. */ import { User } from './user.data.model'; import { Location } from './location.model'; /** * Lifecycle state machine for a Suggestion. * * - pending: Just created, awaiting owner action. * - approved: Owner clicked Approve. Customer apply handler ran successfully. * - rejected: Owner clicked Reject (with optional reason). * - stale: Target was unresolvable at approve time. Owner can dismiss. * - apply_failed: Customer apply handler threw during a suggestionApproved event. * Status set by the SDK after the throw was caught. */ export type SuggestionStatus = 'pending' | 'accepted' | 'rejected' | 'stale' | 'apply_failed'; /** * Global per-user-per-session suggestion mode. Not persisted; reload returns to 'editing'. */ export type SuggestionMode = 'editing' | 'suggesting'; /** * Discriminator for the substrate that produced a suggestion. v1: always 'custom'. * Wrapper libraries (e.g. tiptap-velt-comments) widen this union when they integrate. * * Customers should treat unknown values as opaque; the field exists so customer code * can differentiate substrate when domain-specific rendering matters. */ export type SuggestionTargetType = 'custom'; /** * Single-arg config passed to `SuggestionElement.registerTarget(config)`. * Carrying both `targetId` and `getter` in one object so the API can grow * (e.g., metadata, target-specific options) without breaking customers. */ export interface RegisterTargetConfig { targetId: string; getter: TargetGetter; /** * Writes a value into the target — the app's own write path (form state, store, save). With a setter the SDK * puts the target back once an edit's suggestion is committed (see `restoreOnCommit`) and applies an accepted * suggestion's value on the client that accepted it. Without one the SDK never writes to the target. */ setter?: TargetSetter; /** * With a `setter`: once the suggestion made from an edit is committed, call `setter(valueOnFocus, { reason: * 'restore' })` so the target shows its saved value again. Default true. Accept applies through the setter * either way. */ restoreOnCommit?: boolean; } /** * Registered with `registerTarget({ targetId, getter, setter })`. The SDK calls it: * - `reason: 'restore'` — the suggestion made from an edit was committed; `value` is the target's value when the * edit started (put the field back; there is nothing new to save while suggesting). * - `reason: 'accept'` — a suggestion on this target was accepted on THIS client; `value` is the accepted value * (save it). Called once, after the accepted status is saved and before `suggestionApproved` fires. Other * clients don't call their setter: they get the value through the app's own data. * * While suggestion mode is on, don't save a registered target's edits yourself — save in the 'accept' call. * A setter that throws (or rejects) is caught and logged; it never blocks the suggestion. */ export type TargetSetter = (value: T, context: TargetSetterContext) => void | Promise; export interface TargetSetterContext { targetId: string; reason: 'restore' | 'accept'; /** `reason: 'accept'` only: the accepted suggestion, as `suggestionApproved` carries it. */ suggestion?: Suggestion; } /** * Function the customer registers via SuggestionElement.registerTarget(config). * Required for any non-primitive (wrapper) target. * * The SDK calls this getter twice in a typical edit cycle: * 1. On focus of the tagged element — to snapshot the pre-edit value. * 2. On commit (focusout / change) — to read the current value for the diff. * * IMPORTANT — edit-time state, not persisted state: the getter must reflect * what the user is currently editing, not what's persisted in the customer's * app store. If the customer's state is only updated on commit/approve (as * is typical when suggesting mode is on), reading from that state would * return the snapshot value at commit time, the diff check would short- * circuit, and no suggestion would ever fire. * * Recommended: read from the DOM (controlled or uncontrolled inputs) so the * getter always returns what's visible to the user. * * el.registerTarget('row.123', () => ({ * qty: parseInt(qtyInput.value, 10), * price: parseInt(priceInput.value, 10), * })); * * For controlled inputs (state updates on every keystroke), reading from * the customer state is fine: `() => myState.row123`. The contract is * "edit-time state" — whichever source of truth has it. */ export type TargetGetter = () => T; /** * Returned from SuggestionElement.on(...). Calling it removes the handler. */ export type Unsubscribe = () => void; /** * Details about a target edit, passed to the customer's resolver handler and * to subscribers of `targetEditStart` / `targetEditCommit` events. * * `element` is the DOM element that produced the edit. It's the tagged * descendant — or, for wrappers that nest interactive controls inside a * tagged container, the inner element that actually fired the event. In * either case the SDK walks up to the nearest ancestor carrying * `data-velt-suggestion-target` to resolve `targetId`. * * `element` is provided for read access only — customers should not retain * the reference past the synchronous handler call. */ export interface TargetEditDetails { targetId: string; oldValue: T; newValue: T; element: Element | null; } /** * Return type of `onTargetEditCommit`. Returning a value auto-commits the * suggestion using the (optional) overrides; returning null skips the * auto-commit so a subscriber to `targetEditCommit` can drive it explicitly. */ export interface TargetEditCommitResult { /** * Override the SDK's default diff summary (`Replace: "{old}" with "{new}"`; * `Add:`/`Remove:` when one side is absent; a per-key op list when both * values are plain objects). When provided without `summaryHtml`, it is * used for BOTH the plain `commentText` and (escaped) the `commentHtml` * of the seeded first comment. */ summary?: string; /** * Optional HTML version of the summary, used as the `commentHtml` of the * suggestion's seeded first comment (the plain `summary` — or the SDK's * default diff summary — stays in `commentText`). When BOTH are omitted, * the SDK renders a default styled HTML diff (old/removed values in red * italic, new/added values in green italic). Sanitized with DOMPurify at * render time — script/event-handler content is stripped; inline `style` * attributes are preserved. */ summaryHtml?: string; /** Customer metadata persisted on the resulting suggestion (`Suggestion.metadata`). */ metadata?: Record; /** Where the change sits in a text target (`Suggestion.textChange`). Overrides the one the SDK works out. */ textChange?: SuggestionTextChange; } /** * Where a suggestion on TEXT sits: what it removes and adds, the unchanged text around it, and which * occurrence of that text it is. Stored as `annotation.suggestion.textChange` and returned as * `Suggestion.textChange`, the same for every kind of text target (contenteditable fields, rich-text * editors), so any screen can find the change again and draw it in place. * * - Passed by an integration on `commitSuggestion`, or worked out by the SDK for a contenteditable * target with no registered getter. * - Never re-written after commit: readers find the spot again from the context each time. * - Self-hosting: suggestion content — with a comment resolver it is stored by the resolver only, * like `oldValue` / `newValue`. * - The SDK may add optional keys later; unknown keys passed in are dropped (use `metadata` for your * own data). */ export interface SuggestionTextChange { /** Text the suggestion removes ('' for a pure insertion). */ removed: string; /** Text the suggestion adds ('' for a pure deletion). */ added: string; /** Up to 32 characters of unchanged text right before the change. */ contextBefore: string; /** Up to 32 characters of unchanged text right after the change. */ contextAfter: string; /** Which non-overlapping match (1-based) of `contextBefore + removed + contextAfter` in the old text it is. */ occurrence: number; } /** * Return type of `onTargetEditStart`. Reserved for future fields; v1 has * no behavior-bearing return values, so customers may omit a return. * * Roadmap: future versions may accept `{ oldValue }` here so customers can * override the SDK's auto-snapshot with a domain-canonical value. */ export interface TargetEditStartResult { } export type TargetEditStartHandler = (details: TargetEditDetails) => TargetEditStartResult | void | null; export type TargetEditCommitHandler = (details: TargetEditDetails) => TargetEditCommitResult | null; /** * Config passed to `SuggestionElement.enableSuggestionMode(config?)`. * Both callbacks are optional. If `onTargetEditCommit` is omitted, customers * can still drive auto-commit by subscribing to the `targetEditCommit` event * and calling the pre-bound `commitSuggestion` builder on the payload. */ export interface EnableSuggestionModeConfig { /** * Invoked on focus of a tagged element, after the SDK captures the * snapshot. v1: informational — return value is reserved for future * use (e.g. `{ oldValue }` to override the SDK's auto-snapshot). */ onTargetEditStart?: TargetEditStartHandler; /** * Invoked once per detected commit (on `change` for atomic inputs, on * `focusout` for text-like inputs). Returning a `TargetEditCommitResult` * auto-commits with the supplied summary/metadata; returning null defers * to event subscribers. */ onTargetEditCommit?: TargetEditCommitHandler; /** * When active AND no `onTargetEditCommit` handler is provided, every * detected commit auto-commits with the SDK's default summary/summaryHtml * (equivalent to a handler returning `{}`). * * **Default: true** — a bare `enableSuggestionMode()` turns edits into * suggestions with zero config. Pass `autoCommit: false` for detect-only * mode (events fire, nothing commits until a subscriber calls the event's * `commitSuggestion` builder). * * A provided `onTargetEditCommit` handler always wins — including its * null-return deferral contract — so handler-based integrations are * unaffected. The `targetEditCommit` event still fires; its pre-bound * `commitSuggestion` builder becomes a no-op for edits already * auto-committed by this flag (same double-commit guard as the handler * path). */ autoCommit?: boolean; } /** * SDK-managed suggestion data persisted on a CommentAnnotation. * Present iff annotation.type === 'suggestion'. * * Customer code must not write to this directly — use the SuggestionElement API. */ export interface SuggestionData { /** Lifecycle state machine. */ status: SuggestionStatus; /** Stable, customer-owned target identifier. */ targetId: string; /** v1: always 'custom'. Wrappers widen later. */ targetType: SuggestionTargetType; /** Snapshot taken at startSuggestion / focus time. Frozen via structuredClone. */ oldValue: any; /** Value submitted via commitSuggestion. */ newValue: any; /** Optional human-readable description for logs / notifications. */ summary: string | null; /** * True if the live value at approve time differed from oldValue. * v1 records flag only; v1.1 will surface a confirmation prompt. */ driftDetected: boolean; /** Populated only when status === 'rejected'. */ rejectReason: string | null; /** * Full User snapshot of the resolver, populated when status moves to * approved | rejected | stale | apply_failed. Snapshot rather than userId * so customer code can render name/email/photoUrl without an extra lookup, * and so historical suggestions retain their resolver record even if the * user later updates their profile. */ resolvedBy: User | null; resolvedAt: number | null; /** * Customer metadata from `CommitSuggestionConfig.metadata` (a JSON clone; absent when none was given). * Self-hosting: content — with a comment resolver it is stored by the resolver only. */ metadata?: Record; /** * Where the change sits in a text target (absent when unknown). Self-hosting: content — with a * comment resolver it is stored by the resolver only. */ textChange?: SuggestionTextChange; } /** * Fields shared across every Suggestion regardless of status. * Internal — used to build the per-status discriminated types below. */ interface SuggestionBase { /** Annotation document id (same as the underlying CommentAnnotation.annotationId). */ annotationId: string; /** Stable, customer-owned target identifier. */ targetId: string; /** v1: always 'custom'. */ targetType: SuggestionTargetType; /** Snapshot taken at startSuggestion / focus time. */ oldValue: T; /** Value submitted via commitSuggestion. */ newValue: T; /** Optional human-readable description. */ summary: string | null; /** * Customer-defined metadata supplied via CommitSuggestionConfig.metadata (always an object; * `{}` when none was given). Contains only the customer's keys. */ metadata: Record; /** * Where the change sits in a text target; null (or absent) when unknown — non-text targets such as plain fields * and objects, and older suggestions. Optional so code that builds `Suggestion` values needs no change. */ textChange?: SuggestionTextChange | null; /** True iff the live value at approve time differed from oldValue. */ driftDetected: boolean; /** * User of the suggestion's creator (sourced from annotation.from). */ createdBy?: User; createdAt: number; } /** A suggestion in the 'pending' state — newly created, no owner action yet. */ export interface PendingSuggestion extends SuggestionBase { status: 'pending'; rejectReason: null; resolvedBy: null; resolvedAt: null; } /** A suggestion that has been approved (apply handler success or pending invocation). */ export interface ApprovedSuggestion extends SuggestionBase { status: 'accepted' | 'apply_failed'; rejectReason: null; resolvedBy: User; resolvedAt: number; } /** * A suggestion that has been rejected. `rejectReason` may be null when the * rejecter dismissed without supplying a reason — matches the persisted * `SuggestionData.rejectReason: string | null` shape. */ export interface RejectedSuggestion extends SuggestionBase { status: 'rejected'; rejectReason: string | null; resolvedBy: User; resolvedAt: number; } /** A suggestion whose target was unresolvable at approve time. */ export interface StaleSuggestion extends SuggestionBase { status: 'stale'; rejectReason: null; resolvedBy: User | null; resolvedAt: number | null; } /** * Public Suggestion — discriminated union keyed by `status`. TypeScript narrows * field types per status (e.g. `resolvedBy: User` is non-null on approved/rejected, * `rejectReason: string | null` on rejected since one-click reject without a reason * is supported). */ export type Suggestion = PendingSuggestion | ApprovedSuggestion | RejectedSuggestion | StaleSuggestion; export interface CommitSuggestionConfig { /** * Must be registered (via data-velt-target attribute or registerTarget call) * before commit, otherwise the suggestion is rejected with a dev-mode warning. */ targetId: string; /** Any JSON-serializable value. Customer's apply handler interprets it. */ newValue: T; /** * Optional human-readable string for logs and notifications. When provided * without `summaryHtml`, it is used for BOTH the seeded comment's plain * `commentText` and (escaped) its `commentHtml`. When omitted, the seeded * comment falls back to the SDK's default diff summary * (`Replace: "{old}" with "{new}"`; `Add:`/`Remove:` when one side is * absent; a per-key op list when both values are plain objects). */ summary?: string; /** * Optional HTML version of the summary — becomes the `commentHtml` of the * suggestion's seeded first comment (plain `summary` or the default diff * summary stays in `commentText`). When BOTH are omitted, the SDK renders * a default styled HTML diff (old/removed values in red italic, new/added * values in green italic). Sanitized with DOMPurify at render time; inline * `style` attributes are preserved so rich diff styling survives. */ summaryHtml?: string; /** * Optional customer-defined metadata (a plain JSON object). Stored on the suggestion * (`annotation.suggestion.metadata`) and returned as `Suggestion.metadata`. With a comment * resolver (self-hosting) it is stored by the resolver only. */ metadata?: Record; /** * Optional: where the change sits in a text target. Integrations that know it (a rich-text editor) * pass it; for a contenteditable target with no registered getter the SDK works it out when it is * omitted. An invalid value is not saved (dev warning); the commit still succeeds. With a comment * resolver (self-hosting) it is stored by the resolver only. */ textChange?: SuggestionTextChange; /** * Optional location to file the suggestion under (only `id` is required), like `addManualComment`'s * `location`. When omitted, the suggestion takes the location of its target element's nearest * `data-velt-location-id` (or `data-velt-location` with an `id`) container, else the root location. Pass * it when the target has no element (a `registerTarget` getter) but sits in a location's container. * A location already set with `setLocations` is used as set (your other fields are not used); any other * location is added to the page's locations, as for manual comments. */ location?: Location; /** * Optional comment context for the suggestion's annotation, stored as `addComment` stores a comment's `context` * (e.g. `{ textEditorConfig: { editorId } }`, the editor it was made in, as a rich-text text comment records it). * A page-level comment context provider replaces it, as for every comment. It is comment context, not suggestion * content: under self-hosting it is kept in Velt's copy (except `context.textEditorConfig.text`, which goes to the * comment resolver, as for comments). A JSON copy is taken at commit. Not saved, with a dev warning: anything that * is not stored as an object (string, number, array, Date) or cannot be stored as JSON. The SDK's own access keys * (`accessFields`, `_setAccessFields`, `_replaceAccessFields`, `_setVisibilityConfig`) are dropped with a dev * warning; `access` (context access) is kept, as for a comment. */ context?: Record; } /** * Pre-bound builder attached to `targetEditCommit` payloads. Calling it * commits the suggestion with the SDK's default summary/metadata, optionally * overridden by `result`. If the customer's `onTargetEditCommit` handler * already returned a non-null result for this edit, this builder is a no-op * (resolves immediately) so subscribers can't double-commit. */ export type TargetEditCommitBuilder = (result?: TargetEditCommitResult) => Promise<{ id: string; } | null>; export interface SuggestionGetSuggestionsFilter { targetId?: string; status?: SuggestionStatus | SuggestionStatus[]; } export {};