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` 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..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. 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,29 @@ #### 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 +- **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 12e0dbc0..f13451db 100644 --- a/openspec/changes/plugin-block-data/tasks.md +++ b/openspec/changes/plugin-block-data/tasks.md @@ -1,70 +1,81 @@ ## 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 -- [ ] 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) -- [ ] 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) -- [ ] 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` + +## 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 + +## 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 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.spec.ts b/packages/collaboration-manager/src/Operation.spec.ts index 87bf21c1..c0633632 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,45 @@ describe('Operation', () => { expect(() => op.inverse()).toThrow('Unsupported operation type'); }); }); + describe('.serialize()', () => { + /** + * 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 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, + 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 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, + 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/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..adde8df4 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,222 @@ 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); + }); + + /** + * 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); + + const result = transformer.transform(operation, againstOp); + + expect(result.serialize()).toEqual(operation.serialize()); + }); + + 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' + ); + + 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', () => { + const incoming = pluginOp(2); + const unsentLocal = new Operation( + OperationType.Modify, + Index.pluginData(2, createPluginDataName('spoiler'), 'id', 'doc1' as DocumentId), + { payload: true, + prevPayload: false }, + 'user2' + ); + + 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', () => { + const incoming = pluginOp(2); + const unsentLocal = new Operation( + OperationType.Modify, + pluginIndex(3), + { payload: true, + prevPayload: false }, + 'user2' + ); + + 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()); + }); + + /** + * 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, + 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..bbc399b1 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,63 @@ export class OperationsTransformer { } } + /** + * Method that transforms operation against a plugin data operation + * + * 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 new transformed operation + */ + #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; + + /** + * 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 > revision) { + return new Operation(OperationType.Neutral, index, { payload: [] }, operation.userId, operation.rev); + } + + return Operation.from(operation); + } + /** * Method that transforms operation against data (value) operation * @@ -264,7 +325,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 +413,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/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); + }); }); }); 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); diff --git a/packages/core/src/api/BlocksAPI.integration.spec.ts b/packages/core/src/api/BlocksAPI.integration.spec.ts index 317b8297..a8bd5db4 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; @@ -63,10 +65,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 +1189,188 @@ 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 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' }); + + 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 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' } } }); + 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..1a94a2f7 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 {}, @@ -100,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, @@ -726,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/core/src/components/BlockManager.ts b/packages/core/src/components/BlockManager.ts index ee0f3a47..5d0fdaa7 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,47 @@ 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); + const plugins = this.#model.getBlockSerialized(blockIndex).plugins; + + /** + * 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]; + } + + /** + * 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..5769c833 --- /dev/null +++ b/packages/core/src/components/UndoRedoManager.integration.spec.ts @@ -0,0 +1,90 @@ +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 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 }); + + manager.undo(); + + expect(pluginData(model)).toEqual({ id: 'intro' }); + }); +}); 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..0660dcbb 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,33 @@ 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, 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 { + 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 +124,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) 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..a6ce4ff0 100644 --- a/packages/model/src/entities/BlockNode/BlockNode.integration.spec.ts +++ b/packages/model/src/entities/BlockNode/BlockNode.integration.spec.ts @@ -1,9 +1,16 @@ -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'; 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'; @@ -237,4 +244,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_NAME), { id: 'intro' }); + blockNode.updatePluginData(createPluginDataName(TO_STRING_NAME), { id: 'other' }); + + expect(blockNode.serialized.plugins) + .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_NAME]: { id: 'intro' } } }); + + expect(blockNode.serialized.plugins) + .toEqual({ [PROTO_NAME]: { 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..680f1a35 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,38 @@ describe('BlockNode', () => { }); }); - describe('.updateTuneData()', () => { + describe('constructing with plugin data', () => { afterEach(() => { jest.clearAllMocks(); }); - it('should call .update() method of the BlockTune', () => { - const blockTuneName = 'align' as BlockTuneName; + 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(); + }); + + 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 +895,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 +1722,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 +1735,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 +1747,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..44c08912 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'; @@ -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 be associated with one or more BlockTunes, which can modify the behavior of the BlockNode. + * 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,9 +79,11 @@ 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 because + * names come from documents: assigning a `__proto__` key to an ordinary object creates no own + * property, silently losing that plugin's data. */ - #tunes: Record; + #plugins: Record = Object.create(null) as Record; /** * Constructor for BlockNode class. @@ -90,33 +92,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 +142,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 +157,22 @@ export class BlockNode extends EventBus { entry => this.#serializeData(entry) ); - const serializedTunes = mapObject( - this.#tunes, - tune => tune.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, name: this.#name, data: serializedData, - tunes: serializedTunes, + plugins: serializedPlugins, }; } @@ -256,14 +254,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 +590,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 */ - #listenAndBubbleTuneEvent(tune: BlockTune, name: BlockTuneName): void { - tune.addEventListener( + #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 + */ + #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 a0f21684..1a23775a 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'); @@ -1520,6 +1520,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()', () => { @@ -1727,11 +1755,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', @@ -1742,22 +1770,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', @@ -1769,8 +1797,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 0c4cea54..921e0d02 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); } /** @@ -520,6 +521,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 */ @@ -573,7 +578,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..e31e9e93 --- /dev/null +++ b/packages/model/src/entities/PluginDataNode/PluginDataNode.spec.ts @@ -0,0 +1,432 @@ +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('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(); + }); + + /** + * 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, + 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); + }); + + 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('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('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, + 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({ + 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..5e4e33d4 --- /dev/null +++ b/packages/model/src/entities/PluginDataNode/index.ts @@ -0,0 +1,145 @@ +import { getContext } from '../../utils/Context.js'; +import { deepEqual } from '../../utils/deepEqual.js'; +import type { PluginDataNodeConstructorParameters } from './types/index.js'; +import { + PartialIndex, + type PluginDataSerialized, + type PluginDataName, + EventBus, + 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. + * + * `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 + * 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; + + /** + * 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. + * + * 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 = detach(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]; + + /** + * 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. + * + * 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 (deepEqual(previousValue, value) && (value !== undefined || !(key in this.#data))) { + return; + } + + if (value === undefined) { + delete this.#data[key]; + } else { + /** + * 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 }), { + /** + * 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()!) + ); + } + + /** + * 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 detach(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'; diff --git a/packages/model/src/utils/deepEqual.spec.ts b/packages/model/src/utils/deepEqual.spec.ts new file mode 100644 index 00000000..f89c4c0a --- /dev/null +++ b/packages/model/src/utils/deepEqual.spec.ts @@ -0,0 +1,87 @@ +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 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 }); + + 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. 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', diff --git a/packages/sdk/src/api/BlocksAPI.ts b/packages/sdk/src/api/BlocksAPI.ts index 65b4c78e..6e1e1281 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,43 @@ 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 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` + * @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..244e60f2 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -32,6 +32,32 @@ 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, 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] + : Record; + /** * Identifier of a plugin — the value of its static `name`. * @@ -39,7 +65,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 +95,8 @@ export type { BlockNodeInit, BlockNodeSerialized, BlockToolName, - BlockTuneName, - BlockTuneSerialized, + PluginDataName, + PluginDataSerialized, TextRange, InlineFragment, InlineTreeNodeSerialized, @@ -102,7 +128,7 @@ export { generateBlockId, createBlockToolName, createDataKey, - createBlockTuneName, + createPluginDataName, createInlineToolName, createInlineToolData, EventAction, @@ -122,13 +148,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 = {