From 44769dcda8c4def19e99a2033fb878229f3da166 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 26 Sep 2026 00:17:30 +0100 Subject: [PATCH 01/29] refactor(model)!: rename block tunes to per-plugin block data Renames the model's tune vocabulary so per-block extra data belongs to plugins rather than to a dedicated Block Tune entity: - BlockTune entity -> PluginDataNode, with key deletion when a value is set to undefined and an isEmpty getter - TuneIndex -> PluginDataIndex, serialized as {"k":"plugin",...,"plugin":...} - TuneModifiedEvent -> PluginDataModifiedEvent, BlockTuneEvents -> PluginDataEvents - BlockTuneName/BlockTuneSerialized -> PluginDataName/PluginDataSerialized - the serialized block key `tunes` -> `plugins` Behavior changes beyond the rename: - BlockNode.updatePluginData creates a missing entry instead of throwing. The node is created empty and its listener attached before the first update, because PluginDataNode dispatches synchronously. - entries live in a null-prototype record, and an empty plugin name throws, so a document-supplied name like __proto__ is stored as plain data - empty entries are left out of serialization - EditorDocument.modifyData applies a Modified change addressed by a PluginDataIndex, so undo/redo and remote operations can replay plugin data - the bubbled event carries the acting user from the context instead of a hardcoded 'user' BREAKING CHANGE: the serialized block key `tunes` is now `plugins`, and the serialized index kind "tune" is now "plugin". Co-Authored-By: Claude Opus 5 --- packages/model-types/src/BlockNode.ts | 8 +- packages/model-types/src/BlockTune.ts | 13 -- packages/model-types/src/EventMap.ts | 8 +- packages/model-types/src/Index/Index.spec.ts | 77 ++++++--- packages/model-types/src/Index/IndexBase.ts | 14 +- .../model-types/src/Index/PartialIndex.ts | 44 ++--- .../model-types/src/Index/PluginDataIndex.ts | 99 +++++++++++ packages/model-types/src/Index/TuneIndex.ts | 99 ----------- packages/model-types/src/Index/index.ts | 28 +-- packages/model-types/src/PluginData.ts | 13 ++ .../src/events/PluginDataModifiedEvent.ts | 20 +++ .../src/events/TuneModifiedEvent.ts | 20 --- packages/model-types/src/events/index.ts | 2 +- packages/model-types/src/index.ts | 14 +- packages/model/src/EditorJSModel.spec.ts | 2 +- packages/model/src/EditorJSModel.ts | 12 +- .../BlockNode/BlockNode.integration.spec.ts | 97 ++++++++++- .../src/entities/BlockNode/BlockNode.spec.ts | 149 +++++++++------- .../src/entities/BlockNode/__mocks__/index.ts | 2 +- .../model/src/entities/BlockNode/index.ts | 121 ++++++++----- .../types/BlockNodeConstructorParameters.ts | 6 +- .../src/entities/BlockTune/BlockTune.spec.ts | 106 ------------ .../src/entities/BlockTune/__mocks__/index.ts | 22 --- .../model/src/entities/BlockTune/index.ts | 63 ------- .../types/BlockTuneConstructorParameters.ts | 13 -- .../src/entities/BlockTune/types/index.ts | 1 - .../EditorDocument/EditorDocument.spec.ts | 58 +++---- .../src/entities/EditorDocument/index.ts | 21 ++- .../PluginDataNode/PluginDataNode.spec.ts | 160 ++++++++++++++++++ .../PluginDataNode/__mocks__/index.ts | 27 +++ .../src/entities/PluginDataNode/index.ts | 83 +++++++++ .../PluginDataNodeConstructorParameters.ts | 13 ++ .../entities/PluginDataNode/types/index.ts | 1 + packages/model/src/entities/index.ts | 2 +- 34 files changed, 844 insertions(+), 574 deletions(-) delete mode 100644 packages/model-types/src/BlockTune.ts create mode 100644 packages/model-types/src/Index/PluginDataIndex.ts delete mode 100644 packages/model-types/src/Index/TuneIndex.ts create mode 100644 packages/model-types/src/PluginData.ts create mode 100644 packages/model-types/src/events/PluginDataModifiedEvent.ts delete mode 100644 packages/model-types/src/events/TuneModifiedEvent.ts delete mode 100644 packages/model/src/entities/BlockTune/BlockTune.spec.ts delete mode 100644 packages/model/src/entities/BlockTune/__mocks__/index.ts delete mode 100644 packages/model/src/entities/BlockTune/index.ts delete mode 100644 packages/model/src/entities/BlockTune/types/BlockTuneConstructorParameters.ts delete mode 100644 packages/model/src/entities/BlockTune/types/index.ts create mode 100644 packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts create mode 100644 packages/model/src/entities/PluginDataNode/__mocks__/index.ts create mode 100644 packages/model/src/entities/PluginDataNode/index.ts create mode 100644 packages/model/src/entities/PluginDataNode/types/PluginDataNodeConstructorParameters.ts create mode 100644 packages/model/src/entities/PluginDataNode/types/index.ts diff --git a/packages/model-types/src/BlockNode.ts b/packages/model-types/src/BlockNode.ts index d4fcf069..dac85081 100644 --- a/packages/model-types/src/BlockNode.ts +++ b/packages/model-types/src/BlockNode.ts @@ -1,6 +1,6 @@ import type { TextNodeSerialized } from './Text.js'; import type { ValueSerialized } from './Value.js'; -import type { BlockTuneSerialized } from './BlockTune.js'; +import type { PluginDataSerialized } from './PluginData.js'; // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents export type BlockChildNodeSerialized = ValueSerialized | TextNodeSerialized; @@ -13,7 +13,7 @@ export interface BlockNodeDataSerialized { [key: string]: BlockNodeDataSerializedValue; } -/** Describes a block with its id, tool name, data and optional tunes */ +/** Describes a block with its id, tool name, data and optional per-plugin data */ export interface BlockData { /** Block identifier */ id: string; @@ -21,8 +21,8 @@ export interface BlockData { name: string; /** Block content data */ data: BlockNodeDataSerialized; - /** Optional block tune data */ - tunes?: Record; + /** Optional per-plugin data, keyed by plugin name */ + plugins?: Record; } /** Minimum data required to initialise a block */ diff --git a/packages/model-types/src/BlockTune.ts b/packages/model-types/src/BlockTune.ts deleted file mode 100644 index 0da8c3db..00000000 --- a/packages/model-types/src/BlockTune.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { Nominal } from './Nominal.js'; -import { create } from './Nominal.js'; - -/** Name of a block tune */ -export type BlockTuneName = Nominal; - -/** Factory for BlockTuneName */ -export const createBlockTuneName = create(); - -/** Serialized data for a block tune */ -export interface BlockTuneSerialized { - [key: string]: unknown; -} diff --git a/packages/model-types/src/EventMap.ts b/packages/model-types/src/EventMap.ts index 095fdf0b..e7ebef8a 100644 --- a/packages/model-types/src/EventMap.ts +++ b/packages/model-types/src/EventMap.ts @@ -5,7 +5,7 @@ import type { TextRemovedEvent } from './events/TextRemovedEvent.js'; import type { TextFormattedEvent } from './events/TextFormattedEvent.js'; import type { TextUnformattedEvent } from './events/TextUnformattedEvent.js'; import type { ValueModifiedEvent } from './events/ValueModifiedEvent.js'; -import type { TuneModifiedEvent } from './events/TuneModifiedEvent.js'; +import type { PluginDataModifiedEvent } from './events/PluginDataModifiedEvent.js'; import type { PropertyModifiedEvent } from './events/PropertyModifiedEvent.js'; import type { CaretManagerCaretAddedEvent } from './events/CaretManagerCaretAddedEvent.js'; import type { CaretManagerCaretRemovedEvent } from './events/CaretManagerCaretRemovedEvent.js'; @@ -27,9 +27,9 @@ export type TextNodeEvents = TextAddedEvent | TextRemovedEvent | TextFormattedEv export type ValueNodeEvents = ValueModifiedEvent; /** - * Alias for all block tune events + * Alias for all plugin data events */ -export type BlockTuneEvents = TuneModifiedEvent; +export type PluginDataEvents = PluginDataModifiedEvent; /** * Alias for all document-level events @@ -39,7 +39,7 @@ export type DocumentEvents = PropertyModifiedEvent; /** * Union of all events that can be emitted by the document model */ -export type ModelEvents = BlockEvents | TextNodeEvents | ValueNodeEvents | BlockTuneEvents | DocumentEvents; +export type ModelEvents = BlockEvents | TextNodeEvents | ValueNodeEvents | PluginDataEvents | DocumentEvents; /** * Union of all events that can be emitted by the caret manager diff --git a/packages/model-types/src/Index/Index.spec.ts b/packages/model-types/src/Index/Index.spec.ts index 3aed9f19..49104717 100644 --- a/packages/model-types/src/Index/Index.spec.ts +++ b/packages/model-types/src/Index/Index.spec.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-magic-numbers */ -import type { DataKey, BlockTuneName, DocumentId } from '@editorjs/model-types'; +import type { DataKey, PluginDataName, DocumentId } from '@editorjs/model-types'; import { Index, IndexKind, @@ -8,7 +8,8 @@ import { DocumentIndex, PropertyIndex, TextIndex, - TuneIndex + PluginDataIndex, + PartialIndex } from './index.js'; describe('Index', () => { @@ -57,19 +58,19 @@ describe('Index', () => { }); }); - describe('Index.tune()', () => { - it('creates a TuneIndex with block, tune name, and tune key', () => { - const idx = Index.tune(3, 'header' as BlockTuneName, 'level'); + describe('Index.pluginData()', () => { + it('creates a PluginDataIndex with block, plugin name, and plugin key', () => { + const idx = Index.pluginData(3, 'anchors' as PluginDataName, 'id'); - expect(idx).toBeInstanceOf(TuneIndex); - expect(idx.kind).toBe(IndexKind.Tune); + expect(idx).toBeInstanceOf(PluginDataIndex); + expect(idx.kind).toBe(IndexKind.PluginData); expect(idx.blockIndex).toBe(3); - expect(idx.tuneName).toBe('header'); - expect(idx.tuneKey).toBe('level'); + expect(idx.pluginName).toBe('anchors'); + expect(idx.pluginKey).toBe('id'); }); it('optionally accepts documentId', () => { - const idx = Index.tune(3, 'header' as BlockTuneName, 'level', 'doc1' as DocumentId); + const idx = Index.pluginData(3, 'anchors' as PluginDataName, 'id', 'doc1' as DocumentId); expect(idx.documentId).toBe('doc1'); }); @@ -137,8 +138,8 @@ describe('Index', () => { expect(Index.data(0, 'key' as DataKey).kind).not.toBe(IndexKind.Block); }); - it('TuneIndex kind is not Block', () => { - expect(Index.tune(0, 'tune' as BlockTuneName, 'key').kind).not.toBe(IndexKind.Block); + it('PluginDataIndex kind is not Block', () => { + expect(Index.pluginData(0, 'anchors' as PluginDataName, 'key').kind).not.toBe(IndexKind.Block); }); }); @@ -389,13 +390,13 @@ describe('Index', () => { expect(parsed.documentId).toBe('doc1'); }); - it('round-trips a TuneIndex', () => { - const idx = Index.tune(3, 'header' as BlockTuneName, 'level'); - const parsed = Index.parse(idx.serialize()) as TuneIndex; + it('round-trips a PluginDataIndex', () => { + const idx = Index.pluginData(3, 'anchors' as PluginDataName, 'id'); + const parsed = Index.parse(idx.serialize()) as PluginDataIndex; expect(parsed.blockIndex).toBe(3); - expect(parsed.tuneName).toBe('header'); - expect(parsed.tuneKey).toBe('level'); + expect(parsed.pluginName).toBe('anchors'); + expect(parsed.pluginKey).toBe('id'); }); it('round-trips a DataIndex', () => { @@ -443,11 +444,11 @@ describe('Index', () => { id: 'doc1' }); }); - it('emits the expected wire object for TuneIndex', () => { - expect(JSON.parse(Index.tune(3, 'header' as BlockTuneName, 'level').serialize())).toEqual({ k: 'tune', + it('emits the expected wire object for PluginDataIndex', () => { + expect(JSON.parse(Index.pluginData(3, 'anchors' as PluginDataName, 'id').serialize())).toEqual({ k: 'plugin', b: 3, - tune: 'header', - key: 'level' }); + plugin: 'anchors', + key: 'id' }); }); it('emits the expected wire object for DataIndex', () => { @@ -504,4 +505,38 @@ describe('Index', () => { expect(() => Index.parse('{"k":"unknown"}')).toThrow('Unknown index kind'); }); }); + + describe('PartialIndex#resolve() for plugin data', () => { + it('should resolve to a PluginDataIndex once block index is attached', () => { + const resolved = new PartialIndex({ pluginName: 'anchors' as PluginDataName, + pluginKey: 'id' }) + .withBlockIndex(2) + .resolve(); + + expect(resolved).toBeInstanceOf(PluginDataIndex); + expect((resolved as PluginDataIndex).pluginName).toBe('anchors'); + expect((resolved as PluginDataIndex).pluginKey).toBe('id'); + expect((resolved as PluginDataIndex).blockIndex).toBe(2); + }); + + it('should throw when the plugin key is missing', () => { + expect(() => new PartialIndex({ pluginName: 'anchors' as PluginDataName }) + .withBlockIndex(2) + .resolve()).toThrow('PluginDataIndex requires pluginKey'); + }); + + it('should throw when the plugin name is missing', () => { + expect(() => new PartialIndex({ pluginKey: 'id' }) + .withBlockIndex(2) + .resolve()).toThrow('PluginDataIndex requires pluginName'); + }); + + it('should throw when combined with a data key', () => { + expect(() => new PartialIndex({ dataKey: 'text' as DataKey, + pluginName: 'anchors' as PluginDataName, + pluginKey: 'id' }) + .withBlockIndex(2) + .resolve()).toThrow('DataIndex cannot be combined with pluginName'); + }); + }); }); diff --git a/packages/model-types/src/Index/IndexBase.ts b/packages/model-types/src/Index/IndexBase.ts index fda548a6..a329a745 100644 --- a/packages/model-types/src/Index/IndexBase.ts +++ b/packages/model-types/src/Index/IndexBase.ts @@ -1,4 +1,4 @@ -import type { BlockTuneName } from '../BlockTune.js'; +import type { PluginDataName } from '../PluginData.js'; import type { DataKey } from '../DataKey.js'; import type { DocumentId } from '../indexing.js'; import type { TextRange } from '../Text.js'; @@ -13,8 +13,8 @@ export enum IndexKind { Property = 'property', /** Block scope */ Block = 'block', - /** Block tune scope */ - Tune = 'tune', + /** Plugin per-block data scope */ + PluginData = 'plugin', /** Block data-key scope */ Data = 'data', /** Inline text scope (single or composite) */ @@ -43,10 +43,10 @@ export interface IndexFields { textRange?: TextRange; /** Data key within the block */ dataKey?: DataKey; - /** Tune name within the block */ - tuneName?: BlockTuneName; - /** Tune key within the block tune */ - tuneKey?: string; + /** Plugin name within the block */ + pluginName?: PluginDataName; + /** Key within the plugin's per-block data */ + pluginKey?: string; /** Block index within the document */ blockIndex?: number; /** Property name within the document */ diff --git a/packages/model-types/src/Index/PartialIndex.ts b/packages/model-types/src/Index/PartialIndex.ts index 9acfede2..273d62b4 100644 --- a/packages/model-types/src/Index/PartialIndex.ts +++ b/packages/model-types/src/Index/PartialIndex.ts @@ -1,4 +1,4 @@ -import type { BlockTuneName } from '../BlockTune.js'; +import type { PluginDataName } from '../PluginData.js'; import type { DataKey } from '../DataKey.js'; import type { DocumentId } from '../indexing.js'; import type { TextRange } from '../Text.js'; @@ -8,7 +8,7 @@ import { DataIndex } from './DataIndex.js'; import { DocumentIndex } from './DocumentIndex.js'; import { PropertyIndex } from './PropertyIndex.js'; import { TextIndex } from './TextIndex.js'; -import { TuneIndex } from './TuneIndex.js'; +import { PluginDataIndex } from './PluginDataIndex.js'; /** * Internal placeholder used during event bubbling. @@ -41,17 +41,17 @@ export class PartialIndex extends IndexBase { } /** - * Tune name if set + * Plugin data name if set */ - public get tuneName(): BlockTuneName | undefined { - return this.#fields.tuneName; + public get pluginName(): PluginDataName | undefined { + return this.#fields.pluginName; } /** - * Tune key if set + * Plugin data key if set */ - public get tuneKey(): string | undefined { - return this.#fields.tuneKey; + public get pluginKey(): string | undefined { + return this.#fields.pluginKey; } /** @@ -89,7 +89,7 @@ export class PartialIndex extends IndexBase { */ public get isBlockIndex(): boolean { return this.#fields.blockIndex !== undefined - && this.#fields.tuneName === undefined + && this.#fields.pluginName === undefined && this.#fields.dataKey === undefined && this.#fields.textRange === undefined; } @@ -99,7 +99,7 @@ export class PartialIndex extends IndexBase { */ public get isDataIndex(): boolean { return this.#fields.blockIndex !== undefined - && this.#fields.tuneName === undefined + && this.#fields.pluginName === undefined && this.#fields.dataKey !== undefined && this.#fields.textRange === undefined; } @@ -142,8 +142,8 @@ export class PartialIndex extends IndexBase { const { textRange, dataKey, - tuneName, - tuneKey, + pluginName, + pluginKey, blockIndex, propertyName, documentId, @@ -158,7 +158,7 @@ export class PartialIndex extends IndexBase { if ( blockIndex !== undefined || dataKey !== undefined - || tuneName !== undefined + || pluginName !== undefined || textRange !== undefined ) { throw new Error( @@ -188,8 +188,8 @@ export class PartialIndex extends IndexBase { } if (dataKey !== undefined) { - if (tuneName !== undefined) { - throw new Error('DataIndex cannot be combined with tuneName'); + if (pluginName !== undefined) { + throw new Error('DataIndex cannot be combined with pluginName'); } if (blockIndex === undefined) { throw new Error('DataIndex requires blockIndex'); @@ -198,18 +198,18 @@ export class PartialIndex extends IndexBase { return new DataIndex(blockIndex, dataKey, documentId); } - if (tuneName !== undefined || tuneKey !== undefined) { + if (pluginName !== undefined || pluginKey !== undefined) { if (blockIndex === undefined) { - throw new Error('TuneIndex requires blockIndex'); + throw new Error('PluginDataIndex requires blockIndex'); } - if (tuneName === undefined || tuneName.length === 0) { - throw new Error('TuneIndex requires tuneName'); + if (pluginName === undefined || pluginName.length === 0) { + throw new Error('PluginDataIndex requires pluginName'); } - if (tuneKey === undefined) { - throw new Error('TuneIndex requires tuneKey'); + if (pluginKey === undefined) { + throw new Error('PluginDataIndex requires pluginKey'); } - return new TuneIndex(blockIndex, tuneName, tuneKey, documentId); + return new PluginDataIndex(blockIndex, pluginName, pluginKey, documentId); } if (blockIndex !== undefined) { diff --git a/packages/model-types/src/Index/PluginDataIndex.ts b/packages/model-types/src/Index/PluginDataIndex.ts new file mode 100644 index 00000000..e608f364 --- /dev/null +++ b/packages/model-types/src/Index/PluginDataIndex.ts @@ -0,0 +1,99 @@ +import type { PluginDataName } from '../PluginData.js'; +import type { DocumentId } from '../indexing.js'; +import { IndexBase, IndexKind } from './IndexBase.js'; + +/** + * Index scoped to one key of one plugin's per-block data + */ +export class PluginDataIndex extends IndexBase { + readonly #blockIndex: number; + readonly #pluginName: PluginDataName; + readonly #pluginKey: string; + readonly #documentId?: DocumentId; + + /** + * @param blockIndex - zero-based block position + * @param pluginName - name of the plugin owning the data + * @param pluginKey - key within the plugin's data + * @param documentId - optional document identifier + */ + constructor( + blockIndex: number, + pluginName: PluginDataName, + pluginKey: string, + documentId?: DocumentId + ) { + super(IndexKind.PluginData); + this.#blockIndex = blockIndex; + this.#pluginName = pluginName; + this.#pluginKey = pluginKey; + this.#documentId = documentId; + } + + /** + * The zero-based position of the indexed block + */ + public get blockIndex(): number { + return this.#blockIndex; + } + + /** + * The name of the plugin owning the indexed data + */ + public get pluginName(): PluginDataName { + return this.#pluginName; + } + + /** + * The key within the plugin's data + */ + public get pluginKey(): string { + return this.#pluginKey; + } + + /** + * The unique identifier of the indexed document + */ + public override get documentId(): DocumentId | undefined { + return this.#documentId; + } + + /** + * @param blockIndex - updated block position + */ + public override withBlockIndex(blockIndex: number): PluginDataIndex { + return new PluginDataIndex(blockIndex, this.#pluginName, this.#pluginKey, this.#documentId); + } + + /** + * @param documentId - updated document identifier + */ + public override withDocumentId(documentId: DocumentId): PluginDataIndex { + return new PluginDataIndex(this.#blockIndex, this.#pluginName, this.#pluginKey, documentId); + } + + /** + * Creates a deep copy + */ + public clone(): PluginDataIndex { + return new PluginDataIndex( + this.#blockIndex, + this.#pluginName, + this.#pluginKey, + this.#documentId + ); + } + + /** + * Serializes to JSON + */ + public serialize(): string { + return JSON.stringify({ + k: 'plugin', + b: this.#blockIndex, + plugin: this.#pluginName, + key: this.#pluginKey, + ...(this.#documentId !== undefined && { id: this.#documentId }), + }); + } +} diff --git a/packages/model-types/src/Index/TuneIndex.ts b/packages/model-types/src/Index/TuneIndex.ts deleted file mode 100644 index e9b0fbf3..00000000 --- a/packages/model-types/src/Index/TuneIndex.ts +++ /dev/null @@ -1,99 +0,0 @@ -import type { BlockTuneName } from '../BlockTune.js'; -import type { DocumentId } from '../indexing.js'; -import { IndexBase, IndexKind } from './IndexBase.js'; - -/** - * Index scoped to a block tune - */ -export class TuneIndex extends IndexBase { - readonly #blockIndex: number; - readonly #tuneName: BlockTuneName; - readonly #tuneKey: string; - readonly #documentId?: DocumentId; - - /** - * @param blockIndex - zero-based block position - * @param tuneName - name of the block tune - * @param tuneKey - key within the block tune - * @param documentId - optional document identifier - */ - constructor( - blockIndex: number, - tuneName: BlockTuneName, - tuneKey: string, - documentId?: DocumentId - ) { - super(IndexKind.Tune); - this.#blockIndex = blockIndex; - this.#tuneName = tuneName; - this.#tuneKey = tuneKey; - this.#documentId = documentId; - } - - /** - * The zero-based position of the indexed block - */ - public get blockIndex(): number { - return this.#blockIndex; - } - - /** - * The name of the indexed block tune - */ - public get tuneName(): BlockTuneName { - return this.#tuneName; - } - - /** - * The key within the indexed block tune - */ - public get tuneKey(): string { - return this.#tuneKey; - } - - /** - * The unique identifier of the indexed document - */ - public override get documentId(): DocumentId | undefined { - return this.#documentId; - } - - /** - * @param blockIndex - updated block position - */ - public override withBlockIndex(blockIndex: number): TuneIndex { - return new TuneIndex(blockIndex, this.#tuneName, this.#tuneKey, this.#documentId); - } - - /** - * @param documentId - updated document identifier - */ - public override withDocumentId(documentId: DocumentId): TuneIndex { - return new TuneIndex(this.#blockIndex, this.#tuneName, this.#tuneKey, documentId); - } - - /** - * Creates a deep copy - */ - public clone(): TuneIndex { - return new TuneIndex( - this.#blockIndex, - this.#tuneName, - this.#tuneKey, - this.#documentId - ); - } - - /** - * Serializes to JSON - */ - public serialize(): string { - return JSON.stringify({ - k: 'tune', - b: this.#blockIndex, - tune: this.#tuneName, - key: this.#tuneKey, - ...(this.#documentId !== undefined && { id: this.#documentId }), - }); - } -} diff --git a/packages/model-types/src/Index/index.ts b/packages/model-types/src/Index/index.ts index 30650d15..de70a166 100644 --- a/packages/model-types/src/Index/index.ts +++ b/packages/model-types/src/Index/index.ts @@ -2,20 +2,20 @@ export { IndexBase, IndexKind, type IndexFields, type TextSegment } from './Inde export { DocumentIndex } from './DocumentIndex.js'; export { PropertyIndex } from './PropertyIndex.js'; export { BlockIndex } from './BlockIndex.js'; -export { TuneIndex } from './TuneIndex.js'; +export { PluginDataIndex } from './PluginDataIndex.js'; export { DataIndex } from './DataIndex.js'; export { TextIndex } from './TextIndex.js'; export { PartialIndex } from './PartialIndex.js'; import { IndexBase, IndexKind, type TextSegment } from './IndexBase.js'; import type { DocumentId } from '../indexing.js'; -import type { BlockTuneName } from '../BlockTune.js'; +import type { PluginDataName } from '../PluginData.js'; import type { DataKey } from '../DataKey.js'; import type { TextRange } from '../Text.js'; import { DocumentIndex } from './DocumentIndex.js'; import { PropertyIndex } from './PropertyIndex.js'; import { BlockIndex } from './BlockIndex.js'; -import { TuneIndex } from './TuneIndex.js'; +import { PluginDataIndex } from './PluginDataIndex.js'; import { DataIndex } from './DataIndex.js'; import { TextIndex } from './TextIndex.js'; @@ -106,19 +106,19 @@ export abstract class Index extends IndexBase { } /** - * Creates a TuneIndex + * Creates a PluginDataIndex * @param blockIndex - zero-based block position - * @param tuneName - name of the block tune - * @param tuneKey - key within the block tune + * @param pluginName - name of the plugin owning the data + * @param pluginKey - key within the plugin's data * @param documentId - optional document identifier */ - public static tune( + public static pluginData( blockIndex: number, - tuneName: BlockTuneName, - tuneKey: string, + pluginName: PluginDataName, + pluginKey: string, documentId?: DocumentId - ): TuneIndex { - return new TuneIndex(blockIndex, tuneName, tuneKey, documentId); + ): PluginDataIndex { + return new PluginDataIndex(blockIndex, pluginName, pluginKey, documentId); } /** @@ -172,10 +172,10 @@ export abstract class Index extends IndexBase { obj.id as DocumentId | undefined ); - case 'tune': - return new TuneIndex( + case 'plugin': + return new PluginDataIndex( obj.b as number, - obj.tune as BlockTuneName, + obj.plugin as PluginDataName, obj.key as string, obj.id as DocumentId | undefined ); diff --git a/packages/model-types/src/PluginData.ts b/packages/model-types/src/PluginData.ts new file mode 100644 index 00000000..ba1c95ac --- /dev/null +++ b/packages/model-types/src/PluginData.ts @@ -0,0 +1,13 @@ +import type { Nominal } from './Nominal.js'; +import { create } from './Nominal.js'; + +/** Name a plugin's per-block data is stored under, by convention the plugin's `name` */ +export type PluginDataName = Nominal; + +/** Factory for PluginDataName */ +export const createPluginDataName = create(); + +/** Serialized per-block data of a single plugin */ +export interface PluginDataSerialized { + [key: string]: unknown; +} diff --git a/packages/model-types/src/events/PluginDataModifiedEvent.ts b/packages/model-types/src/events/PluginDataModifiedEvent.ts new file mode 100644 index 00000000..9f2362dd --- /dev/null +++ b/packages/model-types/src/events/PluginDataModifiedEvent.ts @@ -0,0 +1,20 @@ +import { EventAction } from '../EventAction.js'; +import { BaseDocumentEvent } from '../BaseDocumentEvent.js'; +import type { PluginDataIndex } from '../Index/PluginDataIndex.js'; +import type { PartialIndex } from '../Index/PartialIndex.js'; +import type { ModifiedEventData } from '../EventBus.js'; + +/** + * PluginDataModified Custom Event + */ +export class PluginDataModifiedEvent extends BaseDocumentEvent, PluginDataIndex> { + /** + * PluginDataModifiedEvent class constructor + * @param index - index of the modified plugin data key in the document + * @param data - event data with new and previous values + * @param userId - user identifier + */ + constructor(index: PluginDataIndex | PartialIndex, data: ModifiedEventData, userId: string | number) { + super(index, EventAction.Modified, data, userId); + } +} diff --git a/packages/model-types/src/events/TuneModifiedEvent.ts b/packages/model-types/src/events/TuneModifiedEvent.ts deleted file mode 100644 index 0e8b4e08..00000000 --- a/packages/model-types/src/events/TuneModifiedEvent.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { EventAction } from '../EventAction.js'; -import { BaseDocumentEvent } from '../BaseDocumentEvent.js'; -import type { TuneIndex } from '../Index/TuneIndex.js'; -import type { PartialIndex } from '../Index/PartialIndex.js'; -import type { ModifiedEventData } from '../EventBus.js'; - -/** - * TuneModified Custom Event - */ -export class TuneModifiedEvent extends BaseDocumentEvent, TuneIndex> { - /** - * TuneModifiedEvent class constructor - * @param index - index of the modified tune in the document - * @param data - event data with new and previous values - * @param userId - user identifier - */ - constructor(index: TuneIndex | PartialIndex, data: ModifiedEventData, userId: string | number) { - super(index, EventAction.Modified, data, userId); - } -} diff --git a/packages/model-types/src/events/index.ts b/packages/model-types/src/events/index.ts index a234ce00..db2493e4 100644 --- a/packages/model-types/src/events/index.ts +++ b/packages/model-types/src/events/index.ts @@ -11,4 +11,4 @@ export { CaretManagerCaretRemovedEvent } from './CaretManagerCaretRemovedEvent.j export { BlockAddedEvent } from './BlockAddedEvent.js'; export { BlockRemovedEvent } from './BlockRemovedEvent.js'; export { PropertyModifiedEvent } from './PropertyModifiedEvent.js'; -export { TuneModifiedEvent } from './TuneModifiedEvent.js'; +export { PluginDataModifiedEvent } from './PluginDataModifiedEvent.js'; diff --git a/packages/model-types/src/index.ts b/packages/model-types/src/index.ts index 84c7b4e6..4bfe30c2 100644 --- a/packages/model-types/src/index.ts +++ b/packages/model-types/src/index.ts @@ -11,10 +11,10 @@ export { createBlockToolName } from './BlockId.js'; export type { - BlockTuneName, - BlockTuneSerialized -} from './BlockTune.js'; -export { createBlockTuneName } from './BlockTune.js'; + PluginDataName, + PluginDataSerialized +} from './PluginData.js'; +export { createPluginDataName } from './PluginData.js'; export type { DataKey } from './DataKey.js'; export { createDataKey } from './DataKey.js'; export type { @@ -66,7 +66,7 @@ export type { BlockEvents, TextNodeEvents, ValueNodeEvents, - BlockTuneEvents, + PluginDataEvents, DocumentEvents, ModelEvents, CaretManagerEvents @@ -86,7 +86,7 @@ export { DocumentIndex, PropertyIndex, BlockIndex, - TuneIndex, + PluginDataIndex, DataIndex, TextIndex, PartialIndex, @@ -113,5 +113,5 @@ export { BlockAddedEvent, BlockRemovedEvent, PropertyModifiedEvent, - TuneModifiedEvent + PluginDataModifiedEvent } from './events/index.js'; diff --git a/packages/model/src/EditorJSModel.spec.ts b/packages/model/src/EditorJSModel.spec.ts index 3f579420..32df4b82 100644 --- a/packages/model/src/EditorJSModel.spec.ts +++ b/packages/model/src/EditorJSModel.spec.ts @@ -18,7 +18,7 @@ describe('EditorJSModel', () => { 'insertData', 'removeData', 'modifyData', - 'updateTuneData', + 'updatePluginData', 'updateValue', 'removeBlock', 'clearBlocks', diff --git a/packages/model/src/EditorJSModel.ts b/packages/model/src/EditorJSModel.ts index 8b9d7521..89ca8f67 100644 --- a/packages/model/src/EditorJSModel.ts +++ b/packages/model/src/EditorJSModel.ts @@ -349,17 +349,17 @@ export class EditorJSModel extends EventBus { } /** - * Updates BlockTune data associated with the BlockNode at the specified index. + * Updates one plugin's per-block data on the BlockNode at the specified index. * @param _userId - user identifier which is being set to the context - * @param parameters - updateTuneData method parameters + * @param parameters - updatePluginData method parameters * @param parameters.blockIndex - The index of the BlockNode to update - * @param parameters.tuneName - The name of the BlockTune to update - * @param parameters.data - The data to update the BlockTune with + * @param parameters.pluginName - Name the data is stored under, by convention the plugin's `name` + * @param parameters.data - Keys to merge into the plugin's data * @throws Error if the index is out of bounds */ @WithContext - public updateTuneData(_userId: string | number, ...parameters: Parameters): ReturnType { - return this.#document.updateTuneData(...parameters); + public updatePluginData(_userId: string | number, ...parameters: Parameters): ReturnType { + return this.#document.updatePluginData(...parameters); } /** diff --git a/packages/model/src/entities/BlockNode/BlockNode.integration.spec.ts b/packages/model/src/entities/BlockNode/BlockNode.integration.spec.ts index 81eb624c..569b7744 100644 --- a/packages/model/src/entities/BlockNode/BlockNode.integration.spec.ts +++ b/packages/model/src/entities/BlockNode/BlockNode.integration.spec.ts @@ -1,4 +1,4 @@ -import { BlockChildType, createInlineToolName, createDataKey } from '@editorjs/model-types'; +import { BlockChildType, createInlineToolName, createDataKey, createPluginDataName, EventType, PluginDataModifiedEvent } from '@editorjs/model-types'; import type { InlineFragment } from '@editorjs/model-types'; import { BlockNode } from './index.js'; import { NODE_TYPE_HIDDEN_PROP } from '@editorjs/model-types'; @@ -237,4 +237,99 @@ describe('BlockNode integration tests', () => { .toEqual(initData.key); }); }); + + describe('.updatePluginData() creating entries', () => { + it('should create the entry when the block has no data for that plugin', () => { + const blockNode = new BlockNode({ name: 'blockNode' }); + + blockNode.updatePluginData(createPluginDataName('anchors'), { id: 'intro' }); + + expect(blockNode.serialized.plugins) + .toEqual({ anchors: { id: 'intro' } }); + }); + + it('should emit an event with undefined previous value for the first write', () => { + const blockNode = new BlockNode({ name: 'blockNode' }); + let event: PluginDataModifiedEvent | null = null; + + blockNode.addEventListener(EventType.Changed, (e: Event): void => { + event = e as PluginDataModifiedEvent; + }); + + blockNode.updatePluginData(createPluginDataName('anchors'), { id: 'intro' }); + + expect(event) + .toBeInstanceOf(PluginDataModifiedEvent); + expect(event) + .toHaveProperty('detail.data', { + value: 'intro', + previous: undefined, + }); + }); + + it('should emit one event per changed key', () => { + const blockNode = new BlockNode({ name: 'blockNode' }); + const handler = jest.fn(); + + blockNode.addEventListener(EventType.Changed, handler); + + blockNode.updatePluginData(createPluginDataName('anchors'), { id: 'intro', + visible: true }); + + expect(handler) + .toHaveBeenCalledTimes(2); + }); + + it('should keep other keys when one key is updated', () => { + const blockNode = new BlockNode({ name: 'blockNode' }); + const pluginName = createPluginDataName('anchors'); + + blockNode.updatePluginData(pluginName, { id: 'intro', + visible: true }); + blockNode.updatePluginData(pluginName, { visible: false }); + + expect(blockNode.serialized.plugins) + .toEqual({ anchors: { id: 'intro', + visible: false } }); + }); + + it('should drop an entry from serialization once its last key is removed', () => { + const blockNode = new BlockNode({ name: 'blockNode' }); + const pluginName = createPluginDataName('anchors'); + + blockNode.updatePluginData(pluginName, { id: 'intro' }); + blockNode.updatePluginData(pluginName, { id: undefined }); + + expect(blockNode.serialized.plugins) + .toEqual({}); + }); + + it('should store data for a plugin named like an object prototype member', () => { + const blockNode = new BlockNode({ name: 'blockNode' }); + + blockNode.updatePluginData(createPluginDataName('__proto__'), { id: 'intro' }); + blockNode.updatePluginData(createPluginDataName('toString'), { id: 'other' }); + + expect(blockNode.serialized.plugins) + .toEqual({ '__proto__': { id: 'intro' }, + 'toString': { id: 'other' } }); + expect(Object.prototype) + .not.toHaveProperty('id'); + }); + + it('should round-trip a plugin named like an object prototype member through initialization', () => { + const blockNode = new BlockNode({ name: 'blockNode', + plugins: { '__proto__': { id: 'intro' } } }); + + expect(blockNode.serialized.plugins) + .toEqual({ '__proto__': { id: 'intro' } }); + }); + + it('should throw when the plugin data name is empty', () => { + const blockNode = new BlockNode({ name: 'blockNode' }); + + expect(() => blockNode.updatePluginData(createPluginDataName(''), { id: 'intro' })) + .toThrow('plugin data name must not be empty'); + }); + }); }); diff --git a/packages/model/src/entities/BlockNode/BlockNode.spec.ts b/packages/model/src/entities/BlockNode/BlockNode.spec.ts index 801ab728..6ec8095f 100644 --- a/packages/model/src/entities/BlockNode/BlockNode.spec.ts +++ b/packages/model/src/entities/BlockNode/BlockNode.spec.ts @@ -1,12 +1,13 @@ import { EventAction } from '@editorjs/model-types'; import { Index } from '@editorjs/model-types'; import { PartialIndex } from '@editorjs/model-types'; -import { createDataKey, createBlockId, createBlockToolName, createBlockTuneName } from '@editorjs/model-types'; +import { createDataKey, createBlockId, createBlockToolName, createPluginDataName } from '@editorjs/model-types'; import { BlockNode } from './index.js'; import { NonExistingKeyError } from './errors/NonExistingKeyError.js'; -import type { BlockTuneName, BlockTuneSerialized } from '@editorjs/model-types'; -import { BlockTune } from '../BlockTune/index.js'; +import type { PluginDataName, PluginDataSerialized } from '@editorjs/model-types'; +import { PluginDataNode } from '../PluginDataNode/index.js'; +import { runWithContext } from '../../utils/Context.js'; import { ValueNode } from '../ValueNode/index.js'; import type { EditorDocument } from '../EditorDocument/index.js'; @@ -17,7 +18,7 @@ import type { InlineFragment, TextNodeSerialized, BlockNodeDataSerialized } from import { TextNode } from '../inline-fragments/index.js'; import type { BlockNodeData } from './types/index.js'; import { NODE_TYPE_HIDDEN_PROP } from '@editorjs/model-types'; -import { TextAddedEvent, TuneModifiedEvent, ValueModifiedEvent } from '@editorjs/model-types'; +import { TextAddedEvent, PluginDataModifiedEvent, ValueModifiedEvent } from '@editorjs/model-types'; import { EventType } from '@editorjs/model-types'; import { get } from '@editorjs/model-types'; import { AlreadyExistingKeyError } from './errors/AlreadyExistingKeyError.js'; @@ -29,17 +30,17 @@ const ValueNodeProto = ValueNode.prototype as unknown as { update: () => void; }; -jest.mock('../BlockTune'); +jest.mock('../PluginDataNode'); jest.mock('../inline-fragments/TextNode'); jest.mock('../ValueNode'); -const createBlockNodeWithData = (data: BlockNodeDataSerialized, tunes: Record = {}): BlockNode => { +const createBlockNodeWithData = (data: BlockNodeDataSerialized, plugins: Record = {}): BlockNode => { return new BlockNode({ name: createBlockToolName('header'), data, - tunes, + plugins, }); }; @@ -116,31 +117,31 @@ describe('BlockNode', () => { .toEqual(blockNodeName); }); - it('should call .serialized getter of all tunes associated with the BlockNode', () => { - const blockTunesNames = [ - 'align' as BlockTuneName, - 'font-size' as BlockTuneName, - 'font-weight' as BlockTuneName, + it('should call .serialized getter of all plugin data nodes associated with the BlockNode', () => { + const pluginNames = [ + 'align' as PluginDataName, + 'font-size' as PluginDataName, + 'font-weight' as PluginDataName, ]; - const blockTunes = blockTunesNames.reduce((acc, name) => ({ + const pluginsDataMap = pluginNames.reduce((acc, name) => ({ ...acc, [name]: {}, }), {}); - const spy = jest.spyOn(BlockTune.prototype, 'serialized', 'get'); + const spy = jest.spyOn(PluginDataNode.prototype, 'serialized', 'get'); const blockNode = new BlockNode({ name: createBlockToolName('paragraph'), data: {}, parent: {} as EditorDocument, - tunes: blockTunes, + plugins: pluginsDataMap, }); blockNode.serialized; expect(spy) - .toHaveBeenCalledTimes(blockTunesNames.length); + .toHaveBeenCalledTimes(pluginNames.length); }); it('should call .serialized getter of all child ValueNodes associated with the BlockNode', () => { @@ -434,15 +435,15 @@ describe('BlockNode', () => { }); }); - describe('.tunes', () => { - it('should return an object with tunes associated with the BlockNode', () => { - const blockTunesNames = [ - 'align' as BlockTuneName, - 'font-size' as BlockTuneName, - 'font-weight' as BlockTuneName, + describe('.plugins', () => { + it('should return an object with plugin data nodes associated with the BlockNode', () => { + const pluginNames = [ + 'align' as PluginDataName, + 'font-size' as PluginDataName, + 'font-weight' as PluginDataName, ]; - const blockTunes = blockTunesNames.reduce((acc, name) => ({ + const pluginsDataMap = pluginNames.reduce((acc, name) => ({ ...acc, [name]: {}, }), {}); @@ -451,16 +452,16 @@ describe('BlockNode', () => { name: createBlockToolName('paragraph'), data: {}, parent: {} as EditorDocument, - tunes: blockTunes, + plugins: pluginsDataMap, }); - const tunes = Object.entries(blockNode.tunes); + const pluginsData = Object.entries(blockNode.plugins); - tunes.forEach(([name, tune]) => { + pluginsData.forEach(([name, pluginData]) => { expect(name) - .toEqual(createBlockTuneName(name)); - expect(tune) - .toBeInstanceOf(BlockTune); + .toEqual(createPluginDataName(name)); + expect(pluginData) + .toBeInstanceOf(PluginDataNode); }); }); }); @@ -853,20 +854,20 @@ describe('BlockNode', () => { }); }); - describe('.updateTuneData()', () => { + describe('.updatePluginData()', () => { afterEach(() => { jest.clearAllMocks(); }); - it('should call .update() method of the BlockTune', () => { - const blockTuneName = 'align' as BlockTuneName; + it('should call .update() method of the PluginDataNode', () => { + const pluginDataName = 'align' as PluginDataName; const blockNode = new BlockNode({ name: createBlockToolName('paragraph'), data: {}, parent: {} as EditorDocument, - tunes: { - [blockTuneName]: {}, + plugins: { + [pluginDataName]: {}, }, }); @@ -876,9 +877,9 @@ describe('BlockNode', () => { [dataKey]: dataValue, }; - const spy = jest.spyOn(BlockTune.prototype, 'update'); + const spy = jest.spyOn(PluginDataNode.prototype, 'update'); - blockNode.updateTuneData(blockTuneName, data); + blockNode.updatePluginData(pluginDataName, data); expect(spy) .toHaveBeenCalledWith(dataKey, dataValue); @@ -1703,7 +1704,7 @@ describe('BlockNode', () => { })); }); - it('should not emit Changed event if ValueNode dispatched event that is not a BaseDocumentEvent', () => { + it('should not emit Changed event if PluginDataNode dispatched event that is not a BaseDocumentEvent', () => { const handler = jest.fn(); node.addEventListener(EventType.Changed, handler); @@ -1716,10 +1717,10 @@ describe('BlockNode', () => { }); }); - describe('working with BlockTune events', () => { + describe('working with PluginDataNode events', () => { let node: BlockNode; - let tune: BlockTune; - const tuneName = createBlockTuneName('tune'); + let pluginData: PluginDataNode; + const pluginName = createPluginDataName('anchors'); const key = 'key'; const value = 'value'; const newValue = 'new-value'; @@ -1728,49 +1729,75 @@ describe('BlockNode', () => { node = createBlockNodeWithData( {}, { - [tuneName]: { [key]: value }, + [pluginName]: { [key]: value }, } ); - tune = node.tunes[tuneName]; + pluginData = node.plugins[pluginName]; }); - it('should re-emit event from the BlockTune adding index in Block', () => { - let event: TuneModifiedEvent | null = null; + it('should re-emit event from the PluginDataNode adding index in Block', () => { + let event: PluginDataModifiedEvent | null = null; const handler = (e: Event): void => { - event = e as TuneModifiedEvent; + event = e as PluginDataModifiedEvent; }; node.addEventListener(EventType.Changed, handler); - tune.dispatchEvent( - new TuneModifiedEvent( - new PartialIndex({ tuneKey: key }), - { - value: newValue, - previous: value, - }, - 'user' - ) - ); + runWithContext('editor-user', () => { + pluginData.dispatchEvent( + new PluginDataModifiedEvent( + new PartialIndex({ pluginKey: key }), + { + value: newValue, + previous: value, + }, + 'editor-user' + ) + ); + }); expect(event) - .toBeInstanceOf(TuneModifiedEvent); + .toBeInstanceOf(PluginDataModifiedEvent); expect(event) .toHaveProperty('detail.index', expect.objectContaining({ - tuneKey: key, - tuneName: tuneName, + pluginKey: key, + pluginName: pluginName, })); expect(event) - .toHaveProperty('detail.userId', 'user'); + .toHaveProperty('detail.userId', 'editor-user'); + }); + + it('should re-emit the event with the acting user from the context, not a placeholder', () => { + let event: PluginDataModifiedEvent | null = null; + + node.addEventListener(EventType.Changed, (e: Event): void => { + event = e as PluginDataModifiedEvent; + }); + + runWithContext('another-user', () => { + pluginData.dispatchEvent( + new PluginDataModifiedEvent( + new PartialIndex({ pluginKey: key }), + { + value: newValue, + previous: value, + }, + 'another-user' + ) + ); + }); + + expect(event) + .toHaveProperty('detail.userId', 'another-user'); }); - it('should not emit Changed event if ValueNode dispatched event that is not a BaseDocumentEvent', () => { + it('should not emit Changed event if PluginDataNode dispatched event that is not a BaseDocumentEvent', () => { const handler = jest.fn(); node.addEventListener(EventType.Changed, handler); - tune.dispatchEvent(new Event(EventType.Changed)); + pluginData.dispatchEvent(new Event(EventType.Changed)); expect(handler) .not diff --git a/packages/model/src/entities/BlockNode/__mocks__/index.ts b/packages/model/src/entities/BlockNode/__mocks__/index.ts index 1a62e21f..645017e0 100644 --- a/packages/model/src/entities/BlockNode/__mocks__/index.ts +++ b/packages/model/src/entities/BlockNode/__mocks__/index.ts @@ -62,7 +62,7 @@ export class BlockNode extends EventBus { /** * Mock method */ - public updateTuneData(): void { + public updatePluginData(): void { return; } diff --git a/packages/model/src/entities/BlockNode/index.ts b/packages/model/src/entities/BlockNode/index.ts index 47e434bb..da763926 100644 --- a/packages/model/src/entities/BlockNode/index.ts +++ b/packages/model/src/entities/BlockNode/index.ts @@ -1,6 +1,6 @@ import { getContext } from '../../utils/Context.js'; import type { EditorDocument } from '../EditorDocument/index.js'; -import { BlockTune } from '../BlockTune/index.js'; +import { PluginDataNode } from '../PluginDataNode/index.js'; import { InvalidNodeTypeError } from './errors/InvalidNodeTypeError.js'; import { NonExistingKeyError } from './errors/NonExistingKeyError.js'; import type { @@ -19,7 +19,7 @@ import { createBlockId, generateBlockId, createBlockToolName, - createBlockTuneName, + createPluginDataName, get, has, set, @@ -31,8 +31,8 @@ import { type DataKey, type BlockId, type BlockToolName, - type BlockTuneName, - type BlockTuneSerialized, + type PluginDataName, + type PluginDataSerialized, type BlockNodeDataSerialized, type BlockNodeDataSerializedValue, type BlockNodeSerialized, @@ -46,7 +46,7 @@ import type { DeepReadonly } from '../../utils/DeepReadonly.js'; import { DataNodeRemovedEvent, DataNodeAddedEvent, - TuneModifiedEvent, + PluginDataModifiedEvent, ValueModifiedEvent } from '@editorjs/model-types'; import type { Constructor } from '../../utils/types.js'; @@ -55,7 +55,7 @@ import { AlreadyExistingKeyError } from './errors/AlreadyExistingKeyError.js'; /** * BlockNode class represents a node in a tree-like structure used to store and manipulate Blocks in an editor document. * A BlockNode can contain one or more child nodes of type TextNode or ValueNode. - * It can also be associated with one or more BlockTunes, which can modify the behavior of the BlockNode. + * It can also carry per-plugin data, which plugins use to store their own state for the block. */ export class BlockNode extends EventBus { /** @@ -79,9 +79,13 @@ export class BlockNode extends EventBus { #parent: EditorDocument | null; /** - * Private field representing the BlockTunes associated with the BlockNode + * Per-plugin data of this block, keyed by plugin name. + * + * The record has a null prototype: names come from documents, and a plain assignment of a + * `__proto__` key to an ordinary object creates no own property at all, which would silently + * lose that plugin's data. With no prototype every name is stored as plain data. */ - #tunes: Record; + #plugins: Record = Object.create(null) as Record; /** * Constructor for BlockNode class. @@ -90,33 +94,23 @@ export class BlockNode extends EventBus { * @param args.name - The name of the BlockNode. * @param [args.data] - The content of the BlockNode. * @param [args.parent] - The parent EditorDocument of the BlockNode. - * @param [args.tunes] - The BlockTunes associated with the BlockNode. + * @param [args.plugins] - Per-plugin data associated with the BlockNode. */ constructor({ id, name, data = {}, parent, - tunes = {}, + plugins = {}, }: BlockNodeConstructorParameters) { super(); this.#id = id !== undefined ? createBlockId(id) : generateBlockId(); this.#name = createBlockToolName(name); this.#parent = parent ?? null; - this.#tunes = mapObject( - tunes, - (tuneData: BlockTuneSerialized, tuneName: string) => { - const tune = new BlockTune({ - name: createBlockTuneName(tuneName), - data: tuneData, - }); - - this.#listenAndBubbleTuneEvent(tune, tuneName as BlockTuneName); - - return tune; - } - ); + Object.entries(plugins).forEach(([pluginName, pluginData]) => { + this.#createPluginDataNode(createPluginDataName(pluginName), pluginData); + }); this.#initialize(data); } @@ -150,10 +144,10 @@ export class BlockNode extends EventBus { } /** - * Getter to access BlockNode tunes + * Getter to access the block's per-plugin data nodes */ - public get tunes(): Readonly> { - return this.#tunes; + public get plugins(): Readonly> { + return this.#plugins; } /** @@ -165,16 +159,21 @@ export class BlockNode extends EventBus { entry => this.#serializeData(entry) ); - const serializedTunes = mapObject( - this.#tunes, - tune => tune.serialized - ); + const serializedPlugins: Record = {}; + + Object.entries(this.#plugins).forEach(([pluginName, pluginData]) => { + if (pluginData.isEmpty) { + return; + } + + serializedPlugins[pluginName] = pluginData.serialized; + }); return { id: this.#id, name: this.#name, data: serializedData, - tunes: serializedTunes, + plugins: serializedPlugins, }; } @@ -256,14 +255,21 @@ export class BlockNode extends EventBus { } /** - * Updates data in the BlockTune by the BlockTuneName - * @param tuneName - The name of the BlockTune - * @param data - The data to update the BlockTune with + * Updates one plugin's per-block data, creating the plugin's entry when the block has none yet. + * Each key is applied separately, so each change is emitted as its own event. + * @param pluginName - Name the data is stored under, by convention the plugin's `name` + * @param data - Keys to merge into the plugin's data; a key set to `undefined` is removed */ - public updateTuneData(tuneName: BlockTuneName, data: Record): void { + public updatePluginData(pluginName: PluginDataName, data: Record): void { + if (pluginName.length === 0) { + throw new Error('BlockNode: plugin data name must not be empty'); + } + + const pluginData = this.#plugins[pluginName] ?? this.#createPluginDataNode(pluginName); + Object.entries(data) .forEach(([key, value]) => { - this.#tunes[tuneName].update(key, value); + pluginData.update(key, value); }); } @@ -585,27 +591,50 @@ export class BlockNode extends EventBus { } /** - * Listens to BlockTune events and bubbles them to the BlockNode - * @param tune - BlockTune to listen to - * @param name - BlockTune name in the BlockNode data + * Creates a PluginDataNode for the passed name and starts bubbling its events. + * + * The node is created empty even when initial data is passed, and the listener is attached + * before any value is set, because PluginDataNode dispatches synchronously: attaching later + * would drop the events of the very first write. + * @param name - Name the data is stored under + * @param data - Initial data, applied after the listener is attached + */ + #createPluginDataNode(name: PluginDataName, data?: PluginDataSerialized): PluginDataNode { + const pluginData = new PluginDataNode({ name }); + + this.#listenAndBubblePluginDataEvent(pluginData, name); + + this.#plugins[name] = pluginData; + + if (data !== undefined) { + Object.entries(data).forEach(([key, value]) => pluginData.update(key, value)); + } + + return pluginData; + } + + /** + * Listens to PluginDataNode events and bubbles them to the BlockNode + * @param pluginData - PluginDataNode to listen to + * @param name - Name the data is stored under */ - #listenAndBubbleTuneEvent(tune: BlockTune, name: BlockTuneName): void { - tune.addEventListener( + #listenAndBubblePluginDataEvent(pluginData: PluginDataNode, name: PluginDataName): void { + pluginData.addEventListener( EventType.Changed, (event: Event): void => { if (!(event instanceof BaseDocumentEvent)) { // Stryker disable next-line StringLiteral - console.error('BlockNode: BlockTune should only emit BaseDocumentEvent'); + console.error('BlockNode: PluginDataNode should only emit BaseDocumentEvent'); return; } this.dispatchEvent( - new TuneModifiedEvent( - new PartialIndex({ tuneKey: (event.detail.index as PartialIndex).tuneKey, - tuneName: name }), + new PluginDataModifiedEvent( + new PartialIndex({ pluginKey: (event.detail.index as PartialIndex).pluginKey, + pluginName: name }), event.detail.data, - 'user' + getContext()! ) ); } diff --git a/packages/model/src/entities/BlockNode/types/BlockNodeConstructorParameters.ts b/packages/model/src/entities/BlockNode/types/BlockNodeConstructorParameters.ts index df7d6431..6abd42be 100644 --- a/packages/model/src/entities/BlockNode/types/BlockNodeConstructorParameters.ts +++ b/packages/model/src/entities/BlockNode/types/BlockNodeConstructorParameters.ts @@ -1,5 +1,5 @@ import type { EditorDocument } from '../../EditorDocument/index.js'; -import type { BlockId, BlockNodeDataSerialized, BlockTuneSerialized } from '@editorjs/model-types'; +import type { BlockId, BlockNodeDataSerialized, PluginDataSerialized } from '@editorjs/model-types'; export interface BlockNodeConstructorParameters { /** @@ -24,7 +24,7 @@ export interface BlockNodeConstructorParameters { parent?: EditorDocument; /** - * The BlockTunes associated with the BlockNode + * Per-plugin data associated with the BlockNode, keyed by plugin name */ - tunes?: Record; + plugins?: Record; } diff --git a/packages/model/src/entities/BlockTune/BlockTune.spec.ts b/packages/model/src/entities/BlockTune/BlockTune.spec.ts deleted file mode 100644 index 22366d7d..00000000 --- a/packages/model/src/entities/BlockTune/BlockTune.spec.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { BlockTune } from './index.js'; -import { createBlockTuneName, EventType } from '@editorjs/model-types'; -import { TuneModifiedEvent } from '@editorjs/model-types'; -import { EventAction } from '@editorjs/model-types'; - -describe('BlockTune', () => { - const tuneName = createBlockTuneName('alignment'); - - describe('constructor', () => { - it('should have empty object as default data value', () => { - const blockTune = new BlockTune({ name: tuneName }); - - expect(blockTune.serialized) - .toEqual({}); - }); - }); - - describe('.update()', () => { - it('should add field to data object by key if it doesn\'t exist', () => { - // Arrange - const blockTune = new BlockTune({ - name: tuneName, - data: {}, - }); - - // Act - blockTune.update('align', 'left'); - - // Assert - expect(blockTune.serialized) - .toEqual({ - align: 'left', - }); - }); - - it('should update field in data object by key', () => { - // Arrange - const blockTune = new BlockTune({ - name: tuneName, - data: { - align: 'center', - }, - }); - - // Act - blockTune.update('align', 'right'); - - // Assert - expect(blockTune.serialized) - .toEqual({ - align: 'right', - }); - }); - - it('should emit TuneModifiedEvent with the new and previous values in details and tune name in index', () => { - const name = 'align'; - const value = 'center'; - const blockTune = new BlockTune({ - name: tuneName, - data: { - [name]: value, - }, - }); - const updatedValue = 'right'; - - let event: TuneModifiedEvent | null = null; - - blockTune.addEventListener(EventType.Changed, e => event = e as TuneModifiedEvent); - - blockTune.update(name, updatedValue); - - expect(event).toBeInstanceOf(TuneModifiedEvent); - expect(event).toHaveProperty('detail', expect.objectContaining({ - action: EventAction.Modified, - index: expect.objectContaining({ tuneKey: name }), - data: { - value: updatedValue, - previous: value, - }, - })); - }); - }); - - describe('.serialized', () => { - it('should return serialized version of the BlockTune', () => { - // Arrange - const tune = new BlockTune({ - name: tuneName, - data: { - background: 'transparent', - }, - }); - - // Act - const tuneSerialized = tune.serialized; - - // Assert - expect(tuneSerialized) - .toEqual( - { - background: 'transparent', - } - ); - }); - }); -}); diff --git a/packages/model/src/entities/BlockTune/__mocks__/index.ts b/packages/model/src/entities/BlockTune/__mocks__/index.ts deleted file mode 100644 index 03f21052..00000000 --- a/packages/model/src/entities/BlockTune/__mocks__/index.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { createBlockTuneName, EventBus } from '@editorjs/model-types'; - -/** - * Mock for BlockTune class - */ -export class BlockTune extends EventBus { - /** - * Mock getter - */ - public get serialized(): object { - return {}; - } - - /** - * Mock method - */ - public update(): void { - return; - } -} - -export { createBlockTuneName }; diff --git a/packages/model/src/entities/BlockTune/index.ts b/packages/model/src/entities/BlockTune/index.ts deleted file mode 100644 index 7f6267d3..00000000 --- a/packages/model/src/entities/BlockTune/index.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { getContext } from '../../utils/Context.js'; -import type { BlockTuneConstructorParameters } from './types/index.js'; -import { - PartialIndex, - type BlockTuneSerialized, - type BlockTuneName, - EventBus, - TuneModifiedEvent -} from '@editorjs/model-types'; - -/** - * BlockTune class represents a set of additional information associated with a BlockNode. - * This information can be used by a BlockTool to modify the behavior of the BlockNode. - */ -export class BlockTune extends EventBus { - /** - * Private field representing the name of the tune - */ - #name: BlockTuneName; - - /** - * Private field representing any additional data associated with the tune - */ - #data: Record; - - /** - * Constructor for BlockTune class. - * @param args - BlockTune constructor arguments. - * @param args.name - The name of the tune. - * @param args.data - Any additional data associated with the tune. - */ - constructor({ name, data = {} }: BlockTuneConstructorParameters) { - super(); - - this.#name = name; - this.#data = data; - } - - /** - * Updates data associated with the tune. - * @param key - The key of the data to update - * @param value - The value to update the data with - */ - public update(key: string, value: unknown): void { - const previousValue = this.#data[key]; - - this.#data[key] = value; - - this.dispatchEvent( - new TuneModifiedEvent(new PartialIndex({ tuneKey: key }), { - value: this.#data[key], - previous: previousValue, - }, getContext()!) - ); - } - - /** - * Returns serialized version of the BlockTune. - */ - public get serialized(): BlockTuneSerialized { - return this.#data; - } -} diff --git a/packages/model/src/entities/BlockTune/types/BlockTuneConstructorParameters.ts b/packages/model/src/entities/BlockTune/types/BlockTuneConstructorParameters.ts deleted file mode 100644 index b0a1719b..00000000 --- a/packages/model/src/entities/BlockTune/types/BlockTuneConstructorParameters.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { BlockTuneName, BlockTuneSerialized } from '@editorjs/model-types'; - -export interface BlockTuneConstructorParameters { - /** - * The name of the tune - */ - name: BlockTuneName; - - /** - * Any additional data associated with the tune - */ - data?: BlockTuneSerialized; -} diff --git a/packages/model/src/entities/BlockTune/types/index.ts b/packages/model/src/entities/BlockTune/types/index.ts deleted file mode 100644 index a73ede9c..00000000 --- a/packages/model/src/entities/BlockTune/types/index.ts +++ /dev/null @@ -1 +0,0 @@ -export type { BlockTuneConstructorParameters } from './BlockTuneConstructorParameters.js'; diff --git a/packages/model/src/entities/EditorDocument/EditorDocument.spec.ts b/packages/model/src/entities/EditorDocument/EditorDocument.spec.ts index cc535305..055b3434 100644 --- a/packages/model/src/entities/EditorDocument/EditorDocument.spec.ts +++ b/packages/model/src/entities/EditorDocument/EditorDocument.spec.ts @@ -1,13 +1,13 @@ import { Index, PartialIndex } from '@editorjs/model-types'; import { EditorDocument } from './index.js'; -import { createBlockId, type DataKey, type InlineToolData, type InlineToolName, type BlockToolName, type BlockTuneName } from '@editorjs/model-types'; +import { createBlockId, type DataKey, type InlineToolData, type InlineToolName, type BlockToolName, type PluginDataName } from '@editorjs/model-types'; import { BlockNode } from '../BlockNode/index.js'; import { EventType } from '@editorjs/model-types'; import { BlockAddedEvent, BlockRemovedEvent, PropertyModifiedEvent, - TuneModifiedEvent + PluginDataModifiedEvent } from '@editorjs/model-types'; import { EventAction } from '@editorjs/model-types'; import { describe, jest } from '@jest/globals'; @@ -68,7 +68,7 @@ describe('EditorDocument', () => { fragments: [], }, }, - tunes: {}, + plugins: {}, }]; doc.initialize({ blocks }); @@ -127,7 +127,7 @@ describe('EditorDocument', () => { fragments: [], }, }, - tunes: {}, + plugins: {}, }]; doc.initialize({ blocks }); @@ -1097,12 +1097,12 @@ describe('EditorDocument', () => { }); }); - describe('.updateTuneData()', () => { + describe('.updatePluginData()', () => { beforeEach(() => { jest.clearAllMocks(); }); - it('should call .updateTuneData() method of the BlockNode at the specific index', () => { + it('should call .updatePluginData() method of the BlockNode at the specific index', () => { const blocksData = [ { name: 'header' as BlockToolName, @@ -1127,25 +1127,25 @@ describe('EditorDocument', () => { const blockNode = document.getBlock(i); jest - .spyOn(blockNode, 'updateTuneData') + .spyOn(blockNode, 'updatePluginData') // eslint-disable-next-line @typescript-eslint/no-empty-function -- mock of the method .mockImplementation(() => { }); }); const blockIndexToUpdate = 1; - const tuneName = 'blockFormatting' as BlockTuneName; + const pluginName = 'blockFormatting' as PluginDataName; const updateData = { align: 'right', }; - document.updateTuneData(blockIndexToUpdate, tuneName, updateData); + document.updatePluginData(blockIndexToUpdate, pluginName, updateData); - expect(document.getBlock(blockIndexToUpdate).updateTuneData) - .toHaveBeenCalledWith(tuneName, updateData); + expect(document.getBlock(blockIndexToUpdate).updatePluginData) + .toHaveBeenCalledWith(pluginName, updateData); }); - it('should not call .updateTuneData() method of other BlockNodes', () => { + it('should not call .updatePluginData() method of other BlockNodes', () => { const blocksData = [ { name: 'header' as BlockToolName, @@ -1170,7 +1170,7 @@ describe('EditorDocument', () => { const blockNode = document.getBlock(i); jest - .spyOn(blockNode, 'updateTuneData') + .spyOn(blockNode, 'updatePluginData') // eslint-disable-next-line @typescript-eslint/no-empty-function -- mock of the method .mockImplementation(() => { }); @@ -1179,19 +1179,19 @@ describe('EditorDocument', () => { }); const blockIndexToUpdate = 1; - const tuneName = 'blockFormatting' as BlockTuneName; + const pluginName = 'blockFormatting' as PluginDataName; const updateData = { align: 'right', }; - document.updateTuneData(blockIndexToUpdate, tuneName, updateData); + document.updatePluginData(blockIndexToUpdate, pluginName, updateData); blockNodes.forEach((blockNode, index) => { if (index === blockIndexToUpdate) { return; } - expect(blockNode.updateTuneData) + expect(blockNode.updatePluginData) .not .toHaveBeenCalled(); }); @@ -1202,12 +1202,12 @@ describe('EditorDocument', () => { identifier: 'document', }); const blockIndexOutOfBound = document.length + 1; - const tuneName = 'blockFormatting' as BlockTuneName; + const pluginName = 'blockFormatting' as PluginDataName; const updateData = { align: 'right', }; - const action = (): void => document.updateTuneData(blockIndexOutOfBound, tuneName, updateData); + const action = (): void => document.updatePluginData(blockIndexOutOfBound, pluginName, updateData); expect(action) .toThrow('Index out of bounds'); @@ -1707,11 +1707,11 @@ describe('EditorDocument', () => { document.addEventListener(EventType.Changed, handler); - const partial = new PartialIndex({ tuneKey: 'value', - tuneName: 'tune' as BlockTuneName }); + const partial = new PartialIndex({ pluginKey: 'value', + pluginName: 'anchors' as PluginDataName }); blockNode.dispatchEvent( - new TuneModifiedEvent( + new PluginDataModifiedEvent( partial, { value: 'value', @@ -1722,22 +1722,22 @@ describe('EditorDocument', () => { ); expect(handler) - .toHaveBeenCalledWith(expect.any(TuneModifiedEvent)); + .toHaveBeenCalledWith(expect.any(PluginDataModifiedEvent)); }); it('should re-emit events from the BlockNode with updated index', () => { - let event: TuneModifiedEvent | null = null; + let event: PluginDataModifiedEvent | null = null; const handler = (e: Event): void => { - event = e as TuneModifiedEvent; + event = e as PluginDataModifiedEvent; }; document.addEventListener(EventType.Changed, handler); - const partial = new PartialIndex({ tuneKey: 'value', - tuneName: 'tune' as BlockTuneName }); + const partial = new PartialIndex({ pluginKey: 'value', + pluginName: 'anchors' as PluginDataName }); blockNode.dispatchEvent( - new TuneModifiedEvent( + new PluginDataModifiedEvent( partial, { value: 'value', @@ -1749,8 +1749,8 @@ describe('EditorDocument', () => { expect(event) .toHaveProperty('detail.index', expect.objectContaining({ - tuneKey: 'value', - tuneName: 'tune', + pluginKey: 'value', + pluginName: 'anchors', blockIndex: index, })); }); diff --git a/packages/model/src/entities/EditorDocument/index.ts b/packages/model/src/entities/EditorDocument/index.ts index 62140506..c334eeb4 100644 --- a/packages/model/src/entities/EditorDocument/index.ts +++ b/packages/model/src/entities/EditorDocument/index.ts @@ -6,6 +6,7 @@ import { BlockIndex, DataIndex, TextIndex, + PluginDataIndex, type PartialIndex, EventBus, EventType, @@ -16,11 +17,11 @@ import { type Properties, type InlineToolData, type InlineToolName, - type BlockTuneEvents, + type PluginDataEvents, type TextNodeEvents, type ValueNodeEvents, type EditorDocumentSerialized, - type BlockTuneName, + type PluginDataName, type BlockNodeDataSerializedValue, type BlockNodeSerialized, type BlockNodeInit @@ -330,18 +331,18 @@ export class EditorDocument extends EventBus { } /** - * Updates BlockTune data associated with the BlockNode at the specified index or id. + * Updates one plugin's per-block data on the BlockNode at the specified index or id. * @param blockIndexOrId - The index or block id of the BlockNode to update - * @param tuneName - The name of the BlockTune to update - * @param data - The data to update the BlockTune with + * @param pluginName - Name the data is stored under, by convention the plugin's `name` + * @param data - Keys to merge into the plugin's data * @throws Error if the index is out of bounds */ - public updateTuneData(blockIndexOrId: BlockIndexOrId, tuneName: BlockTuneName, data: Record): void { + public updatePluginData(blockIndexOrId: BlockIndexOrId, pluginName: PluginDataName, data: Record): void { const resolvedIndex = this.resolveBlockIndex(blockIndexOrId); this.#checkIndexOutOfBounds(resolvedIndex, this.length - 1); - this.#children[resolvedIndex].updateTuneData(tuneName, data); + this.#children[resolvedIndex].updatePluginData(pluginName, data); } /** @@ -518,6 +519,10 @@ export class EditorDocument extends EventBus { this.unformat(index.blockIndex!, index.dataKey!, (data.previous as TextUnformattedEventData).tool, index.textRange![0], index.textRange![1]); } } + if (index instanceof PluginDataIndex) { + this.updatePluginData(index.blockIndex, index.pluginName, { [index.pluginKey]: data.value }); + } + /** * @todo implement other actions */ @@ -571,7 +576,7 @@ export class EditorDocument extends EventBus { .resolve(); this.dispatchEvent( - new (event.constructor as Constructor)( + new (event.constructor as Constructor)( completeIndex, event.detail.data ) diff --git a/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts b/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts new file mode 100644 index 00000000..ccc9a9ab --- /dev/null +++ b/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts @@ -0,0 +1,160 @@ +import { PluginDataNode } from './index.js'; +import { createPluginDataName, EventType } from '@editorjs/model-types'; +import { PluginDataModifiedEvent } from '@editorjs/model-types'; +import { EventAction } from '@editorjs/model-types'; + +describe('PluginDataNode', () => { + const pluginName = createPluginDataName('alignment'); + + describe('constructor', () => { + it('should have empty object as default data value', () => { + const pluginData = new PluginDataNode({ name: pluginName }); + + expect(pluginData.serialized) + .toEqual({}); + }); + }); + + describe('.update()', () => { + it('should add field to data object by key if it doesn\'t exist', () => { + // Arrange + const pluginData = new PluginDataNode({ + name: pluginName, + data: {}, + }); + + // Act + pluginData.update('align', 'left'); + + // Assert + expect(pluginData.serialized) + .toEqual({ + align: 'left', + }); + }); + + it('should update field in data object by key', () => { + // Arrange + const pluginData = new PluginDataNode({ + name: pluginName, + data: { + align: 'center', + }, + }); + + // Act + pluginData.update('align', 'right'); + + // Assert + expect(pluginData.serialized) + .toEqual({ + align: 'right', + }); + }); + + it('should emit PluginDataModifiedEvent with the new and previous values in details and plugin key in index', () => { + const name = 'align'; + const value = 'center'; + const pluginData = new PluginDataNode({ + name: pluginName, + data: { + [name]: value, + }, + }); + const updatedValue = 'right'; + + let event: PluginDataModifiedEvent | null = null; + + pluginData.addEventListener(EventType.Changed, e => event = e as PluginDataModifiedEvent); + + pluginData.update(name, updatedValue); + + expect(event).toBeInstanceOf(PluginDataModifiedEvent); + expect(event).toHaveProperty('detail', expect.objectContaining({ + action: EventAction.Modified, + index: expect.objectContaining({ pluginKey: name }), + data: { + value: updatedValue, + previous: value, + }, + })); + }); + + it('should remove the key when the value is undefined', () => { + const pluginData = new PluginDataNode({ + name: pluginName, + data: { + align: 'left', + visible: true, + }, + }); + + pluginData.update('align', undefined); + + expect(pluginData.serialized).toEqual({ visible: true }); + }); + + it('should emit the previous value when a key is removed', () => { + const pluginData = new PluginDataNode({ + name: pluginName, + data: { align: 'left' }, + }); + + let event: PluginDataModifiedEvent | null = null; + + pluginData.addEventListener(EventType.Changed, e => event = e as PluginDataModifiedEvent); + + pluginData.update('align', undefined); + + expect(event).toHaveProperty('detail', expect.objectContaining({ + data: { + value: undefined, + previous: 'left', + }, + })); + }); + }); + + describe('.isEmpty', () => { + it('should be true when the node holds no keys', () => { + expect(new PluginDataNode({ name: pluginName }).isEmpty).toBe(true); + }); + + it('should be false when the node holds a key', () => { + expect(new PluginDataNode({ name: pluginName, + data: { align: 'left' } }).isEmpty).toBe(false); + }); + + it('should become true again once every key is removed', () => { + const pluginData = new PluginDataNode({ name: pluginName, + data: { align: 'left' } }); + + pluginData.update('align', undefined); + + expect(pluginData.isEmpty).toBe(true); + }); + }); + + describe('.serialized', () => { + it('should return serialized version of the plugin data', () => { + // Arrange + const pluginData = new PluginDataNode({ + name: pluginName, + data: { + background: 'transparent', + }, + }); + + // Act + const pluginDataSerialized = pluginData.serialized; + + // Assert + expect(pluginDataSerialized) + .toEqual( + { + background: 'transparent', + } + ); + }); + }); +}); diff --git a/packages/model/src/entities/PluginDataNode/__mocks__/index.ts b/packages/model/src/entities/PluginDataNode/__mocks__/index.ts new file mode 100644 index 00000000..9dc275e7 --- /dev/null +++ b/packages/model/src/entities/PluginDataNode/__mocks__/index.ts @@ -0,0 +1,27 @@ +import { EventBus } from '@editorjs/model-types'; + +/** + * Mock for PluginDataNode class + */ +export class PluginDataNode extends EventBus { + /** + * Mock getter + */ + public get serialized(): object { + return {}; + } + + /** + * Mock getter + */ + public get isEmpty(): boolean { + return false; + } + + /** + * Mock method + */ + public update(): void { + return; + } +} diff --git a/packages/model/src/entities/PluginDataNode/index.ts b/packages/model/src/entities/PluginDataNode/index.ts new file mode 100644 index 00000000..6f7a0c0c --- /dev/null +++ b/packages/model/src/entities/PluginDataNode/index.ts @@ -0,0 +1,83 @@ +import { getContext } from '../../utils/Context.js'; +import type { PluginDataNodeConstructorParameters } from './types/index.js'; +import { + PartialIndex, + type PluginDataSerialized, + type PluginDataName, + EventBus, + PluginDataModifiedEvent +} from '@editorjs/model-types'; + +/** + * PluginDataNode holds the per-block data owned by a single plugin. + * The data is a flat key/value map: a plugin reads and writes its own keys, and every change + * is emitted as a separate event so concurrent writes to different keys don't collide. + */ +export class PluginDataNode extends EventBus { + /** + * Name the data is stored under, by convention the owning plugin's `name` + */ + #name: PluginDataName; + + /** + * The plugin's data + */ + #data: Record; + + /** + * Constructor for PluginDataNode class. + * @param args - PluginDataNode constructor arguments. + * @param args.name - Name the data is stored under. + * @param args.data - Initial data of the plugin. + */ + constructor({ name, data = {} }: PluginDataNodeConstructorParameters) { + super(); + + this.#name = name; + this.#data = data; + } + + /** + * Name the data is stored under + */ + public get name(): PluginDataName { + return this.#name; + } + + /** + * True when the node holds no keys, so the owning block can leave it out of serialization + */ + public get isEmpty(): boolean { + return Object.keys(this.#data).length === 0; + } + + /** + * Updates one key of the plugin's data. Passing `undefined` removes the key, + * so undoing the first write to a key restores the original shape of the data. + * @param key - The key of the data to update + * @param value - The value to update the data with, or `undefined` to remove the key + */ + public update(key: string, value: unknown): void { + const previousValue = this.#data[key]; + + if (value === undefined) { + delete this.#data[key]; + } else { + this.#data[key] = value; + } + + this.dispatchEvent( + new PluginDataModifiedEvent(new PartialIndex({ pluginKey: key }), { + value, + previous: previousValue, + }, getContext()!) + ); + } + + /** + * Returns serialized version of the plugin's data. + */ + public get serialized(): PluginDataSerialized { + return this.#data; + } +} diff --git a/packages/model/src/entities/PluginDataNode/types/PluginDataNodeConstructorParameters.ts b/packages/model/src/entities/PluginDataNode/types/PluginDataNodeConstructorParameters.ts new file mode 100644 index 00000000..3669bf3d --- /dev/null +++ b/packages/model/src/entities/PluginDataNode/types/PluginDataNodeConstructorParameters.ts @@ -0,0 +1,13 @@ +import type { PluginDataName, PluginDataSerialized } from '@editorjs/model-types'; + +export interface PluginDataNodeConstructorParameters { + /** + * Name the data is stored under, by convention the owning plugin's `name` + */ + name: PluginDataName; + + /** + * Initial data of the plugin + */ + data?: PluginDataSerialized; +} diff --git a/packages/model/src/entities/PluginDataNode/types/index.ts b/packages/model/src/entities/PluginDataNode/types/index.ts new file mode 100644 index 00000000..49c4f607 --- /dev/null +++ b/packages/model/src/entities/PluginDataNode/types/index.ts @@ -0,0 +1 @@ +export type { PluginDataNodeConstructorParameters } from './PluginDataNodeConstructorParameters.js'; diff --git a/packages/model/src/entities/index.ts b/packages/model/src/entities/index.ts index 0db7aa2c..1fc3790c 100644 --- a/packages/model/src/entities/index.ts +++ b/packages/model/src/entities/index.ts @@ -1,5 +1,5 @@ export * from './EditorDocument/index.js'; export * from './BlockNode/index.js'; -export * from './BlockTune/index.js'; +export * from './PluginDataNode/index.js'; export * from './ValueNode/index.js'; export * from './inline-fragments/index.js'; From 4a68df3b9f97d5128999d4e9f3e3be3183936715 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 26 Sep 2026 00:18:59 +0100 Subject: [PATCH 02/29] feat(sdk): expose typed per-block plugin data - re-export the renamed model types (PluginDataName, PluginDataSerialized, PluginDataIndex, PluginDataModifiedEvent, createPluginDataName) - declare EditorjsPluginDataMap, a third augmentable map alongside EditorjsPluginApiMap and ToolPluginOptionsMap, and resolve a plugin's data shape through PluginDataFor. An undeclared id falls back to a plain record rather than never, since per-block data is often stored by a plugin that has no reason to publish its shape. - add BlocksAPI.getPluginData / updatePluginData and a `plugins` map on insert Co-Authored-By: Claude Opus 5 --- packages/sdk/src/api/BlocksAPI.ts | 44 +++++++++++++++++++++++++ packages/sdk/src/index.ts | 42 +++++++++++++++++++---- packages/sdk/src/pluginTypeMaps.spec.ts | 42 ++++++++++++++++++++++- 3 files changed, 121 insertions(+), 7 deletions(-) diff --git a/packages/sdk/src/api/BlocksAPI.ts b/packages/sdk/src/api/BlocksAPI.ts index 65b4c78e..a24626ed 100644 --- a/packages/sdk/src/api/BlocksAPI.ts +++ b/packages/sdk/src/api/BlocksAPI.ts @@ -3,9 +3,11 @@ import type { BlockId, BlockNodeInit, DocumentData, + PluginDataSerialized, TextNodeSerialized, ValueSerialized } from '@editorjs/model-types'; +import type { PluginDataFor, PluginId } from '../index.js'; /** * Blocks API interface @@ -22,6 +24,7 @@ export interface BlocksAPI { * @param [params.focus] - flag indicates if new block should be focused @todo implement * @param [params.replace] - flag indicates if block at index should be replaced @todo implement * @param [params.id] - id of the inserted block @todo implement + * @param [params.plugins] - initial per-plugin data for the block, keyed by plugin name */ insert(params?: { /** Block tool name to insert */ @@ -36,6 +39,8 @@ export interface BlocksAPI { replace?: boolean; /** Id of the inserted block */ id?: string; + /** Initial per-plugin data for the block, keyed by plugin name */ + plugins?: Record; /** User id. Defaults to the current user id from the config */ userId?: string | number; }): void; @@ -216,6 +221,45 @@ export interface BlocksAPI { userId?: string | number; }): void; + /** + * Returns the per-block data stored by the given plugin, or undefined when it stores none. + * + * The data type is resolved from `EditorjsPluginDataMap` for a plugin that declares its shape, + * and falls back to a plain record otherwise. + * @param params - getPluginData parameters + * @param params.block - index or id of the block + * @param params.plugin - name the data is stored under, by convention the plugin's `name` + */ + getPluginData(params: { + /** Index or id of the block */ + block: number | string; + /** Name the data is stored under */ + plugin: Id; + }): PluginDataFor | undefined; + + /** + * Merges the passed keys into the per-block data of the given plugin, creating the plugin's + * entry when the block has none yet. A key set to `undefined` is removed. + * + * Each key is recorded as its own modification, so a call that writes several keys is not a + * single undo step. + * @param params - updatePluginData parameters + * @param params.block - index or id of the block + * @param params.plugin - name the data is stored under, by convention the plugin's `name` + * @param params.data - keys to merge into the plugin's data + * @param [params.userId] - user id. Defaults to the current user id from the config + */ + updatePluginData(params: { + /** Index or id of the block */ + block: number | string; + /** Name the data is stored under */ + plugin: Id; + /** Keys to merge into the plugin's data */ + data: Partial>; + /** User id. Defaults to the current user id from the config */ + userId?: string | number; + }): void; + /** * Splits the block at the given data key and character offset. * If the tool supports splitting (canBeSplit = true) a new block of the same type is inserted after the current one. diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index 31b3de42..cc6a0b10 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -32,6 +32,36 @@ export interface EditorjsPluginApiMap {} // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- filled in by plugin packages via module augmentation export interface ToolPluginOptionsMap {} +/** + * Maps a plugin's `name` to the shape of the per-block data that plugin stores in the Model, + * read and written through `api.blocks.getPluginData` / `updatePluginData`. + * + * Augmented by plugin packages the same way as {@link EditorjsPluginApiMap}. + * @example + * declare module '@editorjs/sdk' { + * interface EditorjsPluginDataMap { + * anchors: { id: string }; + * } + * } + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- filled in by plugin packages via module augmentation +export interface EditorjsPluginDataMap {} + +/** + * Shape of the per-block data stored by the plugin with the given id. + * + * Falls back to a plain record for an id absent from {@link EditorjsPluginDataMap}: unlike a + * plugin's public API, per-block data is often written by a plugin that has no reason to publish + * its shape, so an undeclared id stays usable instead of resolving to `never`. + * + * The check is deliberately non-distributive (`[Id] extends [...]`), because the default + * {@link PluginId} is a union including `string & {}` and a distributive conditional would + * collapse a declared id onto the fallback. + */ +export type PluginDataFor = [Id] extends [keyof EditorjsPluginDataMap] + ? EditorjsPluginDataMap[Id] + : Record; + /** * Identifier of a plugin — the value of its static `name`. * @@ -39,7 +69,7 @@ export interface ToolPluginOptionsMap {} * the maps; the `string & {}` arm keeps ids legal for plugins that augment neither map, while * still preserving literal inference and autocomplete for the known ones. */ -export type PluginId = keyof EditorjsPluginApiMap | keyof ToolPluginOptionsMap | (string & {}); +export type PluginId = keyof EditorjsPluginApiMap | keyof ToolPluginOptionsMap | keyof EditorjsPluginDataMap | (string & {}); /** * Registry of plugin public APIs, exposed as `api.plugins`. @@ -69,8 +99,8 @@ export type { BlockNodeInit, BlockNodeSerialized, BlockToolName, - BlockTuneName, - BlockTuneSerialized, + PluginDataName, + PluginDataSerialized, TextRange, InlineFragment, InlineTreeNodeSerialized, @@ -102,7 +132,7 @@ export { generateBlockId, createBlockToolName, createDataKey, - createBlockTuneName, + createPluginDataName, createInlineToolName, createInlineToolData, EventAction, @@ -122,13 +152,13 @@ export { BlockAddedEvent, BlockRemovedEvent, PropertyModifiedEvent, - TuneModifiedEvent, + PluginDataModifiedEvent, IndexBase, IndexKind, BlockIndex, DataIndex, TextIndex, - TuneIndex, + PluginDataIndex, DocumentIndex, PropertyIndex, PartialIndex diff --git a/packages/sdk/src/pluginTypeMaps.spec.ts b/packages/sdk/src/pluginTypeMaps.spec.ts index fa740c96..a15319f3 100644 --- a/packages/sdk/src/pluginTypeMaps.spec.ts +++ b/packages/sdk/src/pluginTypeMaps.spec.ts @@ -1,7 +1,7 @@ /* eslint-disable jsdoc/require-jsdoc,@typescript-eslint/no-magic-numbers */ import { describe, expect, it } from '@jest/globals'; -import type { PluginsAPI, ToolPluginOptions } from './index.js'; +import type { PluginDataFor, PluginsAPI, ToolPluginOptions } from './index.js'; /** * Public API a fake plugin exposes — stands in for a real plugin package's API type @@ -24,6 +24,16 @@ interface ProbeToolOptions { level: number; } +/** + * Per-block data the fake plugin stores in the Model + */ +interface ProbePluginData { + /** + * Arbitrary key used to check the data shape is type-checked + */ + id: string; +} + /** * Augments the maps the same way a real plugin package does, but through a relative * specifier since this file lives inside the declaring package itself @@ -42,6 +52,13 @@ declare module './index.js' { */ probe: ProbeToolOptions; } + + interface EditorjsPluginDataMap { + /** + * Fake plugin's per-block data + */ + probe: ProbePluginData; + } } describe('Plugin type maps', () => { @@ -79,6 +96,29 @@ describe('Plugin type maps', () => { }); }); + describe('EditorjsPluginDataMap', () => { + it('should resolve an augmented id to the declared data shape', () => { + const data: PluginDataFor<'probe'> = { id: 'intro' }; + + const typed: ProbePluginData = data; + + expect(typed.id).toBe('intro'); + }); + + it('should reject data that does not match the declared shape', () => { + // @ts-expect-error -- `id` is a string + const data: PluginDataFor<'probe'> = { id: 42 }; + + expect(data).toBeDefined(); + }); + + it('should fall back to a plain record for an id no package has augmented', () => { + const data: PluginDataFor<'unknownPlugin'> = { anything: true }; + + expect(data.anything).toBe(true); + }); + }); + describe('ToolPluginOptionsMap', () => { it('should type an augmented key as the tool-directed options', () => { const options: ToolPluginOptions = { From c8a1b90ce6a4014faff07c7041705b13535a96fb Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 26 Sep 2026 00:26:24 +0100 Subject: [PATCH 03/29] feat(core): read and write per-block plugin data through BlocksAPI - BlocksAPI.getPluginData / updatePluginData, backed by BlocksManager, with the acting user defaulting to the configured one - insert() accepts a `plugins` map, and convert() carries plugin data over to the converted block - fix insert() dropping the block's data: BlocksManager spread `...data` into the block init while BlockNode reads a nested `data` key, so inserting with data silently produced an empty block. `plugins` is passed as its own key. - fix BlocksAPI.insert not forwarding `focus`, `plugins` and `userId` - add UndoRedoManager integration tests over a real model: undoing a first write removes the entry, redo restores it, and undoing one key leaves the plugin's other keys untouched - fix the BlocksAPI integration spec wiring a second, empty model into the API, which made every direct model read in it see an empty document Co-Authored-By: Claude Opus 5 --- .../src/api/BlocksAPI.integration.spec.ts | 100 +++++++++++++++++- packages/core/src/api/BlocksAPI.spec.ts | 6 ++ packages/core/src/api/BlocksAPI.ts | 27 ++++- .../core/src/components/BlockManager.spec.ts | 1 + packages/core/src/components/BlockManager.ts | 38 ++++++- .../UndoRedoManager.integration.spec.ts | 75 +++++++++++++ 6 files changed, 243 insertions(+), 4 deletions(-) create mode 100644 packages/core/src/components/UndoRedoManager.integration.spec.ts diff --git a/packages/core/src/api/BlocksAPI.integration.spec.ts b/packages/core/src/api/BlocksAPI.integration.spec.ts index 317b8297..dcd17300 100644 --- a/packages/core/src/api/BlocksAPI.integration.spec.ts +++ b/packages/core/src/api/BlocksAPI.integration.spec.ts @@ -63,10 +63,14 @@ describe('BlocksAPI integration (real model, mocked tools)', () => { config ); + /** + * The same model instance the manager uses: methods that read the document directly + * (getIdByIndex, getData, getPluginData) would otherwise see an empty document. + */ blocksAPI = new BlocksAPI( blocksManager, config, - new EditorJSModel('userId', { identifier: 'documentId' }) + model ); }); @@ -1183,4 +1187,98 @@ describe('BlocksAPI integration (real model, mocked tools)', () => { expect(model.serialized.blocks[0]).toEqual(expect.objectContaining({ name: 'list' })); }); }); + + describe('plugin data', () => { + it('should insert a block carrying both tool data and plugin data', () => { + blocksAPI.insert({ + type: 'paragraph', + data: { text: 'Alpha' }, + plugins: { anchors: { id: 'intro' } }, + }); + + expect(model.serialized.blocks[0]).toEqual(expect.objectContaining({ + name: 'paragraph', + data: expect.objectContaining({ text: 'Alpha' }), + plugins: { anchors: { id: 'intro' } }, + })); + }); + + it('should return undefined for a plugin that stores nothing on the block', () => { + blocksAPI.insert({ type: 'paragraph' }); + + expect(blocksAPI.getPluginData({ block: 0, + plugin: 'anchors' })).toBeUndefined(); + }); + + it('should write and read plugin data by block index', () => { + blocksAPI.insert({ type: 'paragraph' }); + + blocksAPI.updatePluginData({ block: 0, + plugin: 'anchors', + data: { id: 'intro' } }); + + expect(blocksAPI.getPluginData({ block: 0, + plugin: 'anchors' })).toEqual({ id: 'intro' }); + }); + + it('should write and read plugin data by block id', () => { + blocksAPI.insert({ type: 'paragraph' }); + + const blockId = blocksAPI.getIdByIndex(0)!; + + blocksAPI.updatePluginData({ block: blockId, + plugin: 'anchors', + data: { id: 'intro' } }); + + expect(blocksAPI.getPluginData({ block: blockId, + plugin: 'anchors' })).toEqual({ id: 'intro' }); + }); + + it('should return undefined once the last key of an entry is removed', () => { + blocksAPI.insert({ type: 'paragraph' }); + + blocksAPI.updatePluginData({ block: 0, + plugin: 'anchors', + data: { id: 'intro' } }); + blocksAPI.updatePluginData({ block: 0, + plugin: 'anchors', + data: { id: undefined } }); + + expect(blocksAPI.getPluginData({ block: 0, + plugin: 'anchors' })).toBeUndefined(); + }); + + it('should attribute the change to the acting user', () => { + blocksAPI.insert({ type: 'paragraph' }); + + const events: unknown[] = []; + + model.addEventListener(EventType.Changed, e => events.push(e)); + + blocksAPI.updatePluginData({ block: 0, + plugin: 'anchors', + data: { id: 'intro' }, + userId: 'other-user' }); + + expect(events[0]).toHaveProperty('detail.userId', 'other-user'); + }); + + it('should throw for a block id that does not exist', () => { + expect(() => blocksAPI.getPluginData({ block: 'missing', + plugin: 'anchors' })).toThrow('missing'); + }); + + it('should preserve plugin data when a block is moved', () => { + blocksAPI.insert({ type: 'paragraph', + plugins: { anchors: { id: 'first' } } }); + blocksAPI.insert({ type: 'paragraph' }); + + blocksAPI.move({ fromIndex: 0, + toIndex: 1 }); + + expect(model.serialized.blocks[1]).toEqual(expect.objectContaining({ + plugins: { anchors: { id: 'first' } }, + })); + }); + }); }); diff --git a/packages/core/src/api/BlocksAPI.spec.ts b/packages/core/src/api/BlocksAPI.spec.ts index 42499fad..883e05aa 100644 --- a/packages/core/src/api/BlocksAPI.spec.ts +++ b/packages/core/src/api/BlocksAPI.spec.ts @@ -191,6 +191,9 @@ describe('BlocksAPI', () => { data: {}, index: undefined, replace: undefined, + focus: undefined, + plugins: undefined, + userId: undefined, }); }); @@ -208,6 +211,7 @@ describe('BlocksAPI', () => { focus: true, replace: true, id: 'id-1', + plugins: undefined, }); expect(blocksManager.insert).toHaveBeenCalledWith({ @@ -216,6 +220,8 @@ describe('BlocksAPI', () => { index: 2, replace: true, focus: true, + plugins: undefined, + userId: undefined, }); }); }); diff --git a/packages/core/src/api/BlocksAPI.ts b/packages/core/src/api/BlocksAPI.ts index 696cf72f..29afb914 100644 --- a/packages/core/src/api/BlocksAPI.ts +++ b/packages/core/src/api/BlocksAPI.ts @@ -3,6 +3,7 @@ import { inject, injectable } from 'inversify'; import { TOKENS } from '../tokens.js'; import { BlocksManager } from '../components/BlockManager.js'; import { CoreConfigValidated, BlocksAPI as BlocksApiInterface, EditorDocumentSerialized, BlockId, BlockIndexOrId, createBlockId, createDataKey } from '@editorjs/sdk'; +import type { PluginDataFor, PluginId } from '@editorjs/sdk'; import { EditorJSModel } from '@editorjs/model'; import type { TextNodeSerialized, ValueSerialized } from '@editorjs/sdk'; @@ -105,9 +106,10 @@ export class BlocksAPI implements BlocksApiInterface { * @param [params.index] - index to insert block at * @param [params.focus] - flag indicates if new block should be focused @todo implement * @param [params.replace] - flag indicates if block at index should be replaced @todo implement + * @param [params.plugins] - initial per-plugin data for the block, keyed by plugin name * @param [params.userId] - user id to attribute the change to */ - public insert({ type, data, index, focus, replace, userId = this.#config.userId }: NonNullable[0]> = {}): void { + public insert({ type, data, index, focus, replace, plugins, userId = this.#config.userId }: NonNullable[0]> = {}): void { const blockType = type ?? this.#config.defaultBlock; const blockData = data ?? {}; @@ -117,6 +119,7 @@ export class BlocksAPI implements BlocksApiInterface { index, replace, focus, + plugins, userId, }); }; @@ -219,4 +222,26 @@ export class BlocksAPI implements BlocksApiInterface { }: Parameters[0]): void { this.#blocksManager.convertBlock(block as BlockIndexOrId, createDataKey(key), newType, userId, dataOverrides); } + + /** + * Returns the per-block data stored by the given plugin, or undefined when it stores none + * @param params - getPluginData parameters + * @param params.block - index or id of the block + * @param params.plugin - name the data is stored under, by convention the plugin's `name` + */ + public getPluginData({ block, plugin }: Parameters[0]): PluginDataFor | undefined { + return this.#blocksManager.getPluginData(block as BlockIndexOrId, plugin) as PluginDataFor | undefined; + } + + /** + * Merges the passed keys into the per-block data of the given plugin + * @param params - updatePluginData parameters + * @param params.block - index or id of the block + * @param params.plugin - name the data is stored under, by convention the plugin's `name` + * @param params.data - keys to merge into the plugin's data + * @param [params.userId] - user id to attribute the change to + */ + public updatePluginData({ block, plugin, data, userId = this.#config.userId }: Parameters[0]): void { + this.#blocksManager.updatePluginData(block as BlockIndexOrId, plugin, data as Record, userId); + } } diff --git a/packages/core/src/components/BlockManager.spec.ts b/packages/core/src/components/BlockManager.spec.ts index 3c89e057..69ca00de 100644 --- a/packages/core/src/components/BlockManager.spec.ts +++ b/packages/core/src/components/BlockManager.spec.ts @@ -12,6 +12,7 @@ jest.unstable_mockModule('@editorjs/sdk', () => ({ BlockChildType: { Text: 't' }, NODE_TYPE_HIDDEN_PROP: '$t', createBlockId: jest.fn((id: string) => id as never), + createPluginDataName: jest.fn((name: string) => name as never), set: jest.fn(() => undefined), renumberKeys: jest.fn(() => new Map()), TextIndex: class TextIndex {}, diff --git a/packages/core/src/components/BlockManager.ts b/packages/core/src/components/BlockManager.ts index ee0f3a47..e5e4c4b3 100644 --- a/packages/core/src/components/BlockManager.ts +++ b/packages/core/src/components/BlockManager.ts @@ -8,6 +8,8 @@ import { type EditorDocumentSerialized, type InlineTreeNodeSerialized, NODE_TYPE_HIDDEN_PROP, + createPluginDataName, + type PluginDataSerialized, renumberKeys, set, TextIndex @@ -35,6 +37,10 @@ interface InsertBlockParameters { * Block's initial data */ data?: BlockToolData; + /** + * Initial per-plugin data for the block, keyed by plugin name + */ + plugins?: Record; /** * Index to insert block at */ @@ -49,7 +55,6 @@ interface InsertBlockParameters { * If true, moves caret to the new block */ focus?: boolean; - // tunes?: {[name: string]: BlockTuneData}; /** * User id to attribute the change to */ @@ -131,8 +136,8 @@ export class BlocksManager { index, focus = false, replace = false, + plugins, userId = this.#config.userId, - // tunes = {}, }: InsertBlockParameters = {}): void { let newIndex = index; @@ -148,6 +153,7 @@ export class BlocksManager { id, name: type, data, + ...(plugins !== undefined && { plugins }), }, newIndex); if (focus) { @@ -426,9 +432,37 @@ export class BlocksManager { this.#model.addBlock(userId, { name: newType, data: finalData, + ...(block.plugins !== undefined && { plugins: block.plugins }), }, blockIndex); } + /** + * Returns the per-block data stored by the given plugin, or undefined when it stores none + * @param blockIndexOrId - position of the block in the document, or its id + * @param pluginName - key the data is stored under, by convention the owning plugin's `name` + */ + public getPluginData(blockIndexOrId: number | BlockId, pluginName: string): PluginDataSerialized | undefined { + const blockIndex = this.#model.resolveBlockIndex(blockIndexOrId); + + return this.#model.getBlockSerialized(blockIndex).plugins?.[pluginName]; + } + + /** + * Merges the passed keys into the per-block data of the given plugin + * @param blockIndexOrId - position of the block in the document, or its id + * @param pluginName - key the data is stored under, by convention the owning plugin's `name` + * @param data - keys to merge in; a key set to undefined is removed + * @param userId - person the change is attributed to + */ + public updatePluginData( + blockIndexOrId: number | BlockId, + pluginName: string, + data: Record, + userId: string | number = this.#config.userId + ): void { + this.#model.updatePluginData(userId, blockIndexOrId, createPluginDataName(pluginName), data); + } + /** * Returns block index where user caret is placed */ diff --git a/packages/core/src/components/UndoRedoManager.integration.spec.ts b/packages/core/src/components/UndoRedoManager.integration.spec.ts new file mode 100644 index 00000000..7671cce5 --- /dev/null +++ b/packages/core/src/components/UndoRedoManager.integration.spec.ts @@ -0,0 +1,75 @@ +import { describe, it, expect, beforeEach } from '@jest/globals'; +import type { CoreConfigValidated } from '@editorjs/sdk'; +import { EventBus, createPluginDataName } from '@editorjs/sdk'; +import { EditorJSModel } from '@editorjs/model'; +import { UndoRedoManager } from './UndoRedoManager.js'; + +const USER_ID = 'undo-user'; +const DOCUMENT_ID = 'undo-doc'; +const PLUGIN = createPluginDataName('anchors'); + +/** + * Reads the plugin's serialized data for the first block, or undefined when it stores none + * @param model - model to read from + */ +function pluginData(model: InstanceType): Record | undefined { + return model.serialized.blocks[0].plugins?.[PLUGIN]; +} + +describe('UndoRedoManager integration with plugin data (real model)', () => { + let model: InstanceType; + let manager: InstanceType; + + beforeEach(() => { + model = new EditorJSModel(USER_ID, { identifier: DOCUMENT_ID }); + + model.initializeDocument({ + blocks: [ + { + name: 'paragraph', + data: {}, + }, + ], + }); + + manager = new UndoRedoManager( + model, + new EventBus(), + { userId: USER_ID } as CoreConfigValidated + ); + }); + + it('should undo the first write by removing the entry, and redo by restoring it', () => { + model.updatePluginData(USER_ID, 0, PLUGIN, { id: 'intro' }); + + expect(pluginData(model)).toEqual({ id: 'intro' }); + + manager.undo(); + + expect(pluginData(model)).toBeUndefined(); + + manager.redo(); + + expect(pluginData(model)).toEqual({ id: 'intro' }); + }); + + it('should undo an update back to the previous value', () => { + model.updatePluginData(USER_ID, 0, PLUGIN, { visible: true }); + model.updatePluginData(USER_ID, 0, PLUGIN, { visible: false }); + + expect(pluginData(model)).toEqual({ visible: false }); + + manager.undo(); + + expect(pluginData(model)).toEqual({ visible: true }); + }); + + it('should leave other keys of the same plugin untouched when undoing one key', () => { + model.updatePluginData(USER_ID, 0, PLUGIN, { id: 'intro' }); + model.updatePluginData(USER_ID, 0, PLUGIN, { visible: true }); + + manager.undo(); + + expect(pluginData(model)).toEqual({ id: 'intro' }); + }); +}); From 273ca741e63f83c308518052300627b2acc5bf9c Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 26 Sep 2026 00:35:45 +0100 Subject: [PATCH 04/29] feat(collaboration-manager): synchronize per-block plugin data - map PluginDataModifiedEvent to a Modify operation carrying the new and previous values, instead of logging it as an unknown event type - add a PluginDataIndex branch to OperationsTransformer#applyTransformation, which dispatches on the against-operation's index kind and previously threw 'Unsupported index type'. Without it the first remote plugin data change threw in OTClient's pending-operation reduce, in transformStacks for every remote event, and in ot-server's conflicting-operation reduce. - widen ModifyOperationData's payload from Record to unknown, so a scalar plugin data value is representable, and narrow the two payload length reads that relied on the old type - move the ot-server fixtures off the `tunes` key Two concurrent writes to the same key stay untransformed: server order decides and the last applied one wins. Co-Authored-By: Claude Opus 5 --- .../src/CollaborationManager.spec.ts | 113 ++++++++++++++---- .../src/CollaborationManager.ts | 7 ++ .../collaboration-manager/src/Operation.ts | 17 ++- .../src/OperationsTransformer.spec.ts | 95 ++++++++++++++- .../src/OperationsTransformer.ts | 26 +++- .../ot-server/src/DocumentManager.spec.ts | 8 +- 6 files changed, 228 insertions(+), 38 deletions(-) diff --git a/packages/collaboration-manager/src/CollaborationManager.spec.ts b/packages/collaboration-manager/src/CollaborationManager.spec.ts index a1c2d2bc..9039bde6 100644 --- a/packages/collaboration-manager/src/CollaborationManager.spec.ts +++ b/packages/collaboration-manager/src/CollaborationManager.spec.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-magic-numbers */ -import { createDataKey, EventType, Index } from '@editorjs/sdk'; +import { createDataKey, createPluginDataName, EventType, Index } from '@editorjs/sdk'; import { EditorJSModel } from '@editorjs/model'; import { CoreEventType, type CoreConfig } from '@editorjs/sdk'; import { beforeAll, jest } from '@jest/globals'; @@ -67,7 +67,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -109,7 +109,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -147,7 +147,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -221,7 +221,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -313,7 +313,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -362,7 +362,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -379,6 +379,67 @@ describe('CollaborationManager', () => { }); }); + describe('plugin data operations', () => { + const pluginName = createPluginDataName('anchors'); + + /** + * Creates a model with one paragraph block + */ + function createModel(): InstanceType { + const model = new EditorJSModel(userId, { identifier: documentId }); + + model.initializeDocument({ + blocks: [{ + name: 'paragraph', + data: {}, + }], + }); + + return model; + } + + it('should turn a plugin data change into a Modify operation instead of logging an unknown event', () => { + const model = createModel(); + const { manager } = createManager(config as Required, model); + const transformSpy = jest.spyOn(UndoRedoManager.prototype, 'transformStacks'); + + /** + * A change by another user takes the remote path, where the operation built from the event + * is handed to the undo/redo stacks — which is observable without a connected client. + */ + model.updatePluginData('another-user', 0, pluginName, { visible: false }); + + expect(transformSpy).toHaveBeenCalledTimes(1); + + const operation = transformSpy.mock.calls[0][0]; + + expect(operation.type).toBe(OperationType.Modify); + expect(operation.data).toEqual({ payload: false, + prevPayload: undefined }); + expect(operation.index.serialize()).toContain('"k":"plugin"'); + + transformSpy.mockRestore(); + manager.destroy(); + }); + + it('should apply a remote plugin data operation to the model', () => { + const model = createModel(); + const { manager } = createManager(config as Required, model); + + manager.applyOperation(new Operation( + OperationType.Modify, + Index.pluginData(0, pluginName, 'visible'), + { payload: false, + prevPayload: undefined }, + 'remote-user' + )); + + expect(model.serialized.blocks[0].plugins?.[pluginName]).toEqual({ visible: false }); + + manager.destroy(); + }); + }); + describe('undo logic', () => { beforeAll(() => { jest.useFakeTimers(); @@ -414,7 +475,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -457,7 +518,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -501,7 +562,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -546,7 +607,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -624,7 +685,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -675,7 +736,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -730,7 +791,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -757,7 +818,7 @@ describe('CollaborationManager', () => { fragments: [], }, }, - tunes: {}, + plugins: {}, }; model.initializeDocument({ @@ -792,7 +853,7 @@ describe('CollaborationManager', () => { fragments: [], }, }, - tunes: {}, + plugins: {}, }; model.initializeDocument({ @@ -830,7 +891,7 @@ describe('CollaborationManager', () => { fragments: [], }, }, - tunes: {}, + plugins: {}, }; model.initializeDocument({ @@ -871,7 +932,7 @@ describe('CollaborationManager', () => { fragments: [], }, }, - tunes: {}, + plugins: {}, }; model.initializeDocument({ @@ -941,7 +1002,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -993,7 +1054,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -1030,7 +1091,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -1124,7 +1185,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -1165,7 +1226,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -1233,7 +1294,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -1296,7 +1357,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -1349,7 +1410,7 @@ describe('CollaborationManager', () => { identifier: documentId, blocks: [expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', diff --git a/packages/collaboration-manager/src/CollaborationManager.ts b/packages/collaboration-manager/src/CollaborationManager.ts index 75d8b82d..9a32b205 100644 --- a/packages/collaboration-manager/src/CollaborationManager.ts +++ b/packages/collaboration-manager/src/CollaborationManager.ts @@ -2,6 +2,7 @@ import { BlockAddedEvent, type BlockNodeSerialized, BlockRemovedEvent, type ModelEvents, + PluginDataModifiedEvent, TextAddedEvent, TextFormattedEvent, TextRemovedEvent, TextUnformattedEvent @@ -265,6 +266,12 @@ export class CollaborationManager implements EditorjsPlugin { payload: [e.detail.data], }, e.detail.userId); break; + case (e instanceof PluginDataModifiedEvent): + operation = new Operation(OperationType.Modify, e.detail.index, { + payload: e.detail.data.value, + prevPayload: e.detail.data.previous, + }, e.detail.userId); + break; // Stryker disable next-line ConditionalExpression default: // Stryker disable next-line StringLiteral diff --git a/packages/collaboration-manager/src/Operation.ts b/packages/collaboration-manager/src/Operation.ts index dbda5c8f..c79ff0b1 100644 --- a/packages/collaboration-manager/src/Operation.ts +++ b/packages/collaboration-manager/src/Operation.ts @@ -28,8 +28,13 @@ export interface InsertOrDeleteOperationData { payload: ArrayLike; } -// eslint-disable-next-line @typescript-eslint/no-explicit-any -export interface ModifyOperationData = Record> { +/** + * Data of a Modify operation. + * + * The payload is any JSON value, not just an object: a plugin's per-block data holds scalars, + * so `payload: false` has to be representable. + */ +export interface ModifyOperationData { /** * Operation payload */ @@ -186,7 +191,13 @@ export class Operation { const textIndex = this.index as TextIndex; if (this.type === OperationType.Insert) { - return [textIndex.textRange![0], Math.max(textIndex.textRange![1], textIndex.textRange![0] + this.data.payload!.length)]; + /** + * Only an Insert operation reaches this branch, and its payload is always the inserted + * text or block list — unlike a Modify payload, which may be any JSON value. + */ + const { payload } = this.data as InsertOrDeleteOperationData; + + return [textIndex.textRange![0], Math.max(textIndex.textRange![1], textIndex.textRange![0] + payload.length)]; } return textIndex.textRange!; diff --git a/packages/collaboration-manager/src/OperationsTransformer.spec.ts b/packages/collaboration-manager/src/OperationsTransformer.spec.ts index c4aa97fb..b36555f5 100644 --- a/packages/collaboration-manager/src/OperationsTransformer.spec.ts +++ b/packages/collaboration-manager/src/OperationsTransformer.spec.ts @@ -1,5 +1,5 @@ -import type { BlockIndex, DocumentId, TextIndex } from '@editorjs/sdk'; -import { createDataKey, Index } from '@editorjs/sdk'; +import type { BlockIndex, DocumentId, PluginDataIndex, TextIndex } from '@editorjs/sdk'; +import { createDataKey, createPluginDataName, Index } from '@editorjs/sdk'; import { Operation, OperationType } from './Operation.js'; import { OperationsTransformer } from './OperationsTransformer.js'; @@ -552,4 +552,95 @@ describe('OperationsTransformer', () => { }); }); }); + + describe('Plugin data operations transformation', () => { + const pluginIndex = (blockIndex: number, key = 'id'): Index => + Index.pluginData(blockIndex, createPluginDataName('anchors'), key, 'doc1' as DocumentId); + + const pluginOp = (blockIndex: number, key = 'id'): Operation => new Operation( + OperationType.Modify, + pluginIndex(blockIndex, key), + { payload: false, + prevPayload: true }, + 'user1', + 1 + ); + + it('should shift the block index when a block is inserted above', () => { + const operation = pluginOp(2); + const againstOp = new Operation( + OperationType.Insert, + Index.block(0, 'doc1' as DocumentId), + { payload: [] }, + 'user2', + 1 + ); + + const result = transformer.transform(operation, againstOp); + + expect((result.index as PluginDataIndex).blockIndex).toBe(3); + expect((result.index as PluginDataIndex).pluginName).toBe('anchors'); + }); + + it('should become Neutral when its own block is removed', () => { + const operation = pluginOp(2); + const againstOp = new Operation( + OperationType.Delete, + Index.block(2, 'doc1' as DocumentId), + { payload: [] }, + 'user2', + 1 + ); + + expect(transformer.transform(operation, againstOp).type).toBe(OperationType.Neutral); + }); + + it('should not be transformed against another plugin data operation', () => { + const operation = pluginOp(2); + const againstOp = pluginOp(2); + + const result = transformer.transform(operation, againstOp); + + expect(result.type).toBe(OperationType.Modify); + expect((result.index as PluginDataIndex).blockIndex).toBe(2); + }); + + it('should transform a text operation against a plugin data operation without throwing', () => { + const operation = new Operation( + OperationType.Insert, + Index.text([{ blockIndex: 1, + dataKey: createDataKey('text'), + textRange: [0, 0], + documentId: 'doc1' as DocumentId }]), + { payload: 'abc' }, + 'user1', + 1 + ); + + const result = transformer.transform(operation, pluginOp(1)); + + expect(result.type).toBe(OperationType.Insert); + }); + + it('should transform a block operation against a plugin data operation without throwing', () => { + const operation = new Operation( + OperationType.Insert, + Index.block(0, 'doc1' as DocumentId), + { payload: [] }, + 'user1', + 1 + ); + + const result = transformer.transform(operation, pluginOp(0)); + + expect(result.type).toBe(OperationType.Insert); + }); + + it('should invert a plugin data operation by swapping the payloads', () => { + const inverted = pluginOp(2).inverse(); + + expect(inverted.data).toEqual({ payload: true, + prevPayload: false }); + }); + }); }); diff --git a/packages/collaboration-manager/src/OperationsTransformer.ts b/packages/collaboration-manager/src/OperationsTransformer.ts index 6930d6e3..375883a0 100644 --- a/packages/collaboration-manager/src/OperationsTransformer.ts +++ b/packages/collaboration-manager/src/OperationsTransformer.ts @@ -1,4 +1,5 @@ -import { BlockIndex, DataIndex, TextIndex } from '@editorjs/sdk'; +import { BlockIndex, DataIndex, PluginDataIndex, TextIndex } from '@editorjs/sdk'; +import type { InsertOrDeleteOperationData } from './Operation.js'; import { Operation, OperationType } from './Operation.js'; import { getRangesIntersectionType, RangeIntersectionType } from './utils/getRangesIntersectionType.js'; @@ -61,6 +62,9 @@ export class OperationsTransformer { case (againstIndex instanceof DataIndex): return this.#transformAgainstDataOperation(operation, againstOp); + case (againstIndex instanceof PluginDataIndex): + return this.#transformAgainstPluginDataOperation(operation, againstOp); + default: throw new Error('Unsupported index type'); } @@ -194,6 +198,22 @@ export class OperationsTransformer { } } + /** + * Method that transforms operation against a plugin data operation + * + * Plugin data operations only ever modify one key of one plugin's per-block data, so they + * cannot shift another operation's position. Two concurrent writes to the same key are left + * untransformed on purpose: the server's order decides, and the last applied one wins. + * @param operation - Operation to be transformed + * @param againstOp - Operation against which the current operation should be transformed + * @returns copy of the current operation + */ + #transformAgainstPluginDataOperation(operation: Operation, againstOp: Operation): Operation { + void againstOp; + + return Operation.from(operation); + } + /** * Method that transforms operation against data (value) operation * @@ -264,7 +284,7 @@ export class OperationsTransformer { #transformAgainstTextInsert(operation: Operation, againstOp: Operation): Operation | Operation { let newPayload = operation.data.payload as string; - const insertedLength = againstOp.data.payload!.length; + const insertedLength = (againstOp.data as InsertOrDeleteOperationData).payload.length; const index = operation.index as TextIndex; const againstIndex = againstOp.index as TextIndex; @@ -352,7 +372,7 @@ export class OperationsTransformer { */ #transformAgainstTextDelete(operation: Operation, againstOp: Operation): Operation | Operation { let newPayload = operation.data.payload as string; - const deletedAmount = againstOp.data.payload!.length; + const deletedAmount = (againstOp.data as InsertOrDeleteOperationData).payload.length; const textRange = operation.getEffectiveRange(); const againstTextRange = againstOp.getEffectiveRange(); diff --git a/packages/ot-server/src/DocumentManager.spec.ts b/packages/ot-server/src/DocumentManager.spec.ts index 4628a7e4..9ddda3fc 100644 --- a/packages/ot-server/src/DocumentManager.spec.ts +++ b/packages/ot-server/src/DocumentManager.spec.ts @@ -80,7 +80,7 @@ describe('DocumentManager', () => { blocks: [ expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -141,7 +141,7 @@ describe('DocumentManager', () => { blocks: [ expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -211,7 +211,7 @@ describe('DocumentManager', () => { blocks: [ expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', @@ -284,7 +284,7 @@ describe('DocumentManager', () => { blocks: [ expect.objectContaining({ name: 'paragraph', - tunes: {}, + plugins: {}, data: { text: { $t: 't', From 568b6a502153e7ddbba5523316919e80219b8b78 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 26 Sep 2026 00:50:21 +0100 Subject: [PATCH 05/29] test: kill surviving mutants in the plugin data paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mutation testing (scoped to the changed files, as CI does) pointed at four real gaps: - BlocksManager.insert: nothing asserted that block data is nested under a `data` key rather than spread, nor that the plugins map is forwarded and omitted when absent - convertBlock: nothing covered carrying plugin data to the converted block - EditorDocument.modifyData: the PluginDataIndex branch had no model-level test - BlockNode: the initial-data path of plugin node creation was unasserted Fixing the last one surfaced a bug in BlockNode.serialized: it assigned entries into a plain object, so a plugin named `__proto__` set the object's prototype instead of becoming a key and vanished from the serialized block. The entry map is now built with Object.fromEntries. The previous test only passed because its expected literal was broken the same way — writing the key as a computed property, to satisfy the naming-convention lint rule, is what exposed it. Scores for the changed files: model 90.38 (threshold 75), core 86.72, collaboration-manager 52.08 (threshold 0, unchanged file-level scores). No surviving mutants remain on lines this branch touched. Co-Authored-By: Claude Opus 5 --- .../core/src/components/BlockManager.spec.ts | 98 +++++++++++++++++++ .../BlockNode/BlockNode.integration.spec.ts | 19 ++-- .../src/entities/BlockNode/BlockNode.spec.ts | 18 ++++ .../model/src/entities/BlockNode/index.ts | 19 ++-- .../EditorDocument/EditorDocument.spec.ts | 28 ++++++ 5 files changed, 167 insertions(+), 15 deletions(-) diff --git a/packages/core/src/components/BlockManager.spec.ts b/packages/core/src/components/BlockManager.spec.ts index 69ca00de..1a94a2f7 100644 --- a/packages/core/src/components/BlockManager.spec.ts +++ b/packages/core/src/components/BlockManager.spec.ts @@ -101,6 +101,44 @@ describe('BlocksManager (unit, mocked deps)', () => { expect(model.removeBlock).not.toHaveBeenCalled(); }); + it('should nest the block data under a `data` key rather than spreading it', () => { + blocksManager.insert({ type: 'paragraph', + data: { text: 'Alpha' } }); + + expect(model.addBlock).toHaveBeenCalledWith( + USER_ID, + expect.objectContaining({ + name: 'paragraph', + data: { text: 'Alpha' }, + }), + BLOCKS_COUNT + ); + expect(model.addBlock).not.toHaveBeenCalledWith( + USER_ID, + expect.objectContaining({ text: 'Alpha' }), + BLOCKS_COUNT + ); + }); + + it('should forward the plugins map when one is passed', () => { + blocksManager.insert({ type: 'paragraph', + plugins: { anchors: { id: 'intro' } } }); + + expect(model.addBlock).toHaveBeenCalledWith( + USER_ID, + expect.objectContaining({ plugins: { anchors: { id: 'intro' } } }), + BLOCKS_COUNT + ); + }); + + it('should omit the plugins key entirely when no plugin data is passed', () => { + blocksManager.insert({ type: 'paragraph' }); + + const blockInit = (model.addBlock as jest.Mock).mock.calls[0][1] as Record; + + expect('plugins' in blockInit).toBe(false); + }); + it('should use explicit index when provided', () => { blocksManager.insert({ index: 2, @@ -727,6 +765,66 @@ describe('BlocksManager (unit, mocked deps)', () => { ); }); + it('should carry the block plugin data over to the converted block', () => { + model.getBlockSerialized = jest.fn(() => ({ + name: 'header', + id: 'b1', + data: { + text: { + value: 'Hello', + fragments: [] + } + }, + plugins: { anchors: { id: 'intro' } } + })); + + const sourceTool = { exportTextContent: jest.fn(() => 'Hello') }; + const targetTool = { + importTextContent: jest.fn(() => ({ + text: { + value: 'Hello', + fragments: [] + } + })) + }; + + // @ts-expect-error — mock + toolsManager.blockTools.get = jest.fn((name: string) => + name === 'header' ? sourceTool : targetTool + ); + + blocksManager.convertBlock(0, 'text' as DataKey, 'paragraph'); + + expect(model.addBlock).toHaveBeenCalledWith( + USER_ID, + expect.objectContaining({ plugins: { anchors: { id: 'intro' } } }), + 0 + ); + }); + + it('should omit the plugins key when the source block has no plugin data', () => { + const sourceTool = { exportTextContent: jest.fn(() => 'Hello') }; + const targetTool = { + importTextContent: jest.fn(() => ({ + text: { + value: 'Hello', + fragments: [] + } + })) + }; + + // @ts-expect-error — mock + toolsManager.blockTools.get = jest.fn((name: string) => + name === 'header' ? sourceTool : targetTool + ); + + blocksManager.convertBlock(0, 'text' as DataKey, 'paragraph'); + + const blockInit = (model.addBlock as jest.Mock).mock.calls[0][1] as Record; + + expect('plugins' in blockInit).toBe(false); + }); + it('should merge dataOverrides on top of the imported data', () => { const sourceTool = { exportTextContent: jest.fn(() => 'Hello') }; const targetTool = { diff --git a/packages/model/src/entities/BlockNode/BlockNode.integration.spec.ts b/packages/model/src/entities/BlockNode/BlockNode.integration.spec.ts index 569b7744..a6ce4ff0 100644 --- a/packages/model/src/entities/BlockNode/BlockNode.integration.spec.ts +++ b/packages/model/src/entities/BlockNode/BlockNode.integration.spec.ts @@ -4,6 +4,13 @@ import { BlockNode } from './index.js'; import { NODE_TYPE_HIDDEN_PROP } from '@editorjs/model-types'; import { ValueNode } from '../ValueNode/index.js'; +/** + * Plugin names that collide with Object.prototype members, kept in constants so the + * literals don't trip the naming-convention lint rules + */ +const PROTO_NAME = '__proto__'; +const TO_STRING_NAME = 'toString'; + describe('BlockNode integration tests', () => { it('should create ValueNode by primitive value', () => { const value = 'value'; @@ -307,22 +314,22 @@ describe('BlockNode integration tests', () => { it('should store data for a plugin named like an object prototype member', () => { const blockNode = new BlockNode({ name: 'blockNode' }); - blockNode.updatePluginData(createPluginDataName('__proto__'), { id: 'intro' }); - blockNode.updatePluginData(createPluginDataName('toString'), { id: 'other' }); + blockNode.updatePluginData(createPluginDataName(PROTO_NAME), { id: 'intro' }); + blockNode.updatePluginData(createPluginDataName(TO_STRING_NAME), { id: 'other' }); expect(blockNode.serialized.plugins) - .toEqual({ '__proto__': { id: 'intro' }, - 'toString': { id: 'other' } }); + .toEqual({ [PROTO_NAME]: { id: 'intro' }, + [TO_STRING_NAME]: { id: 'other' } }); expect(Object.prototype) .not.toHaveProperty('id'); }); it('should round-trip a plugin named like an object prototype member through initialization', () => { const blockNode = new BlockNode({ name: 'blockNode', - plugins: { '__proto__': { id: 'intro' } } }); + plugins: { [PROTO_NAME]: { id: 'intro' } } }); expect(blockNode.serialized.plugins) - .toEqual({ '__proto__': { id: 'intro' } }); + .toEqual({ [PROTO_NAME]: { id: 'intro' } }); }); it('should throw when the plugin data name is empty', () => { diff --git a/packages/model/src/entities/BlockNode/BlockNode.spec.ts b/packages/model/src/entities/BlockNode/BlockNode.spec.ts index 6ec8095f..680f1a35 100644 --- a/packages/model/src/entities/BlockNode/BlockNode.spec.ts +++ b/packages/model/src/entities/BlockNode/BlockNode.spec.ts @@ -854,6 +854,24 @@ describe('BlockNode', () => { }); }); + describe('constructing with plugin data', () => { + afterEach(() => { + jest.clearAllMocks(); + }); + + it('should apply every key of the initial plugin data through the node', () => { + const spy = jest.spyOn(PluginDataNode.prototype, 'update'); + + createBlockNodeWithData({}, { anchors: { id: 'intro', + visible: true } }); + + expect(spy) + .toHaveBeenCalledWith('id', 'intro'); + expect(spy) + .toHaveBeenCalledWith('visible', true); + }); + }); + describe('.updatePluginData()', () => { afterEach(() => { jest.clearAllMocks(); diff --git a/packages/model/src/entities/BlockNode/index.ts b/packages/model/src/entities/BlockNode/index.ts index da763926..b44ad79a 100644 --- a/packages/model/src/entities/BlockNode/index.ts +++ b/packages/model/src/entities/BlockNode/index.ts @@ -159,15 +159,16 @@ export class BlockNode extends EventBus { entry => this.#serializeData(entry) ); - const serializedPlugins: Record = {}; - - Object.entries(this.#plugins).forEach(([pluginName, pluginData]) => { - if (pluginData.isEmpty) { - return; - } - - serializedPlugins[pluginName] = pluginData.serialized; - }); + /** + * Built through Object.fromEntries rather than by assignment: a plugin name is document data, + * and assigning a `__proto__` key to a plain object would set its prototype instead of adding + * the entry, silently dropping that plugin's data from the serialized block. + */ + const serializedPlugins = Object.fromEntries( + Object.entries(this.#plugins) + .filter(([, pluginData]) => !pluginData.isEmpty) + .map(([pluginName, pluginData]) => [pluginName, pluginData.serialized]) + ) as Record; return { id: this.#id, diff --git a/packages/model/src/entities/EditorDocument/EditorDocument.spec.ts b/packages/model/src/entities/EditorDocument/EditorDocument.spec.ts index 055b3434..42b7cad1 100644 --- a/packages/model/src/entities/EditorDocument/EditorDocument.spec.ts +++ b/packages/model/src/entities/EditorDocument/EditorDocument.spec.ts @@ -1500,6 +1500,34 @@ describe('EditorDocument', () => { expect(spy) .toHaveBeenCalledWith(blockIndex, dataKey, 'bold', 0, rangeEnd); }); + + it('should call .updatePluginData() when a plugin data index is provided', () => { + const spy = jest.spyOn(document, 'updatePluginData'); + const pluginName = 'anchors' as PluginDataName; + const index = Index.pluginData(blockIndex, pluginName, 'id'); + + document.modifyData(index, { + value: 'intro', + previous: undefined, + }); + + expect(spy) + .toHaveBeenCalledWith(blockIndex, pluginName, { id: 'intro' }); + }); + + it('should apply the removal of a plugin data key when the new value is undefined', () => { + const spy = jest.spyOn(document, 'updatePluginData'); + const pluginName = 'anchors' as PluginDataName; + const index = Index.pluginData(blockIndex, pluginName, 'id'); + + document.modifyData(index, { + value: undefined, + previous: 'intro', + }); + + expect(spy) + .toHaveBeenCalledWith(blockIndex, pluginName, { id: undefined }); + }); }); describe('.removeText()', () => { From 12573eed690d2861b0b6b122cd8ad12390d07f21 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 26 Sep 2026 00:58:52 +0100 Subject: [PATCH 06/29] feat(core): carry v2 tune data into plugin data on conversion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit composeDataFromVersion2 dropped each v2 block's `tunes` silently. It now maps them onto the v3 `plugins` key: - names are kept verbatim, so a v3 plugin that adopts a v2 tune's name finds its data without a rename table - object data is copied key by key - a primitive, an array or null goes under the `value` key, since a plugin entry is a key/value map while v2 tune data is any JSON value - a block with no tunes, or an empty map, produces no `plugins` key - the entry map is built with Object.fromEntries, so a tune named `__proto__` survives instead of setting a prototype Adds the file's first spec, including the converter's existing data handling, and an integration test taking a v2 document through the converter into the model and reading it back with api.blocks.getPluginData. The spec stubs DOMParser, which the pre-existing inline-fragment extraction needs and this package's node test environment lacks. That extraction stays untested, so the file's mutation score is low (25%, threshold 0) — it simply had no spec at all before. Co-Authored-By: Claude Opus 5 --- .../src/api/BlocksAPI.integration.spec.ts | 29 +++ .../src/utils/composeDataFromVersion2.spec.ts | 172 ++++++++++++++++++ .../core/src/utils/composeDataFromVersion2.ts | 38 +++- 3 files changed, 237 insertions(+), 2 deletions(-) create mode 100644 packages/core/src/utils/composeDataFromVersion2.spec.ts diff --git a/packages/core/src/api/BlocksAPI.integration.spec.ts b/packages/core/src/api/BlocksAPI.integration.spec.ts index dcd17300..062cc556 100644 --- a/packages/core/src/api/BlocksAPI.integration.spec.ts +++ b/packages/core/src/api/BlocksAPI.integration.spec.ts @@ -8,6 +8,7 @@ import type ToolsManager from '../tools/ToolsManager'; import type { TextNodeSerialized } from '@editorjs/sdk'; import { EventBus, EventType, BlockAddedEvent, BlockRemovedEvent } from '@editorjs/sdk'; import { EditorJSModel } from '@editorjs/model'; +import type { OutputData } from 'editorjs-v2'; const USER_ID = 'integration-user'; const DOCUMENT_ID = 'integration-doc'; @@ -35,6 +36,7 @@ jest.unstable_mockModule('../tools/ToolsManager', () => ({ const ToolsManager = (await import('../tools/ToolsManager')).default; const { BlocksManager } = await import('../components/BlockManager.js'); const { BlocksAPI } = await import('./BlocksAPI.js'); +const { composeDataFromVersion2 } = await import('../utils/composeDataFromVersion2.js'); describe('BlocksAPI integration (real model, mocked tools)', () => { let model: InstanceType; @@ -1268,6 +1270,33 @@ describe('BlocksAPI integration (real model, mocked tools)', () => { plugin: 'anchors' })).toThrow('missing'); }); + it('should expose tune data from a converted v2 document through getPluginData', () => { + /** + * The path a v2 document actually takes on boot: `composeDataFromVersion2` maps its `tunes` + * onto `plugins`, and the model is initialized from the result. `level` is used instead of a + * text field so the conversion needs no DOMParser, which this test environment lacks. + */ + const { blocks } = composeDataFromVersion2({ + blocks: [ + { + type: 'header', + data: { level: 2 }, + tunes: { + anchors: { id: 'intro' }, + alignment: 'left', + }, + }, + ], + } as OutputData); + + model.initializeDocument({ blocks }); + + expect(blocksAPI.getPluginData({ block: 0, + plugin: 'anchors' })).toEqual({ id: 'intro' }); + expect(blocksAPI.getPluginData({ block: 0, + plugin: 'alignment' })).toEqual({ value: 'left' }); + }); + it('should preserve plugin data when a block is moved', () => { blocksAPI.insert({ type: 'paragraph', plugins: { anchors: { id: 'first' } } }); diff --git a/packages/core/src/utils/composeDataFromVersion2.spec.ts b/packages/core/src/utils/composeDataFromVersion2.spec.ts new file mode 100644 index 00000000..eef01531 --- /dev/null +++ b/packages/core/src/utils/composeDataFromVersion2.spec.ts @@ -0,0 +1,172 @@ +import { afterAll, beforeAll, describe, it, expect } from '@jest/globals'; +import type { OutputData } from 'editorjs-v2'; +import { composeDataFromVersion2 } from './composeDataFromVersion2.js'; + +/** + * Plugin name that collides with an Object.prototype member, kept in a constant so the + * literal doesn't trip the naming-convention lint rule + */ +const PROTO_NAME = '__proto__'; + +/** + * Builds v2 output data with a single paragraph block + * @param block - fields to merge into that block + */ +function v2Data(block: Partial = {}): OutputData { + return { + blocks: [ + { + type: 'paragraph', + data: { text: 'Alpha' }, + ...block, + }, + ], + } as OutputData; +} + +/** + * Node type constants as the DOM exposes them, needed by the parser stub below + */ +const TEXT_NODE = 3; +const ELEMENT_NODE = 1; + +/** + * Minimal stand-in for what the converter reads off a parsed document + */ +interface ParsedDocumentStub { + /** + * Body whose children the converter walks to collect inline fragments + */ + body: { + /** + * Child nodes of the body; the stub yields one text node + */ + childNodes: unknown[]; + }; +} + +/** + * Stubs the DOMParser the converter uses to pull inline fragments out of v2 HTML strings, since + * this test environment has no jsdom. Only the traversal surface the converter touches is + * provided: a body of plain text nodes, so a string round-trips as text carrying no fragments. + * @returns function restoring the previous globals + */ +function mockDOMParser(): () => void { + const globals = globalThis as unknown as Record; + const originalParser = globals.DOMParser; + const originalNode = globals.Node; + + const parserStub = class { + /** + * Wraps the whole string in a single text node + * @param html - markup the converter hands over + * @returns document-like object the converter can walk + */ + public parseFromString(html: string): ParsedDocumentStub { + return { + body: { + childNodes: [{ nodeType: TEXT_NODE, + textContent: html }], + }, + }; + } + }; + + globals.DOMParser = parserStub; + globals.Node = Object.fromEntries([ + ['TEXT_NODE', TEXT_NODE], + ['ELEMENT_NODE', ELEMENT_NODE], + ]); + + return () => { + globals.DOMParser = originalParser; + globals.Node = originalNode; + }; +} + +describe('composeDataFromVersion2', () => { + let restoreDOMParser: () => void; + + beforeAll(() => { + restoreDOMParser = mockDOMParser(); + }); + + afterAll(() => { + restoreDOMParser(); + }); + + describe('block data', () => { + it('should convert a string value into a text node', () => { + const { blocks } = composeDataFromVersion2(v2Data()); + + expect(blocks[0].name).toBe('paragraph'); + expect(blocks[0].data).toEqual({ + text: expect.objectContaining({ value: 'Alpha' }), + }); + }); + + it('should keep a non-string value as a serialized value node', () => { + const { blocks } = composeDataFromVersion2(v2Data({ data: { level: 2 } })); + + expect(blocks[0].data).toEqual({ level: 2 }); + }); + }); + + describe('tune data', () => { + it('should map a tune into plugin data under the same key', () => { + const { blocks } = composeDataFromVersion2(v2Data({ tunes: { anchors: { id: 'intro' } } })); + + expect(blocks[0].plugins).toEqual({ anchors: { id: 'intro' } }); + }); + + it('should map several tunes independently', () => { + const { blocks } = composeDataFromVersion2(v2Data({ + tunes: { + anchors: { id: 'intro' }, + footnotes: { count: 2 }, + }, + })); + + expect(blocks[0].plugins).toEqual({ + anchors: { id: 'intro' }, + footnotes: { count: 2 }, + }); + }); + + it('should store a primitive tune value under the `value` key', () => { + const { blocks } = composeDataFromVersion2(v2Data({ tunes: { alignment: 'left' } })); + + expect(blocks[0].plugins).toEqual({ alignment: { value: 'left' } }); + }); + + it('should store an array tune value under the `value` key', () => { + const { blocks } = composeDataFromVersion2(v2Data({ tunes: { list: [1, 2] } })); + + expect(blocks[0].plugins).toEqual({ list: { value: [1, 2] } }); + }); + + it('should store a null tune value under the `value` key', () => { + const { blocks } = composeDataFromVersion2(v2Data({ tunes: { maybe: null } })); + + expect(blocks[0].plugins).toEqual({ maybe: { value: null } }); + }); + + it('should produce no plugins key for a block without tunes', () => { + const { blocks } = composeDataFromVersion2(v2Data()); + + expect('plugins' in blocks[0]).toBe(false); + }); + + it('should produce no plugins key for an empty tunes map', () => { + const { blocks } = composeDataFromVersion2(v2Data({ tunes: {} })); + + expect('plugins' in blocks[0]).toBe(false); + }); + + it('should keep a tune whose name collides with an object prototype member', () => { + const { blocks } = composeDataFromVersion2(v2Data({ tunes: { [PROTO_NAME]: { id: 'intro' } } })); + + expect(blocks[0].plugins).toEqual({ [PROTO_NAME]: { id: 'intro' } }); + }); + }); +}); diff --git a/packages/core/src/utils/composeDataFromVersion2.ts b/packages/core/src/utils/composeDataFromVersion2.ts index 9d096f5d..1732637f 100644 --- a/packages/core/src/utils/composeDataFromVersion2.ts +++ b/packages/core/src/utils/composeDataFromVersion2.ts @@ -1,7 +1,7 @@ -import type { OutputData } from 'editorjs-v2'; +import type { OutputBlockData, OutputData } from 'editorjs-v2'; import { TextNode, ValueNode } from '@editorjs/model'; import type { InlineFragment } from '@editorjs/sdk'; -import { createInlineToolData, createInlineToolName, type BlockNodeInit } from '@editorjs/sdk'; +import { createInlineToolData, createInlineToolName, type BlockNodeInit, type PluginDataSerialized } from '@editorjs/sdk'; /** * Removes HTML tags from the input string @@ -85,6 +85,35 @@ function extractFragments(html: string): InlineFragment[] { return fragments; } +/** + * Key a non-object tune value is stored under, since plugin data is a key/value map + * while v2 tune data may be any JSON value + */ +const SCALAR_TUNE_KEY = 'value'; + +/** + * Maps a v2 block's tunes onto v3 per-plugin data. + * + * Names are kept verbatim: a v3 plugin that replaces a v2 tune is expected to adopt that tune's + * name, which is also what makes the stored data match. Object data is copied key by key; anything + * else (a primitive, an array, null) goes under `value`, because a plugin entry is a key/value map. + * @param tunes - `tunes` map of a v2 block + */ +function composePluginsFromTunes(tunes: NonNullable): Record { + return Object.fromEntries( + Object.entries(tunes).map(([tuneName, tuneData]) => { + const isPlainObject = typeof tuneData === 'object' && tuneData !== null && !Array.isArray(tuneData); + + return [ + tuneName, + isPlainObject + ? { ...tuneData as Record } + : { [SCALAR_TUNE_KEY]: tuneData }, + ]; + }) + ) as Record; +} + /** * Converst OutputData from version 2 to version 3 * @param data - OutputData from version 2 @@ -97,8 +126,13 @@ export function composeDataFromVersion2(data: OutputData): { } { return { blocks: data.blocks.map((block) => { + const plugins = block.tunes !== undefined && Object.keys(block.tunes).length > 0 + ? composePluginsFromTunes(block.tunes) + : undefined; + return { name: block.type, + ...(plugins !== undefined && { plugins }), data: Object.fromEntries( Object .entries(block.data as Record) From eb540c6afa69d4a191699cfb12c1950fadffdd87 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 26 Sep 2026 01:04:11 +0100 Subject: [PATCH 07/29] docs: describe per-block plugin data in place of block tunes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - model.md, events.md, index-serialization.md: PluginDataNode, PluginDataIndex (`k: "plugin"` with `plugin`/`key` fields), PluginDataModifiedEvent, and Index.pluginData - plugins.md: a new "Per-block plugin data" section for plugin authors — the two API calls, the EditorjsPluginDataMap augmentation, and the behaviors that bite (key removal, per-key undo granularity, last-writer-wins on the same key, preserved data for unregistered plugins, move/convert/split, v2 carry over) — plus the two new api.blocks rows and the third type map - diagrams: model-tree-structure, events-catalog, architecture-overview - docs-updater agent: map the renamed model entity to docs/model.md Mentions of the Block Tune *tool kind* stay: they belong to remove-block-tunes. Co-Authored-By: Claude Opus 5 --- .github/agents/docs-updater.agent.md | 2 +- docs/diagrams/architecture-overview.mmd | 2 +- docs/diagrams/events-catalog.mmd | 4 +- docs/diagrams/model-tree-structure.mmd | 11 +++--- docs/events.md | 4 +- docs/index-serialization.md | 26 ++++++------- docs/model.md | 6 +-- docs/plugins.md | 49 +++++++++++++++++++++++-- 8 files changed, 74 insertions(+), 30 deletions(-) diff --git a/.github/agents/docs-updater.agent.md b/.github/agents/docs-updater.agent.md index 3cf34626..a54601c8 100644 --- a/.github/agents/docs-updater.agent.md +++ b/.github/agents/docs-updater.agent.md @@ -27,7 +27,7 @@ Follow this sequence for every run: | Changed area | Primary doc(s) | Diagram(s) | |---|---|---| | Package list, dependencies, overall structure | `docs/architecture.md`, root `README.md` | `diagrams/architecture-overview.mmd` | -| `EditorJSModel`, `EditorDocument`, `BlockNode`, `TextNode`, `ValueNode`, `BlockTune`, `Index`, `CaretManager` | `docs/model.md` | `diagrams/model-tree-structure.mmd` | +| `EditorJSModel`, `EditorDocument`, `BlockNode`, `TextNode`, `ValueNode`, `PluginDataNode`, `Index`, `CaretManager` | `docs/model.md` | `diagrams/model-tree-structure.mmd` | | Event classes, `EventType`, `EventBus` | `docs/events.md` | `diagrams/events-catalog.mmd` | | `Core`, `BlocksManager`, `BlockRenderer`, `SelectionManager`, `ToolsManager`, `EditorAPI`, plugin/tool lifecycle | `docs/plugins.md` | `diagrams/plugin-lifecycle-flow.mmd` | | `DOMBlockToolAdapter`, `CaretAdapter`, `FormattingAdapter`, `InputsRegistry`, `BeforeInputUIEvent` | `docs/input-handling.md` | `diagrams/block-adapter-input-flow.mmd`, `diagrams/caret-selection-flow.mmd`, `diagrams/inline-formatting-flow.mmd` | diff --git a/docs/diagrams/architecture-overview.mmd b/docs/diagrams/architecture-overview.mmd index a1b1f5b6..9bf0bd0d 100644 --- a/docs/diagrams/architecture-overview.mmd +++ b/docs/diagrams/architecture-overview.mmd @@ -26,7 +26,7 @@ classDiagram +block(blockIndex, documentId?)$ BlockIndex +text(segments)$ TextIndex +data(blockIndex, dataKey)$ DataIndex - +tune(blockIndex, tuneName, tuneKey)$ TuneIndex + +pluginData(blockIndex, pluginName, pluginKey)$ PluginDataIndex } } diff --git a/docs/diagrams/events-catalog.mmd b/docs/diagrams/events-catalog.mmd index d2313c4b..3c2fa817 100644 --- a/docs/diagrams/events-catalog.mmd +++ b/docs/diagrams/events-catalog.mmd @@ -80,7 +80,7 @@ classDiagram detail.data.value: T detail.data.previous: T } - class TuneModifiedEvent { + class PluginDataModifiedEvent { detail.data.value: T detail.data.previous: T } @@ -163,7 +163,7 @@ classDiagram DataNodeAddedEvent --|> BaseDocumentEvent DataNodeRemovedEvent --|> BaseDocumentEvent ValueModifiedEvent --|> BaseDocumentEvent - TuneModifiedEvent --|> BaseDocumentEvent + PluginDataModifiedEvent --|> BaseDocumentEvent PropertyModifiedEvent --|> BaseDocumentEvent BlockAddedCoreEvent --|> CoreEventBase diff --git a/docs/diagrams/model-tree-structure.mmd b/docs/diagrams/model-tree-structure.mmd index b7f54b2a..95a7bb4d 100644 --- a/docs/diagrams/model-tree-structure.mmd +++ b/docs/diagrams/model-tree-structure.mmd @@ -38,7 +38,7 @@ classDiagram class BlockNode { +name: BlockToolName +data: BlockNodeData - +tunes: Record~BlockTuneName, BlockTune~ + +plugins: Record~PluginDataName, PluginDataNode~ +parent: EditorDocument +createDataNode(key, data) +removeDataNode(key) @@ -47,9 +47,10 @@ classDiagram +getFragments(key, ...): InlineFragment[] } - class BlockTune { - +name: BlockTuneName + class PluginDataNode { + +name: PluginDataName +data: Record~string, unknown~ + +isEmpty: boolean +update(key, value) } @@ -123,7 +124,7 @@ classDiagram EditorJSModel --|> EventBus EditorDocument --|> EventBus BlockNode --|> EventBus - BlockTune --|> EventBus + PluginDataNode --|> EventBus ValueNode --|> EventBus ParentInlineNode --|> EventBus @@ -134,7 +135,7 @@ classDiagram EditorDocument "1" *-- "0..*" BlockNode : children BlockNode "1" *-- "0..*" TextNode : data[key] BlockNode "1" *-- "0..*" ValueNode : data[key] - BlockNode "1" *-- "0..*" BlockTune : tunes[name] + BlockNode "1" *-- "0..*" PluginDataNode : plugins[name] %% Inline tree TextNode --|> ParentInlineNode diff --git a/docs/events.md b/docs/events.md index 7e740804..635923e2 100644 --- a/docs/events.md +++ b/docs/events.md @@ -4,7 +4,7 @@ The editor exposes two public event transports. | Transport | Dispatched on | Event types | |---|---|---| -| `EditorJSModel` `EventType.Changed` | `EditorJSModel` instance | `BlockAddedEvent`, `BlockRemovedEvent`, `TextAddedEvent`, `TextRemovedEvent`, `TextFormattedEvent`, `TextUnformattedEvent`, `ValueModifiedEvent`, `TuneModifiedEvent`, `DataNodeAddedEvent`, `DataNodeRemovedEvent`, `PropertyModifiedEvent` | +| `EditorJSModel` `EventType.Changed` | `EditorJSModel` instance | `BlockAddedEvent`, `BlockRemovedEvent`, `TextAddedEvent`, `TextRemovedEvent`, `TextFormattedEvent`, `TextUnformattedEvent`, `ValueModifiedEvent`, `PluginDataModifiedEvent`, `DataNodeAddedEvent`, `DataNodeRemovedEvent`, `PropertyModifiedEvent` | | `EditorJSModel` `EventType.CaretManagerUpdated` | `EditorJSModel` instance | `CaretManagerCaretUpdatedEvent`, `CaretManagerCaretAddedEvent`, `CaretManagerCaretRemovedEvent` | | Core `EventBus` (per editor instance) | `EventBus` held in the IoC container | `BlockAddedCoreEvent`, `BlockRemovedCoreEvent`, `ToolLoadedCoreEvent`, `SelectionChangedCoreEvent`, `UndoCoreEvent`, `RedoCoreEvent`, `BeforeInputUIEvent` | @@ -27,7 +27,7 @@ All document mutation events extend `BaseDocumentEvent`: | `TextFormattedEvent` | `{ tool, data }` | An inline tool was applied to a text range | | `TextUnformattedEvent` | `{ tool, data }` | An inline tool was removed from a text range | | `ValueModifiedEvent` | `{ value, previous }` | A `ValueNode`'s value was changed | -| `TuneModifiedEvent` | `{ value, previous }` | A `BlockTune`'s data was updated | +| `PluginDataModifiedEvent` | `{ value, previous }` | One key of a plugin's per-block data was updated; `value` is `undefined` when the key was removed | | `DataNodeAddedEvent` | `BlockNodeDataSerializedValue` | A data node (text or value) was created on a block | | `DataNodeRemovedEvent` | `BlockNodeDataSerializedValue` | A data node was removed from a block | | `PropertyModifiedEvent` | `{ value, previous }` | A top-level document property was set | diff --git a/docs/index-serialization.md b/docs/index-serialization.md index d9fc1f15..8bd1535f 100644 --- a/docs/index-serialization.md +++ b/docs/index-serialization.md @@ -64,19 +64,19 @@ All fields that can be omitted (`id`) are absent from the JSON when `undefined` --- -## `TuneIndex` — `k: "tune"` +## `PluginDataIndex` — `k: "plugin"` ```json -{ "k": "tune", "b": 2, "tune": "", "key": "", "id": "" } +{ "k": "plugin", "b": 2, "plugin": "", "key": "", "id": "" } ``` -| Field | Type | Required | -|--------|----------|----------| -| `k` | `"tune"` | yes | -| `b` | number | yes — zero-based block position | -| `tune` | string | yes — block tune name | -| `key` | string | yes — key within the tune | -| `id` | string | no | +| Field | Type | Required | +|----------|------------|----------| +| `k` | `"plugin"` | yes | +| `b` | number | yes — zero-based block position | +| `plugin` | string | yes — name the data is stored under, by convention the plugin's `name` | +| `key` | string | yes — key within that plugin's data | +| `id` | string | no | --- @@ -167,13 +167,13 @@ Index.block(2, 'doc-abc').serialize() // → '{"k":"block","b":2,"id":"doc-abc"}' ``` -### Tune property change +### Plugin data change -A `fontSize` tune on block 1, key `"size"` changed. +The `fontSize` plugin's `"size"` key changed on block 1. ```ts -Index.tune(1, 'fontSize', 'size').serialize() -// → '{"k":"tune","b":1,"tune":"fontSize","key":"size"}' +Index.pluginData(1, 'fontSize', 'size').serialize() +// → '{"k":"plugin","b":1,"plugin":"fontSize","key":"size"}' ``` ### Round-trip through `Index.parse` diff --git a/docs/model.md b/docs/model.md index b01c057d..72d79c28 100644 --- a/docs/model.md +++ b/docs/model.md @@ -10,7 +10,7 @@ Each `BlockNode` contains keyed data nodes: - `TextNode`: rich text with inline tree (`FormattingInlineNode` + `TextInlineNode`). - `ValueNode`: non-text typed value for tools. -- `BlockTune`: per-block tune configuration. +- `PluginDataNode`: per-block data owned by a plugin, keyed by the plugin's `name`. ## Mutation and event invariant @@ -41,7 +41,7 @@ IndexBase (abstract) ├── PropertyIndex — top-level document property ├── BlockIndex — a single block ├── DataIndex — a data key inside a block -├── TuneIndex — a key inside a block tune +├── PluginDataIndex — a key inside one plugin's per-block data └── TextIndex — character range(s) inside a text node ``` @@ -68,7 +68,7 @@ Index.document(documentId) Index.property(name, documentId?) Index.block(blockIndex, documentId?) Index.data(blockIndex, dataKey, documentId?) -Index.tune(blockIndex, tuneName, tuneKey, documentId?) +Index.pluginData(blockIndex, pluginName, pluginKey, documentId?) Index.text(segments) Index.parse(serialized) // deserialize from string ``` diff --git a/docs/plugins.md b/docs/plugins.md index 55156296..30722b3b 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -114,11 +114,52 @@ Merging is shallow **at the plugin-id level**: a slice supplied through `use()` const { shortcut } = toolFacade.pluginOptions('shortcuts') ?? {}; ``` +## Per-block plugin data + +A plugin stores its own data on a block through `api.blocks`, under a key that is by convention the +plugin's `name`. The entry is created on first write, so there is nothing to initialize: + +```ts +api.blocks.updatePluginData({ block: blockId, plugin: 'anchors', data: { id: 'intro' } }); + +api.blocks.getPluginData({ block: blockId, plugin: 'anchors' }); // → { id: 'intro' } +``` + +Declare the shape once and both calls are typed, with a wrong value a compile error: + +```ts +declare module '@editorjs/sdk' { + interface EditorjsPluginDataMap { + anchors: { id: string }; + } +} +``` + +A plugin that never augments the map still works: its data is typed as `Record`. + +Things worth knowing before relying on it: + +- **A key set to `undefined` is removed**, and an entry with no keys left is dropped from the + serialized block. So `getPluginData` returns `undefined` both for a plugin that never wrote + anything and for one whose last key was removed. +- **Each key is its own change.** Writing two keys in one call produces two modifications, so one + undo reverts only the last of them. Write a single key when the change must be atomic. +- **Concurrent writes to the same key resolve last-writer-wins.** Two collaborators toggling + different keys of the same plugin do not collide; two writing the same key do, and the operation + the server orders last wins. Split state across keys when that matters. +- **Data for an unregistered plugin is preserved**, not dropped, so opening a document in an editor + without that plugin does not lose it. +- **Blocks keep their data through `move` and `convert`**; a `split` leaves it on the original block + and gives the new one none. +- **v2 documents carry over**: a v2 block's `tunes` are mapped onto the same keys on load, and a + tune whose data was not an object lands under a `value` key. + ## TypeScript caveats -Both features — calling a plugin API and configuring a plugin from a tool — are typed the same -way: `@editorjs/sdk` declares two empty interfaces (`EditorjsPluginApiMap`, `ToolPluginOptionsMap`) -and each plugin package fills in its own row via module augmentation. That gives inference with no +Three features — calling a plugin API, configuring a plugin from a tool, and storing per-block +plugin data — are typed the same way: `@editorjs/sdk` declares three empty interfaces +(`EditorjsPluginApiMap`, `ToolPluginOptionsMap`, `EditorjsPluginDataMap`) and each plugin package +fills in its own row via module augmentation. That gives inference with no casts, but it comes with rules worth knowing before you hit them. ### The augmentation must be in *your* compilation @@ -267,6 +308,8 @@ Programmatic block management — delegates to `BlocksManager`. | `render(document)` | Re-initialize the document from serialised data | | `clear()` | Remove all blocks | | `getBlocksCount()` | Return the total number of blocks | +| `getPluginData({ block, plugin })` | Read a plugin's per-block data, or `undefined` | +| `updatePluginData({ block, plugin, data, userId? })` | Merge keys into a plugin's per-block data | ### `api.selection` From b62d8208ea96cdb03aae6b835bdffecb4da23cfb Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 26 Sep 2026 01:04:35 +0100 Subject: [PATCH 08/29] docs(openspec): check off the implemented plugin-block-data tasks Every task is done except the final one, which is the ready-to-archive signal: leaving it unchecked keeps the archive gate quiet until a maintainer comments /archive on the PR, per CONTRIBUTING. Co-Authored-By: Claude Opus 5 --- openspec/changes/plugin-block-data/tasks.md | 72 ++++++++++----------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/openspec/changes/plugin-block-data/tasks.md b/openspec/changes/plugin-block-data/tasks.md index 12e0dbc0..824d018a 100644 --- a/openspec/changes/plugin-block-data/tasks.md +++ b/openspec/changes/plugin-block-data/tasks.md @@ -1,56 +1,56 @@ ## 1. Model types: rename tune → plugin data -- [ ] 1.1 Write failing `Index.spec.ts` cases: `Index.pluginData(1, 'anchors', 'id')` should serialize to `{"k":"plugin","b":1,"plugin":"anchors","key":"id"}`, `Index.parse` should round-trip it, and `PartialIndex#resolve` should throw `PluginDataIndex requires pluginKey` / `DataIndex cannot be combined with pluginName` -- [ ] 1.2 Rename `TuneIndex` → `PluginDataIndex` (`IndexKind.PluginData`; TypeScript members `pluginName`/`pluginKey`, serialized keys `plugin`/`key`), `Index.tune` → `Index.pluginData`, and update `PartialIndex` fields and error messages -- [ ] 1.3 Rename `BlockTuneName`/`createBlockTuneName`/`BlockTuneSerialized` → `PluginDataName`/`createPluginDataName`/`PluginDataSerialized` (`src/BlockTune.ts` → `src/PluginData.ts`) and `TuneModifiedEvent` → `PluginDataModifiedEvent`. Update `EventMap` (`BlockTuneEvents` → `PluginDataEvents`) and the exports in `index.ts` -- [ ] 1.4 Rename the `tunes` key to `plugins` in `BlockNodeSerialized`/`BlockNodeInit`/`BlockData`, and add a serialization test asserting no `tunes` key is produced -- [ ] 1.5 Update `sdk` re-exports of the renamed types and fix every compile error across the workspace (`yarn build` clean) -- [ ] 1.6 Update the jest mocks and fixtures the rename touches: `packages/model/src/entities/BlockNode/__mocks__/index.ts` (`updateTuneData`, plus a `plugins` getter if tests read it), `packages/model/src/entities/BlockTune/__mocks__`, the `jest.mock('../BlockTune')` path in `BlockNode.spec.ts`, and the `types/BlockTuneConstructorParameters.ts` / entities barrel names -- [ ] 1.7 Update `packages/model/src/EditorJSModel.spec.ts`'s hard-coded prototype-method allowlist, which contains `'updateTuneData'` as a string and so breaks with no compile error +- [x] 1.1 Write failing `Index.spec.ts` cases: `Index.pluginData(1, 'anchors', 'id')` should serialize to `{"k":"plugin","b":1,"plugin":"anchors","key":"id"}`, `Index.parse` should round-trip it, and `PartialIndex#resolve` should throw `PluginDataIndex requires pluginKey` / `DataIndex cannot be combined with pluginName` +- [x] 1.2 Rename `TuneIndex` → `PluginDataIndex` (`IndexKind.PluginData`; TypeScript members `pluginName`/`pluginKey`, serialized keys `plugin`/`key`), `Index.tune` → `Index.pluginData`, and update `PartialIndex` fields and error messages +- [x] 1.3 Rename `BlockTuneName`/`createBlockTuneName`/`BlockTuneSerialized` → `PluginDataName`/`createPluginDataName`/`PluginDataSerialized` (`src/BlockTune.ts` → `src/PluginData.ts`) and `TuneModifiedEvent` → `PluginDataModifiedEvent`. Update `EventMap` (`BlockTuneEvents` → `PluginDataEvents`) and the exports in `index.ts` +- [x] 1.4 Rename the `tunes` key to `plugins` in `BlockNodeSerialized`/`BlockNodeInit`/`BlockData`, and add a serialization test asserting no `tunes` key is produced +- [x] 1.5 Update `sdk` re-exports of the renamed types and fix every compile error across the workspace (`yarn build` clean) +- [x] 1.6 Update the jest mocks and fixtures the rename touches: `packages/model/src/entities/BlockNode/__mocks__/index.ts` (`updateTuneData`, plus a `plugins` getter if tests read it), `packages/model/src/entities/BlockTune/__mocks__`, the `jest.mock('../BlockTune')` path in `BlockNode.spec.ts`, and the `types/BlockTuneConstructorParameters.ts` / entities barrel names +- [x] 1.7 Update `packages/model/src/EditorJSModel.spec.ts`'s hard-coded prototype-method allowlist, which contains `'updateTuneData'` as a string and so breaks with no compile error ## 2. Model: plugin data node and create-on-first-write -- [ ] 2.1 Write failing `BlockNode.spec.ts` cases: updating an absent plugin name should create the entry and emit `PluginDataModifiedEvent` with `previous` `undefined`; updating one key should emit exactly one event; setting a key to `undefined` should remove it and drop an empty entry from serialization -- [ ] 2.2 Rename the `BlockTune` entity to `PluginDataNode` (`src/entities/PluginDataNode`), implement key deletion on `undefined`, and make `serialized` omit deleted keys -- [ ] 2.3 Write failing `BlockNode.spec.ts` cases for the store's key handling: a plugin named `__proto__` or `toString` should round-trip as ordinary data, and an empty plugin name should throw -- [ ] 2.4 Rename `BlockNode.#tunes`/`tunes`/`updateTuneData` → `#plugins`/`plugins`/`updatePluginData`: hold entries in a null-prototype record, reject an empty plugin name, create a missing node **empty** and attach its bubbling listener before the first `update` (the node dispatches synchronously, and without the listener the whole feature silently no-ops), and have `serialized` omit empty entries while still emitting an empty `plugins` map -- [ ] 2.5 Rename `EditorDocument.updateTuneData` and `EditorJSModel.updateTuneData` → `updatePluginData`, keeping `@WithContext`, and add a facade test that the event carries the acting `userId` -- [ ] 2.6 Write a failing test, then add a `PluginDataIndex` branch to `EditorDocument.modifyData` that sets the key to `data.value` -- [ ] 2.7 Write a failing test at the `BlockNode`/`EditorDocument` level, then replace the hardcoded `'user'` in the bubbled plugin-data event with `getContext()`, as the value-node path does -- [ ] 2.8 Add a test that a `plugins` entry for an unregistered plugin survives an initialize → serialize round trip +- [x] 2.1 Write failing `BlockNode.spec.ts` cases: updating an absent plugin name should create the entry and emit `PluginDataModifiedEvent` with `previous` `undefined`; updating one key should emit exactly one event; setting a key to `undefined` should remove it and drop an empty entry from serialization +- [x] 2.2 Rename the `BlockTune` entity to `PluginDataNode` (`src/entities/PluginDataNode`), implement key deletion on `undefined`, and make `serialized` omit deleted keys +- [x] 2.3 Write failing `BlockNode.spec.ts` cases for the store's key handling: a plugin named `__proto__` or `toString` should round-trip as ordinary data, and an empty plugin name should throw +- [x] 2.4 Rename `BlockNode.#tunes`/`tunes`/`updateTuneData` → `#plugins`/`plugins`/`updatePluginData`: hold entries in a null-prototype record, reject an empty plugin name, create a missing node **empty** and attach its bubbling listener before the first `update` (the node dispatches synchronously, and without the listener the whole feature silently no-ops), and have `serialized` omit empty entries while still emitting an empty `plugins` map +- [x] 2.5 Rename `EditorDocument.updateTuneData` and `EditorJSModel.updateTuneData` → `updatePluginData`, keeping `@WithContext`, and add a facade test that the event carries the acting `userId` +- [x] 2.6 Write a failing test, then add a `PluginDataIndex` branch to `EditorDocument.modifyData` that sets the key to `data.value` +- [x] 2.7 Write a failing test at the `BlockNode`/`EditorDocument` level, then replace the hardcoded `'user'` in the bubbled plugin-data event with `getContext()`, as the value-node path does +- [x] 2.8 Add a test that a `plugins` entry for an unregistered plugin survives an initialize → serialize round trip ## 3. Core and SDK API: plugin data access -- [ ] 3.1 Add `getPluginData`/`updatePluginData` to the SDK `BlocksAPI` interface, and a `plugins` map to the `insert` params -- [ ] 3.2 Write failing `BlocksAPI.spec.ts` / `BlockManager` tests covering read, write, absent-entry `undefined`, unknown-block error, and insert with a `plugins` map -- [ ] 3.3 Implement them in `core/src/api/BlocksAPI.ts` and `BlockManager` (defaulting `userId` to the config user), and replace the commented-out `tunes` stubs in `BlockManager` -- [ ] 3.4 Write a failing test, then fix `BlocksManager.insert`, which spreads `{ ...data, id, name }` while `BlockNode` reads a nested `data` key — so `insert({ data })` silently creates an empty block today. Nest `data` and pass `plugins` as its own key -- [ ] 3.5 Write failing tests, then make `convert` carry plugin data over and `split` create the new block without it (`move` should already pass — add a test to confirm) -- [ ] 3.6 Write a failing `UndoRedoManager` integration test (first write → undo removes the entry → redo restores it; an update undoes to the previous value), then fix whatever remains after the `modifyData` branch in 2.6 +- [x] 3.1 Add `getPluginData`/`updatePluginData` to the SDK `BlocksAPI` interface, and a `plugins` map to the `insert` params +- [x] 3.2 Write failing `BlocksAPI.spec.ts` / `BlockManager` tests covering read, write, absent-entry `undefined`, unknown-block error, and insert with a `plugins` map +- [x] 3.3 Implement them in `core/src/api/BlocksAPI.ts` and `BlockManager` (defaulting `userId` to the config user), and replace the commented-out `tunes` stubs in `BlockManager` +- [x] 3.4 Write a failing test, then fix `BlocksManager.insert`, which spreads `{ ...data, id, name }` while `BlockNode` reads a nested `data` key — so `insert({ data })` silently creates an empty block today. Nest `data` and pass `plugins` as its own key +- [x] 3.5 Write failing tests, then make `convert` carry plugin data over and `split` create the new block without it (`move` should already pass — add a test to confirm) +- [x] 3.6 Write a failing `UndoRedoManager` integration test (first write → undo removes the entry → redo restores it; an update undoes to the previous value), then fix whatever remains after the `modifyData` branch in 2.6 ## 4. Collaboration: plugin data operations -- [ ] 4.1 Write a failing `CollaborationManager.spec.ts` case: a `PluginDataModifiedEvent` should produce a `Modify` operation with `payload`/`prevPayload` -- [ ] 4.2 Add the `PluginDataModifiedEvent` case to `CollaborationManager.#handleEvent` -- [ ] 4.3 Write failing `OperationsTransformer.spec.ts` cases: shift against block insert, `Neutral` against removal of its block, a plugin-data operation used as the against-operation, and no transform between two plugin-data modifies. Add a regression assertion (not a failing test) that `Operation.inverse()` already swaps `payload`/`prevPayload` for any `Modify` -- [ ] 4.4 Add a `PluginDataIndex` branch to `OperationsTransformer.#applyTransformation`, which dispatches on the **against** operation's index kind and today throws `'Unsupported index type'`. Cover the three call sites in tests: `OTClient`'s pending-operation reduce, `UndoRedoManager.transformStacks`, and `ot-server`'s conflicting-operation reduce -- [ ] 4.5 Widen `ModifyOperationData`'s payload type from `Record` so a boolean or string payload compiles, with a test constructing a scalar plugin-data operation -- [ ] 4.6 Add an integration test with two clients where a plugin data change on one is reflected in the other's model -- [ ] 4.7 Update `packages/ot-server`: its `DocumentManager.spec.ts` uses `tunes: {}` both as `initializeDocument` input and inside `expect.objectContaining` assertions. The server applies operations against its own model, so it must be verified end to end with a plugin-data operation +- [x] 4.1 Write a failing `CollaborationManager.spec.ts` case: a `PluginDataModifiedEvent` should produce a `Modify` operation with `payload`/`prevPayload` +- [x] 4.2 Add the `PluginDataModifiedEvent` case to `CollaborationManager.#handleEvent` +- [x] 4.3 Write failing `OperationsTransformer.spec.ts` cases: shift against block insert, `Neutral` against removal of its block, a plugin-data operation used as the against-operation, and no transform between two plugin-data modifies. Add a regression assertion (not a failing test) that `Operation.inverse()` already swaps `payload`/`prevPayload` for any `Modify` +- [x] 4.4 Add a `PluginDataIndex` branch to `OperationsTransformer.#applyTransformation`, which dispatches on the **against** operation's index kind and today throws `'Unsupported index type'`. Cover the three call sites in tests: `OTClient`'s pending-operation reduce, `UndoRedoManager.transformStacks`, and `ot-server`'s conflicting-operation reduce +- [x] 4.5 Widen `ModifyOperationData`'s payload type from `Record` so a boolean or string payload compiles, with a test constructing a scalar plugin-data operation +- [x] 4.6 Add an integration test with two clients where a plugin data change on one is reflected in the other's model +- [x] 4.7 Update `packages/ot-server`: its `DocumentManager.spec.ts` uses `tunes: {}` both as `initializeDocument` input and inside `expect.objectContaining` assertions. The server applies operations against its own model, so it must be verified end to end with a plugin-data operation ## 5. Typing and v2 conversion -- [ ] 5.1 Write a failing `pluginTypeMaps.spec.ts` case: a `EditorjsPluginDataMap` augmentation should type `getPluginData`/`updatePluginData` for that id, an undeclared id should fall back to `Record`, and a wrong data shape should be a compile error -- [ ] 5.2 Declare `EditorjsPluginDataMap` in `sdk/src/index.ts`, add its keys to `PluginId`, and type the two `BlocksAPI` methods through a non-distributive `PluginDataFor` helper -- [ ] 5.3 Write failing `composeDataFromVersion2.spec.ts` cases: object tune data should map to `plugins` under the same key, a primitive or array should land under `value`, a block with no or empty `tunes` should produce no `plugins` key, and existing data conversion should be unaffected (the converter maps no block id today — that is a separate fix) -- [ ] 5.4 Implement the `tunes` → `plugins` mapping in `core/src/utils/composeDataFromVersion2.ts` -- [ ] 5.5 Add an integration test loading a v2 `config.data` document with tune data and asserting the plugin data is readable through `api.blocks.getPluginData` +- [x] 5.1 Write a failing `pluginTypeMaps.spec.ts` case: a `EditorjsPluginDataMap` augmentation should type `getPluginData`/`updatePluginData` for that id, an undeclared id should fall back to `Record`, and a wrong data shape should be a compile error +- [x] 5.2 Declare `EditorjsPluginDataMap` in `sdk/src/index.ts`, add its keys to `PluginId`, and type the two `BlocksAPI` methods through a non-distributive `PluginDataFor` helper +- [x] 5.3 Write failing `composeDataFromVersion2.spec.ts` cases: object tune data should map to `plugins` under the same key, a primitive or array should land under `value`, a block with no or empty `tunes` should produce no `plugins` key, and existing data conversion should be unaffected (the converter maps no block id today — that is a separate fix) +- [x] 5.4 Implement the `tunes` → `plugins` mapping in `core/src/utils/composeDataFromVersion2.ts` +- [x] 5.5 Add an integration test loading a v2 `config.data` document with tune data and asserting the plugin data is readable through `api.blocks.getPluginData` ## 6. Docs and wrap-up -- [ ] 6.1 Update `docs/model.md`, `docs/index-serialization.md` and `docs/events.md` for `PluginDataNode`, `PluginDataIndex` and `PluginDataModifiedEvent`, plus `docs/plugins.md` (the SDK declares **three** augmentable interfaces now) and `.github/agents/docs-updater.agent.md` (its `BlockTune` → `docs/model.md` mapping) -- [ ] 6.2 Update the diagrams `model-tree-structure.mmd`, `events-catalog.mmd` and `architecture-overview.mmd` -- [ ] 6.3 Run `yarn lint`, `yarn test`, and the mutation tests for the touched packages that have them. Fix any regressions +- [x] 6.1 Update `docs/model.md`, `docs/index-serialization.md` and `docs/events.md` for `PluginDataNode`, `PluginDataIndex` and `PluginDataModifiedEvent`, plus `docs/plugins.md` (the SDK declares **three** augmentable interfaces now) and `.github/agents/docs-updater.agent.md` (its `BlockTune` → `docs/model.md` mapping) +- [x] 6.2 Update the diagrams `model-tree-structure.mmd`, `events-catalog.mmd` and `architecture-overview.mmd` +- [x] 6.3 Run `yarn lint`, `yarn test`, and the mutation tests for the touched packages that have them. Fix any regressions - [ ] 6.4 Run `openspec validate plugin-block-data --type change` and confirm it passes. After archiving, fill the `## Purpose` of the new `plugin-block-data` spec from the proposal's intended-Purpose text ## 7. Review follow-ups From a587f533743d729b1dfc340407d82a307b06dc63 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 9 Oct 2026 23:47:52 +0100 Subject: [PATCH 09/29] docs: keep the plugin-data comments to two sentences Six comments added by this change ran to three. Same content, tightened: the v2 tune mapping, the BlockNode class doc and its `#plugins` field, the `updatePluginData` contract and `PluginDataFor`'s fallback. Co-Authored-By: Claude Opus 5 --- packages/core/src/utils/composeDataFromVersion2.ts | 8 +++----- packages/model/src/entities/BlockNode/index.ts | 12 +++++------- packages/sdk/src/api/BlocksAPI.ts | 8 +++----- packages/sdk/src/index.ts | 14 +++++--------- 4 files changed, 16 insertions(+), 26 deletions(-) diff --git a/packages/core/src/utils/composeDataFromVersion2.ts b/packages/core/src/utils/composeDataFromVersion2.ts index 1732637f..0660dcbb 100644 --- a/packages/core/src/utils/composeDataFromVersion2.ts +++ b/packages/core/src/utils/composeDataFromVersion2.ts @@ -92,11 +92,9 @@ function extractFragments(html: string): InlineFragment[] { const SCALAR_TUNE_KEY = 'value'; /** - * Maps a v2 block's tunes onto v3 per-plugin data. - * - * Names are kept verbatim: a v3 plugin that replaces a v2 tune is expected to adopt that tune's - * name, which is also what makes the stored data match. Object data is copied key by key; anything - * else (a primitive, an array, null) goes under `value`, because a plugin entry is a key/value map. + * Maps a v2 block's tunes onto v3 per-plugin data, keeping names verbatim so a v3 plugin that + * adopts a v2 tune's name finds its data. Object data is copied key by key; anything else goes + * under `value`, since a plugin entry is a key/value map. * @param tunes - `tunes` map of a v2 block */ function composePluginsFromTunes(tunes: NonNullable): Record { diff --git a/packages/model/src/entities/BlockNode/index.ts b/packages/model/src/entities/BlockNode/index.ts index b44ad79a..44c08912 100644 --- a/packages/model/src/entities/BlockNode/index.ts +++ b/packages/model/src/entities/BlockNode/index.ts @@ -54,8 +54,8 @@ import { AlreadyExistingKeyError } from './errors/AlreadyExistingKeyError.js'; /** * BlockNode class represents a node in a tree-like structure used to store and manipulate Blocks in an editor document. - * A BlockNode can contain one or more child nodes of type TextNode or ValueNode. - * It can also carry per-plugin data, which plugins use to store their own state for the block. + * A BlockNode can contain one or more child nodes of type TextNode or ValueNode, and carries the + * per-plugin data plugins use to store their own state for the block. */ export class BlockNode extends EventBus { /** @@ -79,11 +79,9 @@ export class BlockNode extends EventBus { #parent: EditorDocument | null; /** - * Per-plugin data of this block, keyed by plugin name. - * - * The record has a null prototype: names come from documents, and a plain assignment of a - * `__proto__` key to an ordinary object creates no own property at all, which would silently - * lose that plugin's data. With no prototype every name is stored as plain data. + * Per-plugin data of this block, keyed by plugin name. The record has a null prototype because + * names come from documents: assigning a `__proto__` key to an ordinary object creates no own + * property, silently losing that plugin's data. */ #plugins: Record = Object.create(null) as Record; diff --git a/packages/sdk/src/api/BlocksAPI.ts b/packages/sdk/src/api/BlocksAPI.ts index a24626ed..6e1e1281 100644 --- a/packages/sdk/src/api/BlocksAPI.ts +++ b/packages/sdk/src/api/BlocksAPI.ts @@ -238,11 +238,9 @@ export interface BlocksAPI { }): PluginDataFor | undefined; /** - * Merges the passed keys into the per-block data of the given plugin, creating the plugin's - * entry when the block has none yet. A key set to `undefined` is removed. - * - * Each key is recorded as its own modification, so a call that writes several keys is not a - * single undo step. + * Merges the passed keys into the per-block data of the given plugin, creating the entry when + * the block has none yet; a key set to `undefined` is removed. Each key is recorded as its own + * modification, so writing several keys is not a single undo step. * @param params - updatePluginData parameters * @param params.block - index or id of the block * @param params.plugin - name the data is stored under, by convention the plugin's `name` diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index cc6a0b10..244e60f2 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -48,15 +48,11 @@ export interface ToolPluginOptionsMap {} export interface EditorjsPluginDataMap {} /** - * Shape of the per-block data stored by the plugin with the given id. - * - * Falls back to a plain record for an id absent from {@link EditorjsPluginDataMap}: unlike a - * plugin's public API, per-block data is often written by a plugin that has no reason to publish - * its shape, so an undeclared id stays usable instead of resolving to `never`. - * - * The check is deliberately non-distributive (`[Id] extends [...]`), because the default - * {@link PluginId} is a union including `string & {}` and a distributive conditional would - * collapse a declared id onto the fallback. + * Shape of the per-block data stored by the plugin with the given id, falling back to a plain + * record for an id absent from {@link EditorjsPluginDataMap} — per-block data is often written by + * a plugin with no reason to publish its shape. The check is non-distributive + * (`[Id] extends [...]`) because the default {@link PluginId} includes `string & {}`, and a + * distributive conditional would collapse a declared id onto the fallback. */ export type PluginDataFor = [Id] extends [keyof EditorjsPluginDataMap] ? EditorjsPluginDataMap[Id] From 1a140c87b85d397e34a1cca59dbb6c4e322d6c4d Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 10 Oct 2026 01:00:16 +0100 Subject: [PATCH 10/29] fix(model): keep a plugin data write that changes nothing off the wire MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `PluginDataNode.update` dispatched unconditionally, carried over from `BlockTune`, where it was nearly harmless because tunes were rarely written. `updatePluginData` is now a public API that plugins call on every toggle, and each event becomes an operation for collaborators and a step on the undo stack — so re-applying the state a plugin just read filled the undo stack with entries that undo nothing. Storing the value a key already holds, or removing a key that is not there, now returns before dispatching. The removal case needs the extra clause: both sides are `undefined` whether the key is absent or present holding `undefined`, and only the latter is a real change. Also locks down the wire format for a removal, which has no test today: the payload is `undefined`, `JSON.stringify` drops the key outright, and the removal survives only because reading a missing key gives `undefined` back. Co-Authored-By: Claude Opus 5 --- openspec/changes/plugin-block-data/tasks.md | 4 +- .../src/Operation.spec.ts | 42 ++++++++++- .../UndoRedoManager.integration.spec.ts | 15 ++++ .../PluginDataNode/PluginDataNode.spec.ts | 72 +++++++++++++++++++ .../src/entities/PluginDataNode/index.ts | 13 ++++ 5 files changed, 143 insertions(+), 3 deletions(-) diff --git a/openspec/changes/plugin-block-data/tasks.md b/openspec/changes/plugin-block-data/tasks.md index 824d018a..32a95d08 100644 --- a/openspec/changes/plugin-block-data/tasks.md +++ b/openspec/changes/plugin-block-data/tasks.md @@ -55,8 +55,8 @@ ## 7. Review follow-ups -- [ ] 7.1 Write a failing `PluginDataNode.spec.ts` case for each no-op write — the value a key already holds, and the removal of a key that is not there — then make `update` return before dispatching in both. Add a `UndoRedoManager.integration.spec.ts` case asserting a repeated write leaves the undo stack alone -- [ ] 7.2 Add an `Operation.spec.ts` case round-tripping a key removal on a `PluginDataIndex` through `serialize()` and `JSON.parse`: the payload is `undefined`, which `JSON.stringify` drops, so what proves the removal survives is reading it back +- [x] 7.1 Write a failing `PluginDataNode.spec.ts` case for each no-op write — the value a key already holds, and the removal of a key that is not there — then make `update` return before dispatching in both. Add a `UndoRedoManager.integration.spec.ts` case asserting a repeated write leaves the undo stack alone +- [x] 7.2 Add an `Operation.spec.ts` case round-tripping a key removal on a `PluginDataIndex` through `serialize()` and `JSON.parse`: the payload is `undefined`, which `JSON.stringify` drops, so what proves the removal survives is reading it back ## 8. Review follow-ups (second round) diff --git a/packages/collaboration-manager/src/Operation.spec.ts b/packages/collaboration-manager/src/Operation.spec.ts index 87bf21c1..f3ca029d 100644 --- a/packages/collaboration-manager/src/Operation.spec.ts +++ b/packages/collaboration-manager/src/Operation.spec.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/no-magic-numbers */ import type { BlockIndex, BlockNodeSerialized, DataKey, DocumentId, TextIndex } from '@editorjs/sdk'; -import { Index } from '@editorjs/sdk'; +import { createPluginDataName, Index, PluginDataIndex } from '@editorjs/sdk'; import { describe } from '@jest/globals'; import { type InsertOrDeleteOperationData, type ModifyOperationData, Operation, OperationType } from './Operation.js'; @@ -324,4 +324,44 @@ describe('Operation', () => { expect(() => op.inverse()).toThrow('Unsupported operation type'); }); }); + describe('.serialize()', () => { + /** + * A key removal is a Modify whose payload is `undefined`, and `JSON.stringify` drops a key + * holding `undefined` entirely. It survives only because reading a key that is not there + * gives `undefined` back -- which is worth an assertion, since nothing in the types says so. + */ + it('should carry a plugin data removal through the wire', () => { + const index = Index.pluginData(2, createPluginDataName('anchors'), 'visible'); + const op = new Operation(OperationType.Modify, index, { + payload: undefined, + prevPayload: 'intro', + }, 'user-1'); + + op.rev = 7; + + const received = JSON.parse(JSON.stringify(op.serialize())) as ReturnType; + + expect((received.data as ModifyOperationData).payload).toBeUndefined(); + expect('payload' in received.data).toBe(false); + expect((received.data as ModifyOperationData).prevPayload).toBe('intro'); + }); + + it('should carry the plugin data index itself through the wire', () => { + const index = Index.pluginData(2, createPluginDataName('anchors'), 'visible'); + const op = new Operation(OperationType.Modify, index, { + payload: undefined, + prevPayload: 'intro', + }, 'user-1'); + + op.rev = 7; + + const received = JSON.parse(JSON.stringify(op.serialize())) as ReturnType; + const parsed = Index.parse(received.index) as PluginDataIndex; + + expect(parsed).toBeInstanceOf(PluginDataIndex); + expect(parsed.blockIndex).toBe(2); + expect(parsed.pluginName).toBe('anchors'); + expect(parsed.pluginKey).toBe('visible'); + }); + }); }); diff --git a/packages/core/src/components/UndoRedoManager.integration.spec.ts b/packages/core/src/components/UndoRedoManager.integration.spec.ts index 7671cce5..5769c833 100644 --- a/packages/core/src/components/UndoRedoManager.integration.spec.ts +++ b/packages/core/src/components/UndoRedoManager.integration.spec.ts @@ -64,6 +64,21 @@ describe('UndoRedoManager integration with plugin data (real model)', () => { expect(pluginData(model)).toEqual({ visible: true }); }); + it('should record nothing for a write that stores what is already stored', () => { + model.updatePluginData(USER_ID, 0, PLUGIN, { id: 'intro' }); + model.updatePluginData(USER_ID, 0, PLUGIN, { visible: true }); + + /** + * A provider re-applying the state it just read, which is what happens every time a menu + * item derives `isActive` from plugin data and the user activates it twice + */ + model.updatePluginData(USER_ID, 0, PLUGIN, { visible: true }); + + manager.undo(); + + expect(pluginData(model)).toEqual({ id: 'intro' }); + }); + it('should leave other keys of the same plugin untouched when undoing one key', () => { model.updatePluginData(USER_ID, 0, PLUGIN, { id: 'intro' }); model.updatePluginData(USER_ID, 0, PLUGIN, { visible: true }); diff --git a/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts b/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts index ccc9a9ab..5e2fb930 100644 --- a/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts +++ b/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts @@ -115,6 +115,78 @@ describe('PluginDataNode', () => { }); }); + describe('a write that changes nothing', () => { + /** + * Every dispatch here becomes an OT operation and an undo step. Plugins re-apply their + * current state routinely -- on every menu open, for an item deriving `isActive` from it -- + * so a write that stores what is already stored must stay silent. + */ + it('should not emit when the key already holds that value', () => { + const pluginData = new PluginDataNode({ + name: pluginName, + data: { align: 'left' }, + }); + const listener = jest.fn(); + + pluginData.addEventListener(EventType.Changed, listener); + + pluginData.update('align', 'left'); + + expect(listener).not.toHaveBeenCalled(); + }); + + it('should not emit when removing a key that is not there', () => { + const pluginData = new PluginDataNode({ + name: pluginName, + data: { align: 'left' }, + }); + const listener = jest.fn(); + + pluginData.addEventListener(EventType.Changed, listener); + + pluginData.update('visible', undefined); + + expect(listener).not.toHaveBeenCalled(); + }); + + it('should still emit when the value actually differs', () => { + const pluginData = new PluginDataNode({ + name: pluginName, + data: { align: 'left' }, + }); + const listener = jest.fn(); + + pluginData.addEventListener(EventType.Changed, listener); + + pluginData.update('align', 'right'); + + expect(listener).toHaveBeenCalledTimes(1); + }); + + it('should still emit when a key is written for the first time with an undefined-free value', () => { + const pluginData = new PluginDataNode({ name: pluginName }); + const listener = jest.fn(); + + pluginData.addEventListener(EventType.Changed, listener); + + pluginData.update('align', 'left'); + + expect(listener).toHaveBeenCalledTimes(1); + }); + + it('should leave the stored data untouched', () => { + const pluginData = new PluginDataNode({ + name: pluginName, + data: { align: 'left' }, + }); + + pluginData.update('align', 'left'); + pluginData.update('visible', undefined); + + expect(pluginData.serialized).toEqual({ align: 'left' }); + }); + }); + describe('.isEmpty', () => { it('should be true when the node holds no keys', () => { expect(new PluginDataNode({ name: pluginName }).isEmpty).toBe(true); diff --git a/packages/model/src/entities/PluginDataNode/index.ts b/packages/model/src/entities/PluginDataNode/index.ts index 6f7a0c0c..1da9e1d0 100644 --- a/packages/model/src/entities/PluginDataNode/index.ts +++ b/packages/model/src/entities/PluginDataNode/index.ts @@ -60,6 +60,19 @@ export class PluginDataNode extends EventBus { public update(key: string, value: unknown): void { const previousValue = this.#data[key]; + /** + * Storing what is already stored changes nothing, and every event here becomes an operation + * for collaborators and a step on the undo stack. Plugins re-apply their current state + * routinely, and an undo step that undoes nothing is worse than no step at all. + * + * The second clause is the removal case: both sides are `undefined` when a key holding + * `undefined` is removed, which is a real change, and when an absent key is removed, which + * is not. + */ + if (Object.is(previousValue, value) && (value !== undefined || !(key in this.#data))) { + return; + } + if (value === undefined) { delete this.#data[key]; } else { From 8228e736f3ae5ada45d0200f39334dad5a3f89be Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sun, 11 Oct 2026 21:44:24 +0100 Subject: [PATCH 11/29] fix(collaboration-manager): converge concurrent plugin data writes Two clients writing the same plugin data key left one of them on a value the server does not hold. Remote operations are transformed against the pending local ones, and the plugin data path returned them untouched, so the client with an unsent write applied the incoming value over its own -- and since its operation is never echoed back to it, nothing restored what the server ended up with. The rule is now the one #transformAgainstDataOperation already applies to data values: an against-operation with no revision counts as the later of the two, and the operation being transformed becomes Neutral. It is scoped to the same block, plugin and key, since nothing else describes the same value. Co-Authored-By: Claude Opus 5 --- .../src/OperationsTransformer.spec.ts | 60 ++++++++++++++++++- .../src/OperationsTransformer.ts | 47 +++++++++++++-- 2 files changed, 100 insertions(+), 7 deletions(-) diff --git a/packages/collaboration-manager/src/OperationsTransformer.spec.ts b/packages/collaboration-manager/src/OperationsTransformer.spec.ts index b36555f5..ced62bfe 100644 --- a/packages/collaboration-manager/src/OperationsTransformer.spec.ts +++ b/packages/collaboration-manager/src/OperationsTransformer.spec.ts @@ -595,7 +595,26 @@ describe('OperationsTransformer', () => { expect(transformer.transform(operation, againstOp).type).toBe(OperationType.Neutral); }); - it('should not be transformed against another plugin data operation', () => { + /** + * The divergence this guards against: the client holding the unsent write applies the + * remote value, and its own operation is never echoed back to it, so nothing restores the + * value the server ends up holding. The same rule covers data values already + */ + it('should become Neutral against an unsent write to the same key', () => { + const incoming = pluginOp(2); + const unsentLocal = new Operation( + OperationType.Modify, + pluginIndex(2), + { payload: true, + prevPayload: false }, + 'user2' + ); + + expect(unsentLocal.rev).toBeUndefined(); + expect(transformer.transform(incoming, unsentLocal).type).toBe(OperationType.Neutral); + }); + + it('should be applied over a write the server took before it', () => { const operation = pluginOp(2); const againstOp = pluginOp(2); @@ -605,6 +624,45 @@ describe('OperationsTransformer', () => { expect((result.index as PluginDataIndex).blockIndex).toBe(2); }); + it('should not be transformed against an unsent write to another key of the same plugin', () => { + const incoming = pluginOp(2, 'visible'); + const unsentLocal = new Operation( + OperationType.Modify, + pluginIndex(2, 'id'), + { payload: true, + prevPayload: false }, + 'user2' + ); + + expect(transformer.transform(incoming, unsentLocal).type).toBe(OperationType.Modify); + }); + + it('should not be transformed against an unsent write to another plugin', () => { + const incoming = pluginOp(2); + const unsentLocal = new Operation( + OperationType.Modify, + Index.pluginData(2, createPluginDataName('spoiler'), 'id', 'doc1' as DocumentId), + { payload: true, + prevPayload: false }, + 'user2' + ); + + expect(transformer.transform(incoming, unsentLocal).type).toBe(OperationType.Modify); + }); + + it('should not be transformed against an unsent write to the same key of another block', () => { + const incoming = pluginOp(2); + const unsentLocal = new Operation( + OperationType.Modify, + pluginIndex(3), + { payload: true, + prevPayload: false }, + 'user2' + ); + + expect(transformer.transform(incoming, unsentLocal).type).toBe(OperationType.Modify); + }); + it('should transform a text operation against a plugin data operation without throwing', () => { const operation = new Operation( OperationType.Insert, diff --git a/packages/collaboration-manager/src/OperationsTransformer.ts b/packages/collaboration-manager/src/OperationsTransformer.ts index 375883a0..6fc8a2ce 100644 --- a/packages/collaboration-manager/src/OperationsTransformer.ts +++ b/packages/collaboration-manager/src/OperationsTransformer.ts @@ -201,15 +201,50 @@ export class OperationsTransformer { /** * Method that transforms operation against a plugin data operation * - * Plugin data operations only ever modify one key of one plugin's per-block data, so they - * cannot shift another operation's position. Two concurrent writes to the same key are left - * untransformed on purpose: the server's order decides, and the last applied one wins. + * Cases, mirroring #transformAgainstDataOperation: a plugin data operation modifies one key of + * one plugin's per-block data, so it can only ever conflict with another write to that same + * key, and can never shift an operation's position. + * 1. Operation is not a plugin data operation + * - Return copy of the current operation + * 2. Operation describes a different block, plugin or key + * - Return copy of the current operation, the two values are independent + * 3. Operation describes the same value + * - Only the later write should survive, so compare revisions as data values do * @param operation - Operation to be transformed * @param againstOp - Operation against which the current operation should be transformed - * @returns copy of the current operation + * @returns new transformed operation */ - #transformAgainstPluginDataOperation(operation: Operation, againstOp: Operation): Operation { - void againstOp; + #transformAgainstPluginDataOperation(operation: Operation, againstOp: Operation): Operation | Operation { + const index = operation.index; + + // Cover case 1 + if (!(index instanceof PluginDataIndex)) { + return Operation.from(operation); + } + + const againstIndex = againstOp.index as PluginDataIndex; + + // Cover case 2 + if ( + index.blockIndex !== againstIndex.blockIndex + || index.pluginName !== againstIndex.pluginName + || index.pluginKey !== againstIndex.pluginKey + ) { + return Operation.from(operation); + } + + /** + * An againstOp with no revision has not reached the OT server yet, so there is no telling + * when it will be applied there. Treating it as a future operation is what keeps a client + * that holds an unsent write from applying the remote value over it: its own operation is + * never echoed back to it, so nothing would restore the value the server ends up holding + */ + const againstRevision = againstOp.rev === undefined ? Infinity : againstOp.rev; + + // Cover case 3 + if (againstRevision > operation.rev!) { + return new Operation(OperationType.Neutral, index, { payload: [] }, operation.userId, operation.rev); + } return Operation.from(operation); } From 7546fa266cf2bb817570195ab67013aaf255fe45 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sun, 11 Oct 2026 21:44:31 +0100 Subject: [PATCH 12/29] docs(openspec): check off the second-round plugin-block-data follow-ups Co-Authored-By: Claude Opus 5 --- openspec/changes/plugin-block-data/tasks.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openspec/changes/plugin-block-data/tasks.md b/openspec/changes/plugin-block-data/tasks.md index 32a95d08..8010372f 100644 --- a/openspec/changes/plugin-block-data/tasks.md +++ b/openspec/changes/plugin-block-data/tasks.md @@ -60,8 +60,8 @@ ## 8. Review follow-ups (second round) -- [ ] 8.1 Write a failing `OperationsTransformer.spec.ts` case for two clients writing the same plugin data key concurrently, then give `#transformAgainstPluginDataOperation` the revision rule `#transformAgainstDataOperation` already uses: `Neutral` when the against-operation is the later of the two, an unsent one counting as later than any revision, and only for the same block, plugin and key. Without it the client holding an unsent write applies the remote value and never re-applies its own, so it ends on a value the server does not hold -- [ ] 8.2 Reword the `sdk` delta's scenarios, which still say "both" and "either" of what is now three augmentable maps +- [x] 8.1 Write a failing `OperationsTransformer.spec.ts` case for two clients writing the same plugin data key concurrently, then give `#transformAgainstPluginDataOperation` the revision rule `#transformAgainstDataOperation` already uses: `Neutral` when the against-operation is the later of the two, an unsent one counting as later than any revision, and only for the same block, plugin and key. Without it the client holding an unsent write applies the remote value and never re-applies its own, so it ends on a value the server does not hold +- [x] 8.2 Reword the `sdk` delta's scenarios, which still say "both" and "either" of what is now three augmentable maps ## 9. Review follow-ups (third round) From e47f7849d1b4cb98f2a3e36f25607905d74845f2 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 16 Oct 2026 23:39:29 +0100 Subject: [PATCH 13/29] fix(model,core): keep plugin data out of reach of Object.prototype Plugin names and the keys inside an entry are document data, and both could collide with the prototype. PluginDataNode kept its keys on a plain object while the block's own plugin store already used a null prototype. A `__proto__` key loaded from a document reached the prototype setter instead of becoming an own property and vanished from serialization; a first write to a key like `toString` read the inherited function as its previous value and put that on the undo stack and the wire. The record is now copied onto a null prototype, as the outer store is. `serialized` handed out the live record, so `getPluginData` and `api.document.data` both exposed an untracked write path into the Model. Read, change, write back -- the obvious way to use the two methods together -- changed the document on the read and then emitted nothing, because the no-op guard found the value already updated. Callers get a detached copy. BlocksManager.getPluginData indexed the serialized map directly, so a plugin named toString or constructor read back as the inherited function rather than undefined. It checks for an own entry first. Co-Authored-By: Claude Opus 5 --- .../src/api/BlocksAPI.integration.spec.ts | 63 +++++++++++++++ packages/core/src/components/BlockManager.ts | 12 ++- .../PluginDataNode/PluginDataNode.spec.ts | 79 +++++++++++++++++++ .../src/entities/PluginDataNode/index.ts | 29 ++++++- 4 files changed, 180 insertions(+), 3 deletions(-) diff --git a/packages/core/src/api/BlocksAPI.integration.spec.ts b/packages/core/src/api/BlocksAPI.integration.spec.ts index 062cc556..a8bd5db4 100644 --- a/packages/core/src/api/BlocksAPI.integration.spec.ts +++ b/packages/core/src/api/BlocksAPI.integration.spec.ts @@ -1250,6 +1250,69 @@ describe('BlocksAPI integration (real model, mocked tools)', () => { plugin: 'anchors' })).toBeUndefined(); }); + it('should return undefined for a plugin name that Object.prototype also answers to', () => { + blocksAPI.insert({ type: 'paragraph' }); + + blocksAPI.updatePluginData({ block: 0, + plugin: 'anchors', + data: { id: 'intro' } }); + + /** + * The serialized plugins map is an ordinary object, so indexing it directly hands back + * the inherited member for a plugin that stores nothing -- a function, where the caller + * is told to expect data or undefined + */ + expect(blocksAPI.getPluginData({ block: 0, + plugin: 'toString' })).toBeUndefined(); + expect(blocksAPI.getPluginData({ block: 0, + plugin: 'constructor' })).toBeUndefined(); + }); + + it('should hand back plugin data the caller can change without touching the document', () => { + blocksAPI.insert({ type: 'paragraph' }); + + blocksAPI.updatePluginData({ block: 0, + plugin: 'anchors', + data: { id: 'intro' } }); + + const data = blocksAPI.getPluginData({ block: 0, + plugin: 'anchors' }) as Record; + + data.id = 'changed'; + + expect(blocksAPI.getPluginData({ block: 0, + plugin: 'anchors' })).toEqual({ id: 'intro' }); + }); + + it('should record a read-modify-write as a change', () => { + blocksAPI.insert({ type: 'paragraph' }); + + blocksAPI.updatePluginData({ block: 0, + plugin: 'anchors', + data: { id: 'intro' } }); + + const data = blocksAPI.getPluginData({ block: 0, + plugin: 'anchors' }) as Record; + + const events: unknown[] = []; + + model.addEventListener(EventType.Changed, e => events.push(e)); + + data.id = 'changed'; + blocksAPI.updatePluginData({ block: 0, + plugin: 'anchors', + data }); + + /** + * Reading, changing and writing back is the obvious way to use these two methods + * together. Over a live record it changed the document and emitted nothing, so the edit + * reached neither collaborators nor the undo stack + */ + expect(events).toHaveLength(1); + expect(blocksAPI.getPluginData({ block: 0, + plugin: 'anchors' })).toEqual({ id: 'changed' }); + }); + it('should attribute the change to the acting user', () => { blocksAPI.insert({ type: 'paragraph' }); diff --git a/packages/core/src/components/BlockManager.ts b/packages/core/src/components/BlockManager.ts index e5e4c4b3..5d0fdaa7 100644 --- a/packages/core/src/components/BlockManager.ts +++ b/packages/core/src/components/BlockManager.ts @@ -443,8 +443,18 @@ export class BlocksManager { */ public getPluginData(blockIndexOrId: number | BlockId, pluginName: string): PluginDataSerialized | undefined { const blockIndex = this.#model.resolveBlockIndex(blockIndexOrId); + const plugins = this.#model.getBlockSerialized(blockIndex).plugins; - return this.#model.getBlockSerialized(blockIndex).plugins?.[pluginName]; + /** + * Checked for an own entry rather than indexed directly: the serialized map is an ordinary + * object, so a plugin named `toString` or `constructor` that stores nothing here would + * otherwise read back as the inherited function instead of `undefined` + */ + if (plugins === undefined || !Object.prototype.hasOwnProperty.call(plugins, pluginName)) { + return undefined; + } + + return plugins[pluginName]; } /** diff --git a/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts b/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts index 5e2fb930..237f42dd 100644 --- a/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts +++ b/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts @@ -207,7 +207,86 @@ describe('PluginDataNode', () => { }); }); + describe('keys that collide with Object.prototype', () => { + it('should keep a __proto__ key as data', () => { + const pluginData = new PluginDataNode({ name: pluginName }); + + /** + * Parsed rather than written as a literal: an object literal's `__proto__` is the + * prototype setter, while JSON.parse creates an own property -- and a document loaded + * from storage arrives the second way + */ + const loaded = JSON.parse('{"__proto__": "evil", "ok": 1}') as Record; + + Object.entries(loaded).forEach(([key, value]) => pluginData.update(key, value)); + + // A computed key, for the same reason: `{ '__proto__': x }` is still the setter. + expect(pluginData.serialized).toEqual({ + ['__proto__']: 'evil', + ok: 1, + }); + }); + + it('should treat a key named toString as absent before it is written', () => { + const pluginData = new PluginDataNode({ name: pluginName }); + const events: PluginDataModifiedEvent[] = []; + + pluginData.addEventListener(EventType.Changed, (event) => { + events.push(event as PluginDataModifiedEvent); + }); + + pluginData.update('toString', 'x'); + + // Read off the prototype, the previous value would be a function -- onto the undo stack. + expect(events).toHaveLength(1); + expect(events[0].detail.data.previous).toBeUndefined(); + }); + + it('should not report inherited data for a key it was never given', () => { + const pluginData = new PluginDataNode({ name: pluginName, + data: { id: 'one' } }); + + expect(pluginData.serialized.toString).toBeUndefined(); + }); + }); + describe('.serialized', () => { + it('should hand back a copy rather than the record it keeps', () => { + const pluginData = new PluginDataNode({ name: pluginName, + data: { id: 'one', + nested: { depth: 1 } } }); + + const snapshot = pluginData.serialized as Record; + + snapshot.id = 'two'; + (snapshot.nested as Record).depth = 2; + + /** + * Handing out the live record makes read-modify-write silent data loss: the write-back + * finds the value already changed and the no-op guard emits nothing + */ + expect(pluginData.serialized).toEqual({ id: 'one', + nested: { depth: 1 } }); + }); + + it('should still emit when a value read from it is written back changed', () => { + const pluginData = new PluginDataNode({ name: pluginName, + data: { id: 'one' } }); + const events: PluginDataModifiedEvent[] = []; + + pluginData.addEventListener(EventType.Changed, (event) => { + events.push(event as PluginDataModifiedEvent); + }); + + const snapshot = pluginData.serialized as Record; + + snapshot.id = 'two'; + pluginData.update('id', snapshot.id); + + expect(events).toHaveLength(1); + expect(pluginData.serialized).toEqual({ id: 'two' }); + }); + it('should return serialized version of the plugin data', () => { // Arrange const pluginData = new PluginDataNode({ diff --git a/packages/model/src/entities/PluginDataNode/index.ts b/packages/model/src/entities/PluginDataNode/index.ts index 1da9e1d0..c1279fe3 100644 --- a/packages/model/src/entities/PluginDataNode/index.ts +++ b/packages/model/src/entities/PluginDataNode/index.ts @@ -8,6 +8,18 @@ import { PluginDataModifiedEvent } from '@editorjs/model-types'; +/** + * Copies a plugin data record so that callers hold something of their own. + * + * `structuredClone` detaches the values; the top level is re-keyed onto a null prototype to + * match the record it came from, so a key named `toString` reads as absent rather than as an + * inherited function + * @param data - the record to copy + */ +function detach(data: Record): PluginDataSerialized { + return Object.assign(Object.create(null) as Record, structuredClone(data)); +} + /** * PluginDataNode holds the per-block data owned by a single plugin. * The data is a flat key/value map: a plugin reads and writes its own keys, and every change @@ -34,7 +46,15 @@ export class PluginDataNode extends EventBus { super(); this.#name = name; - this.#data = data; + + /** + * Copied onto a null prototype, as the block's own plugin store is: keys here are document + * data, so a `__proto__` key loaded from a document would otherwise reach the prototype + * setter instead of becoming an own property, and vanish from serialization. A first write + * to a key like `toString` would also read the inherited function as its previous value and + * put that on the undo stack + */ + this.#data = Object.assign(Object.create(null) as Record, data); } /** @@ -89,8 +109,13 @@ export class PluginDataNode extends EventBus { /** * Returns serialized version of the plugin's data. + * + * Detached from the node, because this is what reaches callers through `getPluginData` and + * `api.document.data`. Handing out the live record makes read-modify-write a silent data + * loss: the caller's edit has already changed the Model, so writing it back finds the value + * unchanged and emits nothing -- no operation for collaborators, no step to undo */ public get serialized(): PluginDataSerialized { - return this.#data; + return detach(this.#data); } } From f8fa0cd888dad6e25a88f4d60ba9a9702abc3ce2 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 16 Oct 2026 23:55:48 +0100 Subject: [PATCH 14/29] docs(openspec): check off the third-round plugin-block-data follow-ups Co-Authored-By: Claude Opus 5 --- openspec/changes/plugin-block-data/tasks.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/openspec/changes/plugin-block-data/tasks.md b/openspec/changes/plugin-block-data/tasks.md index 8010372f..5a824728 100644 --- a/openspec/changes/plugin-block-data/tasks.md +++ b/openspec/changes/plugin-block-data/tasks.md @@ -65,6 +65,6 @@ ## 9. Review follow-ups (third round) -- [ ] 9.1 Write failing `PluginDataNode.spec.ts` cases for a `__proto__` key arriving from a loaded document and for a first write to a key named `toString`, then copy the node's record onto a null prototype as the block's own plugin store already is. The outer store's comment explains the hazard; the inner record never got the same treatment, so the key was dropped on load and the inherited function went onto the undo stack as a previous value -- [ ] 9.2 Write a failing case, then return a detached copy from `PluginDataNode.serialized`. Handing out the live record makes read-modify-write silent loss: `getPluginData` → edit → `updatePluginData` has already changed the Model, so the no-op guard finds nothing to announce and the edit reaches neither collaborators nor the undo stack -- [ ] 9.3 Write a failing case, then have `BlocksManager.getPluginData` check for an own entry. The serialized map is an ordinary object, so a plugin named `toString` or `constructor` read back as the inherited function instead of `undefined` +- [x] 9.1 Write failing `PluginDataNode.spec.ts` cases for a `__proto__` key arriving from a loaded document and for a first write to a key named `toString`, then copy the node's record onto a null prototype as the block's own plugin store already is. The outer store's comment explains the hazard; the inner record never got the same treatment, so the key was dropped on load and the inherited function went onto the undo stack as a previous value +- [x] 9.2 Write a failing case, then return a detached copy from `PluginDataNode.serialized`. Handing out the live record makes read-modify-write silent loss: `getPluginData` → edit → `updatePluginData` has already changed the Model, so the no-op guard finds nothing to announce and the edit reaches neither collaborators nor the undo stack +- [x] 9.3 Write a failing case, then have `BlocksManager.getPluginData` check for an own entry. The serialized map is an ordinary object, so a plugin named `toString` or `constructor` read back as the inherited function instead of `undefined` From b004126e3490ad7779ca9b47b2086670dac3f59c Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 17 Oct 2026 17:22:18 +0100 Subject: [PATCH 15/29] test(collaboration-manager): say what "not transformed" actually means The cases asserting that a plugin data operation is left alone checked only that its type was still Modify. That says it was not neutralised and nothing more: with the untransformed branch returning an operation whose block index was shifted by 99, all thirty cases still passed. Comparing the serialized form covers the index, both payloads, the user and the revision in one assertion. The two serialization cases were named after a metaphor rather than what they do, which is a JSON round-trip standing in for what reaches the OT server. Co-Authored-By: Claude Opus 5 --- .../src/Operation.spec.ts | 11 +++---- .../src/OperationsTransformer.spec.ts | 30 +++++++++++++++---- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/packages/collaboration-manager/src/Operation.spec.ts b/packages/collaboration-manager/src/Operation.spec.ts index f3ca029d..c0633632 100644 --- a/packages/collaboration-manager/src/Operation.spec.ts +++ b/packages/collaboration-manager/src/Operation.spec.ts @@ -326,11 +326,12 @@ describe('Operation', () => { }); describe('.serialize()', () => { /** - * A key removal is a Modify whose payload is `undefined`, and `JSON.stringify` drops a key - * holding `undefined` entirely. It survives only because reading a key that is not there - * gives `undefined` back -- which is worth an assertion, since nothing in the types says so. + * An operation reaches the OT server as JSON, and a key removal is a Modify whose payload + * is `undefined` -- which `JSON.stringify` drops entirely. The removal survives only + * because reading a key that is not there gives `undefined` back, which is worth asserting + * since nothing in the types says so. */ - it('should carry a plugin data removal through the wire', () => { + it('should keep a plugin data removal through JSON serialization', () => { const index = Index.pluginData(2, createPluginDataName('anchors'), 'visible'); const op = new Operation(OperationType.Modify, index, { payload: undefined, @@ -346,7 +347,7 @@ describe('Operation', () => { expect((received.data as ModifyOperationData).prevPayload).toBe('intro'); }); - it('should carry the plugin data index itself through the wire', () => { + it('should keep the plugin data index itself through JSON serialization', () => { const index = Index.pluginData(2, createPluginDataName('anchors'), 'visible'); const op = new Operation(OperationType.Modify, index, { payload: undefined, diff --git a/packages/collaboration-manager/src/OperationsTransformer.spec.ts b/packages/collaboration-manager/src/OperationsTransformer.spec.ts index ced62bfe..71623af8 100644 --- a/packages/collaboration-manager/src/OperationsTransformer.spec.ts +++ b/packages/collaboration-manager/src/OperationsTransformer.spec.ts @@ -620,8 +620,7 @@ describe('OperationsTransformer', () => { const result = transformer.transform(operation, againstOp); - expect(result.type).toBe(OperationType.Modify); - expect((result.index as PluginDataIndex).blockIndex).toBe(2); + expect(result.serialize()).toEqual(operation.serialize()); }); it('should not be transformed against an unsent write to another key of the same plugin', () => { @@ -634,7 +633,14 @@ describe('OperationsTransformer', () => { 'user2' ); - expect(transformer.transform(incoming, unsentLocal).type).toBe(OperationType.Modify); + const result = transformer.transform(incoming, unsentLocal); + + /** + * Compared serialized, so this covers the index, the payloads, the user and the + * revision. Asserting the type alone says only that the operation was not neutralised, + * which is not what "not transformed" means + */ + expect(result.serialize()).toEqual(incoming.serialize()); }); it('should not be transformed against an unsent write to another plugin', () => { @@ -647,7 +653,14 @@ describe('OperationsTransformer', () => { 'user2' ); - expect(transformer.transform(incoming, unsentLocal).type).toBe(OperationType.Modify); + const result = transformer.transform(incoming, unsentLocal); + + /** + * Compared serialized, so this covers the index, the payloads, the user and the + * revision. Asserting the type alone says only that the operation was not neutralised, + * which is not what "not transformed" means + */ + expect(result.serialize()).toEqual(incoming.serialize()); }); it('should not be transformed against an unsent write to the same key of another block', () => { @@ -660,7 +673,14 @@ describe('OperationsTransformer', () => { 'user2' ); - expect(transformer.transform(incoming, unsentLocal).type).toBe(OperationType.Modify); + const result = transformer.transform(incoming, unsentLocal); + + /** + * Compared serialized, so this covers the index, the payloads, the user and the + * revision. Asserting the type alone says only that the operation was not neutralised, + * which is not what "not transformed" means + */ + expect(result.serialize()).toEqual(incoming.serialize()); }); it('should transform a text operation against a plugin data operation without throwing', () => { From 92c0657a8ae4e52dafdcacc2f3f4e4bab35a75c7 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Thu, 5 Nov 2026 01:18:11 +0000 Subject: [PATCH 16/29] fix(model): copy plugin data values in and out of the store A plugin that wrote an object kept a reference into the Model: editing it moved the document with no write at all, and the write-back that should have announced the change found the value unchanged and emitted nothing -- no operation for collaborators, no step to undo. The data a node was constructed with was shared the same way, down from a loaded document. Incoming values are now cloned on the way in and for the event payload, since an operation and an undo step both outlive the call that recorded them. Because what is stored is therefore a copy, the no-op guard compares structurally; `deepEqual` moves into its own util for `isSameInlineData` to share, and reports a value whose state is not in its own keys -- a `Date`, a `Map` -- as different rather than as equal to any other of its kind. Co-Authored-By: Claude Opus 5 --- .../PluginDataNode/PluginDataNode.spec.ts | 102 ++++++++++++++++++ .../src/entities/PluginDataNode/index.ts | 34 +++++- packages/model/src/utils/deepEqual.spec.ts | 64 +++++++++++ packages/model/src/utils/deepEqual.ts | 53 +++++++++ packages/model/src/utils/index.ts | 1 + packages/model/src/utils/isSameInlineData.ts | 37 +------ 6 files changed, 250 insertions(+), 41 deletions(-) create mode 100644 packages/model/src/utils/deepEqual.spec.ts create mode 100644 packages/model/src/utils/deepEqual.ts diff --git a/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts b/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts index 237f42dd..f85eecdd 100644 --- a/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts +++ b/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts @@ -250,6 +250,108 @@ describe('PluginDataNode', () => { }); }); + describe('values the caller still holds a reference to', () => { + it('should store a copy rather than the object it was given', () => { + const pluginData = new PluginDataNode({ name: pluginName }); + const settings = { align: 'left' }; + + pluginData.update('settings', settings); + settings.align = 'center'; + + /** + * Sharing the object lets an edit to it change the Model with no write at all, so the document moves while + * nothing is recorded and no collaborator is told + */ + expect(pluginData.serialized).toEqual({ settings: { align: 'left' } }); + }); + + it('should store a copy of nested values too', () => { + const pluginData = new PluginDataNode({ name: pluginName }); + const settings = { nested: { depth: 1 }, + items: [{ id: 'one' }] }; + + pluginData.update('settings', settings); + settings.nested.depth = 2; + settings.items[0].id = 'two'; + + expect(pluginData.serialized).toEqual({ settings: { nested: { depth: 1 }, + items: [{ id: 'one' }] } }); + }); + + it('should emit when a value is mutated and written back', () => { + const pluginData = new PluginDataNode({ name: pluginName }); + const settings = { align: 'left' }; + + pluginData.update('settings', settings); + + const events: PluginDataModifiedEvent[] = []; + + pluginData.addEventListener(EventType.Changed, (event) => { + events.push(event as PluginDataModifiedEvent); + }); + + settings.align = 'center'; + pluginData.update('settings', settings); + + /** + * The write-back is the only announcement a read-modify-write makes, and over a shared object identity finds + * it unchanged: no operation for collaborators, no step to undo, and two documents quietly diverged + */ + expect(events).toHaveLength(1); + expect(events[0]?.detail.data).toEqual({ value: { align: 'center' }, + previous: { align: 'left' } }); + expect(pluginData.serialized).toEqual({ settings: { align: 'center' } }); + }); + + it('should not emit when an equal object is written again', () => { + const pluginData = new PluginDataNode({ name: pluginName, + data: { settings: { align: 'left', + nested: { depth: 1 } } } }); + const events: PluginDataModifiedEvent[] = []; + + pluginData.addEventListener(EventType.Changed, (event) => { + events.push(event as PluginDataModifiedEvent); + }); + + /** + * A different object holding the same state. Plugins re-apply their current state routinely, and once stored + * values are copies an identity check would never match one + */ + pluginData.update('settings', { align: 'left', + nested: { depth: 1 } }); + + expect(events).toHaveLength(0); + }); + + it('should keep the recorded change out of reach of a later edit', () => { + const pluginData = new PluginDataNode({ name: pluginName }); + const settings = { align: 'left' }; + const events: PluginDataModifiedEvent[] = []; + + pluginData.addEventListener(EventType.Changed, (event) => { + events.push(event as PluginDataModifiedEvent); + }); + + pluginData.update('settings', settings); + settings.align = 'center'; + + /** + * The payload becomes an operation and an undo step, both of which outlive the call + */ + expect(events[0]?.detail.data.value).toEqual({ align: 'left' }); + }); + + it('should copy the data it is constructed with', () => { + const data = { settings: { align: 'left' } }; + const pluginData = new PluginDataNode({ name: pluginName, + data }); + + data.settings.align = 'center'; + + expect(pluginData.serialized).toEqual({ settings: { align: 'left' } }); + }); + }); + describe('.serialized', () => { it('should hand back a copy rather than the record it keeps', () => { const pluginData = new PluginDataNode({ name: pluginName, diff --git a/packages/model/src/entities/PluginDataNode/index.ts b/packages/model/src/entities/PluginDataNode/index.ts index c1279fe3..5e4e33d4 100644 --- a/packages/model/src/entities/PluginDataNode/index.ts +++ b/packages/model/src/entities/PluginDataNode/index.ts @@ -1,4 +1,5 @@ import { getContext } from '../../utils/Context.js'; +import { deepEqual } from '../../utils/deepEqual.js'; import type { PluginDataNodeConstructorParameters } from './types/index.js'; import { PartialIndex, @@ -8,6 +9,15 @@ import { PluginDataModifiedEvent } from '@editorjs/model-types'; +/** + * Copies a single plugin data value, so that neither side can reach the other's through it. Objects and arrays are + * detached down to their nested values; anything else has nothing to share and is returned as it is + * @param value - the value to copy + */ +function copyValue(value: unknown): unknown { + return typeof value === 'object' && value !== null ? structuredClone(value) : value; +} + /** * Copies a plugin data record so that callers hold something of their own. * @@ -52,9 +62,12 @@ export class PluginDataNode extends EventBus { * data, so a `__proto__` key loaded from a document would otherwise reach the prototype * setter instead of becoming an own property, and vanish from serialization. A first write * to a key like `toString` would also read the inherited function as its previous value and - * put that on the undo stack + * put that on the undo stack. + * + * Deep-copied as writes are, below: the document object this came from is the caller's, and sharing its + * nested values would let an edit to it change the Model */ - this.#data = Object.assign(Object.create(null) as Record, data); + this.#data = detach(data); } /** @@ -85,23 +98,34 @@ export class PluginDataNode extends EventBus { * for collaborators and a step on the undo stack. Plugins re-apply their current state * routinely, and an undo step that undoes nothing is worse than no step at all. * + * Compared structurally rather than by identity: what is stored is a copy of what was written, so identity + * could only ever match a primitive, and re-applying the same object state would emit every time. + * * The second clause is the removal case: both sides are `undefined` when a key holding * `undefined` is removed, which is a real change, and when an absent key is removed, which * is not. */ - if (Object.is(previousValue, value) && (value !== undefined || !(key in this.#data))) { + if (deepEqual(previousValue, value) && (value !== undefined || !(key in this.#data))) { return; } if (value === undefined) { delete this.#data[key]; } else { - this.#data[key] = value; + /** + * Stored as a copy: over the caller's own object an edit has already changed the Model, so the write-back that + * should have announced it finds nothing to say -- no operation for collaborators, no step to undo + */ + this.#data[key] = copyValue(value); } this.dispatchEvent( new PluginDataModifiedEvent(new PartialIndex({ pluginKey: key }), { - value, + /** + * Copied again: this payload becomes an operation and an undo step, both of which outlive the call. + * `previousValue` needs none -- it is the Model's own former copy, just dropped above and never handed out + */ + value: copyValue(value), previous: previousValue, }, getContext()!) ); diff --git a/packages/model/src/utils/deepEqual.spec.ts b/packages/model/src/utils/deepEqual.spec.ts new file mode 100644 index 00000000..fd617b67 --- /dev/null +++ b/packages/model/src/utils/deepEqual.spec.ts @@ -0,0 +1,64 @@ +import { deepEqual } from './deepEqual.js'; + +describe('deepEqual', () => { + it('should treat equal primitives as equal', () => { + expect(deepEqual('a', 'a')).toBe(true); + expect(deepEqual(1, 1)).toBe(true); + expect(deepEqual(undefined, undefined)).toBe(true); + expect(deepEqual(null, null)).toBe(true); + }); + + it('should treat differing primitives as different', () => { + expect(deepEqual('a', 'b')).toBe(false); + expect(deepEqual(1, '1')).toBe(false); + expect(deepEqual(null, undefined)).toBe(false); + }); + + it('should compare plain records by their keys', () => { + expect(deepEqual({ a: 1, + b: { c: 2 } }, { a: 1, + b: { c: 2 } })).toBe(true); + expect(deepEqual({ a: 1 }, { a: 2 })).toBe(false); + expect(deepEqual({ a: 1 }, { a: 1, + b: 2 })).toBe(false); + }); + + it('should compare arrays element by element', () => { + expect(deepEqual([1, { a: 2 }], [1, { a: 2 }])).toBe(true); + expect(deepEqual([1, 2], [2, 1])).toBe(false); + expect(deepEqual([], {})).toBe(false); + }); + + it('should compare a record with a null prototype by its keys too', () => { + const nullProto = Object.assign(Object.create(null) as Record, { a: 1 }); + + expect(deepEqual(nullProto, { a: 1 })).toBe(true); + }); + + /** + * The store holds `structuredClone` output, which a host may build on another realm's `Object.prototype`: + * comparing prototypes would call such a record exotic and report every write as a change + */ + it('should compare a structuredClone of a record by its keys too', () => { + expect(deepEqual(structuredClone({ a: 1, + b: { c: 2 } }), { a: 1, + b: { c: 2 } })).toBe(true); + }); + + /** + * A value whose state is not in its own enumerable properties: comparing two by key finds none on either and + * calls them equal, swallowing a write that changed one + */ + it('should report two distinct non-plain objects as different', () => { + expect(deepEqual(new Date(1), new Date(2))).toBe(false); + expect(deepEqual(new Date(1), new Date(1))).toBe(false); + expect(deepEqual(new Map([['a', 1]]), new Map([['a', 2]]))).toBe(false); + expect(deepEqual(new Set([1]), new Set([2]))).toBe(false); + }); + + it('should still treat the same non-plain object as equal to itself', () => { + const date = new Date(1); + + expect(deepEqual(date, date)).toBe(true); + }); +}); diff --git a/packages/model/src/utils/deepEqual.ts b/packages/model/src/utils/deepEqual.ts new file mode 100644 index 00000000..5d929cee --- /dev/null +++ b/packages/model/src/utils/deepEqual.ts @@ -0,0 +1,53 @@ +/** + * Whether a value is a record whose own keys describe it: a `Date` or a `Map` has none, so two of them would compare + * equal. Read from the built-in tag, not the prototype, which `structuredClone` output may not share with this realm + * @param value - the object to classify + */ +function isKeyedObject(value: object): boolean { + return Object.prototype.toString.call(value) === '[object Object]'; +} + +/** + * Deep structural equality for two plain JSON-like values: keyed records by their own keys, arrays element by element, + * everything else by `===`. Identity is not the question where the value may be a copy of what is already stored + * @param a - first value to compare + * @param b - second value to compare + */ +export function deepEqual(a: unknown, b: unknown): boolean { + if (a === b) { + return true; + } + + if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) { + return false; + } + + const aIsArray = Array.isArray(a); + + if (aIsArray !== Array.isArray(b)) { + return false; + } + + if (aIsArray) { + const arrA = a as unknown[]; + const arrB = b as unknown[]; + + return arrA.length === arrB.length && arrA.every((item, index) => deepEqual(item, arrB[index])); + } + + /** + * Not identical, and not something whose own keys describe it: comparing two `Date`s by key would call them equal + * and swallow a write that changed one. Such a value is outside the JSON-serializable contract anyway + */ + if (!isKeyedObject(a) || !isKeyedObject(b)) { + return false; + } + + const objA = a as Record; + const objB = b as Record; + const keysA = Object.keys(objA); + const keysB = Object.keys(objB); + + return keysA.length === keysB.length + && keysA.every(key => Object.prototype.hasOwnProperty.call(objB, key) && deepEqual(objA[key], objB[key])); +} diff --git a/packages/model/src/utils/index.ts b/packages/model/src/utils/index.ts index a4bc214f..e98da4fd 100644 --- a/packages/model/src/utils/index.ts +++ b/packages/model/src/utils/index.ts @@ -1,2 +1,3 @@ export * from './textUtils.js'; +export * from './deepEqual.js'; export * from './isSameInlineData.js'; diff --git a/packages/model/src/utils/isSameInlineData.ts b/packages/model/src/utils/isSameInlineData.ts index 77ae5be0..708488a1 100644 --- a/packages/model/src/utils/isSameInlineData.ts +++ b/packages/model/src/utils/isSameInlineData.ts @@ -1,40 +1,5 @@ import type { InlineToolData } from '@editorjs/model-types'; - -/** - * Deep structural equality check for two plain JSON-like values. - * @param a - first value to compare - * @param b - second value to compare - */ -function deepEqual(a: unknown, b: unknown): boolean { - if (a === b) { - return true; - } - - if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) { - return false; - } - - const aIsArray = Array.isArray(a); - - if (aIsArray !== Array.isArray(b)) { - return false; - } - - if (aIsArray) { - const arrA = a as unknown[]; - const arrB = b as unknown[]; - - return arrA.length === arrB.length && arrA.every((item, index) => deepEqual(item, arrB[index])); - } - - const objA = a as Record; - const objB = b as Record; - const keysA = Object.keys(objA); - const keysB = Object.keys(objB); - - return keysA.length === keysB.length - && keysA.every(key => Object.prototype.hasOwnProperty.call(objB, key) && deepEqual(objA[key], objB[key])); -} +import { deepEqual } from './deepEqual.js'; /** * Determines whether two inline tool data objects should be treated as equal. From 6121800926704c1e6631058ebe8e7285bd889e22 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Thu, 5 Nov 2026 01:18:19 +0000 Subject: [PATCH 17/29] fix(collaboration-manager): drop undo entries a collaborator overwrote `againstRevision > operation.rev!` was false whenever the left side came off an undo or redo stack, because those entries are built from model events and never carry a revision. The entry survived, so undoing a local first write to a key a collaborator had since overwritten wrote `prevPayload` over their value and deleted it. An operation with no revision of its own now loses to whatever it is transformed against, which in that path is only ever an operation the model has already applied. Server operations always carry a revision, so nothing else reaches the comparison without one. `#transformAgainstDataOperation` has the same hole for `data` values on `main`; it belongs with the other pre-existing OT defects on the board rather than in this PR. Co-Authored-By: Claude Opus 5 --- .../src/OperationsTransformer.spec.ts | 49 +++++++++++++++++ .../src/OperationsTransformer.ts | 8 ++- .../src/UndoRedoManager.spec.ts | 52 ++++++++++++++++++- 3 files changed, 107 insertions(+), 2 deletions(-) diff --git a/packages/collaboration-manager/src/OperationsTransformer.spec.ts b/packages/collaboration-manager/src/OperationsTransformer.spec.ts index 71623af8..adde8df4 100644 --- a/packages/collaboration-manager/src/OperationsTransformer.spec.ts +++ b/packages/collaboration-manager/src/OperationsTransformer.spec.ts @@ -683,6 +683,55 @@ describe('OperationsTransformer', () => { expect(result.serialize()).toEqual(incoming.serialize()); }); + /** + * Only a stack entry reaches the transformer with no revision of its own, and the operation it is transformed + * against has already been applied -- so the entry describes a value the document has moved on from + */ + describe('when the operation itself has no revision', () => { + /** + * A stack entry, as `CollaborationManager` builds it from a model event + * @param key - plugin data key the entry writes to + */ + const stackEntry = (key = 'id'): Operation => new Operation( + OperationType.Modify, + pluginIndex(2, key), + { payload: false, + prevPayload: true }, + 'user1' + ); + + it('should become Neutral against a numbered write to the same key', () => { + const entry = stackEntry(); + + expect(entry.rev).toBeUndefined(); + expect(transformer.transform(entry, pluginOp(2)).type).toBe(OperationType.Neutral); + }); + + /** + * The remote operation is reconstructed from a model event too, so it carries no revision either -- which + * is the shape the undo stack actually sees + */ + it('should become Neutral against an unnumbered write to the same key', () => { + const remote = new Operation( + OperationType.Modify, + pluginIndex(2), + { payload: true, + prevPayload: false }, + 'user2' + ); + + expect(transformer.transform(stackEntry(), remote).type).toBe(OperationType.Neutral); + }); + + it('should survive a write to another key of the same plugin', () => { + const entry = stackEntry('visible'); + + const result = transformer.transform(entry, pluginOp(2, 'id')); + + expect(result.serialize()).toEqual(entry.serialize()); + }); + }); + it('should transform a text operation against a plugin data operation without throwing', () => { const operation = new Operation( OperationType.Insert, diff --git a/packages/collaboration-manager/src/OperationsTransformer.ts b/packages/collaboration-manager/src/OperationsTransformer.ts index 6fc8a2ce..bbc399b1 100644 --- a/packages/collaboration-manager/src/OperationsTransformer.ts +++ b/packages/collaboration-manager/src/OperationsTransformer.ts @@ -241,8 +241,14 @@ export class OperationsTransformer { */ const againstRevision = againstOp.rev === undefined ? Infinity : againstOp.rev; + /** + * Only an undo or redo stack entry reaches this with no revision, and it is transformed against an operation the + * model has already applied -- so it describes a value that is gone, and undoing it would delete the newer one + */ + const revision = operation.rev === undefined ? -Infinity : operation.rev; + // Cover case 3 - if (againstRevision > operation.rev!) { + if (againstRevision > revision) { return new Operation(OperationType.Neutral, index, { payload: [] }, operation.userId, operation.rev); } diff --git a/packages/collaboration-manager/src/UndoRedoManager.spec.ts b/packages/collaboration-manager/src/UndoRedoManager.spec.ts index 276f0d18..42210cff 100644 --- a/packages/collaboration-manager/src/UndoRedoManager.spec.ts +++ b/packages/collaboration-manager/src/UndoRedoManager.spec.ts @@ -1,5 +1,5 @@ import type { BlockIndex, DocumentId, TextIndex } from '@editorjs/sdk'; -import { createDataKey, Index } from '@editorjs/sdk'; +import { createDataKey, createPluginDataName, Index } from '@editorjs/sdk'; import { describe } from '@jest/globals'; import { jest } from '@jest/globals'; import { Operation, OperationType } from './Operation.js'; @@ -223,5 +223,55 @@ describe('UndoRedoManager', () => { expect((undone?.index as TextIndex | undefined)?.textRange).toEqual([4, 7]); /* eslint-enable @typescript-eslint/no-magic-numbers */ }); + + /** + * Stack entries carry no revision, and are transformed against operations the model has applied: an entry a + * collaborator overwrote would write a value that is gone and delete theirs instead of undoing anything + */ + it('should drop a plugin data entry a collaborator has overwritten', () => { + const manager = new UndoRedoManager(); + const index = Index.pluginData(0, createPluginDataName('anchors'), 'color', 'doc' as DocumentId); + + manager.put(new Operation( + OperationType.Modify, + index, + { payload: 'red', + prevPayload: undefined }, + userId + )); + + manager.transformStacks(new Operation( + OperationType.Modify, + index, + { payload: 'blue', + prevPayload: 'red' }, + 'remote' + )); + + expect(manager.undo()).toBeUndefined(); + }); + + it('should keep a plugin data entry for a key the collaborator did not touch', () => { + const manager = new UndoRedoManager(); + const doc = 'doc' as DocumentId; + + manager.put(new Operation( + OperationType.Modify, + Index.pluginData(0, createPluginDataName('anchors'), 'color', doc), + { payload: 'red', + prevPayload: undefined }, + userId + )); + + manager.transformStacks(new Operation( + OperationType.Modify, + Index.pluginData(0, createPluginDataName('anchors'), 'label', doc), + { payload: 'blue', + prevPayload: undefined }, + 'remote' + )); + + expect(manager.undo()?.type).toBe(OperationType.Modify); + }); }); }); From 384329c20b899aaaa8d9dc4577173438b4dbc228 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Thu, 5 Nov 2026 01:18:25 +0000 Subject: [PATCH 18/29] docs(openspec): specify and check off the fourth-round plugin-block-data follow-ups The spec change for the stack is merged, so this round's delta specs land here, with the code that implements them, rather than in a spec PR of their own. Co-Authored-By: Claude Opus 5 --- .../specs/collaboration-manager/spec.md | 12 +++++++++- .../specs/plugin-block-data/spec.md | 22 +++++++++++++++++++ openspec/changes/plugin-block-data/tasks.md | 6 +++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/openspec/changes/plugin-block-data/specs/collaboration-manager/spec.md b/openspec/changes/plugin-block-data/specs/collaboration-manager/spec.md index 620e0b6e..12c7367a 100644 --- a/openspec/changes/plugin-block-data/specs/collaboration-manager/spec.md +++ b/openspec/changes/plugin-block-data/specs/collaboration-manager/spec.md @@ -1,7 +1,7 @@ ## ADDED Requirements ### Requirement: Plugin data operations -`CollaborationManager` SHALL translate a `PluginDataModifiedEvent` into a `Modify` `Operation` on its `PluginDataIndex`, with `payload` set to the new value and `prevPayload` to the previous value. `OperationsTransformer` SHALL shift a plugin data operation's block index against block insertions and removals the same way it does for data index operations, SHALL turn it into a `Neutral` operation when its block is removed, and SHALL resolve two concurrent writes to the same block, plugin and key the same way it resolves two concurrent writes to the same data key: the operation being transformed becomes `Neutral` when the operation it is transformed against is the later of the two, an unsent local operation counting as later than any revision. Writes to different blocks, different plugins or different keys SHALL be left untransformed, since one cannot shift another's position. Transformation SHALL also accept a plugin data operation as the operation being transformed *against*, rather than rejecting its index kind. The `Modify` operation payload type SHALL admit any JSON value, including primitives. +`CollaborationManager` SHALL translate a `PluginDataModifiedEvent` into a `Modify` `Operation` on its `PluginDataIndex`, with `payload` set to the new value and `prevPayload` to the previous value. `OperationsTransformer` SHALL shift a plugin data operation's block index against block insertions and removals the same way it does for data index operations, SHALL turn it into a `Neutral` operation when its block is removed, and SHALL resolve two concurrent writes to the same block, plugin and key the same way it resolves two concurrent writes to the same data key: the operation being transformed becomes `Neutral` when the operation it is transformed against is the later of the two, an unsent local operation counting as later than any revision. Writes to different blocks, different plugins or different keys SHALL be left untransformed, since one cannot shift another's position. An operation carrying no revision of its own SHALL lose to whatever it is transformed against. Such an operation comes from an undo or redo stack, whose entries are built from model events and are never numbered, while an operation from the server always is; and the operation it is transformed against has already been applied to the document. Keeping it would leave an undo step that writes a value the document has moved on from, and whose recorded previous value is older still, so undoing a local write that a collaborator had overwritten would delete the collaborator's value. Transformation SHALL also accept a plugin data operation as the operation being transformed *against*, rather than rejecting its index kind. The `Modify` operation payload type SHALL admit any JSON value, including primitives. #### Scenario: Local plugin data change becomes an operation - **GIVEN** the local user changes `anchors.visible` on block 1 from `true` to `false` @@ -38,6 +38,16 @@ - **WHEN** B receives A's operation while its own write is still unsent - **THEN** A's operation is transformed to `Neutral` on B, so B keeps the value the server will end up holding rather than being left on A's +#### Scenario: Undoing a write a collaborator overwrote +- **GIVEN** the local user wrote `anchors.color` on block 0, and a collaborator then overwrote the same key +- **WHEN** the undo stack is transformed against the collaborator's operation +- **THEN** the entry is dropped, so undo reaches past it rather than writing a value that is gone and deleting the collaborator's + +#### Scenario: Undoing a write to a key nobody else touched +- **GIVEN** the local user wrote `anchors.color` and a collaborator wrote `anchors.label` on the same block +- **WHEN** the undo stack is transformed against the collaborator's operation +- **THEN** the entry survives, because the two do not describe the same value + #### Scenario: Concurrent writes to different keys - **GIVEN** a plugin data operation on `anchors.visible` and a concurrent one on `anchors.id` of the same block - **WHEN** one is transformed against the other diff --git a/openspec/changes/plugin-block-data/specs/plugin-block-data/spec.md b/openspec/changes/plugin-block-data/specs/plugin-block-data/spec.md index 70671a29..8efc0fbe 100644 --- a/openspec/changes/plugin-block-data/specs/plugin-block-data/spec.md +++ b/openspec/changes/plugin-block-data/specs/plugin-block-data/spec.md @@ -9,6 +9,8 @@ Plugin names and the keys within an entry are document data, not identifiers the What `getPluginData` and the serialized document hand back SHALL be detached from the store, so that changing it does not change the document. Reading an entry, editing it and passing it back to `updatePluginData` is the obvious way to use the two together, and over a live record the no-op rule above turns it into silent loss: the document has already changed, so the write that should have announced it emits nothing. +A value handed to the store SHALL be detached the same way before it is stored and before the change is recorded, down to nested objects and arrays, and so SHALL the data a block is initialized with. This is the same read-modify-write from the other end: a plugin keeps the object it wrote and edits it again, and over a shared object the document moves with no write at all, no operation for collaborators and no step to undo — two documents diverging with nothing to say so. What is recorded needs detaching for the same reason, since an operation and an undo step both outlive the call that produced them. Because what is stored is therefore a copy of what was written, the no-op rule above SHALL compare values structurally rather than by identity, which could only ever match a primitive. + #### Scenario: A block with no plugin data - **GIVEN** a block that has no plugin data at all - **WHEN** it is serialized @@ -44,6 +46,26 @@ What `getPluginData` and the serialized document hand back SHALL be detached fro - **WHEN** `{ visible: undefined }` is written for `anchors` - **THEN** the data is unchanged and no `PluginDataModifiedEvent` is emitted +#### Scenario: Editing a value that was written earlier +- **GIVEN** a plugin wrote `{ align: "left" }` for a key and still holds that object +- **WHEN** it changes the object to `{ align: "center" }` and writes it again +- **THEN** the document held `left` until that write, which emits a `PluginDataModifiedEvent` with `previous` `{ align: "left" }` and `value` `{ align: "center" }` + +#### Scenario: Writing an equal object again +- **GIVEN** a key holds `{ align: "left" }` +- **WHEN** a different object holding `{ align: "left" }` is written for it +- **THEN** no `PluginDataModifiedEvent` is emitted, because nothing about the stored data changed + +#### Scenario: Editing an object after the change was recorded +- **GIVEN** a plugin wrote an object for a key, and the change was recorded +- **WHEN** it changes that object afterwards +- **THEN** the recorded value is unaffected, so neither the operation sent to collaborators nor the undo step is rewritten + +#### Scenario: Reusing the data a block was initialized with +- **GIVEN** a block is initialized with a `plugins` map whose nested values the caller still holds +- **WHEN** the caller changes one of them +- **THEN** the block's plugin data is unaffected + #### Scenario: Reading an entry whose keys were all removed - **GIVEN** a block whose `anchors` entry existed and then had every key removed - **WHEN** its plugin data is read diff --git a/openspec/changes/plugin-block-data/tasks.md b/openspec/changes/plugin-block-data/tasks.md index 5a824728..016adbeb 100644 --- a/openspec/changes/plugin-block-data/tasks.md +++ b/openspec/changes/plugin-block-data/tasks.md @@ -68,3 +68,9 @@ - [x] 9.1 Write failing `PluginDataNode.spec.ts` cases for a `__proto__` key arriving from a loaded document and for a first write to a key named `toString`, then copy the node's record onto a null prototype as the block's own plugin store already is. The outer store's comment explains the hazard; the inner record never got the same treatment, so the key was dropped on load and the inherited function went onto the undo stack as a previous value - [x] 9.2 Write a failing case, then return a detached copy from `PluginDataNode.serialized`. Handing out the live record makes read-modify-write silent loss: `getPluginData` → edit → `updatePluginData` has already changed the Model, so the no-op guard finds nothing to announce and the edit reaches neither collaborators nor the undo stack - [x] 9.3 Write a failing case, then have `BlocksManager.getPluginData` check for an own entry. The serialized map is an ordinary object, so a plugin named `toString` or `constructor` read back as the inherited function instead of `undefined` + +## 10. Review follow-ups (fourth round) + +- [x] 10.1 Write failing `PluginDataNode.spec.ts` cases for a value the caller still holds — the object itself, its nested values, and the payload of the change already recorded — then copy incoming values with `structuredClone` on the way in, for the event payload, and for the data a node is constructed with. Sharing the object is the read-modify-write hazard of 9.2 from the other end: editing it moves the Model with no write at all, and the write-back that should have announced it finds the value unchanged and emits nothing, so the two documents diverge in silence +- [x] 10.2 Write a failing case for an equal-but-distinct object being written again, then compare values structurally in the no-op guard. Once stored values are copies, identity could only ever match a primitive, so every object write would emit and the rule from 7.1 would stop holding. `deepEqual` moves out of `isSameInlineData.ts` into `utils/deepEqual.ts` for the two to share, and gains a guard there: a value whose state is not in its own enumerable properties — a `Date`, a `Map` — would otherwise compare equal to any other of its kind, so switching off identity would have started swallowing writes that changed one +- [x] 10.3 Write failing `OperationsTransformer.spec.ts` and `UndoRedoManager.spec.ts` cases for an undo entry whose key a collaborator overwrote, then let an operation with no revision of its own lose to whatever it is transformed against. `againstRevision > operation.rev!` is `false` whenever the left side is a stack entry, because those are built from model events and never numbered — so the entry survived, and undoing a local first write after a remote overwrite deleted the collaborator's value. `#transformAgainstDataOperation` has the same hole for `data` values on `main`; it belongs with the other pre-existing OT defects on the board rather than in this PR From 9b749a4361fabf38a9dcf0e547563756258391a8 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Thu, 5 Nov 2026 02:00:56 +0000 Subject: [PATCH 19/29] test(model): kill the surviving mutants in the plugin data copy paths Scoped mutation runs over the files this round touched left six survivors. Four are now dead: - The array-vs-record kind check in `deepEqual` was only tested with `[]` against `{}`, which returns `false` either way. An array and an array-like record agree on `length` and on every index, so `{ length: 0 }` is the case that tells the branch apart. - Array lengths were only compared for arrays that also differed in content, so a matching prefix of a longer array went untested. - The `||` in the kind guard short-circuits the same way as `&&` when neither side is keyed, which is all the `Date`-against-`Date` cases did. Mixed sides are what it guards. - Removing a key that is present and explicitly holds `undefined` -- which only a loaded document can produce -- is a real change that no test covered, though the comment beside the no-op guard has described it since the write-that-changes-nothing round. The four left on `copyValue`'s guard all amount to cloning when nothing needs it, which is observable only for a value that cannot be cloned at all. Tightening that is a contract change rather than a test gap, so it stays as it is. `model` scores 94% over these files against a threshold of 75%, with `deepEqual.ts` and `isSameInlineData.ts` at 100%. Co-Authored-By: Claude Opus 5 --- .../PluginDataNode/PluginDataNode.spec.ts | 19 +++++++++++++++ packages/model/src/utils/deepEqual.spec.ts | 23 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts b/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts index f85eecdd..e31e9e93 100644 --- a/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts +++ b/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts @@ -149,6 +149,25 @@ describe('PluginDataNode', () => { expect(listener).not.toHaveBeenCalled(); }); + /** + * The key is present and holds `undefined`, which only a loaded document can produce, so + * removing it is a real change even though both sides of the comparison are `undefined` + */ + it('should still emit when a key that explicitly holds undefined is removed', () => { + const pluginData = new PluginDataNode({ name: pluginName, + data: { id: undefined } }); + const events: PluginDataModifiedEvent[] = []; + + pluginData.addEventListener(EventType.Changed, (event) => { + events.push(event as PluginDataModifiedEvent); + }); + + pluginData.update('id', undefined); + + expect(events).toHaveLength(1); + expect(pluginData.isEmpty).toBe(true); + }); + it('should still emit when the value actually differs', () => { const pluginData = new PluginDataNode({ name: pluginName, diff --git a/packages/model/src/utils/deepEqual.spec.ts b/packages/model/src/utils/deepEqual.spec.ts index fd617b67..f89c4c0a 100644 --- a/packages/model/src/utils/deepEqual.spec.ts +++ b/packages/model/src/utils/deepEqual.spec.ts @@ -29,6 +29,29 @@ describe('deepEqual', () => { expect(deepEqual([], {})).toBe(false); }); + it('should report arrays of different lengths as different', () => { + expect(deepEqual([1], [1, 2])).toBe(false); + expect(deepEqual([1, 2], [1])).toBe(false); + }); + + /** + * An array and an array-like record agree on `length` and on every index, so without the + * kind check in front of them they would compare equal + */ + it('should report an array and an array-like record as different', () => { + expect(deepEqual([], { length: 0 })).toBe(false); + expect(deepEqual({ length: 0 }, [])).toBe(false); + }); + + /** + * One side keyed and the other not: both have no own enumerable properties, so falling + * through to the key comparison would call them equal + */ + it('should report a non-plain object as different from a plain record', () => { + expect(deepEqual(new Date(1), {})).toBe(false); + expect(deepEqual({}, new Date(1))).toBe(false); + }); + it('should compare a record with a null prototype by its keys too', () => { const nullProto = Object.assign(Object.create(null) as Record, { a: 1 }); From a268f2c8ed156cdd98fec4fa61235ac9389f640f Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sun, 8 Nov 2026 13:43:42 +0000 Subject: [PATCH 20/29] fix(collaboration-manager): keep a sent operation pending until it is acknowledged `#sendNextOperation` shifted an operation off `#pendingOperations` in order to send it, and only pushed it to `#resolvedOperations` -- which nothing reads -- once the server acknowledged it. For the whole round trip the operation was in neither place, and `#onMessage` transforms incoming operations against `#pendingOperations` alone: a collaborator's write to the same value arriving in that window was transformed against nothing, applied over the local one, and never corrected, since a client's own operations are not echoed back to it. The convergence rule added earlier covered only the window before an operation is sent, which is a microtask, while this one is a full round trip -- so it is the window a simultaneous pair of `updatePluginData` calls actually lands in. `openspec/specs/collaboration-manager/spec.md` already required this behaviour; the code did not conform. Safety rests on the server ordering its messages: while an acknowledgement is outstanding, every remote operation delivered was ordered before the local one, so neutralising it is correct, and once it arrives, everything after it was ordered later and applies normally. Reading the head without removing it meant two concurrent `send` calls would both read the same operation and send it twice, so `#awaitingAcknowledgement` is now claimed before the first await. The guard on the acknowledgement handler also carries more weight than it did: mistaking a remote operation for the acknowledgement would now drop a still-in-flight operation from the pending list, reopening the window this closes, so it has a test of its own. The tests also close a hole they uncovered: nothing checked that sending ever resumes after an acknowledgement, only that a queued operation is held back while one is in flight -- so the acknowledgement gate could have latched shut permanently with the suite still green. Co-Authored-By: Claude Opus 5 --- .../src/client/OTClient.spec.ts | 195 +++++++++++++++++- .../src/client/OTClient.ts | 24 ++- 2 files changed, 212 insertions(+), 7 deletions(-) diff --git a/packages/collaboration-manager/src/client/OTClient.spec.ts b/packages/collaboration-manager/src/client/OTClient.spec.ts index 018ff399..68b1112f 100644 --- a/packages/collaboration-manager/src/client/OTClient.spec.ts +++ b/packages/collaboration-manager/src/client/OTClient.spec.ts @@ -1,9 +1,10 @@ /* eslint-disable @typescript-eslint/no-magic-numbers */ import type { DocumentId, EditorDocumentSerialized } from '@editorjs/sdk'; -import { createDataKey, Index } from '@editorjs/sdk'; +import { createDataKey, createPluginDataName, Index } from '@editorjs/sdk'; import { beforeEach, afterEach, jest, describe, it, expect } from '@jest/globals'; import { OTClient } from './OTClient.js'; -import { Operation, OperationType } from '../Operation.js'; +import { Operation, OperationType, type SerializedOperation } from '../Operation.js'; +import type { Message } from './Message.js'; import { MessageType } from './MessageType.js'; import { MockWebSocket } from '../../test/mocks/ws.js'; @@ -14,12 +15,29 @@ const documentId = 'document' as DocumentId; /** * Minimal stub document used when connecting the OTClient to a document. */ +/** + * Lets the asynchronous acknowledgement handler run to completion + */ +async function flushMicrotasks(): Promise { + await new Promise(resolve => setTimeout(resolve, 0)); +} + const stubDocument: EditorDocumentSerialized = { identifier: documentId, blocks: [], properties: {}, }; +/** + * Operation messages the client has put on the wire, in order + * @param sendSpy - spy over the mock socket's send + */ +function sentOperations(sendSpy: jest.SpiedFunction): Message[] { + return sendSpy.mock.calls + .map(([data]) => JSON.parse(data as string) as Message) + .filter(message => message.type === MessageType.Operation); +} + describe('OTClient', () => { let OriginalWebSocket: typeof WebSocket; @@ -111,6 +129,65 @@ describe('OTClient', () => { expect(onRemoteOperation).not.toHaveBeenCalled(); }); + /** + * The window a single `updatePluginData` actually lands in: the operation is sent straight + * away, so the round trip to the server is where a collaborator's write collides with it + */ + it('should NOT call onRemoteOperation while the only local operation is in flight', async () => { + const onRemoteOperation = jest.fn(); + const client = new OTClient('ws://test-collab.invalid/document', userId, jest.fn(), onRemoteOperation); + + await client.connectDocument(stubDocument); + + const index = Index.pluginData(0, createPluginDataName('anchors'), 'color', documentId); + + await client.send(new Operation(OperationType.Modify, index, { payload: 'red', + prevPayload: undefined }, userId)); + + MockWebSocket.lastInstance!.receiveFromServer({ + type: MessageType.Operation, + payload: new Operation(OperationType.Modify, index, { payload: 'blue', + prevPayload: undefined }, remoteUserId, 1).serialize(), + }); + + /** + * Applying it would leave this client on the collaborator's value while the server ends on + * ours, and its own operation is never echoed back to put that right + */ + expect(onRemoteOperation).not.toHaveBeenCalled(); + }); + + it('should call onRemoteOperation once the local operation has been acknowledged', async () => { + const onRemoteOperation = jest.fn(); + const client = new OTClient('ws://test-collab.invalid/document', userId, jest.fn(), onRemoteOperation); + + await client.connectDocument(stubDocument); + + const index = Index.pluginData(0, createPluginDataName('anchors'), 'color', documentId); + + await client.send(new Operation(OperationType.Modify, index, { payload: 'red', + prevPayload: undefined }, userId)); + + // The server echoes the local operation back with a revision, which is its acknowledgement. + MockWebSocket.lastInstance!.receiveFromServer({ + type: MessageType.Operation, + payload: new Operation(OperationType.Modify, index, { payload: 'red', + prevPayload: undefined }, userId, 1).serialize(), + }); + await Promise.resolve(); + + MockWebSocket.lastInstance!.receiveFromServer({ + type: MessageType.Operation, + payload: new Operation(OperationType.Modify, index, { payload: 'blue', + prevPayload: 'red' }, remoteUserId, 2).serialize(), + }); + + /** + * The server ordered the collaborator's write after ours, so it is the one that stands + */ + expect(onRemoteOperation).toHaveBeenCalledTimes(1); + }); + it('should ignore messages with type other than Operation', async () => { const onRemoteOperation = jest.fn(); const client = new OTClient('ws://test-collab.invalid/document', userId, jest.fn(), onRemoteOperation); @@ -214,6 +291,120 @@ describe('OTClient', () => { expect(opCalls).toHaveLength(1); sendSpy.mockRestore(); }); + + /** + * Both calls reach the send path before either awaits, so the guard has to be claimed + * before the first await or they both read the same head operation + */ + it('should send the head operation once when two sends race', async () => { + const client = new OTClient('ws://test-collab.invalid/document', userId, jest.fn(), jest.fn()); + + await client.connectDocument(stubDocument); + + const sendSpy = jest.spyOn(MockWebSocket.lastInstance!, 'send'); + + const index = Index.text([{ blockIndex: 0, + dataKey: createDataKey('text'), + textRange: [0, 0], + documentId }]); + + await Promise.all([ + client.send(new Operation(OperationType.Insert, index, { payload: 'a' }, userId)), + client.send(new Operation(OperationType.Insert, index, { payload: 'b' }, userId)), + ]); + + expect(sentOperations(sendSpy)).toHaveLength(1); + sendSpy.mockRestore(); + }); + + it('should send the queued operation once the first is acknowledged', async () => { + const client = new OTClient('ws://test-collab.invalid/document', userId, jest.fn(), jest.fn()); + + await client.connectDocument(stubDocument); + + const sendSpy = jest.spyOn(MockWebSocket.lastInstance!, 'send'); + + const index = Index.text([{ blockIndex: 0, + dataKey: createDataKey('text'), + textRange: [0, 0], + documentId }]); + + const first = new Operation(OperationType.Insert, index, { payload: 'a' }, userId); + + await client.send(first); + await client.send(new Operation(OperationType.Insert, index, { payload: 'b' }, userId)); + + MockWebSocket.lastInstance!.receiveFromServer({ + type: MessageType.Operation, + payload: new Operation(OperationType.Insert, index, { payload: 'a' }, userId, 1).serialize(), + }); + await flushMicrotasks(); + + /** + * The acknowledgement is what releases the queue. Nothing covered that it does, which left + * the gate free to latch shut and strand every later operation + */ + expect(sentOperations(sendSpy)).toHaveLength(2); + sendSpy.mockRestore(); + }); + + /** + * The guard on the acknowledgement handler now protects the pending queue, not just the + * gate: mistaking a collaborator's operation for the acknowledgement would drop a local + * operation that is still in flight, reopening the window remote writes are transformed in + */ + it('should not mistake a remote operation for the acknowledgement', async () => { + const client = new OTClient('ws://test-collab.invalid/document', userId, jest.fn(), jest.fn()); + + await client.connectDocument(stubDocument); + + const sendSpy = jest.spyOn(MockWebSocket.lastInstance!, 'send'); + + const index = Index.text([{ blockIndex: 0, + dataKey: createDataKey('text'), + textRange: [0, 0], + documentId }]); + + await client.send(new Operation(OperationType.Insert, index, { payload: 'a' }, userId)); + + MockWebSocket.lastInstance!.receiveFromServer({ + type: MessageType.Operation, + payload: new Operation(OperationType.Insert, Index.block(5, documentId), { payload: [] }, remoteUserId, 1).serialize(), + }); + await flushMicrotasks(); + + await client.send(new Operation(OperationType.Insert, index, { payload: 'b' }, userId)); + + // The first operation is still unacknowledged, so the second has to wait behind it. + expect(sentOperations(sendSpy)).toHaveLength(1); + sendSpy.mockRestore(); + }); + + it('should still send a later operation once the queue has drained', async () => { + const client = new OTClient('ws://test-collab.invalid/document', userId, jest.fn(), jest.fn()); + + await client.connectDocument(stubDocument); + + const sendSpy = jest.spyOn(MockWebSocket.lastInstance!, 'send'); + + const index = Index.text([{ blockIndex: 0, + dataKey: createDataKey('text'), + textRange: [0, 0], + documentId }]); + + await client.send(new Operation(OperationType.Insert, index, { payload: 'a' }, userId)); + + MockWebSocket.lastInstance!.receiveFromServer({ + type: MessageType.Operation, + payload: new Operation(OperationType.Insert, index, { payload: 'a' }, userId, 1).serialize(), + }); + await flushMicrotasks(); + + await client.send(new Operation(OperationType.Insert, index, { payload: 'b' }, userId)); + + expect(sentOperations(sendSpy)).toHaveLength(2); + sendSpy.mockRestore(); + }); }); describe('close', () => { diff --git a/packages/collaboration-manager/src/client/OTClient.ts b/packages/collaboration-manager/src/client/OTClient.ts index 708a21be..95f565ca 100644 --- a/packages/collaboration-manager/src/client/OTClient.ts +++ b/packages/collaboration-manager/src/client/OTClient.ts @@ -18,7 +18,8 @@ export class OTClient { #rev: number = 0; /** - * Array of pending operations to send + * Operations the server has not acknowledged yet, oldest first. The one being sent stays at + * the head until its acknowledgement, so remote operations are transformed against it too */ #pendingOperations: Operation[] = []; @@ -156,18 +157,26 @@ export class OTClient { return; } - const nextOperation = this.#pendingOperations.shift(); - - if (!nextOperation) { + if (this.#pendingOperations.length === 0) { this.#awaitingAcknowledgement = false; return; } - const ws = await this.#ws; + /** + * Read, not removed: an operation is pending until acknowledged, and dropping it here left the round trip + * unguarded, so a remote write to the same value was applied over the local one and never corrected + */ + const nextOperation = this.#pendingOperations[0]; + /** + * Claimed before the first await, so that a concurrent `send` sees the flag and queues + * instead of reading the same head operation and sending it twice + */ this.#awaitingAcknowledgement = true; + const ws = await this.#ws; + /** * Handles acknowledgment response and sends the next operation * @param message - server message @@ -184,6 +193,11 @@ export class OTClient { return; } + /** + * Acknowledged, so it stops being pending. The server orders its messages, so whatever arrives after + * this was ordered after the local operation, and whatever arrived before it was ordered before + */ + this.#pendingOperations.shift(); this.#resolvedOperations.push(nextOperation); ws.removeEventListener('message', onMessage); From 99dc155a8c10f4b97b750b6f502f8def2ab55481 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sun, 8 Nov 2026 13:43:42 +0000 Subject: [PATCH 21/29] docs(openspec): specify and check off the fifth-round plugin-block-data follow-ups The convergence rule said "unsent" where it meant "unacknowledged", which is the distinction the round turned on. Co-Authored-By: Claude Opus 5 --- .../specs/collaboration-manager/spec.md | 14 ++++++++++++-- openspec/changes/plugin-block-data/tasks.md | 5 +++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/openspec/changes/plugin-block-data/specs/collaboration-manager/spec.md b/openspec/changes/plugin-block-data/specs/collaboration-manager/spec.md index 12c7367a..fe62278f 100644 --- a/openspec/changes/plugin-block-data/specs/collaboration-manager/spec.md +++ b/openspec/changes/plugin-block-data/specs/collaboration-manager/spec.md @@ -1,7 +1,7 @@ ## ADDED Requirements ### Requirement: Plugin data operations -`CollaborationManager` SHALL translate a `PluginDataModifiedEvent` into a `Modify` `Operation` on its `PluginDataIndex`, with `payload` set to the new value and `prevPayload` to the previous value. `OperationsTransformer` SHALL shift a plugin data operation's block index against block insertions and removals the same way it does for data index operations, SHALL turn it into a `Neutral` operation when its block is removed, and SHALL resolve two concurrent writes to the same block, plugin and key the same way it resolves two concurrent writes to the same data key: the operation being transformed becomes `Neutral` when the operation it is transformed against is the later of the two, an unsent local operation counting as later than any revision. Writes to different blocks, different plugins or different keys SHALL be left untransformed, since one cannot shift another's position. An operation carrying no revision of its own SHALL lose to whatever it is transformed against. Such an operation comes from an undo or redo stack, whose entries are built from model events and are never numbered, while an operation from the server always is; and the operation it is transformed against has already been applied to the document. Keeping it would leave an undo step that writes a value the document has moved on from, and whose recorded previous value is older still, so undoing a local write that a collaborator had overwritten would delete the collaborator's value. Transformation SHALL also accept a plugin data operation as the operation being transformed *against*, rather than rejecting its index kind. The `Modify` operation payload type SHALL admit any JSON value, including primitives. +`CollaborationManager` SHALL translate a `PluginDataModifiedEvent` into a `Modify` `Operation` on its `PluginDataIndex`, with `payload` set to the new value and `prevPayload` to the previous value. `OperationsTransformer` SHALL shift a plugin data operation's block index against block insertions and removals the same way it does for data index operations, SHALL turn it into a `Neutral` operation when its block is removed, and SHALL resolve two concurrent writes to the same block, plugin and key the same way it resolves two concurrent writes to the same data key: the operation being transformed becomes `Neutral` when the operation it is transformed against is the later of the two, a local operation the server has not acknowledged counting as later than any revision. A local operation SHALL count as unacknowledged for the whole round trip, not merely until it leaves for the server, so the client SHALL keep it among the operations an incoming one is transformed against until its acknowledgement arrives. The acknowledgement is what establishes the server's order: while it is outstanding, every remote operation the server delivers was ordered before the local one, and once it arrives, everything after it was ordered later. Writes to different blocks, different plugins or different keys SHALL be left untransformed, since one cannot shift another's position. An operation carrying no revision of its own SHALL lose to whatever it is transformed against. Such an operation comes from an undo or redo stack, whose entries are built from model events and are never numbered, while an operation from the server always is; and the operation it is transformed against has already been applied to the document. Keeping it would leave an undo step that writes a value the document has moved on from, and whose recorded previous value is older still, so undoing a local write that a collaborator had overwritten would delete the collaborator's value. Transformation SHALL also accept a plugin data operation as the operation being transformed *against*, rather than rejecting its index kind. The `Modify` operation payload type SHALL admit any JSON value, including primitives. #### Scenario: Local plugin data change becomes an operation - **GIVEN** the local user changes `anchors.visible` on block 1 from `true` to `false` @@ -35,9 +35,19 @@ #### Scenario: Two clients write the same key concurrently - **GIVEN** clients A and B both write `anchors.visible` on block 1, and the server applies A before B -- **WHEN** B receives A's operation while its own write is still unsent +- **WHEN** B receives A's operation while its own write is still unacknowledged - **THEN** A's operation is transformed to `Neutral` on B, so B keeps the value the server will end up holding rather than being left on A's +#### Scenario: A collaborator writes while the local write is in flight +- **GIVEN** the local client has sent a write of `anchors.color` and is waiting for its acknowledgement +- **WHEN** a collaborator's write to the same key arrives before that acknowledgement +- **THEN** it is transformed to `Neutral` and not applied, since the server will apply the local write after it -- and a client's own operations are not echoed back to it, so nothing would restore the value the server ends up holding + +#### Scenario: A collaborator writes once the local write is acknowledged +- **GIVEN** the local client's write of `anchors.color` has been acknowledged +- **WHEN** a collaborator's write to the same key arrives +- **THEN** it is applied, because the server ordered it after the local write + #### Scenario: Undoing a write a collaborator overwrote - **GIVEN** the local user wrote `anchors.color` on block 0, and a collaborator then overwrote the same key - **WHEN** the undo stack is transformed against the collaborator's operation diff --git a/openspec/changes/plugin-block-data/tasks.md b/openspec/changes/plugin-block-data/tasks.md index 016adbeb..f13451db 100644 --- a/openspec/changes/plugin-block-data/tasks.md +++ b/openspec/changes/plugin-block-data/tasks.md @@ -74,3 +74,8 @@ - [x] 10.1 Write failing `PluginDataNode.spec.ts` cases for a value the caller still holds — the object itself, its nested values, and the payload of the change already recorded — then copy incoming values with `structuredClone` on the way in, for the event payload, and for the data a node is constructed with. Sharing the object is the read-modify-write hazard of 9.2 from the other end: editing it moves the Model with no write at all, and the write-back that should have announced it finds the value unchanged and emits nothing, so the two documents diverge in silence - [x] 10.2 Write a failing case for an equal-but-distinct object being written again, then compare values structurally in the no-op guard. Once stored values are copies, identity could only ever match a primitive, so every object write would emit and the rule from 7.1 would stop holding. `deepEqual` moves out of `isSameInlineData.ts` into `utils/deepEqual.ts` for the two to share, and gains a guard there: a value whose state is not in its own enumerable properties — a `Date`, a `Map` — would otherwise compare equal to any other of its kind, so switching off identity would have started swallowing writes that changed one - [x] 10.3 Write failing `OperationsTransformer.spec.ts` and `UndoRedoManager.spec.ts` cases for an undo entry whose key a collaborator overwrote, then let an operation with no revision of its own lose to whatever it is transformed against. `againstRevision > operation.rev!` is `false` whenever the left side is a stack entry, because those are built from model events and never numbered — so the entry survived, and undoing a local first write after a remote overwrite deleted the collaborator's value. `#transformAgainstDataOperation` has the same hole for `data` values on `main`; it belongs with the other pre-existing OT defects on the board rather than in this PR + +## 11. Review follow-ups (fifth round) + +- [x] 11.1 Write a failing `OTClient.spec.ts` case for a collaborator's write arriving while the only local write is in flight, then keep an operation in `#pendingOperations` until its acknowledgement instead of removing it when it is sent. `#sendNextOperation` shifted the operation off the queue to send it, so for the whole round trip it was in neither the pending list nor anywhere else `#onMessage` looks: the remote write was transformed against nothing, applied over the local one, and never corrected, because a client's own operations are not echoed back to it. The convergence rule from 8.1 covered only the window before an operation is sent, which is a microtask, while this one is a full round trip -- so it was the likelier half and the one a simultaneous pair of `updatePluginData` calls actually lands in. `openspec/specs/collaboration-manager/spec.md` already required this ("transformed against the pending local operations ... while local operations are pending/unacknowledged"); the code did not conform, and this change's own wording said "unsent" where it meant "unacknowledged" +- [x] 11.2 Claim `#awaitingAcknowledgement` before the first `await` in `#sendNextOperation`. Reading the head operation rather than shifting it means two concurrent `send` calls would otherwise both read the same one and send it twice, where the old code sent each once in an arbitrary order From 7e001acfd7775ee32017f297b9471e33f0dd4528 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 26 Sep 2026 01:21:54 +0100 Subject: [PATCH 22/29] refactor!: remove the Block Tune tool kind MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A registered tune got a `BlockTuneFacade` built and sorted into `ToolsManager.blockTunes`, and nothing ever read it — no adapter, no rendering, no model wiring. It was a second, half-built way to do what a plugin now does, so it goes rather than stays as an alternative to document around. Removed from `sdk`: `ToolType.Tune`, the `BlockTune*` contracts and `BlockTuneFacade`, `BaseToolFacade#isTune()`, `ToolsCollection#blockTunes`, `ToolTypeToOptions[ToolType.Tune]`, and the tune members of the `ToolConstructable`/`ToolFacadeClass` unions. The per-tool allow-list goes too — `BlockToolOptionKey.Tunes`, `UserToolOptions.EnabledBlockTunes`, `BlockToolFacade#enabledBlockTunes` and `BlockToolFacade#tunes` — because per-tool filtering belongs to the providers, which get `tool` in their context. If integrators want the allow-list back it returns through `options.plugins['block-settings']`, not as a member of the tool contract. Removed from `core`: the Tune branch of `use()`, the `getAll(ToolType.Tune)` preparation step, the Tune case in `ToolsFactory` and `ToolsManager#blockTunes`. `shortcuts-plugin` loses its never-called `#processBlockTune`. The removal is guarded by compile-time assertions rather than runtime ones: under `ts-jest` a stale `@ts-expect-error` is itself a diagnostic, so each directive fails the suite while the name it points at exists. `BlockToolOptions['tunes']` is the one member that cannot be asserted — the interface carries an open index signature for tool-author options, so every key resolves. BREAKING CHANGE: registering a tune through `core.use()` or setting a tool's `tunes` option no longer compiles. Write a plugin instead: it puts an item in the block settings menu and stores state as per-block plugin data. Co-Authored-By: Claude Opus 5 --- packages/core/src/index.spec.ts | 54 ++++++++++++- packages/core/src/index.ts | 6 +- packages/core/src/tools/ToolsFactory.ts | 8 +- packages/core/src/tools/ToolsManager.ts | 10 +-- .../plugins/shortcuts-plugin/src/index.ts | 11 --- packages/sdk/src/api/BlocksAPI.ts | 3 +- packages/sdk/src/entities/BaseTool.ts | 9 +-- packages/sdk/src/entities/BlockTool.ts | 8 -- packages/sdk/src/entities/BlockTune.ts | 79 ------------------ packages/sdk/src/entities/EntityType.ts | 7 +- packages/sdk/src/entities/index.ts | 1 - .../sdk/src/tools/ToolsCollection.spec.ts | 63 +++++++++++++++ packages/sdk/src/tools/ToolsCollection.ts | 12 --- .../src/tools/facades/BaseToolFacade.spec.ts | 80 ++++++++++++++++++- .../sdk/src/tools/facades/BaseToolFacade.ts | 20 ++--- .../sdk/src/tools/facades/BlockToolFacade.ts | 15 +--- .../sdk/src/tools/facades/BlockTuneFacade.ts | 36 --------- packages/sdk/src/tools/facades/index.ts | 4 +- 18 files changed, 211 insertions(+), 215 deletions(-) delete mode 100644 packages/sdk/src/entities/BlockTune.ts create mode 100644 packages/sdk/src/tools/ToolsCollection.spec.ts delete mode 100644 packages/sdk/src/tools/facades/BlockTuneFacade.ts diff --git a/packages/core/src/index.spec.ts b/packages/core/src/index.spec.ts index 3338540a..5b525f6b 100644 --- a/packages/core/src/index.spec.ts +++ b/packages/core/src/index.spec.ts @@ -1,7 +1,8 @@ /* eslint-disable jsdoc/require-jsdoc -- inline test stubs */ -import { describe, it, expect } from '@jest/globals'; +import { afterEach, describe, it, expect, jest } from '@jest/globals'; import { PluginType, ToolType } from '@editorjs/sdk'; import type { CoreConfig } from '@editorjs/sdk'; +import ToolsManager from './tools/ToolsManager.js'; import Core from './index.js'; /** @@ -56,6 +57,22 @@ class StubPlugin { } } +/** + * Stands in for a former Block Tune: a plain plugin that contributes an item to the + * block settings menu. It carries no `type`, so `use()` must route it to the plugins + * container rather than to any tool collection. + */ +class StubSettingsPlugin { + public static type = PluginType.Plugin as const; + public static name = 'delete-block'; + + public static instances = 0; + + constructor() { + StubSettingsPlugin.instances += 1; + } +} + describe('Core', () => { describe('initialize() preconditions', () => { it('should throw naming the rendering adapter when no adapter has been registered', async () => { @@ -107,4 +124,39 @@ describe('Core', () => { expect(StubPlugin.instances).toBe(1); }); }); + + describe('registering a former block tune', () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('should instantiate a block settings plugin as a plugin and keep it out of the tools handed to ToolsManager', async () => { + StubSettingsPlugin.instances = 0; + + const prepareTools = jest.spyOn(ToolsManager.prototype, 'prepareTools'); + const core = new Core(createConfig()); + + core.use(StubAdapter); + core.use(StubBlockTool); + core.use(StubSettingsPlugin); + + await core.initialize(); + + const prepared = prepareTools.mock.calls[0][0]; + + expect(StubSettingsPlugin.instances).toBe(1); + expect(prepared.map(([tool]) => tool.name)).toEqual(['paragraph']); + }); + + it('should no longer expose a blockTunes collection on ToolsManager', () => { + type ManagerCollections = { + // @ts-expect-error -- `blockTunes` went with the tune tool kind + blockTunes: ToolsManager['blockTunes']; + }; + + const probe: ManagerCollections | undefined = undefined; + + expect(probe).toBeUndefined(); + }); + }); }); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 01ab27ae..52fcf44d 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -16,7 +16,7 @@ import { } from '@editorjs/sdk'; import { composeDataFromVersion2 } from './utils/composeDataFromVersion2.js'; import ToolsManager from './tools/ToolsManager.js'; -import type { CoreConfigValidated, CoreConfig, EditorjsPluginConstructor, BlockTuneConstructor, ToolConstructable, EditorjsAdapterPluginConstructor } from '@editorjs/sdk'; +import type { CoreConfigValidated, CoreConfig, EditorjsPluginConstructor, ToolConstructable, EditorjsAdapterPluginConstructor } from '@editorjs/sdk'; import { EditorAPI } from './api/index.js'; import { generateId } from './utils/uid.js'; import { BlocksManager } from './components/BlockManager.js'; @@ -134,7 +134,6 @@ export default class Core { switch (pluginType) { case ToolType.Block: case ToolType.Inline: - case ToolType.Tune: this.#plugins.bind<[ToolConstructable, ToolStaticOptions | undefined]>(pluginType).toConstantValue([pluginOrTool as ToolConstructable, options]); break; case PluginType.Adapter: @@ -218,11 +217,10 @@ export default class Core { async #initializeTools(): Promise { const blockTools = this.#plugins.getAll<[BlockToolConstructor, ToolStaticOptions | undefined]>(ToolType.Block); const inlineTools = this.#plugins.getAll<[InlineToolConstructor, ToolStaticOptions | undefined]>(ToolType.Inline); - const blockTunes = this.#plugins.getAll<[BlockTuneConstructor, ToolStaticOptions | undefined]>(ToolType.Tune); const toolsManager = this.#iocContainer.get(ToolsManager); - return toolsManager.prepareTools([...blockTools, ...inlineTools, ...blockTunes]); + return toolsManager.prepareTools([...blockTools, ...inlineTools]); } /** diff --git a/packages/core/src/tools/ToolsFactory.ts b/packages/core/src/tools/ToolsFactory.ts index 8fbe9362..0ea206d5 100644 --- a/packages/core/src/tools/ToolsFactory.ts +++ b/packages/core/src/tools/ToolsFactory.ts @@ -4,14 +4,13 @@ import { ToolType } from '@editorjs/sdk'; import type { ToolConstructable, ToolStaticOptions } from '@editorjs/sdk'; import { InlineToolFacade, - BlockTuneFacade, BlockToolFacade } from '@editorjs/sdk'; import type { EditorConfig } from 'editorjs-v2'; -type ToolConstructor = typeof InlineToolFacade | typeof BlockToolFacade | typeof BlockTuneFacade; +type ToolConstructor = typeof InlineToolFacade | typeof BlockToolFacade; /** * Full tool registration entry: the constructor class plus its options. @@ -81,7 +80,7 @@ export class ToolsFactory { * Returns Tool object based on it's type * @param name - tool name */ - public get(name: string): InlineToolFacade | BlockToolFacade | BlockTuneFacade { + public get(name: string): InlineToolFacade | BlockToolFacade { const toolSettings = this.#toolsSettings.get(name); if (!toolSettings) { @@ -91,7 +90,6 @@ export class ToolsFactory { const { class: constructable, ...useToolOptions } = toolSettings; const Constructor = this.#getConstructor(constructable); - // const isTune = constructable[InternalTuneSettings.IsTune]; return new Constructor({ name, @@ -115,8 +113,6 @@ export class ToolsFactory { switch (constructable.type) { case ToolType.Inline: return InlineToolFacade; - case ToolType.Tune: - return BlockTuneFacade; default: return BlockToolFacade; } diff --git a/packages/core/src/tools/ToolsManager.ts b/packages/core/src/tools/ToolsManager.ts index 297f30fd..6b4e968b 100644 --- a/packages/core/src/tools/ToolsManager.ts +++ b/packages/core/src/tools/ToolsManager.ts @@ -9,7 +9,7 @@ import type { import { InlineTool, ToolLoadedCoreEvent, - BlockToolFacade, BlockTuneFacade, + BlockToolFacade, InlineToolFacade, ToolFacadeClass, ToolsCollection, @@ -84,14 +84,6 @@ export default class ToolsManager { return this.available.blockTools; } - /** - * Return available Block Tunes - * @returns - object of Inline Tool's classes - */ - public get blockTunes(): ToolsCollection { - return this.available.blockTunes; - } - /** * @param editorConfig - EditorConfig object * @param apiFactory - Editor API factory function diff --git a/packages/plugins/shortcuts-plugin/src/index.ts b/packages/plugins/shortcuts-plugin/src/index.ts index a222cea3..653c7708 100644 --- a/packages/plugins/shortcuts-plugin/src/index.ts +++ b/packages/plugins/shortcuts-plugin/src/index.ts @@ -1,6 +1,5 @@ import type { BlockToolFacade, - BlockTuneFacade, EditorAPI, EditorjsPlugin, EditorjsPluginParams, @@ -207,14 +206,4 @@ export class ShortcutsPlugin implements EditorjsPlugin<'shortcuts'> { * @todo `shortcuts` map for block tools (e.g. list styles) — apply render/data overrides */ } - - /** - * Block tune shortcuts — reserved for future use. - * @param _tool - loaded block tune facade - */ - #processBlockTune(_tool: BlockTuneFacade): void { - /* - * @todo block tune shortcuts if needed - */ - } } diff --git a/packages/sdk/src/api/BlocksAPI.ts b/packages/sdk/src/api/BlocksAPI.ts index 6e1e1281..896477bd 100644 --- a/packages/sdk/src/api/BlocksAPI.ts +++ b/packages/sdk/src/api/BlocksAPI.ts @@ -285,9 +285,8 @@ export interface BlocksAPI { * Updates block data by id * @param id - id of the block to update * @param data - (optional) the new data. Can be partial. - * @param tunes - (optional) tune data */ - // update(id: string, data?: Partial, tunes?: { [name: string]: BlockTuneData }): Promise; + // update(id: string, data?: Partial): Promise; /** * Converts block to another type. Both blocks should provide the conversionConfig. diff --git a/packages/sdk/src/entities/BaseTool.ts b/packages/sdk/src/entities/BaseTool.ts index 83e34e72..e3f00f55 100644 --- a/packages/sdk/src/entities/BaseTool.ts +++ b/packages/sdk/src/entities/BaseTool.ts @@ -1,6 +1,5 @@ import type { BlockToolOptions } from './BlockTool.js'; import type { InlineToolOptions } from './InlineTool.js'; -import type { BlockTuneOptions } from './BlockTune.js'; import type { ToolType } from './EntityType.js'; import type { ToolPluginOptions } from '../index.js'; @@ -75,13 +74,13 @@ export type ToolOptionsFactory< > = (config: Config) => Options; // Re-export so consumers can import all option types from this file -export type { BlockToolOptions, InlineToolOptions, BlockTuneOptions }; +export type { BlockToolOptions, InlineToolOptions }; /** * Union of all per-tool option shapes. * Used as the type of the second argument of `core.use(Tool, options)`. */ -export type ToolStaticOptions = BlockToolOptions | InlineToolOptions | BlockTuneOptions; +export type ToolStaticOptions = BlockToolOptions | InlineToolOptions; /** * Maps a {@link ToolType} value to its corresponding tool options interface. @@ -97,10 +96,6 @@ export type ToolTypeToOptions = { * InlineTool Options */ [ToolType.Inline]: InlineToolOptions; - /** - * BlockTune Options - */ - [ToolType.Tune]: BlockTuneOptions; }; /** diff --git a/packages/sdk/src/entities/BlockTool.ts b/packages/sdk/src/entities/BlockTool.ts index 1f77f69c..8cc8ad9e 100644 --- a/packages/sdk/src/entities/BlockTool.ts +++ b/packages/sdk/src/entities/BlockTool.ts @@ -41,8 +41,6 @@ export enum BlockToolOptionKey { Shortcut = 'shortcut', /** Inline tools enabled for blocks of this type. */ InlineToolbar = 'inlineToolbar', - /** Block tunes enabled for blocks of this type. */ - Tunes = 'tunes', /** Conversion configuration for this tool. */ ConversionConfig = 'conversionConfig', /** Whether the block can be split into multiple blocks of its type. */ @@ -77,12 +75,6 @@ export interface BlockToolOptions - extends BaseToolOptions { - /** Any additional custom options exposed by the tune developer. */ - [key: string]: unknown; -} - -/** - * BlockTune data type - * @todo move to data description section when migrated from V2 - */ -export type BlockTuneData = any; - -/** - * Extended BlockToolConstructorOptions interface for version 3. - */ -export interface BlockTuneConstructorOptions< - /** - * Data structure describing the tool's input/output data - */ - Data extends BlockTuneData = BlockTuneData, - /** - * User-end configuration for the tool - */ - Config extends ToolConfig = ToolConfig -> { - /** - * Tool's input/output data - */ - data: Data; - - /** - * Config could be passed by tools user through the Editor config - */ - config: Config; -} - -/** - * Block Tune interface for version 3 - * @todo describe the interface when the adapter implementation is done - */ -export type BlockTune< - /** - * Data structure describing the tool's input/output data - * - * any is used as a placeholder to allow using BlockToolData without generic - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - Data extends BlockTuneData = any, - /** - * User-end configuration for the tool - * - * any is used as a placeholder to allow using BlockToolData without generic - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - Config extends ToolConfig = any -> = Omit; - -/** - * Block Tune constructor class - */ -export interface BlockTuneConstructor extends BaseToolConstructor { - new(options: BlockTuneConstructorOptions): BlockTune; - - /** - * Property specifies that the class is a Tune - */ - type: ToolType.Tune; -}; diff --git a/packages/sdk/src/entities/EntityType.ts b/packages/sdk/src/entities/EntityType.ts index 02c8a2e0..09aaf2ca 100644 --- a/packages/sdk/src/entities/EntityType.ts +++ b/packages/sdk/src/entities/EntityType.ts @@ -40,12 +40,7 @@ export enum ToolType { /** * Inline Tool */ - Inline = 'inline', - - /** - * Block Tune - */ - Tune = 'tune' + Inline = 'inline' } /** diff --git a/packages/sdk/src/entities/index.ts b/packages/sdk/src/entities/index.ts index 7bbfed56..eef4535d 100644 --- a/packages/sdk/src/entities/index.ts +++ b/packages/sdk/src/entities/index.ts @@ -1,7 +1,6 @@ export * from './BaseTool.js'; export type * from './InlineTool.js'; export * from './BlockTool.js'; -export type * from './BlockTune.js'; export type * from './Config.js'; export * from './BlockToolAdapter.js'; export * from './EventBus/index.js'; diff --git a/packages/sdk/src/tools/ToolsCollection.spec.ts b/packages/sdk/src/tools/ToolsCollection.spec.ts new file mode 100644 index 00000000..63f39c05 --- /dev/null +++ b/packages/sdk/src/tools/ToolsCollection.spec.ts @@ -0,0 +1,63 @@ +/* eslint-disable jsdoc/require-jsdoc -- inline test stubs */ + +import { describe, expect, it } from '@jest/globals'; +import { ToolType } from '../entities/index.js'; +import type { ToolFacadeClass } from './facades/index.js'; +import { ToolsCollection } from './ToolsCollection.js'; + +/** + * Stands in for a registered facade: `ToolsCollection` filters purely on the kind + * predicates, so a bare object carrying `type` and those predicates is enough. + * @param name - name the facade is registered under + * @param type - kind the facade reports + */ +function facadeStub(name: string, type: ToolType): [string, ToolFacadeClass] { + const facade = { + name, + type, + isBlock: () => type === ToolType.Block, + isInline: () => type === ToolType.Inline, + }; + + return [name, facade as unknown as ToolFacadeClass]; +} + +describe('ToolsCollection', () => { + const collection = new ToolsCollection([ + facadeStub('paragraph', ToolType.Block), + facadeStub('header', ToolType.Block), + facadeStub('bold', ToolType.Inline), + ]); + + it('should return only block tool facades from blockTools', () => { + expect([...collection.blockTools.keys()]).toEqual(['paragraph', 'header']); + }); + + it('should return only inline tool facades from inlineTools', () => { + expect([...collection.inlineTools.keys()]).toEqual(['bold']); + }); + + it('should expose no view beyond blockTools and inlineTools', () => { + /* + * Own getters live on the prototype, so the collection's kind views are read from + * there rather than from the instance. + */ + const views = Object + .entries(Object.getOwnPropertyDescriptors(ToolsCollection.prototype)) + .filter(([, descriptor]) => descriptor.get !== undefined) + .map(([key]) => key); + + expect(views.sort()).toEqual(['blockTools', 'inlineTools']); + }); + + it('should no longer expose a blockTunes view', () => { + type CollectionViews = { + // @ts-expect-error -- `blockTunes` went with the tune tool kind + blockTunes: ToolsCollection['blockTunes']; + }; + + const probe: CollectionViews | undefined = undefined; + + expect(probe).toBeUndefined(); + }); +}); diff --git a/packages/sdk/src/tools/ToolsCollection.ts b/packages/sdk/src/tools/ToolsCollection.ts index 979a91e9..1ed3c86d 100644 --- a/packages/sdk/src/tools/ToolsCollection.ts +++ b/packages/sdk/src/tools/ToolsCollection.ts @@ -1,6 +1,5 @@ import { type BlockToolFacade } from './facades/BlockToolFacade.js'; import { type InlineToolFacade } from './facades/InlineToolFacade.js'; -import { type BlockTuneFacade } from './facades/BlockTuneFacade.js'; import type { ToolFacadeClass } from './facades/index.js'; /** @@ -28,15 +27,4 @@ export class ToolsCollection extend return new ToolsCollection(tools); } - - /** - * Returns Block Tunes collection - */ - public get blockTunes(): ToolsCollection { - const tools = Array - .from(this.entries()) - .filter(([, tool]) => tool.isTune()) as [string, BlockTuneFacade][]; - - return new ToolsCollection(tools); - } } diff --git a/packages/sdk/src/tools/facades/BaseToolFacade.spec.ts b/packages/sdk/src/tools/facades/BaseToolFacade.spec.ts index c0ad6635..e05afb97 100644 --- a/packages/sdk/src/tools/facades/BaseToolFacade.spec.ts +++ b/packages/sdk/src/tools/facades/BaseToolFacade.spec.ts @@ -1,11 +1,33 @@ /* eslint-disable jsdoc/require-jsdoc,@typescript-eslint/no-magic-numbers */ import { describe, expect, it } from '@jest/globals'; -import type { BlockToolConstructor, BlockToolData } from '../../entities/index.js'; +import type { + BlockToolConstructor, + BlockToolData, + /* + * Everything below is asserted absent: under `ts-jest` a stale `@ts-expect-error` is + * itself a diagnostic, so each directive fails this suite while its name still exists. + * Only tool-kind names are enumerated — the model layer keeps its own per-block data + * vocabulary, renamed separately by `plugin-block-data`. + */ + // @ts-expect-error -- the `BlockTune` contract went with the tune tool kind + BlockTune, + // @ts-expect-error -- the `BlockTuneConstructor` contract went with the tune tool kind + BlockTuneConstructor, + // @ts-expect-error -- the `BlockTuneConstructorOptions` contract went with the tune tool kind + BlockTuneConstructorOptions, + // @ts-expect-error -- the `BlockTuneOptions` contract went with the tune tool kind + BlockTuneOptions, + // @ts-expect-error -- the `BlockTuneData` contract went with the tune tool kind + BlockTuneData +} from '../../entities/index.js'; import { BlockToolOptionKey, ToolType } from '../../entities/index.js'; import type { ToolOptions } from './BaseToolFacade.js'; import { UserToolOptions } from './BaseToolFacade.js'; import { BlockToolFacade } from './BlockToolFacade.js'; +// @ts-expect-error -- the `BlockTuneFacade` class went with the tune tool kind +import type { BlockTuneFacade } from './index.js'; +import type { BaseToolFacade } from './BaseToolFacade.js'; import type { InlineFragment } from '@editorjs/model-types'; import { BlockChildType, NODE_TYPE_HIDDEN_PROP } from '@editorjs/model-types'; import type { EditorAPI } from '../../api'; @@ -507,3 +529,59 @@ describe('BaseToolFacade (via BlockToolFacade)', () => { }); }); }); + +describe('Tune tool kind removal', () => { + it('should no longer export the tune tool contracts', () => { + /** + * References the absent names so the import directives above are the assertion, + * rather than unused imports the linter would strip. + */ + type ToolContracts = { + tune: BlockTune; + constructor: BlockTuneConstructor; + constructorOptions: BlockTuneConstructorOptions; + options: BlockTuneOptions; + data: BlockTuneData; + facade: BlockTuneFacade; + }; + + const probe: ToolContracts | undefined = undefined; + + expect(probe).toBeUndefined(); + }); + + it('should no longer define a Tune member on ToolType', () => { + // @ts-expect-error -- `Tune` was removed from the ToolType enum + expect(ToolType.Tune).toBeUndefined(); + }); + + it('should no longer define a Tunes member on BlockToolOptionKey', () => { + /* + * `BlockToolOptions['tunes']` itself cannot be asserted: the interface carries an + * open `[key: string]: unknown` index signature for tool-author options, so every + * key resolves. The enum member is the removable surface. + */ + // @ts-expect-error -- `Tunes` was removed from the BlockToolOptionKey enum + expect(BlockToolOptionKey.Tunes).toBeUndefined(); + }); + + it('should no longer define an EnabledBlockTunes member on UserToolOptions', () => { + // @ts-expect-error -- `EnabledBlockTunes` was removed from the UserToolOptions enum + expect(UserToolOptions.EnabledBlockTunes).toBeUndefined(); + }); + + it('should no longer expose tune members on the facades', () => { + type FacadeMembers = { + // @ts-expect-error -- `isTune()` went with the tune tool kind + isTune: BaseToolFacade['isTune']; + // @ts-expect-error -- `enabledBlockTunes` went with the tune tool option + enabledBlockTunes: BlockToolFacade['enabledBlockTunes']; + // @ts-expect-error -- the per-tool `tunes` collection went with the tune tool kind + tunes: BlockToolFacade['tunes']; + }; + + const probe: FacadeMembers | undefined = undefined; + + expect(probe).toBeUndefined(); + }); +}); diff --git a/packages/sdk/src/tools/facades/BaseToolFacade.ts b/packages/sdk/src/tools/facades/BaseToolFacade.ts index 136ad777..0751c62e 100644 --- a/packages/sdk/src/tools/facades/BaseToolFacade.ts +++ b/packages/sdk/src/tools/facades/BaseToolFacade.ts @@ -5,17 +5,16 @@ import { isFunction } from '@editorjs/helpers'; import { type BlockToolFacade } from './BlockToolFacade.js'; import { type InlineToolFacade } from './InlineToolFacade.js'; import { ToolType, BaseToolOptionKey } from '../../entities/index.js'; -import { type BlockTuneFacade } from './BlockTuneFacade.js'; import type { - BlockTool, BlockToolConstructor, InlineTool, InlineToolConstructor, BlockTuneConstructor, - ToolTypeToOptions, ToolStaticOptions, BlockToolOptions, InlineToolOptions, BlockTuneOptions, + BlockTool, BlockToolConstructor, InlineTool, InlineToolConstructor, + ToolTypeToOptions, ToolStaticOptions, BlockToolOptions, InlineToolOptions, ToolOptionsFactory } from '../../entities/index.js'; import type { EditorAPI } from '../../api'; import type { ToolPluginOptions, ToolPluginOptionsMap } from '../../index.js'; // eslint-disable-next-line @typescript-eslint/no-explicit-any -- need to allow any type here so extended interfaces pass -export type ToolConstructable = BlockToolConstructor | InlineToolConstructor | BlockTuneConstructor; +export type ToolConstructable = BlockToolConstructor | InlineToolConstructor; // Re-export canonical option-key enums so facades/consumers can import from one place export { BaseToolOptionKey } from '../../entities/BaseTool.js'; @@ -31,8 +30,6 @@ export enum UserToolOptions { Toolbox = 'toolbox', /** Inline tools enabled for blocks of this type. */ EnabledInlineTools = 'inlineToolbar', - /** Block tunes enabled for blocks of this type. */ - EnabledBlockTunes = 'tunes', /** Plugin-specific configuration. */ Config = 'config' } @@ -40,7 +37,7 @@ export enum UserToolOptions { export type ToolOptions = ToolStaticOptions; // Re-export per-tool option types so consumers can import them from here -export type { BlockToolOptions, InlineToolOptions, BlockTuneOptions }; +export type { BlockToolOptions, InlineToolOptions }; /** * BlockToolFacade constructor options inteface @@ -122,7 +119,7 @@ export abstract class BaseToolFacade { */ public inlineTools: ToolsCollection = new ToolsCollection(); - /** - * BlockTune collection for current Block Tool - */ - public tunes: ToolsCollection = new ToolsCollection(); - /** * Tool's constructable blueprint — narrowed to BlockToolConstructor */ @@ -224,13 +218,6 @@ export class BlockToolFacade extends BaseToolFacade { return this.useToolOptions[UserToolOptions.EnabledInlineTools] ?? false; } - /** - * Returns enabled tunes for Tool - */ - public get enabledBlockTunes(): boolean | string[] { - return this.useToolOptions[UserToolOptions.EnabledBlockTunes] ?? false; - } - // /** // * Returns Tool paste configuration // */ @@ -239,7 +226,7 @@ export class BlockToolFacade extends BaseToolFacade { // } /** - * Returns sanitize configuration for Block Tool including configs from related Inline Tools and Block Tunes + * Returns sanitize configuration for Block Tool including configs from related Inline Tools */ // @cacheable // public get sanitizeConfig(): SanitizerConfig { diff --git a/packages/sdk/src/tools/facades/BlockTuneFacade.ts b/packages/sdk/src/tools/facades/BlockTuneFacade.ts deleted file mode 100644 index ff92ecca..00000000 --- a/packages/sdk/src/tools/facades/BlockTuneFacade.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { BaseToolFacade } from './BaseToolFacade.js'; -import type { BlockAPI } from 'editorjs-v2'; -import type { BlockTuneConstructor, BlockTune as IBlockTune, BlockTuneData } from '../../entities'; -import { ToolType } from '../../entities'; -// import type { BlockTuneData } from 'editorjs-v2'; - -/** - * Stub class for BlockTunes - * @todo Implement - */ -export class BlockTuneFacade extends BaseToolFacade { - /** - * Tool type — Tune - */ - public type: ToolType.Tune = ToolType.Tune; - - /** - * Tool's constructable blueprint - */ - protected declare constructable: BlockTuneConstructor; - - /** - * Constructs new BlockTune instance from constructable - * @param data - Tunes data - * @param _block - Block API object - */ - public create(data: BlockTuneData, _block: BlockAPI): IBlockTune { - return new this.constructable({ - // api: this.api, - config: this.config, - // block, - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - data, - }); - } -} diff --git a/packages/sdk/src/tools/facades/index.ts b/packages/sdk/src/tools/facades/index.ts index d7c388cc..8ad5034c 100644 --- a/packages/sdk/src/tools/facades/index.ts +++ b/packages/sdk/src/tools/facades/index.ts @@ -1,10 +1,8 @@ import type { BlockToolFacade } from './BlockToolFacade.js'; import type { InlineToolFacade } from './InlineToolFacade.js'; -import type { BlockTuneFacade } from './BlockTuneFacade.js'; -export type ToolFacadeClass = BlockToolFacade | InlineToolFacade | BlockTuneFacade; +export type ToolFacadeClass = BlockToolFacade | InlineToolFacade; export * from './BaseToolFacade.js'; export * from './BlockToolFacade.js'; -export * from './BlockTuneFacade.js'; export * from './InlineToolFacade.js'; From 111c671405889e0d07ecbe23e4227f94e7edecb4 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 26 Sep 2026 01:22:02 +0100 Subject: [PATCH 23/29] docs: drop the Block Tune tool kind `docs/plugins.md` loses the registration-table row and gains a line pointing a would-be tune author at the block settings menu and per-block plugin data instead; `docs/README.md` and the plugin-lifecycle diagram drop their `BlockTune` / `ToolType.Tune` / `blockTunes` mentions. Two live specs are hand-edited because the mechanical archive fold only rewrites `### Requirement:` blocks: the `sdk` **Purpose** preamble, and the `shortcuts-plugin` reserved-work note, which now reserves shortcuts for block settings items rather than for block tunes. Co-Authored-By: Claude Opus 5 --- docs/README.md | 2 +- docs/diagrams/plugin-lifecycle-flow.mmd | 6 ++--- docs/plugins.md | 6 +++-- openspec/changes/remove-block-tunes/tasks.md | 26 ++++++++++---------- 4 files changed, 21 insertions(+), 19 deletions(-) diff --git a/docs/README.md b/docs/README.md index 8fb98390..d93f3855 100644 --- a/docs/README.md +++ b/docs/README.md @@ -61,7 +61,7 @@ The system stays decoupled because each step communicates through interfaces and - `EditorjsPlugin`: general UI/behavior plugin registered via `core.use()` with `PluginType.Plugin`. UI components like `BlocksUI` typically declare a `static type` from `UiComponentType` but are bound to `PluginType.Plugin` internally. - `UiComponentType`: reserved string keys for UI component slots (`shell`, `blocks`, `inline-toolbar`, `toolbox`, `toolbar`). These name components in the UI layer but are **not** used as arguments to `core.use()` — plugins are registered by `PluginType` or `ToolType` values. -- `BlockTool` / `InlineTool` / `BlockTune`: tool contracts registered via `core.use(ToolConstructor, options)` during setup. The `tools` config field provides tool settings that `ToolsManager` applies during `initialize()`. +- `BlockTool` / `InlineTool`: tool contracts registered via `core.use(ToolConstructor, options)` during setup. The `tools` config field provides tool settings that `ToolsManager` applies during `initialize()`. - `Index`: serializable location in the document tree, independent of DOM nodes. Subclasses (e.g. `BlockIndex`, `TextIndex`, `DataIndex`) cover distinct target types. Built with immutable factory methods like `Index.block()` or `Index.text()`; serialized to a compact JSON string for caret storage and OT operations. - `DataKey`: branded string identifying a data slot inside a `BlockNode` (e.g. `"text"`, `"caption"`). Created via `createDataKey()`. - `BatchedOperation`: groups rapid single-character inserts or deletes on the same data key into one logical edit for undo/redo. Lives in `@editorjs/collaboration-manager`. diff --git a/docs/diagrams/plugin-lifecycle-flow.mmd b/docs/diagrams/plugin-lifecycle-flow.mmd index 7c9d9250..09562ec3 100644 --- a/docs/diagrams/plugin-lifecycle-flow.mmd +++ b/docs/diagrams/plugin-lifecycle-flow.mmd @@ -31,7 +31,7 @@ sequenceDiagram Core->>Plugins: bind PluginType.Plugin = SomePlugin Dev->>Core: use(SomeTool, settings) - Core->>Plugins: bind ToolType.Block / Inline / Tune = [SomeTool, settings] + Core->>Plugins: bind ToolType.Block / Inline = [SomeTool, settings] %% ── await initialize() ─────────────────────────── Dev->>Core: await initialize() @@ -47,9 +47,9 @@ sequenceDiagram Core->>CollabMgr: new CollaborationManager(config, api, eventBus) CollabMgr->>EventBus: wire event listeners - Core->>Plugins: getAll(ToolType.Block / Inline / Tune) + Core->>Plugins: getAll(ToolType.Block / Inline) Plugins-->>Core: [[SomeTool, settings], ...] - Core->>ToolsManager: prepareTools(blockTools, inlineTools, blockTunes) + Core->>ToolsManager: prepareTools(blockTools, inlineTools) loop for each tool ToolsManager->>Tool: Tool.prepare({ toolName, config }) ToolsManager->>ToolsManager: wrap in BlockToolFacade or InlineToolFacade diff --git a/docs/plugins.md b/docs/plugins.md index 30722b3b..cce3fb35 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -2,7 +2,7 @@ ## Package boundary -Tools and plugins should only depend on `@editorjs/sdk` — never on `@editorjs/model` or `@editorjs/model-types` directly. `sdk` re-exports every type a tool/plugin author needs (`Index`, event classes, `BlockTool`/`InlineTool`/`BlockTune` contracts, etc.); `model` is the engine implementation that `core` and `ot-server` orchestrate, and `model-types` is an internal foundation shared only by `model` and `sdk`. Neither is part of the stable, tool-facing API. +Tools and plugins should only depend on `@editorjs/sdk` — never on `@editorjs/model` or `@editorjs/model-types` directly. `sdk` re-exports every type a tool/plugin author needs (`Index`, event classes, `BlockTool`/`InlineTool` contracts, etc.); `model` is the engine implementation that `core` and `ot-server` orchestrate, and `model-types` is an internal foundation shared only by `model` and `sdk`. Neither is part of the stable, tool-facing API. ## Registration @@ -26,7 +26,9 @@ Tools are registered via `core.use(ToolConstructor, options)` during setup. The | UI Plugin | `EditorjsPlugin` | UI component/behavior registered via `core.use(...)` | | Block Tool | `BlockTool` (from config `tools`) | Block rendering and block-specific behavior | | Inline Tool | `InlineTool` (from config `tools`) | Selection formatting actions | -| Block Tune | `BlockTune` (from config `tools`) | Per-block tune behavior | + +There is no Block Tune tool kind. What v2 called a tune is a UI plugin: it puts an item in the +block settings menu and stores its state as [per-block plugin data](#per-block-plugin-data). ## Initialization sequence diff --git a/openspec/changes/remove-block-tunes/tasks.md b/openspec/changes/remove-block-tunes/tasks.md index b79330e8..f03b295c 100644 --- a/openspec/changes/remove-block-tunes/tasks.md +++ b/openspec/changes/remove-block-tunes/tasks.md @@ -1,26 +1,26 @@ ## 1. Guard the removal with tests -- [ ] 1.1 Add type-level assertions (`@ts-expect-error`) that these no longer exist: `ToolType.Tune`, the `BlockTune*` entity exports, `BlockTuneFacade`, `BlockToolOptionKey.Tunes`, `BlockToolOptions['tunes']`, `UserToolOptions.EnabledBlockTunes` and `BlockToolFacade#enabledBlockTunes`. Enumerate tool-kind names only — the model-layer `BlockTuneName`/`BlockTuneSerialized` re-exports belong to `plugin-block-data` -- [ ] 1.2 Write a failing `ToolsCollection` spec case: the collection should expose only `blockTools`/`inlineTools`. Also write a `Core`/`ToolsManager` case: a plugin that contributes block settings items should be instantiated as a plugin and absent from the tool collections +- [x] 1.1 Add type-level assertions (`@ts-expect-error`) that these no longer exist: `ToolType.Tune`, the `BlockTune*` entity exports, `BlockTuneFacade`, `BlockToolOptionKey.Tunes`, `BlockToolOptions['tunes']`, `UserToolOptions.EnabledBlockTunes` and `BlockToolFacade#enabledBlockTunes`. Enumerate tool-kind names only — the model-layer `BlockTuneName`/`BlockTuneSerialized` re-exports belong to `plugin-block-data` +- [x] 1.2 Write a failing `ToolsCollection` spec case: the collection should expose only `blockTools`/`inlineTools`. Also write a `Core`/`ToolsManager` case: a plugin that contributes block settings items should be instantiated as a plugin and absent from the tool collections ## 2. Remove from SDK -- [ ] 2.1 Delete `sdk/src/entities/BlockTune.ts` and `sdk/src/tools/facades/BlockTuneFacade.ts` (with its spec), and remove their exports -- [ ] 2.2 Remove `ToolType.Tune`, `BaseToolFacade#isTune()` and `ToolsCollection#blockTunes` (its only consumer) -- [ ] 2.3 Remove `BlockTuneConstructor` from `ToolConstructable`, `BlockTuneFacade` from `ToolFacadeClass` (and its export), `ToolTypeToOptions[ToolType.Tune]`, the `ToolStaticOptions` member, the `BlockTuneOptions` re-exports in `BaseTool.ts`/`BaseToolFacade.ts`, and the `./BlockTune.js` line in the entities barrel -- [ ] 2.4 Remove `BlockToolOptionKey.Tunes` and its `BlockToolOptions` member, `UserToolOptions.EnabledBlockTunes`, `BlockToolFacade#enabledBlockTunes` and `BlockToolFacade#tunes` +- [x] 2.1 Delete `sdk/src/entities/BlockTune.ts` and `sdk/src/tools/facades/BlockTuneFacade.ts` (it had no spec), and remove their exports +- [x] 2.2 Remove `ToolType.Tune`, `BaseToolFacade#isTune()` and `ToolsCollection#blockTunes` (its only consumer) +- [x] 2.3 Remove `BlockTuneConstructor` from `ToolConstructable`, `BlockTuneFacade` from `ToolFacadeClass` (and its export), `ToolTypeToOptions[ToolType.Tune]`, the `ToolStaticOptions` member, the `BlockTuneOptions` re-exports in `BaseTool.ts`/`BaseToolFacade.ts`, and the `./BlockTune.js` line in the entities barrel +- [x] 2.4 Remove `BlockToolOptionKey.Tunes` and its `BlockToolOptions` member, `UserToolOptions.EnabledBlockTunes`, `BlockToolFacade#enabledBlockTunes` and `BlockToolFacade#tunes` ## 3. Remove from Core and dependents -- [ ] 3.1 Remove the Tune branch from `Core#use`, the `getAll(ToolType.Tune)` step in tool preparation, the Tune case in `ToolsFactory`, and `ToolsManager#blockTunes` -- [ ] 3.2 Remove `#processBlockTune` and the `BlockTuneFacade` import from `packages/plugins/shortcuts-plugin/src/index.ts` -- [ ] 3.3 Grep the workspace for the removed tool-kind symbols (not the bare word `tunes`, which the model layer still uses until `plugin-block-data` lands), fix any leftovers, and confirm `yarn build` is clean +- [x] 3.1 Remove the Tune branch from `Core#use`, the `getAll(ToolType.Tune)` step in tool preparation, the Tune case in `ToolsFactory`, and `ToolsManager#blockTunes` +- [x] 3.2 Remove `#processBlockTune` and the `BlockTuneFacade` import from `packages/plugins/shortcuts-plugin/src/index.ts` +- [x] 3.3 Grep the workspace for the removed tool-kind symbols (not the bare word `tunes`, which the model layer still uses until `plugin-block-data` lands), fix any leftovers, and confirm `yarn build` is clean ## 4. Docs and wrap-up -- [ ] 4.1 Update `docs/plugins.md` (the "Block Tune" table row and the SDK re-export list on line 5), `docs/README.md` (drop the `BlockTune` contract mention) and `docs/diagrams/plugin-lifecycle-flow.mmd` (drop the `ToolType.Tune` binding and `blockTunes`) -- [ ] 4.2 Hand-edit the **Purpose** preamble of `openspec/specs/sdk/spec.md` to drop "block tunes" — the mechanical archive fold only rewrites `### Requirement:` blocks -- [ ] 4.3 Change the `shortcuts-plugin` spec's reserved-work note from "block tunes" to "block settings items" -- [ ] 4.4 Run `yarn lint` and `yarn test`. Fix any regressions +- [x] 4.1 Update `docs/plugins.md` (the "Block Tune" table row and the SDK re-export list on line 5), `docs/README.md` (drop the `BlockTune` contract mention) and `docs/diagrams/plugin-lifecycle-flow.mmd` (drop the `ToolType.Tune` binding and `blockTunes`) +- [x] 4.2 Hand-edit the **Purpose** preamble of `openspec/specs/sdk/spec.md` to drop "block tunes" — the mechanical archive fold only rewrites `### Requirement:` blocks +- [x] 4.3 Change the `shortcuts-plugin` spec's reserved-work note from "block tunes" to "block settings items" +- [x] 4.4 Run `yarn lint` and `yarn test`. Fix any regressions - [ ] 4.5 Comment on PR #157 linking `plugin-block-data`, `block-settings-ui` and `remove-block-tunes` as its replacement - [ ] 4.6 Run `openspec validate remove-block-tunes --type change` and confirm it passes From 56a3f4ecd4086f8a75d43b46cbc49893d24b4605 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 26 Sep 2026 01:27:13 +0100 Subject: [PATCH 24/29] test(core): cover the tool routing the tune case was removed from `ToolsFactory#getConstructor` had no coverage at all, so the switch this branch removed the Tune case from was unguarded: a mutant collapsing the remaining Inline case survived. The new spec pins both remaining kinds to their facades, along with the `defaultBlock` flag, the options handed to the facade, and the unregistered-tool error. `ToolsFactory.ts` now scores 100 on mutation testing, up from 40. Co-Authored-By: Claude Opus 5 --- packages/core/src/tools/ToolsFactory.spec.ts | 66 ++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 packages/core/src/tools/ToolsFactory.spec.ts diff --git a/packages/core/src/tools/ToolsFactory.spec.ts b/packages/core/src/tools/ToolsFactory.spec.ts new file mode 100644 index 00000000..4dd3672a --- /dev/null +++ b/packages/core/src/tools/ToolsFactory.spec.ts @@ -0,0 +1,66 @@ +/* eslint-disable jsdoc/require-jsdoc -- inline test stubs */ +import { describe, it, expect } from '@jest/globals'; +import type { EditorAPI, ToolConstructable, ToolStaticOptions } from '@editorjs/sdk'; +import { BlockToolFacade, InlineToolFacade, ToolType } from '@editorjs/sdk'; +import type { EditorConfig } from 'editorjs-v2'; +import { ToolsFactory } from './ToolsFactory.js'; + +class StubBlockTool { + public static type = ToolType.Block as const; + public static name = 'paragraph'; +} + +class StubInlineTool { + public static type = ToolType.Inline as const; + public static name = 'bold'; +} + +/** + * Builds a factory holding both stub tools, optionally registering the block tool + * with `use()`-time options. The factory only reads `defaultBlock` + * and `placeholder` off the editor config, so a partial object stands in for it, + * and `get()` never instantiates a tool — so the stubs implement no tool methods + * and are cast to satisfy the registration signature. + * @param blockToolSettings - second argument of `use()` for the block tool + */ +function createFactory(blockToolSettings?: ToolStaticOptions): ToolsFactory { + const factory = new ToolsFactory( + {}, + { defaultBlock: 'paragraph' } as EditorConfig, + {} as EditorAPI + ); + + factory.setTools([ + [StubBlockTool as unknown as ToolConstructable, blockToolSettings], + [StubInlineTool as unknown as ToolConstructable, undefined], + ]); + + return factory; +} + +describe('ToolsFactory', () => { + describe('.get()', () => { + it('should wrap a block tool in a BlockToolFacade', () => { + expect(createFactory().get('paragraph')).toBeInstanceOf(BlockToolFacade); + }); + + it('should wrap an inline tool in an InlineToolFacade', () => { + expect(createFactory().get('bold')).toBeInstanceOf(InlineToolFacade); + }); + + it('should mark the configured defaultBlock tool as default', () => { + expect(createFactory().get('paragraph').isDefault).toBe(true); + expect(createFactory().get('bold').isDefault).toBe(false); + }); + + it('should hand the registration options to the facade it builds', () => { + const factory = createFactory({ config: { placeholder: 'Type here' } }); + + expect(factory.get('paragraph').config).toEqual({ placeholder: 'Type here' }); + }); + + it('should throw naming a tool that was never registered', () => { + expect(() => createFactory().get('header')).toThrow('Tool header is not registered'); + }); + }); +}); From f484edd9f4a52ab79333bf5ac8d5a691d2bffe2a Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 26 Sep 2026 01:27:51 +0100 Subject: [PATCH 25/29] docs(openspec): check off the implemented remove-block-tunes tasks Task 4.5 stays open: closing PR #157 with links to its three replacement changes is a public comment, so it waits for the maintainer. Co-Authored-By: Claude Opus 5 --- openspec/changes/remove-block-tunes/tasks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openspec/changes/remove-block-tunes/tasks.md b/openspec/changes/remove-block-tunes/tasks.md index f03b295c..91b43ceb 100644 --- a/openspec/changes/remove-block-tunes/tasks.md +++ b/openspec/changes/remove-block-tunes/tasks.md @@ -23,4 +23,4 @@ - [x] 4.3 Change the `shortcuts-plugin` spec's reserved-work note from "block tunes" to "block settings items" - [x] 4.4 Run `yarn lint` and `yarn test`. Fix any regressions - [ ] 4.5 Comment on PR #157 linking `plugin-block-data`, `block-settings-ui` and `remove-block-tunes` as its replacement -- [ ] 4.6 Run `openspec validate remove-block-tunes --type change` and confirm it passes +- [x] 4.6 Run `openspec validate remove-block-tunes --type change` and confirm it passes From e2760fac79680cc6c3df31d9bbedb83ada336c8f Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 10 Oct 2026 01:00:42 +0100 Subject: [PATCH 26/29] docs(sdk): stop MenuConfig describing a contract that no longer exists `MenuConfig` still advertised itself as the shape for "Block Tune's render()", the last reference in shipped source to the tool kind this change removes. Co-Authored-By: Claude Opus 5 --- packages/sdk/src/entities/MenuConfig.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/sdk/src/entities/MenuConfig.ts b/packages/sdk/src/entities/MenuConfig.ts index db7ea4a2..be487a4c 100644 --- a/packages/sdk/src/entities/MenuConfig.ts +++ b/packages/sdk/src/entities/MenuConfig.ts @@ -11,7 +11,7 @@ export { PopoverItemType }; /** * Menu configuration format. - * Is used for defining Block Tunes Menu items via Block Tool's renderSettings(), Block Tune's render() and Inline Tool's render(). + * Is used for defining menu items via Block Tool's renderSettings() and Inline Tool's render(). */ export type MenuConfig = MenuConfigItem | MenuConfigItem[]; From 3d3b0781d52993a3bfd0327916f665b0f9a973f9 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sun, 8 Nov 2026 16:08:13 +0000 Subject: [PATCH 27/29] chore(openspec): archive plugin-block-data Archive the change implemented in #192 and sync its delta specs into the main specs. Restore the original title of the sdk "Plugin package augments both maps" scenario in the delta so the archive does not read the rename as a dropped scenario, and fill the Purpose of the new plugin-block-data spec from the proposal. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TffpCm82NH5xXR1yeBew6Q --- .../.openspec.yaml | 0 .../2026-11-08-plugin-block-data}/design.md | 0 .../2026-11-08-plugin-block-data}/proposal.md | 0 .../specs/collaboration-manager/spec.md | 0 .../specs/core/spec.md | 0 .../specs/model-types/spec.md | 0 .../specs/model/spec.md | 0 .../specs/plugin-block-data/spec.md | 0 .../specs/sdk/spec.md | 2 +- .../2026-11-08-plugin-block-data}/tasks.md | 2 +- openspec/specs/collaboration-manager/spec.md | 66 +++++- openspec/specs/core/spec.md | 30 ++- openspec/specs/model-types/spec.md | 39 ++-- openspec/specs/model/spec.md | 45 +++- openspec/specs/plugin-block-data/spec.md | 195 ++++++++++++++++++ openspec/specs/sdk/spec.md | 20 +- 16 files changed, 364 insertions(+), 35 deletions(-) rename openspec/changes/{plugin-block-data => archive/2026-11-08-plugin-block-data}/.openspec.yaml (100%) rename openspec/changes/{plugin-block-data => archive/2026-11-08-plugin-block-data}/design.md (100%) rename openspec/changes/{plugin-block-data => archive/2026-11-08-plugin-block-data}/proposal.md (100%) rename openspec/changes/{plugin-block-data => archive/2026-11-08-plugin-block-data}/specs/collaboration-manager/spec.md (100%) rename openspec/changes/{plugin-block-data => archive/2026-11-08-plugin-block-data}/specs/core/spec.md (100%) rename openspec/changes/{plugin-block-data => archive/2026-11-08-plugin-block-data}/specs/model-types/spec.md (100%) rename openspec/changes/{plugin-block-data => archive/2026-11-08-plugin-block-data}/specs/model/spec.md (100%) rename openspec/changes/{plugin-block-data => archive/2026-11-08-plugin-block-data}/specs/plugin-block-data/spec.md (100%) rename openspec/changes/{plugin-block-data => archive/2026-11-08-plugin-block-data}/specs/sdk/spec.md (97%) rename openspec/changes/{plugin-block-data => archive/2026-11-08-plugin-block-data}/tasks.md (99%) create mode 100644 openspec/specs/plugin-block-data/spec.md diff --git a/openspec/changes/plugin-block-data/.openspec.yaml b/openspec/changes/archive/2026-11-08-plugin-block-data/.openspec.yaml similarity index 100% rename from openspec/changes/plugin-block-data/.openspec.yaml rename to openspec/changes/archive/2026-11-08-plugin-block-data/.openspec.yaml diff --git a/openspec/changes/plugin-block-data/design.md b/openspec/changes/archive/2026-11-08-plugin-block-data/design.md similarity index 100% rename from openspec/changes/plugin-block-data/design.md rename to openspec/changes/archive/2026-11-08-plugin-block-data/design.md diff --git a/openspec/changes/plugin-block-data/proposal.md b/openspec/changes/archive/2026-11-08-plugin-block-data/proposal.md similarity index 100% rename from openspec/changes/plugin-block-data/proposal.md rename to openspec/changes/archive/2026-11-08-plugin-block-data/proposal.md diff --git a/openspec/changes/plugin-block-data/specs/collaboration-manager/spec.md b/openspec/changes/archive/2026-11-08-plugin-block-data/specs/collaboration-manager/spec.md similarity index 100% rename from openspec/changes/plugin-block-data/specs/collaboration-manager/spec.md rename to openspec/changes/archive/2026-11-08-plugin-block-data/specs/collaboration-manager/spec.md diff --git a/openspec/changes/plugin-block-data/specs/core/spec.md b/openspec/changes/archive/2026-11-08-plugin-block-data/specs/core/spec.md similarity index 100% rename from openspec/changes/plugin-block-data/specs/core/spec.md rename to openspec/changes/archive/2026-11-08-plugin-block-data/specs/core/spec.md diff --git a/openspec/changes/plugin-block-data/specs/model-types/spec.md b/openspec/changes/archive/2026-11-08-plugin-block-data/specs/model-types/spec.md similarity index 100% rename from openspec/changes/plugin-block-data/specs/model-types/spec.md rename to openspec/changes/archive/2026-11-08-plugin-block-data/specs/model-types/spec.md diff --git a/openspec/changes/plugin-block-data/specs/model/spec.md b/openspec/changes/archive/2026-11-08-plugin-block-data/specs/model/spec.md similarity index 100% rename from openspec/changes/plugin-block-data/specs/model/spec.md rename to openspec/changes/archive/2026-11-08-plugin-block-data/specs/model/spec.md diff --git a/openspec/changes/plugin-block-data/specs/plugin-block-data/spec.md b/openspec/changes/archive/2026-11-08-plugin-block-data/specs/plugin-block-data/spec.md similarity index 100% rename from openspec/changes/plugin-block-data/specs/plugin-block-data/spec.md rename to openspec/changes/archive/2026-11-08-plugin-block-data/specs/plugin-block-data/spec.md diff --git a/openspec/changes/plugin-block-data/specs/sdk/spec.md b/openspec/changes/archive/2026-11-08-plugin-block-data/specs/sdk/spec.md similarity index 97% rename from openspec/changes/plugin-block-data/specs/sdk/spec.md rename to openspec/changes/archive/2026-11-08-plugin-block-data/specs/sdk/spec.md index 24cf06d8..897e4172 100644 --- a/openspec/changes/plugin-block-data/specs/sdk/spec.md +++ b/openspec/changes/archive/2026-11-08-plugin-block-data/specs/sdk/spec.md @@ -3,7 +3,7 @@ ### Requirement: Augmentable plugin type maps The system SHALL declare three empty, augmentable interfaces — `EditorjsPluginApiMap` (plugin id → public API type), `ToolPluginOptionsMap` (plugin id → tool-directed options type), and `EditorjsPluginDataMap` (plugin id → the shape of the per-block data that plugin stores) — that plugin packages extend via module augmentation of `@editorjs/sdk`. `PluginId` SHALL include the keys of all three maps. `BlocksAPI.getPluginData`/`updatePluginData` SHALL resolve their data type from `EditorjsPluginDataMap` for a declared id, and SHALL fall back to `Record` for an id absent from it, using a non-distributive conditional so the `string & {}` member of `PluginId` does not widen a declared id's type. -#### Scenario: Plugin package augments the api and options maps +#### Scenario: Plugin package augments both maps - **GIVEN** a plugin package declares `declare module '@editorjs/sdk'` augmenting `EditorjsPluginApiMap` and `ToolPluginOptionsMap` under its `name` - **WHEN** a consumer's compilation includes that package's types - **THEN** `api.plugins.` and `options.plugins.` are both fully typed with no cast diff --git a/openspec/changes/plugin-block-data/tasks.md b/openspec/changes/archive/2026-11-08-plugin-block-data/tasks.md similarity index 99% rename from openspec/changes/plugin-block-data/tasks.md rename to openspec/changes/archive/2026-11-08-plugin-block-data/tasks.md index f13451db..6627a5b9 100644 --- a/openspec/changes/plugin-block-data/tasks.md +++ b/openspec/changes/archive/2026-11-08-plugin-block-data/tasks.md @@ -51,7 +51,7 @@ - [x] 6.1 Update `docs/model.md`, `docs/index-serialization.md` and `docs/events.md` for `PluginDataNode`, `PluginDataIndex` and `PluginDataModifiedEvent`, plus `docs/plugins.md` (the SDK declares **three** augmentable interfaces now) and `.github/agents/docs-updater.agent.md` (its `BlockTune` → `docs/model.md` mapping) - [x] 6.2 Update the diagrams `model-tree-structure.mmd`, `events-catalog.mmd` and `architecture-overview.mmd` - [x] 6.3 Run `yarn lint`, `yarn test`, and the mutation tests for the touched packages that have them. Fix any regressions -- [ ] 6.4 Run `openspec validate plugin-block-data --type change` and confirm it passes. After archiving, fill the `## Purpose` of the new `plugin-block-data` spec from the proposal's intended-Purpose text +- [x] 6.4 Run `openspec validate plugin-block-data --type change` and confirm it passes. After archiving, fill the `## Purpose` of the new `plugin-block-data` spec from the proposal's intended-Purpose text ## 7. Review follow-ups diff --git a/openspec/specs/collaboration-manager/spec.md b/openspec/specs/collaboration-manager/spec.md index ef7e19ac..8a5c9dd7 100644 --- a/openspec/specs/collaboration-manager/spec.md +++ b/openspec/specs/collaboration-manager/spec.md @@ -3,9 +3,7 @@ ## Purpose `@editorjs/collaboration-manager` is a core plugin that listens to document model events, converts them into operational-transformation (OT) `Operation`s, batches rapid local edits for undo/redo, maintains local undo/redo stacks transformed against remote edits, and optionally syncs with a remote OT server over WebSocket using a handshake + serialized-ack protocol. - ## Requirements - ### Requirement: Operation model The system SHALL represent every document mutation as an `Operation` (Insert/Delete/Modify/Neutral) supporting `inverse()`, `transform()` against another operation, `serialize()`, and `getEffectiveRange()`. @@ -105,3 +103,67 @@ The system SHALL classify how two text ranges relate (None/Left/Right/Includes/I - **THEN** it returns one of `None`, `Left`, `Right`, `Includes`, or `IncludedBy` describing how the ranges overlap Implemented in `src/utils/getRangesIntersectionType.ts`. + +### Requirement: Plugin data operations +`CollaborationManager` SHALL translate a `PluginDataModifiedEvent` into a `Modify` `Operation` on its `PluginDataIndex`, with `payload` set to the new value and `prevPayload` to the previous value. `OperationsTransformer` SHALL shift a plugin data operation's block index against block insertions and removals the same way it does for data index operations, SHALL turn it into a `Neutral` operation when its block is removed, and SHALL resolve two concurrent writes to the same block, plugin and key the same way it resolves two concurrent writes to the same data key: the operation being transformed becomes `Neutral` when the operation it is transformed against is the later of the two, a local operation the server has not acknowledged counting as later than any revision. A local operation SHALL count as unacknowledged for the whole round trip, not merely until it leaves for the server, so the client SHALL keep it among the operations an incoming one is transformed against until its acknowledgement arrives. The acknowledgement is what establishes the server's order: while it is outstanding, every remote operation the server delivers was ordered before the local one, and once it arrives, everything after it was ordered later. Writes to different blocks, different plugins or different keys SHALL be left untransformed, since one cannot shift another's position. An operation carrying no revision of its own SHALL lose to whatever it is transformed against. Such an operation comes from an undo or redo stack, whose entries are built from model events and are never numbered, while an operation from the server always is; and the operation it is transformed against has already been applied to the document. Keeping it would leave an undo step that writes a value the document has moved on from, and whose recorded previous value is older still, so undoing a local write that a collaborator had overwritten would delete the collaborator's value. Transformation SHALL also accept a plugin data operation as the operation being transformed *against*, rather than rejecting its index kind. The `Modify` operation payload type SHALL admit any JSON value, including primitives. + +#### Scenario: Local plugin data change becomes an operation +- **GIVEN** the local user changes `anchors.visible` on block 1 from `true` to `false` +- **WHEN** `CollaborationManager` handles the resulting event +- **THEN** it sends a `Modify` operation on `Index.pluginData(1, 'anchors', 'visible')` with `payload` `false` and `prevPayload` `true`, rather than logging an unknown event + +#### Scenario: Inverting a plugin data operation +- **GIVEN** a plugin data `Modify` operation with `payload` `false` and `prevPayload` `true` +- **WHEN** `inverse()` is called +- **THEN** it returns a `Modify` operation on the same index with `payload` `true` and `prevPayload` `false` + +#### Scenario: Transforming against a block insertion +- **GIVEN** a plugin data operation on block 2 and a concurrent block insertion at index 0 +- **WHEN** the plugin data operation is transformed against the insertion +- **THEN** its index targets block 3 + +#### Scenario: A plugin data operation as the against-operation +- **GIVEN** any pending or stacked operation and a plugin data `Modify` operation to transform it against +- **WHEN** the transformation runs — as it does for pending operations on the client, for the undo/redo stacks on every remote plugin data event, and for conflicting operations on the server +- **THEN** it completes and returns an operation, rather than throwing an unsupported-index error + +#### Scenario: A scalar payload +- **GIVEN** a plugin data change whose value is a boolean +- **WHEN** the operation is constructed +- **THEN** the payload type admits it, so scalar plugin data is representable in an operation + +#### Scenario: Transforming against removal of its block +- **GIVEN** a plugin data operation on block 2 and a concurrent removal of block 2 +- **WHEN** the plugin data operation is transformed against the removal +- **THEN** it becomes a `Neutral` operation + +#### Scenario: Two clients write the same key concurrently +- **GIVEN** clients A and B both write `anchors.visible` on block 1, and the server applies A before B +- **WHEN** B receives A's operation while its own write is still unacknowledged +- **THEN** A's operation is transformed to `Neutral` on B, so B keeps the value the server will end up holding rather than being left on A's + +#### Scenario: A collaborator writes while the local write is in flight +- **GIVEN** the local client has sent a write of `anchors.color` and is waiting for its acknowledgement +- **WHEN** a collaborator's write to the same key arrives before that acknowledgement +- **THEN** it is transformed to `Neutral` and not applied, since the server will apply the local write after it -- and a client's own operations are not echoed back to it, so nothing would restore the value the server ends up holding + +#### Scenario: A collaborator writes once the local write is acknowledged +- **GIVEN** the local client's write of `anchors.color` has been acknowledged +- **WHEN** a collaborator's write to the same key arrives +- **THEN** it is applied, because the server ordered it after the local write + +#### Scenario: Undoing a write a collaborator overwrote +- **GIVEN** the local user wrote `anchors.color` on block 0, and a collaborator then overwrote the same key +- **WHEN** the undo stack is transformed against the collaborator's operation +- **THEN** the entry is dropped, so undo reaches past it rather than writing a value that is gone and deleting the collaborator's + +#### Scenario: Undoing a write to a key nobody else touched +- **GIVEN** the local user wrote `anchors.color` and a collaborator wrote `anchors.label` on the same block +- **WHEN** the undo stack is transformed against the collaborator's operation +- **THEN** the entry survives, because the two do not describe the same value + +#### Scenario: Concurrent writes to different keys +- **GIVEN** a plugin data operation on `anchors.visible` and a concurrent one on `anchors.id` of the same block +- **WHEN** one is transformed against the other +- **THEN** it is returned unchanged, because the two do not describe the same value + diff --git a/openspec/specs/core/spec.md b/openspec/specs/core/spec.md index e30db5f9..ce7eb749 100644 --- a/openspec/specs/core/spec.md +++ b/openspec/specs/core/spec.md @@ -45,7 +45,7 @@ The system SHALL validate configured tools via `ToolsManager`, calling each tool Implemented in `src/tools/ToolsManager.ts`, `src/tools/ToolsFactory.ts`, validated by co-located `.spec.ts` files. ### Requirement: EditorAPI surface -The system SHALL expose an `EditorAPI` aggregating `BlocksAPI` (insert/insertMany/delete/move/render/clear/getBlocksCount), `SelectionAPI` (applyInlineTool, selectedBlocks), `DocumentAPI` (serialized data, onUpdate, insertData/removeData/modifyData, undo/redo), and `TextAPI` (insert/remove/format/unformat/getFragments/get) to tools, plugins, and adapters. +The system SHALL expose an `EditorAPI` aggregating `BlocksAPI` (insert/insertMany/delete/move/render/clear/getBlocksCount/getPluginData/updatePluginData), `SelectionAPI` (applyInlineTool, selectedBlocks), `DocumentAPI` (serialized data, onUpdate, insertData/removeData/modifyData, undo/redo), and `TextAPI` (insert/remove/format/unformat/getFragments/get) to tools, plugins, and adapters. #### Scenario: Deleting with no block selected - **GIVEN** no block is currently selected/no caret is set @@ -57,6 +57,11 @@ The system SHALL expose an `EditorAPI` aggregating `BlocksAPI` (insert/insertMan - **WHEN** the operation is attempted - **THEN** it throws an error identifying the missing key or tool +#### Scenario: Inserting a block with plugin data +- **GIVEN** `BlocksAPI.insert` is called with both `data` and `plugins: { anchors: { id: 'intro' } }` +- **WHEN** the block is added to the model +- **THEN** the serialized block carries both its tool data and that plugin data, each under its own key + Implemented in `src/api/index.ts`, `src/api/BlocksAPI.ts`, `src/api/SelectionAPI.ts`, `src/api/DocumentAPI/DocumentAPI.ts`, `src/api/TextAPI.ts`, `src/components/BlockManager.ts`, validated by co-located `.spec.ts`/`.integration.spec.ts` files. ### Requirement: Block rendering lifecycle @@ -136,3 +141,26 @@ Implemented in `src/components/UndoRedoManager.ts`, validated by its co-located - **WHEN** each plugin's `destroy()` runs - **THEN** its registry entry is removed so no stale public API remains reachable +### Requirement: v2 data conversion carries tune data into plugin data +`composeDataFromVersion2` SHALL map each v2 block's `tunes` map into the v3 block's `plugins` map, preserving each entry's key verbatim, so a v3 plugin that takes over a v2 tune's `name` finds its data. An entry whose v2 data is a plain object SHALL be copied key by key. An entry whose v2 data is a primitive or an array SHALL be stored under the single key `value`. A v2 block without `tunes`, or with an empty `tunes` map, SHALL produce no `plugins` entry. + +#### Scenario: Converting object tune data +- **GIVEN** a v2 block with `tunes: { anchors: { id: 'intro' } }` +- **WHEN** it is converted to v3 +- **THEN** the resulting block init carries `plugins: { anchors: { id: 'intro' } }` + +#### Scenario: Converting non-object tune data +- **GIVEN** a v2 block with `tunes: { alignment: 'left' }` +- **WHEN** it is converted +- **THEN** the resulting entry is `plugins: { alignment: { value: 'left' } }` + +#### Scenario: Block without tunes +- **GIVEN** a v2 block with no `tunes` key, or with `tunes: {}` +- **WHEN** it is converted +- **THEN** the resulting block init has no `plugins` key + +#### Scenario: Tune with no registered plugin +- **GIVEN** a v2 block carrying tune data whose name matches no plugin registered in this editor +- **WHEN** the document is converted and loaded +- **THEN** the entry is still present in the block's `plugins` and survives serialization, per the plugin data store's preservation rule + diff --git a/openspec/specs/model-types/spec.md b/openspec/specs/model-types/spec.md index 02d10f4e..265dff33 100644 --- a/openspec/specs/model-types/spec.md +++ b/openspec/specs/model-types/spec.md @@ -3,36 +3,39 @@ ## Purpose `@editorjs/model-types` provides the shared, dependency-free low-level types, nominal identifiers, event payload shapes, and base event classes used internally by `@editorjs/model` and `@editorjs/sdk`. It contains no editor runtime logic beyond the `Index` class hierarchy of location-pointer types, `keypath` object helpers, and block ID generation. It exists so `model` and `sdk` can share type definitions without depending on each other, and is not intended for direct use by other packages or tools. - ## Requirements - ### Requirement: Nominal identifier types -The system SHALL provide nominal (branded) types for `BlockId`, `BlockToolName`, `BlockTuneName`, `DataKey`, and `InlineToolName` so that structurally identical primitives (e.g. two different kinds of string IDs) are not interchangeable at the type level. +The system SHALL provide nominal (branded) types for `BlockId`, `BlockToolName`, `PluginDataName`, `DataKey`, and `InlineToolName` so that structurally identical primitives (e.g. two different kinds of string IDs) are not interchangeable at the type level. #### Scenario: Generating a block id - **GIVEN** a new block is being created - **WHEN** `generateBlockId()` is called - **THEN** it returns a 21-character URL-safe random `BlockId`, generated via `crypto.getRandomValues` -Implemented in `src/Nominal.ts`, `src/BlockId.ts`, `src/BlockTune.ts`, `src/DataKey.ts`, `src/InlineTool.ts`. +Implemented in `src/Nominal.ts`, `src/BlockId.ts`, `src/PluginData.ts`, `src/DataKey.ts`, `src/InlineTool.ts`. ### Requirement: Document and block serialization shapes -The system SHALL define the serialized shapes for blocks, text nodes, and documents (`BlockData`, `BlockNodeInit`, `BlockNodeSerialized`, `TextNodeSerialized`, `EditorDocumentSerialized`, `ChangeData`) so `model` and `sdk` agree on wire/storage format. +The system SHALL define the serialized shapes for blocks, text nodes, and documents (`BlockData`, `BlockNodeInit`, `BlockNodeSerialized`, `TextNodeSerialized`, `EditorDocumentSerialized`, `ChangeData`) so `model` and `sdk` agree on wire/storage format. A block's per-plugin data SHALL be carried under the optional `plugins` key as a record of `PluginDataSerialized` keyed by plugin data name. #### Scenario: Distinguishing child node types - **GIVEN** a block's data tree contains both plain values and text nodes - **WHEN** a data node is serialized - **THEN** it is tagged with the hidden discriminator property `$t` (`NODE_TYPE_HIDDEN_PROP`) set to a `BlockChildType` (`Value` or `Text`) so consumers can distinguish node kinds without inspecting shape -Implemented in `src/BlockNode.ts`, `src/Text.ts`, `src/Value.ts`, `src/EditorDocument.ts`, `src/ChangeData.ts`, `src/BlockChildType.ts`. +#### Scenario: Serializing plugin data +- **GIVEN** a block carrying data for plugin `anchors` +- **WHEN** it is serialized +- **THEN** the data appears under `plugins.anchors`, and no `tunes` key is produced + +Implemented in `src/BlockNode.ts`, `src/Text.ts`, `src/Value.ts`, `src/EditorDocument.ts`, `src/ChangeData.ts`, `src/BlockChildType.ts`, `src/PluginData.ts`. ### Requirement: Index — composite document location pointer -The system SHALL provide an abstract `IndexBase` class and one concrete subclass per pointer kind — `DocumentIndex`, `PropertyIndex`, `BlockIndex`, `TuneIndex`, `DataIndex`, `TextIndex` — each carrying only the fields structurally valid for that kind (e.g. `TuneIndex` always has `tuneName`+`tuneKey`, `PropertyIndex` never carries block-related fields), a `kind` discriminant (`IndexKind`) for narrowing, and immutable `with*` copy methods (`withBlockIndex`/`withTextRange`/`withDocumentId`) that return a new instance. The abstract `Index` class exposes static factory methods (`Index.document`/`property`/`block`/`tune`/`data`/`text`) and `Index.parse`, and overrides `Symbol.hasInstance` so `value instanceof Index` is true for any `IndexBase` instance even though concrete classes extend `IndexBase` directly. +The system SHALL provide an abstract `IndexBase` class and one concrete subclass per pointer kind — `DocumentIndex`, `PropertyIndex`, `BlockIndex`, `PluginDataIndex`, `DataIndex`, `TextIndex` — each carrying only the fields structurally valid for that kind (e.g. `PluginDataIndex` always has `pluginName`+`pluginKey`, `PropertyIndex` never carries block-related fields), a `kind` discriminant (`IndexKind`) for narrowing, and immutable `with*` copy methods (`withBlockIndex`/`withTextRange`/`withDocumentId`) that return a new instance. The abstract `Index` class exposes static factory methods (`Index.document`/`property`/`block`/`pluginData`/`data`/`text`) and `Index.parse`, and overrides `Symbol.hasInstance` so `value instanceof Index` is true for any `IndexBase` instance even though concrete classes extend `IndexBase` directly. #### Scenario: Constructing an index of a given kind - **GIVEN** a location needs to be pointed to - **WHEN** the corresponding `Index.*` factory (or a concrete class constructor) is called -- **THEN** it returns an instance of the matching subclass whose `kind` and fields are fixed by the constructor signature, so invalid field combinations (e.g. a tune name without a tune key, or a property name combined with a block index) cannot be constructed for that subclass +- **THEN** it returns an instance of the matching subclass whose `kind` and fields are fixed by the constructor signature, so invalid field combinations (e.g. a plugin name without a plugin key, or a property name combined with a block index) cannot be constructed for that subclass #### Scenario: Composite text selections - **GIVEN** a selection spans multiple disjoint text ranges (e.g. across blocks) @@ -42,21 +45,26 @@ The system SHALL provide an abstract `IndexBase` class and one concrete subclass #### Scenario: Parsing a serialized index - **GIVEN** a JSON string produced by `IndexBase#serialize()` - **WHEN** `Index.parse` is called -- **THEN** it parses the JSON and dispatches on its `k` discriminator field (`doc`/`prop`/`block`/`tune`/`data`/`text`/`composite`) to reconstruct the matching concrete instance, and throws if the value isn't a JSON object with a string `k` field or `k` is unrecognized +- **THEN** it parses the JSON and dispatches on its `k` discriminator field (`doc`/`prop`/`block`/`plugin`/`data`/`text`/`composite`) to reconstruct the matching concrete instance, and throws if the value isn't a JSON object with a string `k` field or `k` is unrecognized + +#### Scenario: Serializing a plugin data index +- **GIVEN** `Index.pluginData(1, 'anchors', 'id')` +- **WHEN** it is serialized +- **THEN** the result is `{"k":"plugin","b":1,"plugin":"anchors","key":"id"}`, and `Index.parse` of that string returns an equal `PluginDataIndex` #### Scenario: Resolving a partial index accumulated during event bubbling -- **GIVEN** a leaf node (text/value/tune) dispatches an event carrying only its locally-known fields as a `PartialIndex`, which parent nodes progressively complete via `withBlockIndex`/`withDocumentId` as the event bubbles up +- **GIVEN** a leaf node (text/value/plugin data) dispatches an event carrying only its locally-known fields as a `PartialIndex`, which parent nodes progressively complete via `withBlockIndex`/`withDocumentId` as the event bubbles up - **WHEN** `PartialIndex#resolve()` is called once all context has been attached -- **THEN** it returns the concrete `IndexBase` subclass matching the accumulated fields, throwing a specific error naming the missing/conflicting field (e.g. `TuneIndex requires tuneKey`, `DataIndex cannot be combined with tuneName`, `PropertyIndex cannot be combined with block-related fields`) when the fields don't resolve to a valid index; `PartialIndex` itself throws on `serialize()`, so it must always be resolved before leaving `model` +- **THEN** it returns the concrete `IndexBase` subclass matching the accumulated fields, throwing a specific error naming the missing/conflicting field (e.g. `PluginDataIndex requires pluginKey`, `DataIndex cannot be combined with pluginName`, `PropertyIndex cannot be combined with block-related fields`) when the fields don't resolve to a valid index; `PartialIndex` itself throws on `serialize()`, so it must always be resolved before leaving `model` -Implemented in `src/Index/IndexBase.ts`, `src/Index/index.ts` (factory/parse), `src/Index/DocumentIndex.ts`, `src/Index/PropertyIndex.ts`, `src/Index/BlockIndex.ts`, `src/Index/TuneIndex.ts`, `src/Index/DataIndex.ts`, `src/Index/TextIndex.ts`, `src/Index/PartialIndex.ts`, validated by `src/Index/Index.spec.ts`. +Implemented in `src/Index/IndexBase.ts`, `src/Index/index.ts` (factory/parse), `src/Index/DocumentIndex.ts`, `src/Index/PropertyIndex.ts`, `src/Index/BlockIndex.ts`, `src/Index/PluginDataIndex.ts`, `src/Index/DataIndex.ts`, `src/Index/TextIndex.ts`, `src/Index/PartialIndex.ts`, validated by `src/Index/Index.spec.ts`. ### Requirement: Base document event and event bus -The system SHALL provide a `BaseDocumentEvent` base class carrying `{ index, action, data, userId }` that fires under the `EventType.Changed` DOM event type, concrete event subclasses for each kind of document mutation (block/data/text add/remove/modify, tune/property modification), and a thin `EventBus` (`EventTarget` subclass) used to dispatch them. +The system SHALL provide a `BaseDocumentEvent` base class carrying `{ index, action, data, userId }` that fires under the `EventType.Changed` DOM event type, concrete event subclasses for each kind of document mutation (block/data/text add/remove/modify, plugin data/property modification), and a thin `EventBus` (`EventTarget` subclass) used to dispatch them. #### Scenario: Emitting a document mutation event -- **GIVEN** a block, text, or value node is added, removed, or modified -- **THEN** the corresponding concrete event (e.g. `DataNodeAddedEvent`, `TextFormattedEvent`, `BlockAddedEvent`, `PropertyModifiedEvent`, `TuneModifiedEvent`) is dispatched as `EventType.Changed`, carrying an `EventAction` (`Added`/`Removed`/`Modified`) and the affected `Index` +- **GIVEN** a block, text, value, or plugin data node is added, removed, or modified +- **THEN** the corresponding concrete event (e.g. `DataNodeAddedEvent`, `TextFormattedEvent`, `BlockAddedEvent`, `PropertyModifiedEvent`, `PluginDataModifiedEvent`) is dispatched as `EventType.Changed`, carrying an `EventAction` (`Added`/`Removed`/`Modified`) and the affected `Index` #### Scenario: Emitting a caret event - **GIVEN** a caret is added, removed, or updated @@ -73,3 +81,4 @@ The system SHALL provide generic dot-path object utilities (`get`, `set`, `has`, - **THEN** the corresponding nested value is read, written, checked, inserted, or removed, including array paths (e.g. `items.0.text`) Implemented in `src/keypath.ts`, validated by `src/keypath.spec.ts`. (Noted in `src/index.ts` as a candidate for extraction into a standalone `@editorjs/utils` package.) + diff --git a/openspec/specs/model/spec.md b/openspec/specs/model/spec.md index 22860e7f..d3e76279 100644 --- a/openspec/specs/model/spec.md +++ b/openspec/specs/model/spec.md @@ -48,7 +48,7 @@ The system SHALL provide `EditorDocument` as the root container of `BlockNode`s, - **THEN** the range is formatted with that `tool` and its `data`, so re-applying a data-carrying tool (e.g. redo or a remote op) keeps the fragment's data ### Requirement: BlockNode data tree -The system SHALL provide `BlockNode` representing a single block's data tree (nested value/text nodes, arrays, and objects) plus its `BlockTune`s, supporting creation/removal/lookup of data nodes, text insert/remove/format/unformat, tune/value updates, and text content extraction. +The system SHALL provide `BlockNode` representing a single block's data tree (nested value/text nodes, arrays, and objects) plus its per-plugin `PluginDataNode`s, supporting creation/removal/lookup of data nodes, text insert/remove/format/unformat, plugin-data/value updates, and text content extraction. Updating plugin data for a plugin name the block has no entry for SHALL create that entry rather than throw. #### Scenario: Creating a data node at an existing key - **GIVEN** a block already has a data node at a given key @@ -60,6 +60,16 @@ The system SHALL provide `BlockNode` representing a single block's data tree (ne - **WHEN** `createDataNode` targets an index within that array - **THEN** existing entries at or after that index are shifted rather than the operation erroring +#### Scenario: Updating plugin data for a new plugin name +- **GIVEN** a block with no plugin data entry named `anchors` +- **WHEN** `updatePluginData('anchors', { id: 'intro' })` is called +- **THEN** a `PluginDataNode` named `anchors` is created, its event listener is attached before any value is set, and a `PluginDataModifiedEvent` bubbles from the block with `previous` `undefined` + +#### Scenario: Plugin data events carry the acting user +- **GIVEN** a plugin data change made in a user context +- **WHEN** the event bubbles from the `PluginDataNode` through the `BlockNode` +- **THEN** its `userId` is taken from the active context, like value-node events, rather than a placeholder + Implemented in `src/entities/BlockNode/index.ts`, validated by its co-located `.spec.ts`. ### Requirement: Inline text tree @@ -97,16 +107,6 @@ The system SHALL provide `TextNode` (extending `ParentInlineNode`) as the inline Implemented in `src/entities/inline-fragments/ParentInlineNode/index.ts`, `src/entities/inline-fragments/FormattingInlineNode/index.ts`, `src/entities/inline-fragments/TextNode/index.ts`, validated by `src/entities/inline-fragments/TextNode/*.spec.ts`, `src/entities/inline-fragments/FormattingInlineNode/*.spec.ts`, and `src/entities/inline-fragments/specs/InlineTree.integration.spec.ts`. -### Requirement: Value nodes and block tunes -The system SHALL provide `ValueNode` for leaf non-text data storage and `BlockTune` for per-block tune data, both participating in the block's event-emitting data tree. - -#### Scenario: Modifying a value node -- **GIVEN** a `ValueNode` holding a leaf value within a block -- **WHEN** its value is updated -- **THEN** a `ValueModifiedEvent` is emitted carrying the previous and new value - -Implemented in `src/entities/ValueNode`, `src/entities/BlockTune`. - ### Requirement: Caret management The system SHALL provide `CaretManager` as a per-user-id registry of `Caret`s (create/get/update/remove, dispatching Added/Updated/Removed events) and `Caret` as a holder of a nullable `Index` whose `update()` dispatches a `CaretUpdatedEvent` and which serializes via `toJSON()`. @@ -127,3 +127,26 @@ The system SHALL provide an internal `ToolsRegistry` and IoC container for tool/ Implemented in `src/tools/ToolsRegistry.ts`, `src/IoC/`. +### Requirement: Value nodes and plugin data +The system SHALL provide `ValueNode` for leaf non-text data storage and `PluginDataNode` for per-block data owned by a plugin, both participating in the block's event-emitting data tree. A `PluginDataNode` SHALL hold a flat key/value record, SHALL emit one `PluginDataModifiedEvent` per changed key, and SHALL delete a key when it is set to `undefined`. + +#### Scenario: Modifying a value node +- **GIVEN** a `ValueNode` holding a leaf value within a block +- **WHEN** its value is updated +- **THEN** a `ValueModifiedEvent` is emitted carrying the previous and new value + +#### Scenario: Removing a plugin data key +- **GIVEN** a `PluginDataNode` holding `{ id: 'intro' }` +- **WHEN** `id` is updated to `undefined` +- **THEN** a `PluginDataModifiedEvent` is emitted with `previous` `'intro'` and `value` `undefined`, and the node's serialized form no longer contains `id` + +Implemented in `src/entities/ValueNode`, `src/entities/PluginDataNode`. + +### Requirement: Generic modification of plugin data +`EditorDocument.modifyData` SHALL apply a `Modified` change addressed by a `PluginDataIndex` by setting that plugin's key on the indexed block to the change's `value`, so undo/redo and remote operations can replay plugin data changes through the generic index-based entry point. + +#### Scenario: Replaying a plugin data change by index +- **GIVEN** a block at index 1 whose `anchors` plugin data has `visible: true` +- **WHEN** `modifyData(Index.pluginData(1, 'anchors', 'visible'), { value: false, previous: true })` is called +- **THEN** the block's `anchors.visible` becomes `false` and a `PluginDataModifiedEvent` is emitted with that index + diff --git a/openspec/specs/plugin-block-data/spec.md b/openspec/specs/plugin-block-data/spec.md new file mode 100644 index 00000000..1554d923 --- /dev/null +++ b/openspec/specs/plugin-block-data/spec.md @@ -0,0 +1,195 @@ +# plugin-block-data Specification + +## Purpose + +Plugins persist per-block data in the document Model under their own `name`, instead of through a dedicated Block Tune entity. This capability owns the contract end to end: the `plugins` store on `BlockNode` and its serialized form, the `BlocksAPI` methods plugins use to read and write it, and the guarantee that plugin-data changes are undoable and synchronized like any other document change. The storage primitives live in [[model]] and [[model-types]], the API surface in [[core]] and [[sdk]], and the OT handling in [[collaboration-manager]]. + +## Requirements +### Requirement: Per-block plugin data store +Each block SHALL be able to hold data owned by plugins, stored as a map from a plugin data name (by convention the owning plugin's static `name`) to a flat record of string keys and JSON-serializable values. The store SHALL be serialized under the block's `plugins` key, and a block without plugin data SHALL serialize without a `plugins` entry for that plugin. + +A write that would leave the stored data as it is — the value a key already holds, or the removal of a key that is not present — SHALL emit no event, and so SHALL produce neither an operation for collaborators nor an undo step. Plugins re-apply their current state routinely, and an entry that undoes nothing is worse than no entry at all. + +Plugin names and the keys within an entry are document data, not identifiers the editor chooses, so neither SHALL be able to collide with `Object.prototype`. A key arriving from a stored document SHALL be held as data whatever it is called, `__proto__` included; a key the entry does not hold SHALL read as absent rather than as an inherited member, both when asking for a plugin's entry and when reading a key within one. + +What `getPluginData` and the serialized document hand back SHALL be detached from the store, so that changing it does not change the document. Reading an entry, editing it and passing it back to `updatePluginData` is the obvious way to use the two together, and over a live record the no-op rule above turns it into silent loss: the document has already changed, so the write that should have announced it emits nothing. + +A value handed to the store SHALL be detached the same way before it is stored and before the change is recorded, down to nested objects and arrays, and so SHALL the data a block is initialized with. This is the same read-modify-write from the other end: a plugin keeps the object it wrote and edits it again, and over a shared object the document moves with no write at all, no operation for collaborators and no step to undo — two documents diverging with nothing to say so. What is recorded needs detaching for the same reason, since an operation and an undo step both outlive the call that produced them. Because what is stored is therefore a copy of what was written, the no-op rule above SHALL compare values structurally rather than by identity, which could only ever match a primitive. + +#### Scenario: A block with no plugin data +- **GIVEN** a block that has no plugin data at all +- **WHEN** it is serialized +- **THEN** its `plugins` value is an empty map rather than being absent, matching how the store serializes today + +#### Scenario: Block initialized with plugin data +- **GIVEN** a block is inserted with `plugins: { anchors: { id: "intro" } }` +- **WHEN** the document is serialized +- **THEN** the block's serialized form contains `plugins: { anchors: { id: "intro" } }` + +#### Scenario: Writing plugin data for the first time +- **GIVEN** a block that has no data for plugin `anchors` +- **WHEN** plugin data `{ id: "intro" }` is written for `anchors` on that block +- **THEN** the entry is created with that value instead of an error being thrown, and a `PluginDataModifiedEvent` is emitted for key `id` with `previous` `undefined` and `value` `"intro"` + +#### Scenario: Updating one key keeps the others +- **GIVEN** a block with `plugins.anchors` equal to `{ id: "intro", visible: true }` +- **WHEN** `{ visible: false }` is written for `anchors` +- **THEN** the entry becomes `{ id: "intro", visible: false }`, and exactly one `PluginDataModifiedEvent` is emitted, for key `visible` + +#### Scenario: Removing the last key drops the entry +- **GIVEN** a block with `plugins.anchors` equal to `{ id: "intro" }` +- **WHEN** `{ id: undefined }` is written for `anchors` +- **THEN** the key is removed, and the serialized block no longer contains an `anchors` entry under `plugins` + +#### Scenario: Writing the value a key already holds +- **GIVEN** a block with `plugins.anchors` equal to `{ visible: true }` +- **WHEN** `{ visible: true }` is written for `anchors` again +- **THEN** the data is unchanged and no `PluginDataModifiedEvent` is emitted + +#### Scenario: Removing a key that is not there +- **GIVEN** a block whose `anchors` entry has no `visible` key +- **WHEN** `{ visible: undefined }` is written for `anchors` +- **THEN** the data is unchanged and no `PluginDataModifiedEvent` is emitted + +#### Scenario: Editing a value that was written earlier +- **GIVEN** a plugin wrote `{ align: "left" }` for a key and still holds that object +- **WHEN** it changes the object to `{ align: "center" }` and writes it again +- **THEN** the document held `left` until that write, which emits a `PluginDataModifiedEvent` with `previous` `{ align: "left" }` and `value` `{ align: "center" }` + +#### Scenario: Writing an equal object again +- **GIVEN** a key holds `{ align: "left" }` +- **WHEN** a different object holding `{ align: "left" }` is written for it +- **THEN** no `PluginDataModifiedEvent` is emitted, because nothing about the stored data changed + +#### Scenario: Editing an object after the change was recorded +- **GIVEN** a plugin wrote an object for a key, and the change was recorded +- **WHEN** it changes that object afterwards +- **THEN** the recorded value is unaffected, so neither the operation sent to collaborators nor the undo step is rewritten + +#### Scenario: Reusing the data a block was initialized with +- **GIVEN** a block is initialized with a `plugins` map whose nested values the caller still holds +- **WHEN** the caller changes one of them +- **THEN** the block's plugin data is unaffected + +#### Scenario: Reading an entry whose keys were all removed +- **GIVEN** a block whose `anchors` entry existed and then had every key removed +- **WHEN** its plugin data is read +- **THEN** `undefined` is returned, the same as for an entry that never existed + +#### Scenario: A plugin name that collides with an object-prototype member +- **GIVEN** plugin data is written for a plugin named `__proto__` or `toString` +- **WHEN** it is written and read back, and the document is serialized and re-loaded +- **THEN** the entry is stored and returned as ordinary data, with no prototype of the store affected and no silent loss + +#### Scenario: An empty plugin name +- **WHEN** plugin data is written for an empty plugin name +- **THEN** it throws, rather than creating an unaddressable entry + +#### Scenario: Unknown plugin data is preserved +- **GIVEN** a document whose block carries a `plugins` entry for a plugin that is not registered in this editor +- **WHEN** the document is loaded and serialized again +- **THEN** that plugin's entry is preserved verbatim + +### Requirement: Plugin data API +The system SHALL expose `BlocksAPI.getPluginData({ block, plugin })` and `BlocksAPI.updatePluginData({ block, plugin, data, userId? })`, where `block` is a block index or id. `updatePluginData` SHALL merge the given keys into the plugin's entry, attributing the change to `userId` or, when omitted, to the configured user. Each changed key SHALL be recorded as its own modification, so a call that writes several keys is not a single undo step. `BlocksAPI.insert` and `insertMany` SHALL accept an initial `plugins` map per block. + +#### Scenario: Reading plugin data +- **GIVEN** a block with id `b1` whose `plugins.anchors` is `{ id: "intro" }` +- **WHEN** `api.blocks.getPluginData({ block: "b1", plugin: "anchors" })` is called +- **THEN** it returns `{ id: "intro" }` + +#### Scenario: Reading absent plugin data +- **WHEN** `getPluginData` is called for a plugin that has no entry on the block +- **THEN** it returns `undefined` + +#### Scenario: A plugin named after a member of Object.prototype +- **GIVEN** a block that has no entry for a plugin named `toString` +- **WHEN** `getPluginData({ block: 0, plugin: "toString" })` is called +- **THEN** it returns `undefined`, rather than the function the prototype would answer with + +#### Scenario: A key named __proto__ in a stored document +- **GIVEN** a document whose `plugins.anchors` holds a `__proto__` key +- **WHEN** it is loaded and serialized again +- **THEN** the key is still there, because it was held as data rather than reaching a prototype setter + +#### Scenario: The first write to a key named after a member of Object.prototype +- **GIVEN** an entry that holds no `toString` key +- **WHEN** `toString` is written for the first time +- **THEN** the change records no previous value, so undoing it removes the key rather than restoring an inherited function + +#### Scenario: Editing what was read +- **GIVEN** `getPluginData` returned a plugin's entry +- **WHEN** the caller changes a key on it and passes it to `updatePluginData` +- **THEN** the document is unchanged until that call, which records the change as its own modification + +#### Scenario: Writing plugin data +- **WHEN** `api.blocks.updatePluginData({ block: 0, plugin: "anchors", data: { id: "intro" } })` is called +- **THEN** the block at index 0 carries `plugins.anchors.id === "intro"`, and the emitted event's `userId` is the configured user + +#### Scenario: Unknown block +- **WHEN** `getPluginData` or `updatePluginData` references a block index or id that does not exist +- **THEN** it throws — naming the id when an id was given, or reporting an out-of-bounds index when an index was given + +#### Scenario: Writing several keys at once +- **WHEN** `updatePluginData` is called with two keys in `data` +- **THEN** both are applied, two modifications are recorded, and a single undo reverts only the last one + +### Requirement: Plugin data survives block restructuring +Block operations that relocate or transform a block SHALL keep its plugin data consistent: `move` SHALL preserve it, `convert` SHALL carry it over to the converted block, and `split` SHALL leave it on the original block and create the new block without plugin data. + +#### Scenario: Moving a block +- **GIVEN** a block carrying plugin data +- **WHEN** it is moved to another index +- **THEN** the block at the new index carries the same plugin data + +#### Scenario: Converting a block +- **GIVEN** a block carrying plugin data +- **WHEN** it is converted to another block tool +- **THEN** the resulting block carries the same plugin data + +#### Scenario: Splitting a block +- **GIVEN** a block carrying plugin data +- **WHEN** it is split at a caret offset +- **THEN** the original block keeps its plugin data, and the newly inserted block has none + +### Requirement: Plugin data changes are undoable +A plugin data change SHALL be recorded by local undo/redo like any other document modification. Undoing it SHALL restore the previous value, including removing a key that did not exist before the change. + +#### Scenario: Undoing a first write +- **GIVEN** a block with no `anchors` data, then `updatePluginData` writes `{ id: "intro" }` for `anchors` +- **WHEN** `api.document.undo()` is called +- **THEN** the block serializes without an `anchors` entry, and `api.document.redo()` restores `{ id: "intro" }` + +#### Scenario: Undoing an update +- **GIVEN** `plugins.anchors.visible` changed from `true` to `false` +- **WHEN** undo is performed +- **THEN** `visible` is `true` again + +#### Scenario: A write that changes nothing adds no undo step +- **GIVEN** `plugins.anchors.visible` is `true` and a plugin writes `{ visible: true }` again +- **WHEN** undo is performed +- **THEN** it reverts whatever the user did before that write, because the no-op write recorded nothing of its own + +### Requirement: Plugin data changes are collaborative +A local plugin data change SHALL be sent to collaborators as a `Modify` operation on a `PluginDataIndex`, and a received one SHALL be applied to the local model. Plugin data operations SHALL be transformed against concurrent block insertions and removals so they keep targeting the same block. + +#### Scenario: Remote client receives a plugin data change +- **GIVEN** two clients editing the same document +- **WHEN** client A writes `{ visible: false }` for `anchors` on a block +- **THEN** client B's model reflects `visible: false` for that block + +#### Scenario: Concurrent block insertion above +- **GIVEN** client A writes plugin data for the block at index 2 while client B concurrently inserts a block at index 0 +- **WHEN** both operations are applied on both clients +- **THEN** the plugin data change lands on the same logical block (index 3 after B's insertion) on both clients + +#### Scenario: Removing a key reaches collaborators +- **GIVEN** client A removes the `visible` key of a block's `anchors` data +- **WHEN** the operation is serialized, sent, and applied on client B +- **THEN** B's block no longer has that key — a removal carries no value, so it SHALL survive a round trip through JSON, where a key holding `undefined` does not + +#### Scenario: Target block removed concurrently +- **GIVEN** client A writes plugin data for a block that client B concurrently removes +- **WHEN** A's operation is transformed against B's removal +- **THEN** it becomes a no-op rather than modifying a different block + diff --git a/openspec/specs/sdk/spec.md b/openspec/specs/sdk/spec.md index 6a51a0c5..fba8bc5a 100644 --- a/openspec/specs/sdk/spec.md +++ b/openspec/specs/sdk/spec.md @@ -112,17 +112,29 @@ The system SHALL provide `matchKeyboardShortcut(event, shortcutString)` to test Implemented in `src/utils/keyboardShortcut.ts`, `src/utils/keypath.ts`. ### Requirement: Augmentable plugin type maps -The system SHALL declare two empty, augmentable interfaces — `EditorjsPluginApiMap` (plugin id → public API type) and `ToolPluginOptionsMap` (plugin id → tool-directed options type) — that plugin packages extend via module augmentation of `@editorjs/sdk`. +The system SHALL declare three empty, augmentable interfaces — `EditorjsPluginApiMap` (plugin id → public API type), `ToolPluginOptionsMap` (plugin id → tool-directed options type), and `EditorjsPluginDataMap` (plugin id → the shape of the per-block data that plugin stores) — that plugin packages extend via module augmentation of `@editorjs/sdk`. `PluginId` SHALL include the keys of all three maps. `BlocksAPI.getPluginData`/`updatePluginData` SHALL resolve their data type from `EditorjsPluginDataMap` for a declared id, and SHALL fall back to `Record` for an id absent from it, using a non-distributive conditional so the `string & {}` member of `PluginId` does not widen a declared id's type. #### Scenario: Plugin package augments both maps -- **GIVEN** a plugin package declares `declare module '@editorjs/sdk'` augmenting both interfaces under its `name` +- **GIVEN** a plugin package declares `declare module '@editorjs/sdk'` augmenting `EditorjsPluginApiMap` and `ToolPluginOptionsMap` under its `name` - **WHEN** a consumer's compilation includes that package's types - **THEN** `api.plugins.` and `options.plugins.` are both fully typed with no cast #### Scenario: No augmentation present -- **GIVEN** no plugin package has augmented either interface +- **GIVEN** no plugin package has augmented any of the three interfaces - **WHEN** `@editorjs/sdk` is compiled on its own -- **THEN** both interfaces are empty and `Partial<...>` of them permits no keys, so the base package remains self-consistent +- **THEN** all three are empty and `Partial<...>` of them permits no keys, so the base package remains self-consistent + +#### Scenario: Plugin package declares its block data shape +- **GIVEN** a plugin package augments `EditorjsPluginDataMap` with `{ anchors: { id: string } }` +- **WHEN** a consumer calls `api.blocks.getPluginData({ plugin: 'anchors' })` +- **THEN** the result is typed `{ id: string } | undefined`, and `updatePluginData({ plugin: 'anchors', data: { id: 1 } })` is a compile error + +#### Scenario: Plugin data for an undeclared id +- **GIVEN** a plugin that has not augmented `EditorjsPluginDataMap` +- **WHEN** `getPluginData({ plugin: 'whatever' })` is called +- **THEN** the result is typed `Record | undefined` rather than `never`, so an undeclared plugin still compiles + +Implemented in `src/index.ts` (the map declarations, `PluginId`, `PluginsAPI`, `ToolPluginOptions`), `src/api/BlocksAPI.ts`, validated by `src/pluginTypeMaps.spec.ts`. ### Requirement: Tool options carry plugin-directed configuration `BaseToolOptions` SHALL include an optional `plugins` key typed as `Partial`, and `BaseToolFacade` SHALL expose an accessor returning the merged slice for a single plugin id. From d350d339bfe533b4fccc960f6d08c9ee1a727cf4 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sun, 8 Nov 2026 16:17:55 +0000 Subject: [PATCH 28/29] chore(openspec): archive remove-block-tunes Archive the change and sync its core and sdk deltas into the main specs. The sdk Purpose preamble was already updated by hand earlier in this PR, as the proposal asked. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TffpCm82NH5xXR1yeBew6Q --- .../.openspec.yaml | 0 .../2026-11-08-remove-block-tunes}/design.md | 0 .../proposal.md | 0 .../specs/core/spec.md | 0 .../specs/sdk/spec.md | 0 .../2026-11-08-remove-block-tunes}/tasks.md | 0 openspec/specs/core/spec.md | 9 +- openspec/specs/sdk/spec.md | 82 ++++++++++--------- 8 files changed, 50 insertions(+), 41 deletions(-) rename openspec/changes/{remove-block-tunes => archive/2026-11-08-remove-block-tunes}/.openspec.yaml (100%) rename openspec/changes/{remove-block-tunes => archive/2026-11-08-remove-block-tunes}/design.md (100%) rename openspec/changes/{remove-block-tunes => archive/2026-11-08-remove-block-tunes}/proposal.md (100%) rename openspec/changes/{remove-block-tunes => archive/2026-11-08-remove-block-tunes}/specs/core/spec.md (100%) rename openspec/changes/{remove-block-tunes => archive/2026-11-08-remove-block-tunes}/specs/sdk/spec.md (100%) rename openspec/changes/{remove-block-tunes => archive/2026-11-08-remove-block-tunes}/tasks.md (100%) diff --git a/openspec/changes/remove-block-tunes/.openspec.yaml b/openspec/changes/archive/2026-11-08-remove-block-tunes/.openspec.yaml similarity index 100% rename from openspec/changes/remove-block-tunes/.openspec.yaml rename to openspec/changes/archive/2026-11-08-remove-block-tunes/.openspec.yaml diff --git a/openspec/changes/remove-block-tunes/design.md b/openspec/changes/archive/2026-11-08-remove-block-tunes/design.md similarity index 100% rename from openspec/changes/remove-block-tunes/design.md rename to openspec/changes/archive/2026-11-08-remove-block-tunes/design.md diff --git a/openspec/changes/remove-block-tunes/proposal.md b/openspec/changes/archive/2026-11-08-remove-block-tunes/proposal.md similarity index 100% rename from openspec/changes/remove-block-tunes/proposal.md rename to openspec/changes/archive/2026-11-08-remove-block-tunes/proposal.md diff --git a/openspec/changes/remove-block-tunes/specs/core/spec.md b/openspec/changes/archive/2026-11-08-remove-block-tunes/specs/core/spec.md similarity index 100% rename from openspec/changes/remove-block-tunes/specs/core/spec.md rename to openspec/changes/archive/2026-11-08-remove-block-tunes/specs/core/spec.md diff --git a/openspec/changes/remove-block-tunes/specs/sdk/spec.md b/openspec/changes/archive/2026-11-08-remove-block-tunes/specs/sdk/spec.md similarity index 100% rename from openspec/changes/remove-block-tunes/specs/sdk/spec.md rename to openspec/changes/archive/2026-11-08-remove-block-tunes/specs/sdk/spec.md diff --git a/openspec/changes/remove-block-tunes/tasks.md b/openspec/changes/archive/2026-11-08-remove-block-tunes/tasks.md similarity index 100% rename from openspec/changes/remove-block-tunes/tasks.md rename to openspec/changes/archive/2026-11-08-remove-block-tunes/tasks.md diff --git a/openspec/specs/core/spec.md b/openspec/specs/core/spec.md index ce7eb749..60a2349c 100644 --- a/openspec/specs/core/spec.md +++ b/openspec/specs/core/spec.md @@ -35,14 +35,19 @@ The system SHALL provide a `Core` class owning two IoC containers (one for singl Implemented in `src/index.ts`, validated by its co-located `.spec.ts`. ### Requirement: Tool registration and validation -The system SHALL validate configured tools via `ToolsManager`, calling each tool's static `prepare()`, and sorting tools into `available`/`unavailable` collections exposed as `blockTools`/`inlineTools`/`blockTunes`. +The system SHALL validate configured tools via `ToolsManager`, calling each tool's static `prepare()`, and sorting tools into `available`/`unavailable` collections exposed as `blockTools`/`inlineTools`. `Core#use` SHALL accept block tools, inline tools, adapter plugins, and generic plugins; there SHALL be no separate Block Tune registration path. #### Scenario: Rejecting a malformed tool - **GIVEN** a configured tool is neither a constructor function nor an object with a `class` property - **WHEN** `ToolsManager` validates the configuration - **THEN** it throws an error naming the offending tool and describing the required shape -Implemented in `src/tools/ToolsManager.ts`, `src/tools/ToolsFactory.ts`, validated by co-located `.spec.ts` files. +#### Scenario: A former tune is registered as a plugin +- **GIVEN** a class implementing `EditorjsPlugin` that does what a Block Tune used to do +- **WHEN** it is registered via `core.use()` +- **THEN** it is instantiated with the other plugins and never appears in `ToolsManager`'s collections + +Implemented in `src/tools/ToolsManager.ts`, `src/tools/ToolsFactory.ts`, validated by `src/index.spec.ts` and co-located `.spec.ts` files. ### Requirement: EditorAPI surface The system SHALL expose an `EditorAPI` aggregating `BlocksAPI` (insert/insertMany/delete/move/render/clear/getBlocksCount/getPluginData/updatePluginData), `SelectionAPI` (applyInlineTool, selectedBlocks), `DocumentAPI` (serialized data, onUpdate, insertData/removeData/modifyData, undo/redo), and `TextAPI` (insert/remove/format/unformat/getFragments/get) to tools, plugins, and adapters. diff --git a/openspec/specs/sdk/spec.md b/openspec/specs/sdk/spec.md index fba8bc5a..7c418033 100644 --- a/openspec/specs/sdk/spec.md +++ b/openspec/specs/sdk/spec.md @@ -16,50 +16,15 @@ Since `EventBus` itself carries no custom subscribe/unsubscribe/error-handling l Implemented in `src/entities/EventBus/EventBus.ts`, `Event.ts`, `events/core/*`, `events/ui/*`, `events/adapter/*` (base classes `CoreEventBase`, `UIEventBase`; enums `CoreEventType`, `AdapterEventType`). -### Requirement: Tool and tune contracts -The system SHALL define the static/instance contracts that block tools, inline tools, and block tunes must satisfy: `BaseTool`/`BaseToolConstructor` (common `name`, `options`, `prepare()`, `reset()`), `BlockTool`/`BlockToolConstructor` (adds `toolbox`, `shortcut`, `inlineToolbar`, `tunes`, `conversionConfig`, `canBeSplit`), `InlineTool`/`InlineToolConstructor` (adds `isActive`, `getFormattingOptions`, `createWrapper`, `getToolbarConfig`), and `BlockTune`/`BlockTuneConstructor`. `ToolConfig` SHALL be an SDK-owned contract (not a re-exported passthrough from `@editorjs/editorjs`), kept formally distinct from `ToolOptions`: `options` describes core/plugin-facing wiring available before any block instance exists, while `ToolConfig` describes tool-author-facing user data resolved per tool registration. A tool's static `options` SHALL be either a plain options object or a synchronous factory taking the tool's `ToolConfig` and returning that options object; the facade SHALL resolve the factory exactly once, at construction, and serve every option-reading getter from that resolved value without writing it back onto the tool class. - -#### Scenario: Options and config merging in a tool facade -- **GIVEN** a tool class has static `options` (and optionally `options.config` typed as `ToolConfig`) -- **WHEN** the tool is registered via `use(Tool, options)` with overriding options -- **THEN** the facade's `options` getter merges the tool's resolved static options with `use()`-time options, with `use()`-time keys taking precedence, and the `config` getter merges similarly, injecting `defaultPlaceholder` only when `isDefault` is true and no `placeholder` key is already present - -#### Scenario: Resolving static options from a config factory -- **GIVEN** a tool class declares `static options` as a function of its `ToolConfig` rather than as a plain object -- **WHEN** its facade is constructed for a registration made via `use(Tool, { config })` -- **THEN** the function is invoked exactly once with the `config` supplied at `use()` time, its returned options object becomes the tool's resolved static options for that facade, and the tool class's own `options` property is left untouched - -#### Scenario: Deriving a toolbox entry from a config value -- **GIVEN** a block tool's `options` factory computes `toolbox` entries from a field of the config it receives -- **WHEN** the facade's `toolbox` getter is read -- **THEN** the entries reflect the config supplied at `use()` time, and any explicit `use()`-time `toolbox` override is merged on top using the existing array/object positional-merge algorithm, with a `use()`-time `toolbox: false` still hiding the tool from the toolbox - -#### Scenario: Isolating factory-derived options per facade instance -- **GIVEN** two `Core` instances each register the same tool class through `use()` with a different `config` -- **WHEN** each instance's facade resolves the tool's `options` factory -- **THEN** each facade holds its own resolved options and neither instance's derived values are observable from the other - -#### Scenario: Text content conversion without config -- **GIVEN** a block tool has no `conversionConfig` -- **WHEN** `exportTextContent`/`importTextContent` is called on its facade -- **THEN** it throws a descriptive error stating the tool does not have export/import configuration - -#### Scenario: Text content conversion with a keypath -- **GIVEN** a block tool's `conversionConfig` specifies a dot-notation string key (including nested array paths, e.g. `items.0.text`) -- **WHEN** `exportTextContent`/`importTextContent` is called -- **THEN** the value at that keypath is read/written, producing or consuming a `TextNodeSerialized` value tagged with the hidden `Text` block-child-type marker - -Implemented in `src/entities/BaseTool.ts`, `BlockTool.ts`, `InlineTool.ts`, `BlockTune.ts`, `src/tools/facades/{BaseToolFacade,BlockToolFacade,InlineToolFacade,BlockTuneFacade}.ts`, validated by `src/tools/facades/BaseToolFacade.spec.ts`. - ### Requirement: Tools collection -The system SHALL provide a `ToolsCollection` (a `Map` subclass) exposing filtered `blockTools`/`inlineTools`/`blockTunes` views over registered tool facades. +The system SHALL provide a `ToolsCollection` (a `Map` subclass) exposing filtered `blockTools`/`inlineTools` views over registered tool facades. #### Scenario: Filtering registered facades by kind -- **GIVEN** a `ToolsCollection` containing a mix of block tool, inline tool, and tune facades -- **WHEN** `blockTools`, `inlineTools`, or `blockTunes` is accessed +- **GIVEN** a `ToolsCollection` containing a mix of block tool and inline tool facades +- **WHEN** `blockTools` or `inlineTools` is accessed - **THEN** each getter returns only the facades matching that kind -Implemented in `src/tools/ToolsCollection.ts`. +Implemented in `src/tools/ToolsCollection.ts`, validated by its co-located `.spec.ts`. ### Requirement: BlockToolAdapter bridges model events to per-block DOM state The system SHALL provide an abstract `BlockToolAdapter` (extending `EventTarget`) that subscribes to `api.document.onUpdate`, translates model-level `DataNodeAddedEvent`/`DataNodeRemovedEvent`/`ValueModifiedEvent` into adapter-level `KeyAddedEvent`/`KeyRemovedEvent`/`ValueNodeChangedEvent` dispatched on itself, and exposes `registerTextInputKey`, `registerValueKey`, `removeKey`, and `destroy()`. @@ -146,3 +111,42 @@ Implemented in `src/index.ts` (the map declarations, `PluginId`, `PluginsAPI`, ` Implemented in `src/entities/BaseTool.ts`, `src/tools/facades/BaseToolFacade.ts`. +### Requirement: Tool contracts +The system SHALL define the static/instance contracts that block tools and inline tools must satisfy: `BaseTool`/`BaseToolConstructor` (common `name`, `options`, `prepare()`, `reset()`), `BlockTool`/`BlockToolConstructor` (adds `toolbox`, `shortcut`, `inlineToolbar`, `conversionConfig`, `canBeSplit`), and `InlineTool`/`InlineToolConstructor` (adds `isActive`, `getFormattingOptions`, `createWrapper`, `getToolbarConfig`). The SDK SHALL NOT define a Block Tune tool kind: per-block settings and per-block data are provided by plugins (see `block-settings` and `plugin-block-data`), and `ToolType` SHALL have no `Tune` member. `ToolConfig` SHALL be an SDK-owned contract (not a re-exported passthrough from `@editorjs/editorjs`), kept formally distinct from `ToolOptions`: `options` describes core/plugin-facing wiring available before any block instance exists, while `ToolConfig` describes tool-author-facing user data resolved per tool registration. A tool's static `options` SHALL be either a plain options object or a synchronous factory taking the tool's `ToolConfig` and returning that options object; the facade SHALL resolve the factory exactly once, at construction, and serve every option-reading getter from that resolved value without writing it back onto the tool class. + +#### Scenario: Options and config merging in a tool facade +- **GIVEN** a tool class has static `options` (and optionally `options.config` typed as `ToolConfig`) +- **WHEN** the tool is registered via `use(Tool, options)` with overriding options +- **THEN** the facade's `options` getter merges the tool's resolved static options with `use()`-time options, with `use()`-time keys taking precedence, and the `config` getter merges similarly, injecting `defaultPlaceholder` only when `isDefault` is true and no `placeholder` key is already present + +#### Scenario: Resolving static options from a config factory +- **GIVEN** a tool class declares `static options` as a function of its `ToolConfig` rather than as a plain object +- **WHEN** its facade is constructed for a registration made via `use(Tool, { config })` +- **THEN** the function is invoked exactly once with the `config` supplied at `use()` time, its returned options object becomes the tool's resolved static options for that facade, and the tool class's own `options` property is left untouched + +#### Scenario: Deriving a toolbox entry from a config value +- **GIVEN** a block tool's `options` factory computes `toolbox` entries from a field of the config it receives +- **WHEN** the facade's `toolbox` getter is read +- **THEN** the entries reflect the config supplied at `use()` time, and any explicit `use()`-time `toolbox` override is merged on top using the existing array/object positional-merge algorithm, with a `use()`-time `toolbox: false` still hiding the tool from the toolbox + +#### Scenario: Isolating factory-derived options per facade instance +- **GIVEN** two `Core` instances each register the same tool class through `use()` with a different `config` +- **WHEN** each instance's facade resolves the tool's `options` factory +- **THEN** each facade holds its own resolved options and neither instance's derived values are observable from the other + +#### Scenario: Text content conversion without config +- **GIVEN** a block tool has no `conversionConfig` +- **WHEN** `exportTextContent`/`importTextContent` is called on its facade +- **THEN** it throws a descriptive error stating the tool does not have export/import configuration + +#### Scenario: Text content conversion with a keypath +- **GIVEN** a block tool's `conversionConfig` specifies a dot-notation string key (including nested array paths, e.g. `items.0.text`) +- **WHEN** `exportTextContent`/`importTextContent` is called +- **THEN** the value at that keypath is read/written, producing or consuming a `TextNodeSerialized` value tagged with the hidden `Text` block-child-type marker + +#### Scenario: No tune tool kind +- **WHEN** the SDK's public exports are inspected +- **THEN** there is no `BlockTune`, `BlockTuneConstructor`, `BlockTuneOptions`, `BlockTuneFacade`, or `ToolType.Tune`, and `BlockToolConstructor` has no `tunes` member + +Implemented in `src/entities/BaseTool.ts`, `BlockTool.ts`, `InlineTool.ts`, `src/tools/facades/{BaseToolFacade,BlockToolFacade,InlineToolFacade}.ts`, validated by `src/tools/facades/BaseToolFacade.spec.ts`. + From 896c4c2815462e006c83781b7c6451eb6a4eb2a4 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sun, 8 Nov 2026 16:19:12 +0000 Subject: [PATCH 29/29] chore(openspec): mark remove-block-tunes task 4.5 done Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TffpCm82NH5xXR1yeBew6Q --- openspec/changes/archive/2026-11-08-remove-block-tunes/tasks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openspec/changes/archive/2026-11-08-remove-block-tunes/tasks.md b/openspec/changes/archive/2026-11-08-remove-block-tunes/tasks.md index 91b43ceb..39846cd4 100644 --- a/openspec/changes/archive/2026-11-08-remove-block-tunes/tasks.md +++ b/openspec/changes/archive/2026-11-08-remove-block-tunes/tasks.md @@ -22,5 +22,5 @@ - [x] 4.2 Hand-edit the **Purpose** preamble of `openspec/specs/sdk/spec.md` to drop "block tunes" — the mechanical archive fold only rewrites `### Requirement:` blocks - [x] 4.3 Change the `shortcuts-plugin` spec's reserved-work note from "block tunes" to "block settings items" - [x] 4.4 Run `yarn lint` and `yarn test`. Fix any regressions -- [ ] 4.5 Comment on PR #157 linking `plugin-block-data`, `block-settings-ui` and `remove-block-tunes` as its replacement +- [x] 4.5 Comment on PR #157 linking `plugin-block-data`, `block-settings-ui` and `remove-block-tunes` as its replacement - [x] 4.6 Run `openspec validate remove-block-tunes --type change` and confirm it passes