/** * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options */ /** * @module ai/toolkit/documentcompare * @publicApi */ import { Plugin, type PluginDependenciesOf } from "@ckeditor/ckeditor5-core"; import { type Operation, type ModelRange, type ModelElement, type ModelSchema } from "@ckeditor/ckeditor5-engine"; import { SuggestionsConversion } from "@ckeditor/ckeditor5-collaboration-core"; import { DocumentDiffer } from "./documentdiffer.js"; import { DocumentCompareUtils } from "./documentcompareutils.js"; import { AIEditorConfig } from "../aicore/aieditorconfig.js"; import { type AIOperationSource } from "../aicore/utils/markoperationsasai.js"; import { type DocumentCompareSnapshot } from "./documentsnapshot.js"; import { type DocumentChange } from "./proposedchange.js"; /** * `DocumentCompare` provides a set of tools that allows you to process editor document data by custom external logic, * evaluate the differences between original and processed data, and apply them as granular changes or tracked * suggestions. * * Contrary to `editor.setData()`, this does not replace the whole editor data. Instead, atomic changes are evaluated and a small set * of changes is applied to the document. This is especially useful when the editor also uses Track Changes, Revision History, and * Real-Time Collaboration features. * * Use {@link #process `process()`}, to run the whole pipeline in one call - it makes a * {@link module:ai/toolkit/documentsnapshot~DocumentCompareSnapshot document snapshot}, processes the data, and applies granular changes: * * ```ts * await documentCompare.process( async snapshot => externalDataProcessing( snapshot.content ) ); * * // Or, to apply changes as suggestions: * await documentCompare.process( async snapshot => externalDataProcessing( snapshot.content ), { asSuggestions: true } ); * ``` * * Some integrations need to process the data in separate steps (e.g. backend processing workflows, or when changes * are not applied immediately to the content). In this case, you can capture a snapshot first and apply the result later: * * ```ts * const snapshot = documentCompare.makeSnapshot(); * const processed = await externalDataProcessing( snapshot.content ); * * // ... * * const patch = documentCompare.computePatch( snapshot, processed, { asSuggestions: true } ); * documentCompare.applyPatch( patch ); * ``` * * If the user should decide whether changes are accepted or rejected, compare the snapshot into separate changes instead, and apply the * ones they keep: * * ```ts * const changes = documentCompare.computeChanges( snapshot, processed ); * * documentCompare.applyChange( changes[ 0 ] ); * ``` * * See also {@link module:ai/toolkit/proposedchanges~ProposedChanges `ProposedChanges` plugin}, a set of tools to display the * proposed changes to the user. * * The snapshot data is stamped with `data-id` attributes, and the comparison pairs the elements of the snapshot and the * processed data by these ids. When the processing cannot retain the ids (for example, when the data goes through Markdown), * capture the snapshot without them. The elements are then paired by their content instead: * * ```ts * const snapshot = documentCompare.makeSnapshot( { useDataIds: false } ); * const processed = await externalDataProcessing( snapshot.content ); * * const patch = documentCompare.computePatch( snapshot, processed ); * documentCompare.applyPatch( patch ); * ``` * * A document from outside the editor (for example, another version of the document) can be compared with the current document present * in the editor. Capture the snapshot without the ids just before the comparison, so the documents are compared by content similarity: * * ```ts * const snapshot = documentCompare.makeSnapshot( { useDataIds: false } ); * const patch = documentCompare.computePatch( snapshot, importedHtml, { asSuggestions: true } ); * documentCompare.applyPatch( patch ); * ``` * * The recommended way to use `DocumentCompare` is to create a snapshot with data IDs, then process the snapshot `content`, and then * use the snapshot to generate the changes using `DocumentCompare` methods. This approach will result in better performance and the best * diff quality, as snapshot data IDs are used by the diff algorithm to pair the elements. Skip IDs or the snapshot only in cases where * they cannot be used. */ export declare class DocumentCompare extends Plugin { static get pluginName(): "DocumentCompare"; static get requires(): PluginDependenciesOf<[DocumentDiffer, DocumentCompareUtils, SuggestionsConversion, AIEditorConfig]>; static override get isOfficialPlugin(): true; static override get isPremiumPlugin(): true; init(): void; afterInit(): void; /** * Captures the current document state as a {@link module:ai/toolkit/documentsnapshot~DocumentCompareSnapshot}. * * The snapshot contains all data and metadata necessary to process the document and then be able to calculate differences between * the original and the processed data. * * Importantly, `snapshot.content` holds data for each root (excluding `$graveyard`), serialized to HTML. By default, the data is * stamped with `data-id` attributes, assigned to structural elements of the data. During processing, make sure that these * `data-id`s are retained. They are used to identify which elements were kept, which were removed, and which are new. * * If the processing cannot retain them, capture the snapshot without the ids * ({@link ~DocumentCompareSnapshotOptions#useDataIds `options.useDataIds: false`}). When data IDs are skipped, * the original and processed data is compared only by the content similarity. * * The content of an inline root is wrapped in a single, artificial `

` element. This wrapper always gets * a `data-id`, even when the snapshot is captured with `options.useDataIds: false`. Process only the content inside the wrapper. * * See also {@link module:ai/toolkit/documentsnapshot~DocumentCompareSnapshot}. * * @param options How the snapshot is captured. * @returns The captured snapshot. */ makeSnapshot(options?: DocumentCompareSnapshotOptions): DocumentCompareSnapshot; /** * Computes a document patch - a set of granular differences between the earlier captured snapshot and the given data. You can apply * the patch using {@link #applyPatch}. All changes from the patch are applied at once. * * Use `options` to set whether the patch should be calculated and applied as tracked changes or as direct changes to the document. * * The passed data is compared against the snapshot state. Later, when a patch is applied, the differences are resolved against any * changes that happened in the editor since the snapshot was taken. This allows you to process the data asynchronously, while retaining * all edits that have happened in the editor in the meantime. * * If you did not make the snapshot for processing purposes (for example, a case where you compare editor data to a different, already * existing document), make the snapshot just before calling `computePatch()`. * * Throws `documentcompare-unsupported-inline-root-content` if the processed data for an inline root contains block content. * * @param snapshot The captured before-state to diff against. * @param data The new data. For multi-root editor, pass an object keyed by root name. * @param options How the comparison is computed. * @returns The patch bringing the document from the snapshot to the processed state. */ computePatch(snapshot: DocumentCompareSnapshot, data: string | Record, options?: DocumentCompareComputePatchOptions): DocumentComparePatch; /** * Compares the earlier captured snapshot and the given data. Returns a set of grouped * {@link module:ai/toolkit/proposedchange~DocumentChange document changes}. Changes are grouped based on where in the document * they sit - related changes made next to each other are put together into one group. Each group is one, atomic, reviewable unit, * to be accepted or rejected independently of each other. * * The document changes can be collected into a * {@link module:ai/toolkit/proposedchangescollection~ProposedChangesCollection set of proposed changes} and passed to * {@link module:ai/toolkit/proposedchanges~ProposedChanges#createController} to create a controller, which binds the changes with * an editor instance and offers an API to operate on them. To provide an interface for managing the changes, * {@link module:ai/toolkit/proposedchanges~ProposedChanges#createView create a proposed changes UI component} and * {@link module:ai/toolkit/proposedchangescontrollertype~ProposedChangesController#attachView attach} it to the controller. * * You can also apply the accepted document changes directly, using {@link #applyChange}. * * The passed data is compared against the snapshot state. When a change is accepted, it is resolved against any changes that * happened in the editor since the snapshot was taken. This allows you to process the data asynchronously, while retaining any edits * that have happened in the editor in the meantime. * * If you did not make the snapshot for processing purposes (for example, a case where you compare editor data to a different, already * existing document), make the snapshot just before calling `computeChanges()`. * * If the processed data for an inline root contains block content, no change is returned for that root and * a `documentcompare-unsupported-inline-root-content` warning is logged. * * @param snapshot The captured before-state to compare against. * @param data The processed data. For multi-root editor, pass an object keyed by root name. * @param options How the comparison is computed. * @returns The changes bringing the document from the snapshot to the processed state, in document order. */ computeChanges(snapshot: DocumentCompareSnapshot, data: string | Record, options?: DocumentCompareComputeChangesOptions): Array; /** * Applies a patch to the current state of the document. * * As a result, all changes described by the patch are reflected in the document. Note that this converges with all changes that * happened on the document after the snapshot used for the patch was made, including both local and remote edits (if real-time * collaboration is enabled). * * Note that the patch can only be applied to the same document as the snapshot, and only during the same editing session. * Otherwise, the method throws `documentcompare-channel-mismatch` or `documentcompare-session-mismatch`. * * The patch is first validated against a copy of the document before anything is committed. If any errors or conflict * resolution problems surface during this dry-run, `documentcompare-invalid-patch` error is thrown, and the editor * data is left intact. * * The changes can be applied directly to the content or as tracked suggestions (requires * {@link module:track-changes/trackchanges~TrackChanges Track changes plugin}, otherwise `documentcompare-no-track-changes` * is thrown). See also {@link #computePatch}. * * @param patch The patch to apply, as produced by {@link #computePatch}. */ applyPatch(patch: DocumentComparePatch): void; /** * Applies a single {@link module:ai/toolkit/proposedchange~DocumentChange document change} the same way * {@link #applyPatch} applies a whole patch. See {@link #applyPatch}. * * @param change The change to apply. * @param options How the change is applied. */ applyChange(change: DocumentChange, options?: DocumentCompareApplyChangeOptions): void; /** * Runs the whole processing pipeline in one call: snapshots the document, hands the snapshot to `callback` for * external processing (e.g. an AI service), then diffs returned data and applies granular changes to the document. * * This is a "shortcut" for using {@link #makeSnapshot}, {@link #computePatch}, and {@link #applyPatch}. * * If diffing or applying fails, the underlying error is rethrown and can be further handled, unless `options.overwriteOnError` is set, * in which case the current document is instead fully replaced with the processed data, the same way as if `editor.setData()` was used. * In this case, changes that happened to the document after the snapshot was taken will be overwritten. See * {@link ~DocumentCompareProcessOptions#overwriteOnError} for the side effects of the replacement. * * Errors thrown or rejected by `callback` are always rethrown, regardless of `options.overwriteOnError`. * * The snapshot is captured with data IDs stamped on the document content, unless `options.useDataIds` is `false`. * See {@link ~DocumentCompareSnapshotOptions#useDataIds}. * * @param callback Receives the captured snapshot and returns the processed data. For multi-root editor, return an object keyed * by root name. Otherwise, return a string with the data of the main root. * @param options Additional processing options. * @returns `true` when the process finished successfully and changes were applied granularly, * `false` when the full-replacement fallback was used. */ process(callback: (snapshot: DocumentCompareSnapshot) => Promise>, options?: DocumentCompareProcessOptions): Promise; } /** * Options for {@link module:ai/toolkit/documentcompare~DocumentCompare#makeSnapshot}. */ export interface DocumentCompareSnapshotOptions { /** * Ranges to capture with the snapshot as the user's selection. Must not intersect. By default, no selection is captured. */ selection?: Iterable; /** * Whether the snapshot content is stamped with `data-id` attributes. * * With `true`, every structural element of the serialized data gets a `data-id` attribute. Later, the comparison uses these IDs * to pair the elements of the snapshot and the processed data. The processing must retain the data IDs on * the elements that were kept. New elements should not get any ID. * * With `false`, no `data-id` is written, and the comparison pairs the elements only by their content similarity instead. Use it when * the processing cannot retain the IDs. * * @default true */ useDataIds?: boolean; } /** * Describes how a {@link ~DocumentComparePatch patch} is applied. */ export interface DocumentComparePatchOptions { /** * Whether the operations carry track-changes suggestion markers. * * @default false */ asSuggestions?: boolean; } /** * Describes how a comparison is computed. */ export interface DocumentCompareComputePatchOptions { /** * Whether the comparison marks removed content for track changes instead of removing it. */ asSuggestions?: boolean; /** * Which AI feature produced the processed data. You can use one of available values or pass a custom string. * When set, the operations applying the patch will be stamped as made-by-AI. This information is passed to suggestions * and revisions meta data. Such suggestions and revisions will be visually marked as made-by-AI accordingly to these * features config ({@link module:track-changes/trackchangesconfig~TrackChangesConfig#showAISource * `config.trackChanges.showAISource`} and {@link module:revision-history/revisionhistoryconfig~RevisionHistoryConfig#showAISource * `config.revisionHistory.showAISource`}). * * Do not set for changes coming from non-AI sources. */ aiSource?: AIOperationSource; } /** * Describes how the document changes are computed. */ export interface DocumentCompareComputeChangesOptions { /** * Whether all changes inside the given `element` should be treated as a one change. Called for every element if defined, before any * other rules are applied. Return `true` or `false` to make a decision, or `undefined` to fall back to default rules. * * Use this to register custom elements or to override default rules. * * Atomic elements are for example tables (excluding layout tables) and elements without paragraph-like elements (e.g. an image with * a caption). */ isAtomic?: (element: ModelElement, schema: ModelSchema) => boolean | undefined; /** * Which AI feature produced the processed data, stamped on the operations applying a computed change. * * See {@link ~DocumentCompareComputePatchOptions#aiSource}. */ aiSource?: AIOperationSource; } /** * Options for {@link module:ai/toolkit/documentcompare~DocumentCompare#process}. */ export interface DocumentCompareProcessOptions extends DocumentCompareComputePatchOptions { /** * What to do when diffing or applying the processed data fails. * * By default, the underlying error is rethrown. * * When the option is set to `true`, the whole document is instead overwritten with the processed data * via `editor.setData()` and {@link module:ai/toolkit/documentcompare~DocumentCompare#process} returns `false`. * * The overwrite ignores the `asSuggestions` and `aiSource` options, so the content is replaced directly and is not marked * as an AI change. It cannot be undone, and it clears the undo stack. * * This option does not cover errors thrown by `callback`, which are always rethrown. * * Note that the overwrite is also performed in real-time collaboration environment, and it may roll back some edits made by remote * users while `callback` was processing. Opt in only when overwriting the whole document is acceptable. * * @default false */ overwriteOnError?: boolean; /** * Whether the snapshot handed to `callback` is stamped with `data-id` attributes. * See {@link ~DocumentCompareSnapshotOptions#useDataIds}. * * @default true */ useDataIds?: boolean; } /** * Options for {@link module:ai/toolkit/documentcompare~DocumentCompare#applyChange}. */ export interface DocumentCompareApplyChangeOptions { /** * Whether the change is applied as track-changes suggestions (`true`) or directly (`false`). * * @default false */ asSuggestions?: boolean; } /** * The result of comparing a snapshot against processed data: the operations to bring the document to the new state, * together with the snapshot metadata. * * Can be applied via {@link module:ai/toolkit/documentcompare~DocumentCompare#applyPatch}. */ export interface DocumentComparePatch { /** * The channel of the document the snapshot was captured from, validated on apply. */ channelId: string; /** * The editing session the snapshot was captured in, validated on apply. */ sessionId: string; /** * The snapshot version the operations are anchored to (used to reconcile them on apply). */ version: number; /** * Which AI feature produced the processed data the patch was computed from, or unset when it did not come from AI. */ aiSource?: AIOperationSource; /** * How the patch is applied. */ options: DocumentComparePatchOptions; /** * The operations to apply, keyed by root name (a root with no changes maps to an empty array). */ operations: Record>; }