diff --git a/openspec/changes/block-settings-ui/.openspec.yaml b/openspec/changes/block-settings-ui/.openspec.yaml new file mode 100644 index 00000000..563fab5a --- /dev/null +++ b/openspec/changes/block-settings-ui/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-09-21 diff --git a/openspec/changes/block-settings-ui/design.md b/openspec/changes/block-settings-ui/design.md new file mode 100644 index 00000000..ef8018c7 --- /dev/null +++ b/openspec/changes/block-settings-ui/design.md @@ -0,0 +1,129 @@ +## Context + +The UI is a set of plugins (`EditorjsUI` shell, `BlocksUI`, `ToolbarUI`, `ToolboxUI`, `InlineToolbarUI`) that wire themselves together through `ui:*` events. None of them has a static `name` or a `publicApi`, so no other plugin can extend them, and `ToolbarUI` has only a plus button. + +PR #157 adds a settings button and a `BlockTunesUI` popover fed by a core `BlockTunesManager` and tune facades. The review argues the menu should be a UI plugin API instead, so any plugin can act as a "tune". This change delivers exactly that one surface — a plugin can put an item in the block settings menu. Changing how a block looks is the other half of v2 tune behavior and is deferred to its own change. + +**Baseline assumption.** This change is implemented on top of `test/editorjs-e2e-and-aria-openspec`, which lands before this PR opens. That branch brings three things this change depends on: `packages/ui/src/messages.ts` (the naming seam for accessible names), the ARIA/keyboard behavior of `ToolbarUI` (toolbar role, roving tabindex over the action buttons, `aria-haspopup`/`aria-expanded`, focus-before-open), and the Playwright harness under `packages/editorjs/e2e/` with its `include-e2e` CI input. It also moves `@editorjs/ui-kit` to `^2.0.0`, which is what gives popovers menu roles, accessible names and internal focus management. If that branch has not landed when implementation starts, stop and re-plan rather than building a toolbar control that violates its invariants. + +Constraints: +- `@editorjs/ui-kit` popover items already support `confirmation`, `isDisabled`, `isActive` and `closeOnActivate` in the pinned 1.1.5, so no upstream change is needed for behavior. Accessibility of the menu comes from ui-kit 2.x via the baseline branch. +- `ui:blocks:block-selected` already carries the target block's index, and `api.blocks.getIdByIndex` turns that into a block id, so no new core event or payload field is needed. + +## Goals / Non-Goals + +**Goals:** +- A block settings menu that any plugin can add items to through `api.plugins['block-settings']`. +- Built-in Move up / Move down / Delete (with confirmation) as an ordinary plugin. + +**Non-Goals:** +- Changing how a block *looks* from a plugin, in any form: no element accessors on `BlocksUI`, no `blockId` on `BlockAddedCoreEvent`, no decoration mechanism. Deferred to its own change; see "Deferred: per-block appearance and attachments". +- Per-block data storage: that is `plugin-block-data`. This change doesn't depend on it. +- Removing the SDK tune kind: that is `remove-block-tunes`. +- Settings items contributed by Block Tools (v2 `renderSettings`). Decided as a follow-up change, not an open question: see D4. +- Keyboard shortcuts for settings items. + +## Decisions + +### D1. Block settings is its own UI plugin with a provider registry +The new `BlockSettingsUI` (`static name = 'block-settings'`) has this `publicApi`: +```ts +interface BlockSettingsAPI { + register(provider: BlockSettingsProvider, options?: { order?: number }): () => void; // returns unregister + close(): void; +} +type BlockSettingsProvider = (ctx: { blockId: BlockId; blockIndex: number; tool: string }) + => BlockSettingsMenuConfig | Promise | undefined; +``` +- On open, every provider is called for the target block. Results are concatenated in ascending `order` (ties are broken by registration order, default `0`) with a separator between providers, then rendered in a ui-kit popover. +- Activation, confirmation, disabled and active state are all expressed in the returned `BlockSettingsMenuConfig`. This answers the question on PR #157: the item declares `onActivate` in its config, the same as `InlineTool#getToolbarConfig`, rather than the core calling an instance method. +- Returning `undefined` or an empty array contributes nothing. This is how a plugin opts out for specific tools, replacing `BlockTool#tunes`. +- Providers are called on every open, so items reflect current state without cache invalidation. +- *Why a separate plugin rather than a `ToolbarUI` API:* the popover has its own lifecycle and events (open, opened, closed), mirroring `ToolboxUI`. `ToolbarUI` owns only where the control sits, not what it means. +- *Alternative:* plugins push static item lists at registration. Rejected, because items depend on the block and its state. + +Wiring follows the Toolbox pattern, with one departure from it: +1. `BlockSettingsUI` renders both the popover **and the button that opens it**, and announces the two together via `ui:block-settings:rendered`. `ToolbarUI` mounts them in its actions area and reassigns its single tab stop once the button joins. +2. The plugin follows `ui:blocks:block-selected` itself to know which block the button acts on, and stops following it while the menu is open. It also opens on a `ui:block-settings:open` event, so a host can request the menu for a block without the button. +3. `ToolbarUI` doesn't reposition while settings are open. + +*Why the button belongs to the plugin rather than the toolbar:* a menu button's `aria-expanded` has to track the menu, and the menu's open state is the plugin's. Split across the two, every open and close would need a round trip through the event bus to keep an attribute honest, and the button would report a block the menu was not built for. `ToolbarUI` treats it as a control of the container like its own plus button -- named, stated and operated by its owner, positioned and tab-managed by the toolbar. + +`BlockSettingsUI` resolves the target block's id with `api.blocks.getIdByIndex(index)` from the index it last saw selected, so this change needs no new event or payload field from `core`. + +The provider context carries both `blockId` and `blockIndex`, but only `blockId` is durable: a menu can stay open while a collaborator inserts or removes blocks above the target, or while an undo does. Item handlers therefore resolve the position from `blockId` at activation time. This is how the tunes in PR #157 behave (`getIndexById` inside `activate()`), and it is worth keeping. + +### D2. Built-in actions are a plugin package in `packages/plugins/` +`@editorjs/default-block-settings-plugin` (`static name = 'default-block-settings'`) registers one provider with `order: 1000` so it sits last. Each handler starts from `api.blocks.getIndexById(ctx.blockId)` and bails out when the block is gone: +- **Move up:** `isDisabled` when the block is first at build time, then `api.blocks.move({ fromIndex: i, toIndex: i - 1 })` with `i` resolved at activation. +- **Move down:** the same, against the last index. +- **Delete:** a `confirmation` item that calls `api.blocks.delete({ block: ctx.blockId })`. + +The disabled state is necessarily a snapshot from when the menu was built; the *action* is not. A stale `isDisabled` at worst greys out an item, while a stale index would move the wrong block. + +It depends only on `@editorjs/sdk`, looks up `api.plugins['block-settings']` lazily at `core:ready`, and is a no-op without it. The bundle registers it. Headless `Core` users opt in. + +### D3. What to port from PR #157 +**Port:** +- The toolbar settings button and styles. +- The `BlockTunes*UIEvent` classes, renamed to `BlockSettings{Open,Opened,Closed,Rendered}UIEvent`. +- The popover wiring in `BlockTunesUI` → `BlockSettingsUI`. +- The behavior and tests of the internal delete, move-up and move-down tunes → `default-block-settings-plugin`. + +Details worth keeping from those files: `PopoverDesktop` configured with `scopeElement: config.holder`, `searchable: false` and `{ [PopoverItemType.Default]: { wrapperTag: 'button' } }`; dispatching the closed event from `PopoverEvent.Closed`; handing the popover element to `ToolbarUI` through a rendered event; and `display: flex; align-items: center` on the toolbar's `__actions` so two buttons sit side by side. PR #157 also fixes a real bug on `main` — `new ToolboxOpenUIEvent('ui:toolbox:open')` passes a string where a payload object belongs ([Toolbar.ts:151](packages/ui/src/Toolbar/Toolbar.ts:151)) — and that fix comes along with the port. + +**Don't port:** `BlockTunesManager` (it instantiates every tune on each block hover), rebuilding popover items on hover rather than on open, `BlockTuneAdapter`, `TuneDataChanged`, the `BlockTuneFacade` changes, moving `BlockSelectedUIEvent` into `sdk`, and the core `tunes/internal` directory. The delete tune there also has no confirmation step, which this change requires. + +**Attribution:** the ported code is Betty Steger's work from PR #157. Commits that bring it over carry `Co-authored-by: Betty Steger <244475+bettysteger@users.noreply.github.com>`. + +### D4. Block Tool settings items are a separate, later change +A block tool contributing its own settings items (v2 `renderSettings`) is deferred, and the shape it will take is fixed now so this change doesn't foreclose it: a tool declares something like `getSettingsConfig(ctx)` returning the same `BlockSettingsMenuConfig`, and a thin core-side provider registered by `BlockSettingsUI` collects it from the tool facade for the target block. +- *Why not now:* the UI has no route to tool instances, so it needs either a core component that owns "settings items of the current block's tool" or a `ToolsManager` accessor on the API. That is its own design, and none of it changes the provider contract. +- *Why the provider shape is enough:* tool-contributed items are just another provider, with an `order` between plugin items and `default-block-settings`. No change to `register` or to `BlockSettingsMenuConfig` is needed when it lands. + +### D5. The settings button meets the toolbar's existing accessibility contract +The settings button is the second control in an already-accessible toolbar, so it adopts that contract rather than inventing one: +- An accessible name from a new `messages.ts` entry, not a hardcoded string. +- `aria-haspopup="menu"` plus `aria-expanded` kept in sync with `ui:block-settings:opened`/`closed`, mirroring the plus button and the toolbox. +- `focus()` on the button before opening the popover, because WebKit does not focus a clicked button and the popover restores focus to whatever was focused when it opened. Without this, closing with Escape drops focus on `` — a bug already found once for the toolbox. +- Both controls appended **before** the roving-tabindex initialization, which runs once over the children present at that moment. A button appended afterwards keeps its default `tabindex="0"`, giving the toolbar two tab stops and breaking the "exactly one tab stop" requirement. +- The popover itself carries an accessible name, the way the toolbox is named through `messages`, and items removed from it leave the accessibility tree. + +### D6. The block settings API types live in `@editorjs/ui` +`BlockSettingsAPI` and `BlockSettingsProvider` are exported from `@editorjs/ui`, which also augments `EditorjsPluginApiMap` under `'block-settings'`. `@editorjs/sdk` stays unaware of individual plugins; it owns only the augmentable map. The item shape is `@editorjs/ui`'s own `BlockSettingsMenuConfig`, named apart from the unrelated `MenuConfig` the SDK already exports for inline tools. +- Consequence: `default-block-settings-plugin` needs `@editorjs/ui` in its compilation for `api.plugins['block-settings']` to typecheck. It takes `@editorjs/ui` as a **devDependency** and imports from it with `import type` only, so there is no runtime coupling and no cycle. +- This is the pattern `plugin-public-api` already describes ("a consumer whose compilation includes that package's types"), and the architecture rule it must respect forbids depending on `@editorjs/model`/`@editorjs/core`, not on a sibling UI package. +- *Alternative:* move the types into `sdk`. Rejected: `sdk` would then carry knowledge of a specific plugin's API. + +### D7. `BlockSettingsUI` declares a new `UiComponentType` member +`EditorjsPluginConstructor` requires a `static type: EntityType`, and `EntityType` is a union of the three enums, so the value has to come from one of them. This change adds `UiComponentType.BlockSettings`. That enum is a list of reserved *UI component* names — not plugin knowledge — and `Toolbar`'s own comment already says the toolbar area "Includes Toolbox and Block Settings". Runtime routing is unaffected: `Core#use` sends anything that is not a tool or adapter through its `default` branch to `PluginType.Plugin`, and `UiComponentType` is read nowhere. +- *Alternative:* reuse `UiComponentType.Toolbar`. Rejected because `Toolbox` has its own member despite also living in the toolbar, so reuse would be inconsistent. + +## Risks / Trade-offs + +- **[`api.plugins['block-settings']` may be absent in a headless setup]** → consumers must tolerate it. `default-block-settings-plugin` guards for it, and the spec requires the no-op. +- **[Losing per-tool tune allow-listing from v2 config]** → providers receive `tool` and decide for themselves. Integrator-level include/exclude can follow via `tool-plugin-options`. +- **[`packages/ui` has no test setup today]** → add Jest with jsdom to the package as part of this change. No package in the monorepo uses jsdom yet, so this is new infrastructure: an explicit `jest-environment-jsdom` dependency, a `moduleNameMapper` for `*.pcss`, `transformIgnorePatterns` covering `@codexteam/*`, the `jest.unstable_mockModule` + dynamic-import convention the other packages use, an ESLint override allowing `@jest/globals` in specs, and `dts()` pointed at `tsconfig.build.json` so declarations stop at source. +- **[Adding CI for `packages/ui` in the same PR]** → there is no `ui.yml` workflow today. `base-coverage` runs `test:coverage` against the base ref for any package whose `package.json` exists there, and `packages/ui` has no such script on the base, so the new workflow must handle that first run. +- **[The `ui` delta will be written against a spec the baseline branch rewrites]** → `Floating toolbar` gains ARIA scenarios on that branch. The delta in this change must be refreshed from the merged spec text before archiving, or the fold will silently revert those scenarios. +- **[Name collision — resolved]** → `main` labels the toolbar container "Block actions" for screen readers (`messages.blockActionsToolbar`) and names a requirement after it. Calling the move/delete package `block-actions` too would have made one phrase mean both the container and a plugin rendering inside a menu within it. The package is therefore `@editorjs/default-block-settings-plugin` (`name: 'default-block-settings'`): the shipped, e2e-asserted accessible name stays as it is, and the new name says what the plugin actually is — the default entries of the block settings menu. A screen reader still announces "Block actions toolbar" on entering the container, which is correct: that is the container, not the menu. + +## Deferred: per-block appearance and attachments + +Letting a plugin change how a block looks is its own change. The investigation so far, so it doesn't have to be redone: + +Two concerns that read as one but aren't: +- **Appearance** — classes and `data-` attributes on the block wrapper. `BlocksUI` already gives every block a wrapper that is `position: relative`, with `.block__contents` centered at `max-width`, so both gutters are free. Adding no DOM means no editing hazard and no conflict between plugins: `classList` is additive. +- **Attachments** — real elements a plugin adds per block (a comment icon and count, a collaborator's avatar, an anchor link icon, a footnote body, an AI-suggestion badge, a read-only overlay). Every case found so far wants a *sibling of contents*, in a gutter or stacked after it. None needs to wrap the contents node, because styling needs collapse into a wrapper class plus a descendant CSS rule, and collapsible/multi-column layouts group several blocks, which is a blocks-holder concern either way. + +Why wrapping the contents node should not be offered at all: reparenting it while the caret is inside destroys the DOM selection, and the restore path (`CaretAdapter#updateIndex`, `#restoreDomSelectionFromCompositeIndex`) is internal to `dom-adapters`. Two plugins wrapping the same block also strand each other's elements on unwrap. Forbidding it makes the conflict structurally impossible instead of a convention. + +Where attachments should live is the open decision, since the blocks holder is `contentEditable: true`: +- **A separate non-editable layer** beside the holder, with one host per block that `BlocksUI` keeps aligned to the block's geometry (ResizeObserver plus add/remove/move). Literally outside the editable region; costs geometry synchronization. +- **An island inside the wrapper**, marked `contenteditable="false"` and `user-select: none`. No positioning work, but it still sits in the editable subtree. + +Mitigating facts for either option: `beforeinput` is always `preventDefault`ed and edits are applied through the Model, so the browser never mutates block DOM, and `clipboard-plugin` builds clipboard data from the Model rather than the DOM. So user editing cannot delete or copy plugin DOM. The residual risks are caret traversal over the element and screen readers reading it in the text flow, which argues for `aria-hidden` by default. + +## Migration Plan + +This change is additive. It can land before or after `plugin-block-data`, and should land before `remove-block-tunes`. Rollback is reverting the PR. diff --git a/openspec/changes/block-settings-ui/proposal.md b/openspec/changes/block-settings-ui/proposal.md new file mode 100644 index 00000000..5c9deda3 --- /dev/null +++ b/openspec/changes/block-settings-ui/proposal.md @@ -0,0 +1,46 @@ +## Why + +A v2 Block Tune did two things in the UI: it added an entry to the block's settings menu, and optionally it changed how the block looks. In v3 neither needs a dedicated entity. Plugins can already expose and consume public APIs (`api.plugins`, see `plugin-public-api`), so a UI plugin can expose the settings menu as an API and any plugin (a "tune") can add items to it. "Tune" then becomes a UI term only. + +This change covers the settings menu only. Changing a block's appearance from a plugin — classes on the block wrapper, and per-block DOM kept out of the editable region — is a separate change, because the two are different concerns with different hazards (see the deferred section in `design.md`). + +This is the second of three changes that replace the Block Tune entity with plugins (see the review on [PR #157](https://github.com/editor-js/document-model/pull/157)): +1. `plugin-block-data`: the data layer. +2. **`block-settings-ui`** (this change): the UI surfaces. +3. `remove-block-tunes`: deleting the old entity. + +This change doesn't depend on `plugin-block-data`: the built-in block settings items need no per-block data. Plugins that do store data combine the two. + +It **does** assume `test/editorjs-e2e-and-aria-openspec` has merged, since it builds on that branch's `messages.ts`, toolbar ARIA/keyboard behavior, Playwright harness and `@editorjs/ui-kit` 2.x. + +## What Changes + +- **Block settings plugin.** The new `BlockSettingsUI` (`name: 'block-settings'`) renders a per-block settings popover. Its `publicApi` lets any plugin register a settings provider: a function called with the target block's context each time the menu opens, returning a `BlockSettingsMenuConfig` with `onActivate`/`confirmation` declared inside it (the same model as `InlineTool#getToolbarConfig`). +- **Toolbar settings button.** `BlockSettingsUI` renders the button that opens its menu and announces it together with the menu; `ToolbarUI` mounts both next to the plus button, treats the button as a control of its roving tabindex, and doesn't reposition while settings are open. The button's own name and state belong to the plugin, because `aria-expanded` has to track a menu whose open state only the plugin knows. +- **Built-in block settings items as a plugin.** The new package `@editorjs/default-block-settings-plugin` (`name: 'default-block-settings'`) provides Move up, Move down, and Delete with a confirmation state (as in v2) through the block-settings API and `BlocksAPI.move`/`delete`. +- **Bundle.** `@editorjs/editorjs` registers `BlockSettingsUI` and `DefaultBlockSettingsPlugin` by default. +- **Types.** `@editorjs/ui` exports the settings API types and augments `EditorjsPluginApiMap`; `sdk` gains only a `UiComponentType.BlockSettings` member for the new plugin's static `type`. +- **Accessibility.** The settings button takes an accessible name from `messages.ts`, reports `aria-haspopup`/`aria-expanded`, is focused before the popover opens, and participates in the toolbar's roving tabindex; the popover itself is named. +- **Test infrastructure.** `packages/ui` gets a Jest (jsdom) setup and a CI workflow, since it has neither today. + +## Capabilities + +### New Capabilities + +- `block-settings`: the per-block settings popover and the plugin-facing registration API for its items. + - *Intended Purpose (paste into the folded spec, since archive writes a `TBD` placeholder):* "The block settings menu (the \"tunes\" menu in v2) is a UI surface that any plugin can add items to; it is not tied to a special entity type. This capability owns the `BlockSettingsUI` plugin, the button that opens it for the selected block, and the `publicApi` through which plugins register settings providers that return `BlockSettingsMenuConfig` items for a given block. The toolbar that hosts the button and the block rendering it builds on live in [[ui]], and cross-plugin access in [[plugin-public-api]]." +- `default-block-settings-plugin`: the built-in Move up / Move down / Delete settings, implemented as a plugin. + - *Intended Purpose:* "`@editorjs/default-block-settings-plugin` supplies the default block settings entries — moving a block up or down and deleting it after confirmation — by registering a provider with [[block-settings]] and calling `BlocksAPI.move`/`delete` from [[core]]. It is the reference example of a \"tune\" built as a plain plugin, and is registered by the [[editorjs-bundle]]." + +### Modified Capabilities + +- `ui`: `ToolbarUI` mounts the settings button and the menu that `BlockSettingsUI` announces, keeps that button in its roving tabindex, and reassigns its single tab stop once the button joins. `BlocksUI` also reports the selected block for a caret move, not only for pointer entry. +- `editorjs-bundle`: the default composition includes `BlockSettingsUI` and `DefaultBlockSettingsPlugin`. + +## Impact + +- **Packages:** `ui`, `editorjs`, the new `packages/plugins/default-block-settings-plugin`, and one enum member in `sdk`. `core` is untouched: the target block's id comes from `api.blocks.getIdByIndex`. +- **CI:** new workflows for `packages/ui` and the new plugin package; `include-e2e` enabled for the bundle. +- **Not breaking:** everything here is new API surface. +- **From PR #157:** its toolbar settings button, styles, popover wiring and `BlockTunes*UIEvent` classes are ported (renamed to `BlockSettings*`), along with the behavior and tests of its internal delete/move-up/move-down tunes. Its `BlockTunesManager` and `BlockTuneAdapter` are not ported. +- **Docs to update:** `docs/plugins.md` (the block settings API and default-block-settings as the reference "tune"), and `docs/events.md` (the `ui:block-settings:*` events). diff --git a/openspec/changes/block-settings-ui/specs/block-settings/spec.md b/openspec/changes/block-settings-ui/specs/block-settings/spec.md new file mode 100644 index 00000000..249254d0 --- /dev/null +++ b/openspec/changes/block-settings-ui/specs/block-settings/spec.md @@ -0,0 +1,139 @@ +## ADDED Requirements + +### Requirement: Block settings plugin +The system SHALL provide `BlockSettingsUI`, an `EditorjsPlugin` with static `name` `block-settings`, that renders a per-block settings popover **and the button that opens it**. Both SHALL be announced together via `ui:block-settings:rendered` for a host to mount; the plugin SHALL NOT place them itself. The popover SHALL open when that button is activated, or on a `ui:block-settings:open` event targeting a block, and SHALL dispatch `ui:block-settings:opened` and `ui:block-settings:closed` when its open state changes. + +#### Scenario: Opening settings for a block +- **GIVEN** at least one settings provider is registered +- **WHEN** a `ui:block-settings:open` event targeting block index 2 is dispatched +- **THEN** the popover opens populated with the items the providers return for block 2, and `ui:block-settings:opened` is dispatched + +#### Scenario: Closing settings +- **GIVEN** the settings popover is open +- **WHEN** it is closed by the user, by an item with default close-on-activate, or by `api.plugins['block-settings'].close()` +- **THEN** `ui:block-settings:closed` is dispatched + +#### Scenario: No items for a block +- **GIVEN** every registered provider returns nothing for the target block +- **WHEN** settings are requested for that block +- **THEN** the popover is not opened + +#### Scenario: No target block +- **GIVEN** no block has been selected, so the requested index resolves to no block id +- **WHEN** block settings are requested +- **THEN** no provider is invoked, the popover is not opened, and no error is thrown + +### Requirement: Block settings button +The button `BlockSettingsUI` announces SHALL carry the whole menu-button contract, because the state it reports is the plugin's own: an accessible name from the UI package's message catalogue, `aria-haspopup="menu"`, and an `aria-expanded` kept in sync with whether the menu is open. Activating it SHALL focus it before opening the menu, so the popover has a control to return focus to when it closes. Activating it while the menu is already open SHALL close the menu instead of rebuilding it, as the menu button pattern requires: the control that opens a menu is also the control that dismisses it. This SHALL hold however the button is activated, pointer or keyboard, which means the state it reads cannot be captured from pointer events alone. The button SHALL also declare itself a non-submitting control, so that an editor mounted inside a form does not post it when the menu is opened. The plugin SHALL follow block selection to know which block the button acts on, and SHALL stop following it while the menu is open, so the open menu and the button cannot come to mean different blocks. + +#### Scenario: The button is announced with the menu +- **WHEN** `BlockSettingsUI` is constructed +- **THEN** `ui:block-settings:rendered` carries both the button and the element the menu renders into + +#### Scenario: The button names the menu it controls +- **WHEN** the button is inspected +- **THEN** it has an accessible name from the message catalogue, `aria-haspopup="menu"`, and `aria-expanded="false"` + +#### Scenario: The button reports the menu state +- **GIVEN** the button has opened the menu +- **THEN** its `aria-expanded` is `"true"`, and it holds focus +- **WHEN** the menu closes, by any route +- **THEN** its `aria-expanded` returns to `"false"` + +#### Scenario: The button closes the menu it opened +- **GIVEN** the button has opened the menu +- **WHEN** the button is activated again +- **THEN** the menu closes, `aria-expanded` returns to `"false"`, and no second menu is built + +#### Scenario: The menu is dismissed while a replacement is being built +- **GIVEN** the menu is open and another block's menu has been requested, whose providers have not returned +- **WHEN** the open menu is dismissed, by Escape or by a click outside +- **THEN** the requested menu does not open when its providers return, because a dismissal abandons a build in flight exactly as a programmatic close does + +#### Scenario: Selection moves while a menu is being built +- **GIVEN** a menu is being built for one block and its providers have not returned +- **WHEN** another block is reported as selected +- **THEN** that build is abandoned, rather than opening one block's actions beside another + +#### Scenario: The target does not move under an open menu +- **GIVEN** the menu is open for the block at index 0 +- **WHEN** another block is reported as selected and the menu is then closed and opened again +- **THEN** the menu built the second time is for the block selected after it closed, not one chosen while it was open + +### Requirement: Block settings menu is accessible +The settings popover SHALL carry an accessible name drawn from the UI package's message catalogue, in the same way the toolbox menu is named. Items removed from the menu SHALL leave the accessibility tree rather than remaining hidden but present. + +#### Scenario: Menu is named +- **WHEN** the block settings popover opens +- **THEN** it exposes an accessible name from the message catalogue, so a screen reader announces what the menu is + +#### Scenario: Removed items leave the tree +- **GIVEN** the menu is rebuilt for a different block with fewer items +- **WHEN** the previous items are removed +- **THEN** they are no longer reachable in the accessibility tree + +### Requirement: Settings provider registration +`BlockSettingsUI` SHALL expose a `publicApi` with `register(provider, options?)` that returns an unregister function. A provider SHALL be a function receiving `{ blockId, blockIndex, tool }` for the target block and returning a `BlockSettingsMenuConfig`, a promise of one, or `undefined`. In that context `blockId` identifies the block for as long as it exists, while `blockIndex` is only its position at the moment the menu was built, so an item's handler SHALL resolve the block's current position from `blockId` rather than reusing `blockIndex`. Providers SHALL be invoked each time the popover opens, and their results SHALL be concatenated in ascending `options.order` (default `0`, ties broken by registration order), with a separator between the contributions of different providers. Item behavior SHALL be taken entirely from the returned `BlockSettingsMenuConfig` (`onActivate`, `isActive`, `isDisabled`, `closeOnActivate`, `children`, or a `confirmation` object whose own handler runs on the second activation — a confirmation item carries no top-level `onActivate`). + +#### Scenario: Plugin contributes an item +- **GIVEN** a plugin calls `api.plugins['block-settings'].register(ctx => ({ title: 'Anchor', icon, onActivate: () => ... }))` +- **WHEN** block settings open for any block +- **THEN** an "Anchor" item is shown, and activating it calls the provider's `onActivate` + +#### Scenario: Provider opts out for a tool +- **GIVEN** a provider returns `undefined` when `ctx.tool` is `"image"` +- **WHEN** block settings open for an image block +- **THEN** that provider contributes no items and no separator + +#### Scenario: Item acts on the block it was built for +- **GIVEN** a provider returns an item whose `onActivate` resolves the block's position from `ctx.blockId` +- **WHEN** the document changes while the menu is open and the item is then activated +- **THEN** the action applies to that same block, because positions are resolved at activation rather than taken from `ctx.blockIndex` + +#### Scenario: Items reflect current state +- **GIVEN** a provider derives an item's `isActive` from state it reads when called (e.g. the block's data via `EditorAPI`) +- **WHEN** that state changes and settings are opened again +- **THEN** the item's active state reflects the new data + +#### Scenario: Ordering providers +- **GIVEN** provider A is registered with `order: 1000` before provider B with default order +- **WHEN** settings open +- **THEN** B's items are shown before A's + +#### Scenario: Unregistering a provider +- **GIVEN** a provider was registered and its returned unregister function is called +- **WHEN** settings open afterwards +- **THEN** that provider is not invoked + +#### Scenario: Item with confirmation +- **GIVEN** a provider returns an item with a `confirmation` config and no top-level `onActivate` +- **WHEN** the user activates the item +- **THEN** the item switches to its confirmation state, and only activating the confirmation runs the handler declared inside `confirmation` + +### Requirement: A failing provider costs only its own items +Providers are third-party code, and the open menu is the one place all of it runs, so no single provider SHALL be able to stop the menu from opening. A provider that throws, whose promise rejects, or that has not settled within a fixed timeout SHALL contribute nothing, SHALL be reported to the console so the plugin behind it can be identified, and SHALL leave no separator behind; every other provider's contribution is still built and shown. A contribution SHALL be discarded rather than rendered when a newer open request has started since it was asked for, or when the menu it was being built for has been closed in the meantime. + +#### Scenario: A provider throws +- **GIVEN** two providers are registered and the first throws when invoked +- **WHEN** block settings open +- **THEN** the menu opens with the second provider's items alone, with no separator for the first, and the failure is reported to the console + +#### Scenario: A provider's promise rejects +- **GIVEN** a provider returns a promise that rejects +- **WHEN** block settings open +- **THEN** it is skipped on the same terms as one that threw synchronously + +#### Scenario: A provider never settles +- **GIVEN** a provider returns a promise that never settles +- **WHEN** block settings open and the timeout elapses +- **THEN** the menu opens without that provider's items rather than never opening, and the timeout is reported to the console + +#### Scenario: A result arrives after a newer request +- **GIVEN** a provider is still working on the menu for one block when settings are requested for another +- **WHEN** the first request's providers finally return +- **THEN** their items are discarded, because the newer request owns the menu + +#### Scenario: The menu is closed while it is being built +- **GIVEN** settings were requested and a provider has not yet returned +- **WHEN** `api.plugins['block-settings'].close()` is called before it does +- **THEN** the menu does not open when the provider finally returns, because a close abandons a build in flight as well as an open menu diff --git a/openspec/changes/block-settings-ui/specs/core/spec.md b/openspec/changes/block-settings-ui/specs/core/spec.md new file mode 100644 index 00000000..01e085a7 --- /dev/null +++ b/openspec/changes/block-settings-ui/specs/core/spec.md @@ -0,0 +1,33 @@ +## MODIFIED Requirements + +### Requirement: EditorAPI surface +The system SHALL expose an `EditorAPI` aggregating `BlocksAPI` (insert/insertMany/delete/move/render/clear/getBlocksCount/getPluginData/updatePluginData/getToolByIndex), `SelectionAPI` (applyInlineTool, selectedBlocks), `DocumentAPI` (serialized data, onUpdate, insertData/removeData/modifyData, undo/redo), and `TextAPI` (insert/remove/format/unformat/getFragments/get) to tools, plugins, and adapters. + +`BlocksAPI` SHALL offer a reader for a single block's tool name, so that a caller needing one scalar about one block does not reach for `DocumentAPI.data` — which serializes every block, every text node and every inline fragment tree in the document, and would do so on each open of a menu. + +#### Scenario: Deleting with no block selected +- **GIVEN** no block is currently selected/no caret is set +- **WHEN** `BlocksAPI.delete()` or `move()` is called without an explicit index +- **THEN** it throws an error ("No block selected to delete" / "No block selected to move") + +#### Scenario: Splitting or converting with an unknown tool +- **GIVEN** a `splitBlock`/`convertBlock` call references a `dataKey` that doesn't exist, or a source/target tool that isn't registered +- **WHEN** the operation is attempted +- **THEN** it throws an error identifying the missing key or tool + +#### Scenario: Inserting a block with plugin data +- **GIVEN** `BlocksAPI.insert` is called with both `data` and `plugins: { anchors: { id: 'intro' } }` +- **WHEN** the block is added to the model +- **THEN** the serialized block carries both its tool data and that plugin data, each under its own key + +#### Scenario: Reading a block's tool name +- **GIVEN** a document whose block at index 1 was inserted with tool `header` +- **WHEN** `BlocksAPI.getToolByIndex(1)` is called +- **THEN** it returns `"header"` + +#### Scenario: Reading the tool name of a block that is not there +- **GIVEN** an index outside the document, or a negative one +- **WHEN** `BlocksAPI.getToolByIndex` is called with it +- **THEN** it returns `undefined` rather than throwing, matching `getIdByIndex` + +Implemented in `src/api/index.ts`, `src/api/BlocksAPI.ts`, `src/api/SelectionAPI.ts`, `src/api/DocumentAPI/DocumentAPI.ts`, `src/api/TextAPI.ts`, `src/components/BlockManager.ts`, validated by co-located `.spec.ts`/`.integration.spec.ts` files. diff --git a/openspec/changes/block-settings-ui/specs/default-block-settings-plugin/spec.md b/openspec/changes/block-settings-ui/specs/default-block-settings-plugin/spec.md new file mode 100644 index 00000000..65d96ca1 --- /dev/null +++ b/openspec/changes/block-settings-ui/specs/default-block-settings-plugin/spec.md @@ -0,0 +1,50 @@ +## ADDED Requirements + +### Requirement: Default block settings plugin +The system SHALL provide `@editorjs/default-block-settings-plugin`, an `EditorjsPlugin` with static `name` `default-block-settings` whose only runtime dependencies are `@editorjs/sdk` and `@codexteam/icons` (it takes `@editorjs/ui` as a devDependency, for `import type` alone, so that `api.plugins['block-settings']` typechecks without a runtime coupling). Once the editor is ready, it SHALL register a settings provider with `block-settings` at `order: 1000`, contributing "Move up", "Move down" and "Delete" items for every block. When no `block-settings` plugin is registered, it SHALL do nothing and SHALL NOT throw. + +#### Scenario: Items are contributed +- **GIVEN** `BlockSettingsUI` and `DefaultBlockSettingsPlugin` are both registered +- **WHEN** block settings open for a block in the middle of the document +- **THEN** "Move up", "Move down" and "Delete" items are shown after the items of providers with a lower order + +#### Scenario: Block settings absent +- **GIVEN** `DefaultBlockSettingsPlugin` is registered on a `Core` without `BlockSettingsUI` +- **WHEN** the editor becomes ready +- **THEN** no error is thrown and the plugin stays inert + +### Requirement: Moving a block from settings +"Move up" SHALL move the target block one index up via `api.blocks.move`, and "Move down" one index down. "Move up" SHALL be disabled for the first block and "Move down" for the last block, evaluated when the menu is built. Every action SHALL resolve the target block's current index from its id when the item is activated, not reuse the index captured when the menu opened, and SHALL do nothing when that lookup reports no such block (the block-index lookup returns `-1` rather than throwing). + +#### Scenario: Moving up +- **GIVEN** settings are open for the block at index 2 +- **WHEN** "Move up" is activated +- **THEN** `api.blocks.move({ fromIndex: 2, toIndex: 1 })` is performed and the block is now at index 1 + +#### Scenario: The document changed while the menu was open +- **GIVEN** settings are open for block `b1`, which was at index 2, and a collaborator then inserts a block above it +- **WHEN** "Move up" is activated +- **THEN** the index is resolved again from `b1`, so `b1` moves from index 3 to index 2 rather than a different block being moved + +#### Scenario: Target block is gone +- **GIVEN** settings are open for block `b1` and `b1` is removed, by a collaborator or an undo, while the menu is open +- **WHEN** "Move up", "Move down" or "Delete" is activated +- **THEN** nothing happens and no error is thrown + +#### Scenario: Boundary blocks +- **GIVEN** a document with three blocks +- **WHEN** settings open for the block at index 0, and later for the block at index 2 +- **THEN** "Move up" is disabled for index 0, and "Move down" is disabled for index 2 + +### Requirement: Deleting a block from settings +"Delete" SHALL require confirmation: activating it SHALL switch the item to a confirmation state, and only activating the confirmation SHALL delete the target block via `api.blocks.delete` by block id. + +#### Scenario: Confirming deletion +- **GIVEN** settings are open for block `b1` +- **WHEN** "Delete" is activated and then its confirmation is activated +- **THEN** block `b1` is removed from the document + +#### Scenario: Abandoning deletion +- **GIVEN** "Delete" was activated once and shows its confirmation state +- **WHEN** the popover is closed without activating the confirmation +- **THEN** no block is deleted diff --git a/openspec/changes/block-settings-ui/specs/editorjs-bundle/spec.md b/openspec/changes/block-settings-ui/specs/editorjs-bundle/spec.md new file mode 100644 index 00000000..709dd9d9 --- /dev/null +++ b/openspec/changes/block-settings-ui/specs/editorjs-bundle/spec.md @@ -0,0 +1,14 @@ +## MODIFIED Requirements + +### Requirement: Batteries-included editor entry point +The system SHALL provide `@editorjs/editorjs`, a package whose default export is an `EditorJS` class that composes `@editorjs/core` with a default set of tools, plugins, infrastructure, and UI so that a caller can construct a fully functional editor from configuration alone. + +#### Scenario: Default composition +- **GIVEN** a caller constructs `new EditorJS(config)` +- **WHEN** the instance is created +- **THEN** it registers the DOM adapter (`DOMAdapters`), collaboration (`CollaborationManager`), default block tool (paragraph), default inline tools (bold, italic, link), default plugins (clipboard, shortcuts, default block settings), and the default UI packages (including `BlockSettingsUI`) on the underlying `Core` before initialization + +#### Scenario: Delegates the engine to Core +- **GIVEN** `EditorJS` composes the editor +- **WHEN** it needs engine behavior (model, block rendering, `EditorAPI`, undo/redo) +- **THEN** it delegates to an internal `@editorjs/core` `Core` instance rather than reimplementing engine logic diff --git a/openspec/changes/block-settings-ui/specs/ui/spec.md b/openspec/changes/block-settings-ui/specs/ui/spec.md new file mode 100644 index 00000000..06b3dff1 --- /dev/null +++ b/openspec/changes/block-settings-ui/specs/ui/spec.md @@ -0,0 +1,154 @@ +## MODIFIED Requirements + +### Requirement: Floating toolbar +The system SHALL provide `ToolbarUI`, which renders a floating toolbar with a plus-button and an actions area, repositions itself to the selected block's offset on `ui:blocks:block-selected` (unless the Toolbox or block settings are open), and opens the Toolbox on plus-button click. It SHALL mount both elements announced via `ui:block-settings:rendered` into its actions area -- the menu, and the button that opens it as a control of the container in its own right -- and SHALL reassign its single tab stop once that button joins. + +#### Scenario: Repositioning on block selection +- **GIVEN** a `BlockSelectedUIEvent` is received and neither the Toolbox nor block settings are currently open +- **WHEN** `ToolbarUI` handles the event +- **THEN** the toolbar moves to the selected block's `offsetTop` + +#### Scenario: Opening the toolbox +- **GIVEN** the user clicks the toolbar's plus button +- **WHEN** the click is handled +- **THEN** `ToolbarUI` dispatches a `ToolboxOpenUIEvent` + +#### Scenario: Mounting an announced widget +- **GIVEN** a plugin announces a button and a menu element through `ui:block-settings:rendered` +- **WHEN** `ToolbarUI` handles the event +- **THEN** both are placed in its actions container, the button as a direct child of it, and exactly one control of the container carries `tabindex="0"` + +#### Scenario: Toolbar stays put while settings are open +- **GIVEN** block settings are open +- **WHEN** the pointer hovers a different block +- **THEN** the toolbar does not move until settings close + +Implemented in `src/Toolbar/Toolbar.ts`, `src/Toolbar/ToolbarRenderedUIEvent.ts`. + +### Requirement: Accessible floating toolbar +`ToolbarUI` SHALL expose its actions container with `role="toolbar"` and an accessible name distinguishing it from the inline toolbar. Its plus-button SHALL have an accessible name (`aria-label`) describing its action, sourced from the message catalogue, and SHALL advertise the menu it controls via `aria-haspopup="menu"`. A control contributed by another plugin SHALL carry its own name and state, set by the plugin that owns it. + +#### Scenario: Toolbar actions container has toolbar role +- **GIVEN** `ToolbarUI` has rendered its actions container +- **WHEN** the element is inspected +- **THEN** it has `role="toolbar"` and a non-empty `aria-label` + +#### Scenario: Plus-button has an accessible name +- **GIVEN** `ToolbarUI` has rendered the plus-button +- **WHEN** the element is inspected +- **THEN** it has a non-empty `aria-label` + +### Requirement: The block actions toolbar is a single tab stop +`role="toolbar"` declares that the group is reached once by `Tab` and navigated internally with the arrow keys; a browser does not provide that on its own. `ToolbarUI` SHALL therefore maintain a roving tabindex over its own controls — exactly one in the tab order at a time, moved by the horizontal arrow keys — and SHALL declare its `aria-orientation`. Only the container's own controls take part: the toolbox and block settings popovers render *inside* the actions container, and their menu items are navigated by `@editorjs/ui-kit`, so keys arriving from within them are left alone. + +The pattern covers the **unmodified** arrow keys only. `ToolbarUI` SHALL ignore an arrow key pressed with any modifier held, and SHALL NOT call `preventDefault()` on it. A modified arrow always belongs to something else, and a screen reader is the case that matters here: VoiceOver moves its cursor with VO+Right and VO+Left, which reach the page as `Control`+`Option`+arrow. Swallowing those traps a VoiceOver user on whichever control their cursor reached, since Safari focuses a control when the cursor lands on it. + +#### Scenario: Modified arrow keys are left to their owner +- **GIVEN** a control of the block actions toolbar holds focus +- **WHEN** an arrow key is pressed with `Control`+`Option`, `Meta`, or `Shift` held +- **THEN** the toolbar does not handle it and the event is not prevented +- **AND** an unmodified arrow key is still handled by the toolbar + +#### Scenario: Only one control is in the tab order +- **GIVEN** `ToolbarUI` has rendered its actions container +- **WHEN** its controls are inspected +- **THEN** exactly one of them has `tabindex="0"` and the rest have `tabindex="-1"` +- **AND** the container declares `aria-orientation` + +#### Scenario: Toolbox keyboard navigation is not intercepted +- **GIVEN** the toolbox has been opened from the plus-button +- **WHEN** the user presses a vertical arrow key inside the menu +- **THEN** the toolbox handles it and moves focus between menu items, unaffected by the toolbar's own arrow-key handling + +#### Scenario: Block settings keyboard navigation is not intercepted +- **GIVEN** block settings have been opened from the settings button +- **WHEN** the user presses a vertical arrow key inside the menu +- **THEN** the popover handles it and moves focus between menu items, unaffected by the toolbar's own arrow-key handling + +#### Scenario: Plus-button reports the toolbox state +- **GIVEN** the toolbox is closed +- **WHEN** the plus-button is inspected +- **THEN** it has `aria-haspopup="menu"` and `aria-expanded="false"` +- **WHEN** the plus-button is activated and the toolbox opens +- **THEN** its `aria-expanded` becomes `"true"` +- **WHEN** the toolbox is dismissed +- **THEN** its `aria-expanded` returns to `"false"` + +#### Scenario: A contributed control joins the tab order +- **GIVEN** a plugin has announced a button through `ui:block-settings:rendered` +- **WHEN** the toolbar's controls are inspected +- **THEN** that button is one of them, reachable by the arrow keys, and exactly one control carries `tabindex="0"` + +### Requirement: Blocks holder rendering and input capture +The system SHALL provide `BlocksUI`, which renders the contenteditable blocks holder, adds/removes block wrappers on `core:BlockAdded`/`core:BlockRemoved`, captures native `beforeinput` and remaps it into a normalized `BeforeInputUIEvent`, delegates native `keydown` as a `KeydownUIEvent` so plugins can claim keyboard shortcuts, handles undo/redo keyboard shortcuts for keys no plugin claimed, and dispatches block selection events. + +Selection SHALL be dispatched both when the pointer enters a block and when the caret moves into one. Pointer entry alone leaves every control that acts on "the selected block" inert for a user who never moves a mouse, and the toolbar carries such controls. The caret is read from the document selection rather than from the editor's own caret state, which is cleared as soon as focus leaves the editable -- which is what reaching for a toolbar control does. + +Only caret movement SHALL be filtered for repeats, because `selectionchange` fires for every keystroke and most of those stay inside one block. Pointer entry SHALL always be dispatched: `mouseenter` only fires on actually crossing into a block, so there is nothing repeated to suppress, and a listener that ignored the previous announcement -- as the toolbar and the settings menu both do while the menu is open -- must still be told when the pointer comes back to a block it was last told about. + +#### Scenario: Inserting a block wrapper at an index +- **GIVEN** a `BlockAddedCoreEvent` with a valid index +- **WHEN** `BlocksUI` processes it +- **THEN** the block element is wrapped and inserted at that position in the blocks holder, or appended if the index is beyond the current list + +#### Scenario: Rejecting an invalid block index +- **GIVEN** a `BlockAddedCoreEvent`/`BlockRemovedCoreEvent` with an out-of-bounds index +- **WHEN** `BlocksUI` processes it +- **THEN** it throws an "Index out of bounds" error + +#### Scenario: Hovering a block dispatches selection +- **GIVEN** the pointer enters a rendered block element +- **WHEN** the `mouseenter` event fires +- **THEN** `BlocksUI` dispatches a `BlockSelectedUIEvent` carrying the block and its index + +#### Scenario: The caret moving into a block dispatches selection +- **GIVEN** the caret is placed in a rendered block, by click or by keyboard +- **WHEN** the document selection changes to a position inside that block +- **THEN** `BlocksUI` dispatches a `BlockSelectedUIEvent` carrying the block and its index, so a keyboard-only user has a selected block without ever moving the pointer + +#### Scenario: Re-entering the block that was last reported +- **GIVEN** the pointer was last reported as entering a block, and the menu that was open at the time has since been dismissed +- **WHEN** the pointer enters that same block again +- **THEN** `BlockSelectedUIEvent` is dispatched again, because anything that ignored the first announcement would otherwise keep acting on an older block + +#### Scenario: The caret staying in one block dispatches nothing +- **GIVEN** the caret is already in a block +- **WHEN** it moves within that same block, as it does on every keystroke +- **THEN** no further `BlockSelectedUIEvent` is dispatched + +#### Scenario: A selection outside every block dispatches nothing +- **GIVEN** the document selection moves to a node that is in no block +- **WHEN** the selection change is handled +- **THEN** no `BlockSelectedUIEvent` is dispatched, and the last reported selection stands + +#### Scenario: Normalizing beforeinput +- **GIVEN** a native `beforeinput` event fires on the blocks holder +- **WHEN** `BlocksUI` intercepts it +- **THEN** the default action is prevented and a `BeforeInputUIEvent` is dispatched carrying `data`, `inputType`, `isComposing`, and `targetRanges`, distinguishing native-input vs. contenteditable sources and cross-input selections + +#### Scenario: Delegating native keydown events +- **GIVEN** a native `keydown` event fires on the blocks holder +- **WHEN** `BlocksUI` intercepts it +- **THEN** it dispatches a `KeydownUIEvent` on the `EventBus` carrying the native event as `nativeEvent`, before any of its own key handling + +#### Scenario: A plugin claims a keyboard shortcut +- **GIVEN** a plugin listening for `KeydownUIEvent` calls `preventDefault()` on the native event +- **WHEN** the dispatch returns +- **THEN** `BlocksUI` performs no further handling for that key, so a plugin-registered shortcut takes precedence over the built-in handling + +#### Scenario: Undo/redo keyboard shortcuts +- **GIVEN** the blocks holder has focus and no plugin claimed the key +- **WHEN** Cmd/Ctrl+Z is pressed +- **THEN** `api.document.undo()` is called with the default action prevented; if Shift is also held, `api.document.redo()` is called instead + +#### Scenario: Delegating native copy events +- **GIVEN** a native `copy` event fires on the blocks holder +- **WHEN** `BlocksUI` intercepts it +- **THEN** it dispatches a `CopyUIEvent` on the `EventBus` carrying the native event as `nativeEvent`, without calling `preventDefault` itself + +#### Scenario: Destroying the blocks UI +- **GIVEN** `BlocksUI` has rendered the blocks holder +- **WHEN** `destroy()` is called +- **THEN** the `beforeinput`, `keydown` and `copy` listeners are removed from the blocks holder, so native events on it no longer dispatch `BeforeInputUIEvent`, `KeydownUIEvent` or `CopyUIEvent`, the `selectionchange` listener is removed from the document, and the blocks holder is detached from the DOM + +Implemented in `src/Blocks/Blocks.ts`, `src/Blocks/events/*`, validated by `src/Blocks/Blocks.spec.ts`. diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md new file mode 100644 index 00000000..eab6903a --- /dev/null +++ b/openspec/changes/block-settings-ui/tasks.md @@ -0,0 +1,103 @@ +## 0. Preconditions + +- [x] 0.1 Confirm `test/editorjs-e2e-and-aria-openspec` is merged into `main` and rebase onto it. It supplies `packages/ui/src/messages.ts`, the toolbar's ARIA/roving-tabindex behavior, the Playwright harness and `@editorjs/ui-kit` 2.x. If it has not landed, stop and re-plan + - Landed as #187 (squash-merged; the branch is deleted). Verified on `main`: `packages/ui/src/messages.ts`, the Playwright harness under `packages/editorjs/e2e/` with `playwright.config.ts` and `playwright.voiceover.config.ts`, `@editorjs/ui-kit` `^2.0.0` in `packages/ui/package.json`, and the ARIA requirements in `openspec/specs/ui/spec.md` +- [x] 0.2 Refresh this change's `specs/ui/spec.md` delta from the merged `openspec/specs/ui/spec.md`, so the `Floating toolbar` requirement keeps that branch's ARIA scenarios instead of reverting them at archive time + - The feared revert never applied: #187 put its ARIA work in **separate** requirements (`Accessible floating toolbar`, `The block actions toolbar is a single tab stop`), not into `Floating toolbar` + - The delta now modifies all three, each header matching the merged spec verbatim. `Floating toolbar` keeps both merged scenarios and only widens the repositioning clause to "unless the Toolbox or block settings are open"; the settings button's ARIA assertions moved to the two requirements that own that vocabulary, each sitting beside the plus-button scenario it mirrors + - Dropped the delta's own `Scenario: The toolbar keeps exactly one tab stop`: the merged `Scenario: Only one control is in the tab order` already asserts exactly-one-`tabindex="0"` across *all* of the container's controls, the settings button included + - Added `Scenario: Block settings keyboard navigation is not intercepted`, mirroring the toolbox one — the settings popover is the second thing rendering inside the actions container whose arrow keys the toolbar must leave alone +- [x] 0.3 Resolve the "block actions" collision before writing any of it + - **Resolved by renaming the plugin, not the toolbar.** `main` ships `messages.blockActionsToolbar = 'Block actions'` as the actions container's accessible name, asserted by `aria.spec.ts` in two places, relied on by `voiceover.spec.ts`, documented in the e2e README's locator table, and carried in the requirement name `The block actions toolbar is a single tab stop`. The plugin is still only spec text, so it is far the cheaper side to move + - `@editorjs/block-actions-plugin` → `@editorjs/default-block-settings-plugin`, `static name` `block-actions` → `default-block-settings`, class `BlockActionsPlugin` → `DefaultBlockSettingsPlugin`, capability `block-actions-plugin` → `default-block-settings-plugin` + - Rejected `block-operations` (`Operation`, `OperationsTransformer` and `ModifyOperationData` already own that word in `collaboration-manager`) and `block-controls` (the roving-tabindex requirement calls the container's children "controls" throughout). The chosen name states the plugin's actual role: the default entries of the block settings menu + - Every surviving "block actions" in this change refers to the toolbar container and must stay verbatim, or the archive fold stops matching the merged requirement + +## 1. UI test setup + +- [ ] 1.1 Add Jest to `packages/ui`: `jest.config.ts` with `testEnvironment: 'jsdom'`, a `moduleNameMapper` for `\.pcss$` and the `@codexteam/ui/styles*` side-effect imports, `transformIgnorePatterns` covering `@codexteam/*` as well as `@editorjs/*`, and the `test`/`test:coverage` scripts using `node --experimental-vm-modules` +- [ ] 1.2 Add the dev dependencies: `jest`, `jest-environment-jsdom` (no package uses jsdom yet, so it must be explicit), `ts-jest`, `babel-jest`, `@babel/core`, `@babel/preset-env`, `@jest/globals`, `@types/jest`, `ts-node` +- [ ] 1.3 Add a `files: ['**/*.spec.ts']` override to `packages/ui/eslint.config.mjs` allowing `@jest/globals`, mirroring `packages/core/eslint.config.mjs`, or `yarn lint` fails on the new specs +- [ ] 1.4 Point `vite.config.ts`'s `dts()` at `tsconfig.build.json` so declaration emit keeps excluding `*.spec.ts` +- [ ] 1.5 Add `.github/workflows/ui.yml` following `.github/workflows/core.yml`, and handle the first-run `base-coverage` step, which checks out the base ref and runs `test:coverage` for a package that has no such script there +- [ ] 1.6 Hand-edit the note in `openspec/specs/ui/spec.md`'s preamble that says the package has no automated test suite — it sits outside any `### Requirement:` block, so the archive fold will not rewrite it + +## 2. Block settings plugin + +- [ ] 2.1 Port the `BlockTunes*UIEvent` classes from PR #157 as `BlockSettings{Open,Opened,Closed,Rendered}UIEvent` under `ui/src/BlockSettings/events`, using `ui:block-settings:*` names. Credit ported work with `Co-authored-by: Betty Steger <244475+bettysteger@users.noreply.github.com>` +- [ ] 2.2 Write failing `BlockSettings.spec.ts` cases: + - the target block's id should be resolved from the reported index via `api.blocks.getIdByIndex` + - providers should be called with `{ blockId, blockIndex, tool }` on each open + - results should be ordered by `order` then registration, with separators between providers + - `undefined`/empty results should contribute nothing + - unregister should work + - no popover should open when there are no items + - `close()` should dispatch closed + - the context handed to providers should carry `blockId`, and the spec's rule that handlers resolve positions from it should be covered by the default-block-settings tests +- [ ] 2.3 Add a `UiComponentType.BlockSettings` member in `sdk` and declare it as `BlockSettingsUI`'s `static type` (`EditorjsPluginConstructor` requires an `EntityType` value) +- [ ] 2.4 Implement `BlockSettingsUI` (`static name = 'block-settings'`, `publicApi: { register, close }`) on a ui-kit popover, porting its setup from PR #157's `BlockTunesUI` (`scopeElement: config.holder`, `searchable: false`, `wrapperTag: 'button'`, closed event from `PopoverEvent.Closed`, element handed over via the rendered event) +- [ ] 2.5 Write failing tests, then give the popover an accessible name from a new `messages.ts` entry, and make removed items leave the accessibility tree +- [ ] 2.6 Write a failing test, then make a request with no resolvable block id a no-op (no providers invoked, no popover, no throw) +- [ ] 2.7 Export `BlockSettingsUI` plus the `BlockSettingsAPI`/`BlockSettingsProvider` types from `@editorjs/ui`, and augment `EditorjsPluginApiMap` under `'block-settings'` there — `sdk` stays unaware of individual plugins + +## 3. Toolbar settings button + +- [ ] 3.1 Port the settings button styles from PR #157 (`IconMenuSmall`, the `__settings-button` rule, and `display: flex; align-items: center` on `__actions`). The button itself is rendered by `BlockSettingsUI` and announced with the menu, so `ToolbarUI` mounts it **before** the roving-tabindex initialization and reassigns its single tab stop once it joins +- [ ] 3.2 Take PR #157's fix for `new ToolboxOpenUIEvent('ui:toolbox:open')` passing a string instead of a payload object (`packages/ui/src/Toolbar/Toolbar.ts:151`), with a test that the dispatched event carries an object payload +- [ ] 3.3 Track the selected block index in `BlockSettingsUI` from `ui:blocks:block-selected` (the toolbar's handler reads only `event.detail.block`), following `ToolboxUI`'s `#selectedBlockIndex`. It belongs to the plugin that owns the button, so the button and the menu cannot come to mean different blocks +- [ ] 3.4 Write failing cases, in `Toolbar.spec.ts` for what the toolbar owns and in `BlockSettings.spec.ts` for what the plugin owns: + - both announced elements should be mounted on `ui:block-settings:rendered`, the button as a direct child of the actions container + - the toolbar should not reposition while settings are open + - exactly one control of the actions container should have `tabindex="0"` after the button joins + - the settings button should have an accessible name from `messages.ts` and `aria-haspopup="menu"` + - `aria-expanded` should follow the plugin's own open state + - the button should be focused before the popover opens + - activating the button again should close the menu rather than rebuild it +- [ ] 3.5 Implement the behavior, splitting it as above: mounting, positioning and the tab stop in `ToolbarUI`, the button and its state in `BlockSettingsUI` + +## 4. Default block settings plugin + +- [ ] 4.1 Scaffold `packages/plugins/default-block-settings-plugin` as a full copy of `shortcuts-plugin`'s layout: `package.json` (the same `build`/`build:declaration`/`lint`/`lint:ci`/`lint:fix`/`test`/`test:coverage`/`test:mutations`/`clear` scripts), `tsconfig.json`, `tsconfig.build.json`, `tsconfig.eslint.json`, `eslint.config.mjs`, `jest.config.ts`, `stryker.conf.mjs`, `.gitignore`, `README.md`, `src/index.ts`, `src/index.spec.ts` +- [ ] 4.2 Add `.github/workflows/default-block-settings-plugin.yml` following `shortcuts-plugin.yml` — without it the package is never linted, tested or built in CI +- [ ] 4.3 Depend on `@editorjs/sdk` at runtime and on `@editorjs/ui` as a devDependency for `import type` only, so `api.plugins['block-settings']` typechecks without runtime coupling +- [ ] 4.4 Write failing tests: + - should register at `order: 1000` on `core:ready` + - should stay inert without `block-settings` + - move up/down should call `api.blocks.move` and be disabled at the boundaries + - handlers should resolve the block's index from `ctx.blockId` at activation, so an insertion above the block while the menu is open still moves the intended block + - actions should do nothing when the target block no longer exists + - delete should use `confirmation` and call `api.blocks.delete` by block id only on confirm +- [ ] 4.5 Implement `DefaultBlockSettingsPlugin`, porting behavior and test cases from PR #157's internal delete/move-up/move-down tunes (keeping their `getIndexById`-at-activation approach) and adding the delete confirmation they lack. Credit with the `Co-authored-by` line from 2.1 +- [ ] 4.6 Register `BlockSettingsUI` and `DefaultBlockSettingsPlugin` in `@editorjs/editorjs`: add `"@editorjs/default-block-settings-plugin": "workspace:^"` to its `package.json`, update the lockfile, extend the `@editorjs/ui` mock factory in `editorjs/src/index.spec.ts` with `BlockSettingsUI`, add a `jest.unstable_mockModule` for the new package, and note that its assertions read `ctor.name` — which for `static name = 'default-block-settings'` is `'default-block-settings'`, not the class name +- [ ] 4.7 Hand-edit `openspec/specs/editorjs-bundle/spec.md`'s Purpose preamble, which enumerates the default plugins — outside any requirement block, so the fold will not rewrite it +- [ ] 4.8 Add `packages/editorjs/e2e/tests/block-settings.spec.ts` using the harness's `mountDocument(page, '?text=Alpha&text=Beta')` fixture: open settings on the second block, move it up, then delete it with confirmation. Confirm `include-e2e: true` is set for the bundle workflow + +## 5. Docs and wrap-up + +- [ ] 5.1 Update `docs/plugins.md` (the block settings API and default-block-settings as the reference "tune") and `docs/events.md` (the `ui:block-settings:*` events) +- [ ] 5.2 Run `yarn lint`, `yarn test`, and the e2e suite. Fix any regressions +- [ ] 5.3 Run `openspec validate block-settings-ui --type change` and confirm it passes. After archiving, fill the `## Purpose` of the new `block-settings` and `default-block-settings-plugin` specs from the proposal's intended-Purpose text + +## 6. Review follow-ups + +- [ ] 6.1 Write a failing `Blocks.spec.ts` case, then dispatch `BlockSelectedUIEvent` for the caret moving into a block as well as for `mouseenter`. Without it `#selectedBlockIndex` stays `-1` for anyone who never moves a pointer, and the settings button is a control that silently does nothing. Read the caret from the document selection: the editor's own caret state is cleared when focus leaves the editable, which is what reaching for the button does +- [ ] 6.2 Write a failing case, then make the settings button close an open menu instead of rebuilding it, per the menu button pattern. ui-kit closes the popover before the button's own handler runs, so the state has to be read on `mousedown` and tracked by the plugin. Cover it in the e2e suite too, since what is being asserted is a second real click +- [ ] 6.3 Add `getToolByIndex` to `BlocksAPI` (core + sdk) and read the provider context's `tool` through it. `api.document.data` serializes the whole document, and the menu was paying that on every open +- [ ] 6.4 Replace the two `api.document.data.blocks.length` reads in `DefaultBlockSettingsPlugin` with `api.blocks.getBlocksCount()`, for the same reason +- [ ] 6.5 Rename the UI package's `MenuConfig` to `BlockSettingsMenuConfig`: `@editorjs/sdk` already exports an unrelated `MenuConfig`, and the two are not interchangeable +- [ ] 6.6 Make `BlockSettingsUI`, `DefaultBlockSettingsPlugin` and `ToolbarUI` drop their event bus listeners in `destroy()`, and stop the plugin registering a provider after it has been destroyed +- [ ] 6.7 Restore `packages/ui`'s `build:declaration` to a script that emits declarations, now that it has dependencies to build first + +## 7. Review follow-ups (second round) + +- [ ] 7.1 Write a failing `BlockSettings.spec.ts` case for a provider whose promise never settles, then race each provider against a timeout and route the expiry into the existing skip-and-log path. `#collectItems` awaits `Promise.all`, so one hanging provider means the menu never opens — and never opens again, because every later attempt waits on the same provider +- [ ] 7.2 Write a failing case, then make `#close()` abandon a build in flight by bumping `#openToken` before its open-state guard. A `close()` during the build window is currently ignored, because `#isOpen` is only set once the providers have returned, and the menu then opens after the close +- [ ] 7.3 Reconcile `design.md` with the specs on who owns the settings button: the specs and the code give the button, its ARIA state and the block it acts on to `BlockSettingsUI`, while the design doc still has `ToolbarUI` owning them and dispatching `ui:block-settings:open`. Rename its remaining `MenuConfig` references to `BlockSettingsMenuConfig` + +## 8. Review follow-ups (third round) + +- [ ] 8.1 Write a failing case, then abandon a build in flight from `#handleClosed` as well as `#close()`. Escape and a click outside reach it straight from the popover, so a menu dismissed while a replacement was being built reappeared when that replacement's providers returned +- [ ] 8.2 Write a failing case, then abandon a build when the selection leaves the block it is for. `#isOpen` is false until the providers return, so selection is still being followed, and the build would open one block's actions beside another +- [ ] 8.3 Write a failing case, then record the toggle's state on the `keydown` of Enter and Space as well as on `mousedown`. A keyboard activation sends a `click` with no pointer events, so the snapshot always said "closed". Note in the PR that the browser path is blocked earlier: ui-kit's flipper calls `preventDefault()` on that Enter, so no click is produced at all and the menu cannot be dismissed from the button — that half belongs upstream +- [ ] 8.4 Give the settings button `type="button"`, so an editor mounted inside a form is not submitted when the menu opens +- [ ] 8.5 Write a failing `Blocks.spec.ts` case, then stop deduplicating pointer entry, keeping it for caret moves. `mouseenter` only fires on crossing into a block, and suppressing a repeat stranded the toolbar and the settings menu, which both ignore selection while the menu is open diff --git a/openspec/changes/plugin-block-data/.openspec.yaml b/openspec/changes/plugin-block-data/.openspec.yaml new file mode 100644 index 00000000..563fab5a --- /dev/null +++ b/openspec/changes/plugin-block-data/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-09-21 diff --git a/openspec/changes/plugin-block-data/design.md b/openspec/changes/plugin-block-data/design.md new file mode 100644 index 00000000..0d873bb4 --- /dev/null +++ b/openspec/changes/plugin-block-data/design.md @@ -0,0 +1,130 @@ +## Context + +The Model already stores per-block extra data: a `BlockTune` entity in `BlockNode.#tunes`, `TuneIndex` (`k: "tune"`), and `TuneModifiedEvent`. Above the Model it is dead-ended: +- `BlockNode.updateTuneData` indexes `this.#tunes[name]` directly, so writing a tune that isn't already present crashes. +- `BlocksAPI` has no method for tune data, and `BlockManager.insert` has `tunes` commented out. +- `EditorDocument.modifyData` only handles `TextIndex`, so undo of a tune change is a silent no-op. +- `CollaborationManager.#handleEvent` has no case for `TuneModifiedEvent` ("Unknown event type"). + +This change turns that store into plugin-owned data. It is the data layer of the "tunes as plugins" effort. `block-settings-ui` adds the UI surfaces and `remove-block-tunes` deletes the SDK tune kind. Constraint: tools and plugins depend only on `@editorjs/sdk`, which re-exports the renamed types. + +## Goals / Non-Goals + +**Goals:** +- Per-block plugin data that is created on first write and readable/writable through `BlocksAPI`. +- Plugin data changes are undoable locally and synchronized through OT. +- Remove "tune" from the Model's vocabulary and wire format. +- Carry v2 `tunes` data into v3 `plugins` when a v2 document is loaded. + +**Non-Goals:** +- Any UI: the settings menu and block decoration are `block-settings-ui`. +- Removing the SDK `BlockTune` tool contract: that is `remove-block-tunes`. +- Rich or nested plugin data (text nodes, arrays with OT-aware element operations). Plugin data stays a flat key → JSON value map per plugin, as `BlockTune` data is today. See "Deferred: plugin data as a node tree" below for what taking this on would require. +- Runtime enforcement that a plugin writes only under its own name. +- The equivalent gap for `ValueModifiedEvent` in `modifyData`/`CollaborationManager`, although the new branch is structured so a value branch can sit next to it. + +## Decisions + +### D1. Plugin data is keyed by the plugin's static `name` +Each `BlockNode` holds `plugins: Record`, where `PluginDataName` is a nominal string and the key is by convention the owning plugin's `name`, the identity already used by `api.plugins` and the plugin type maps. +- *Why:* one identity for "who owns this" across registry, types and stored data, and no separate namespace to collide in. +- *Alternative:* free-form keys. Rejected, because it re-creates the tune-name namespace without an owner. +- The API takes `plugin` as an explicit parameter rather than handing each plugin a pre-scoped API, which keeps `BlocksAPI` a single shared object like the rest of `EditorAPI`. + +### D2. Flat, per-key updates with create-on-first-write +`PluginDataNode` keeps today's `BlockTune` semantics: a flat `Record` updated key by key, with one `PluginDataModifiedEvent` per changed key carrying `{ value, previous }`. +- `BlockNode.updatePluginData(name, data)` creates the node when it is missing. The node is created **empty**, its event listener is attached, and only then is each key applied — constructing it with initial data emits nothing (the constructor path relies on that), and `PluginDataNode.update` dispatches synchronously, so the listener must exist first. Without the listener the whole feature silently no-ops: no event reaches `EditorDocument`, so no undo record and no operation. `#createValueNode` is the precedent. +- Entries are held in a **null-prototype** record and the name must be non-empty. Names arrive from documents, and a plain assignment of a `__proto__` key creates no own property at all (while `Object.fromEntries`, used on load, does), so mixing the load and write paths would silently lose that plugin's data. `PluginRegistry` already solves this the same way. +- Setting a key to `undefined` removes it. A node with no keys is left out of the serialized block, so undoing a first write (value → `undefined`) restores the original serialized shape exactly. +- *Alternative:* a whole-object replace event. Rejected, because per-key events keep OT conflicts narrow: two users changing different keys of the same plugin don't collide. +- *Alternative:* explicit `createPluginData`/`removePluginData` operations. Rejected, because they add Insert/Delete OT cases for no user-visible benefit when the implicit form round-trips. + +### D3. Full rename rather than an alias +- `BlockTune` → `PluginDataNode`. +- `TuneIndex` → `PluginDataIndex` (`IndexKind.PluginData`; serialized `k: "plugin"`, `b`, `plugin`, `key`, `id`). +- `Index.tune` → `Index.pluginData`. +- `TuneModifiedEvent` → `PluginDataModifiedEvent`. +- `BlockTuneName`/`BlockTuneSerialized` → `PluginDataName`/`PluginDataSerialized`. +- `PartialIndex` `tuneName`/`tuneKey` → `pluginName`/`pluginKey`. +- The serialized block key `tunes` → `plugins`. + +*Why:* keeping `tune` inside the Model would preserve exactly the concept this effort removes, and v3 is pre-1.0. *Alternative:* keep the wire names and rename only in TypeScript. Rejected, because the wire format is what integrators see. + +### D4. Plugin data flows through the existing generic undo and OT paths +- `EditorJSModel.updatePluginData(userId, block, plugin, data)` replaces `updateTuneData` and keeps its `@WithContext` decoration, so the emitted events carry the acting user. +- `EditorDocument.modifyData(index, data)` gains a `PluginDataIndex` branch that calls `updatePluginData(blockIndex, plugin, { [key]: data.value })`. `UndoRedoManager` already inverts any `Modified` payload by swapping `value`/`previous`, so no undo-specific code is needed. +- `CollaborationManager.#handleEvent` maps `PluginDataModifiedEvent` → `Operation(Modify, index, { payload: value, prevPayload: previous })`. The apply path already routes `Modify` to `model.modifyData`. +- `OperationsTransformer` needs a `PluginDataIndex` branch in `#applyTransformation`, which dispatches on the *against* operation's index kind and throws for anything it doesn't recognize. This is the load-bearing part: a plugin-data operation becomes the against-op in `OTClient`'s pending-operation reduce, in `UndoRedoManager.transformStacks` for every remote plugin-data event, and in `ot-server`'s conflicting-operation reduce. Being *transformed* is already safe (the text and data branches bail out early), and shifting against block insert/delete already works, because `#transformAgainstBlockOperation` is index-agnostic and `withBlockIndex` is overridden. +- Two plugin-data operations targeting the same block, plugin and key are resolved the same way `#transformAgainstDataOperation` resolves two writes to one data key: the operation being transformed becomes `Neutral` when the one it is transformed against is the later of the two, an unsent local operation counting as later than any revision. Leaving them untransformed, as an earlier draft of this design did, diverges the client that holds an unsent write — it applies the incoming value and never re-applies its own, because its operation is not echoed back to it. +- *Known limits of that rule, both pre-existing and shared with plain data values, tracked on the board as "Concurrent same-key writes diverge clients and can wedge the OT server":* `OTClient` transforms incoming operations only against its queued ones, and an operation is removed from that queue when it is sent, so a write that is in flight is not considered; and `DocumentManager` has no `Neutral` case in its apply switch, so a third concurrent write to one key throws there. Neither is introduced here, but the second becomes reachable from plugin data once two plugin-data operations can neutralise each other. +- `ModifyOperationData` is typed `T extends Record`, so a boolean or string payload does not compile. It widens to unknown-ish JSON for plugin data. +- `BlockNode` currently re-emits the bubbled tune event with a hardcoded `userId: 'user'` instead of `getContext()`. It is masked at the facade level (`EditorJSModel` re-attaches the acting user from context) but wrong for anything listening on `BlockNode` or `EditorDocument`, so it is fixed here. + +### D5. `BlocksAPI` surface +- `getPluginData({ block, plugin }): T | undefined` returns the serialized entry. +- `updatePluginData({ block, plugin, data: Partial, userId? })` merges keys. +- `insert`/`insertMany` accept a `plugins` map. +- `move` already re-inserts the serialized block, so data is preserved. +- `split` keeps data on the original block and gives the new block none. +- `convert` carries plugin data over to the converted block. + +This is consistent with the existing `getData`/`updateValue` naming and parameter-object style. + +Both methods are typed through a new augmentable `EditorjsPluginDataMap` (D6). + +### D6. Plugin data is typed through a third augmentable map +`EditorjsPluginDataMap` (plugin id → stored data shape) joins `EditorjsPluginApiMap` and `ToolPluginOptionsMap`, and `PluginId` gains its keys. +- A declared id infers its shape in both `getPluginData` and `updatePluginData`; an undeclared id falls back to `Record`. +- The conditional is non-distributive (`[Id] extends [keyof ...]`), the same guard `PublicApiFor` uses, so the `string & {}` member of `PluginId` can't collapse a declared id to the fallback. +- *Why the fallback rather than `never`:* unlike `publicApi`, where `never` usefully forces a plugin to declare its `name`, plugin data is often written by a plugin that has no reason to publish its shape. Making that a compile error would be hostile. +- *Alternative:* a generic parameter the caller passes (`getPluginData(...)`). Rejected as the primary mechanism, because the shape then has to be restated at every call site, though the generic stays available. + +### D7. v2 conversion maps `tunes` onto `plugins` verbatim +`composeDataFromVersion2` currently drops `block.tunes`. It will map each entry into `plugins` under the same key. +- **Keys are preserved as-is.** A v3 plugin that replaces a v2 tune is expected to adopt that tune's name, which is also what makes the plugin data key match. No rename table. +- **Object data is copied key by key.** That is the shape a plugin entry already has. +- **An all-empty `plugins` map is still emitted** (as `{}`), matching how `serialized` treats `tunes` today; only individual empty entries are dropped. A block loaded without a `plugins` key therefore gains `plugins: {}` on serialization — which is why D2's round-trip guarantee is about entries, not about byte-identical output. +- **A primitive or an array is stored under the key `value`.** v2 tune data is `any`, and plugin entries are key/value maps, so a scalar needs a key. `value` is predictable and documented, and it beats dropping the data or refusing the document. +- **Data for an unregistered plugin is kept**, which follows from the store's preservation rule (D8), so loading a v2 document in an editor missing that plugin doesn't lose anything. +- *Alternative:* a config-level migration hook so integrators map names themselves. Rejected as the default: it would make the common case (same name) require configuration. It can be added later if renames turn out to be common. + +### D8. Data for unregistered plugins is preserved verbatim +A `plugins` entry whose plugin isn't registered in this editor is loaded, kept and re-serialized unchanged. +- *Why:* in a collaborative document, clients can legitimately run different plugin sets. Dropping unknown entries would let the client with fewer plugins silently delete another client's data. +- *Trade-off:* data for a plugin that has been removed for good lingers in the document. Cleaning that up is an integrator concern, not the editor's. + +## Risks / Trade-offs + +- **[Breaking wire format: `tunes` → `plugins`, `k: "tune"` → `k: "plugin"`]** → v3 is pre-1.0 and tune data has never been writable end to end, so no real stored data is expected. Call it out in the PR description — the repo keeps no changelog files. Clients and `ot-server` must deploy together, since the server applies operations against its own model. +- **[Plugins can write another plugin's data]** → by convention only, documented. A scoped, typed accessor can be added later without breaking the explicit-`plugin` API. +- **[Concurrent modify on the same key resolves to one of the two values, not a merge]** → fine for toggles and scalars. Plugins that need merge semantics split state across keys. +- **[Undo loses a local write that a collaborator has since overwritten]** → the stacked entry is transformed against the remote operation like any other and becomes `Neutral`, so it is dropped from the stack rather than replayed as a stale value. Undo therefore skips past that write instead of undoing it. Accepted: reverting to a value a collaborator has already replaced is worse than not offering the step. +- **[A multi-key `updatePluginData` is not one undo step]** → both history managers refuse to batch `Modified` events, so writing two keys in one call creates two undo steps and one undo reverts only the last key. Accepted for now: plugins that need atomicity write one key, or the batching rules change in a later change. +- **[`BlocksAPI.insert` currently drops block data]** → `BlocksManager.insert` spreads `{ ...data, id, name }` while `BlockNode` reads a nested `data` key, so `insert({ data })` creates an empty block today. Adding `plugins` to the same spread would inherit the bug, so the nesting is fixed as part of this change. + +## Migration Plan + +1. Model-types rename, then the Model behavior (create-on-first-write, key removal, `modifyData`). +2. `BlocksAPI`/`BlockManager` wiring and the undo integration test. +3. Collaboration mapping and transform rules. +4. The `EditorjsPluginDataMap` typing and the v2 converter mapping. + +All of this lands in one PR, since the format break must be atomic. Rollback is reverting the PR. + +## Deferred: plugin data as a node tree + +Making plugin data a real node tree (value nodes, text nodes, arrays) would let a plugin hold rich text — a footnote body, for example — with character-level collaboration instead of last-writer-wins on a whole string. It is deliberately out of scope here. The investigation, so it doesn't have to be redone: + +The Model machinery is already generic: `BlockNode#mapSerializedDataToNodes` builds value/text nodes from arbitrary nested JSON, keyed by a dot-path `DataKey`, and picks the node kind from the `$t` (`NODE_TYPE_HIDDEN_PROP`) marker. Two arrangements are possible: +- **One tree, reserved namespace:** plugin data lives in the block's own data tree under a reserved root key (`plugins.anchors.note`), split out only at serialize time. Plugin text is then addressed by an ordinary `DataIndex`/`TextIndex`, so carets, OT text rules, inline formatting and `InputsRegistry` (keyed by `(blockId, dataKey)`) work unchanged. The preferred option. +- **Separate tree, plugin-scoped indexes:** `PluginDataIndex` grows a keypath and a text-range variant. Cleaner separation, but roughly doubles the index/OT matrix (every transform rule, `PartialIndex.resolve`, `Index.parse`, caret transforms, `modifyData`). + +Prerequisites and consequences, whichever arrangement is chosen: +1. **Create-on-first-write is lost.** Node kind comes from the `$t` marker, so a plugin must create nodes explicitly with initial data (mirroring the existing `createData`/`updateValue`/`insertText` block-data methods). +2. **Two OT gaps must be closed first.** `CollaborationManager` handles only text and block events; `DataNodeAddedEvent`, `DataNodeRemovedEvent` and `ValueModifiedEvent` fall through to "Unknown event type". A tree creates and removes nodes, so these stop being side notes. +3. **Text needs a DOM input.** Editable text requires an input attached through a `BlockToolAdapter`, and a plugin is not a block tool, so it needs adapter access or a new input-attachment API. This is the largest piece of work. +4. **Text extraction must exclude plugin data.** `BlockNode#getTextContent` walks the whole tree and feeds `convertBlock`/`splitBlock`, so plugin text would leak into conversion exports unless skipped. +5. **Caret semantics need defining:** navigation order between a block's own inputs and its plugin inputs, and selections spanning both. +6. **Reads get more awkward:** entries come back as serialized nodes with `$t` markers rather than plain objects, so a convenience accessor is wanted for scalar cases. + +Because this change keeps entries as flat key → JSON value maps, moving to a tree later is a second format change. It can be softened when the time comes by typing an entry's value as the same recursive shape as block data, which makes `$t`-marked nodes an additive extension rather than a break. diff --git a/openspec/changes/plugin-block-data/proposal.md b/openspec/changes/plugin-block-data/proposal.md new file mode 100644 index 00000000..f1dbc5ba --- /dev/null +++ b/openspec/changes/plugin-block-data/proposal.md @@ -0,0 +1,55 @@ +## Why + +Per-block data beyond a block tool's own data (anchors, footnotes, alignment, …) is stored today in `BlockNode`'s `tunes`, but nothing above the Model can reach it: +- `BlockNode.updateTuneData` crashes for a tune the block wasn't created with. +- `BlocksAPI` has no way to read or write it. +- Undo of a change is a silent no-op, because `EditorDocument.modifyData` only handles text formatting. +- `CollaborationManager` drops the event as "Unknown event type". + +This change makes per-block data a working, plugin-owned store, and renames it away from "tunes". It is the first of three changes that replace the Block Tune entity with plugins (see the review on [PR #157](https://github.com/editor-js/document-model/pull/157)): +1. **`plugin-block-data`** (this change): the data layer. +2. `block-settings-ui`: the UI surfaces plugins use. +3. `remove-block-tunes`: deleting the old entity. + +This change stands on its own. Plugins can use the new API before any UI exists. + +## What Changes + +- **Model — per-block plugin data.** Rename the BlockNode `tunes` store to `plugins`, keyed by plugin `name`. Writing to an absent entry creates it. Setting a key to `undefined` removes it, and empty entries are left out of serialization. **BREAKING**: the serialized block key `tunes` → `plugins`. +- **Model types — rename.** `TuneIndex` → `PluginDataIndex` (serialized `k: "plugin"`), `Index.tune()` → `Index.pluginData()`, `TuneModifiedEvent` → `PluginDataModifiedEvent`, `BlockTuneName`/`BlockTuneSerialized` → `PluginDataName`/`PluginDataSerialized`, and the `BlockTune` entity → `PluginDataNode`. **BREAKING** for persisted serialized indexes and for listeners of the tune event. +- **Undo/redo.** `EditorDocument.modifyData` applies `Modified` changes addressed by a `PluginDataIndex`, so the existing generic inversion in `UndoRedoManager` works for plugin data. +- **Collaboration.** `CollaborationManager` turns `PluginDataModifiedEvent` into a `Modify` operation, and `OperationsTransformer` gains a plugin-data branch so such an operation can also be the one *transformed against* — without it the transformer throws `'Unsupported index type'` on the first remote plugin-data change, on every client and on `ot-server`. `ModifyOperationData`'s payload type widens from `Record` so scalar plugin-data values are representable. +- **Core/SDK API.** + - `BlocksAPI.getPluginData({ block, plugin })` and `BlocksAPI.updatePluginData({ block, plugin, data, userId? })`. + - `insert`/`insertMany` accept a `plugins` map. + - A new augmentable `EditorjsPluginDataMap` (plugin id → stored data shape) types both methods, alongside the existing `EditorjsPluginApiMap` and `ToolPluginOptionsMap`. + - `move` and `convert` preserve plugin data, and `split` leaves it on the original block. +- **v2 data conversion.** `composeDataFromVersion2` maps each v2 block's `tunes` into the v3 block's `plugins`, keeping keys verbatim so a v3 plugin that adopts a v2 tune's name finds its data. Object data is copied key by key, and a primitive or array is stored under the key `value`. Today the converter drops `tunes` silently. + +## Capabilities + +### New Capabilities + +- `plugin-block-data`: storing, reading, updating, undoing and syncing per-block data owned by a plugin. + - *Intended Purpose (paste into the folded spec, since archive writes a `TBD` placeholder):* "Plugins persist per-block data in the document Model under their own `name`, instead of through a dedicated Block Tune entity. This capability owns the contract end to end: the `plugins` store on `BlockNode` and its serialized form, the `BlocksAPI` methods plugins use to read and write it, and the guarantee that plugin-data changes are undoable and synchronized like any other document change. The storage primitives live in [[model]] and [[model-types]], the API surface in [[core]] and [[sdk]], and the OT handling in [[collaboration-manager]]." + +### Modified Capabilities + +- `model`: `BlockNode` holds `PluginDataNode`s (created on first write) instead of `BlockTune`s. `EditorDocument.modifyData` handles plugin-data indexes. +- `model-types`: `PluginDataName`, `PluginDataIndex` (`k: "plugin"`), `PluginDataModifiedEvent`, and `plugins` in the block serialization shape. +- `core`: the `EditorAPI` surface includes `getPluginData`/`updatePluginData` and accepts a `plugins` map on insert. `composeDataFromVersion2` carries v2 `tunes` into `plugins`. +- `sdk`: a third augmentable type map, `EditorjsPluginDataMap`, types the plugin data accessors. +- `collaboration-manager`: plugin-data modifications become `Modify` operations and are transformed against block insert/delete. + +## Impact + +- **Packages:** `model-types`, `model`, `sdk` (re-exports, the `BlocksAPI` interface and the new type map), `core`, `collaboration-manager`, `ot-server`. +- **Wire format (breaking, pre-1.0):** the block key `tunes` → `plugins` and the index `k: "tune"` → `k: "plugin"`. `ot-server` is **not** a passthrough — it keeps a server-side `EditorJSModel` and applies every operation — so it participates in the transformer change and its fixtures move off `tunes`. Clients and server must deploy together. +- **Unchanged:** the SDK `BlockTune` tool contract still exists after this change. It never touched Model tune data, and its removal is `remove-block-tunes`. +- **Docs to update:** + - `docs/model.md`: BlockTune, `TuneIndex`, `Index.tune`. + - `docs/index-serialization.md`: the `TuneIndex` section and the "Tune property change" example. + - `docs/events.md`: `TuneModifiedEvent`. + - `docs/plugins.md`: the line that says `@editorjs/sdk` declares **two** augmentable interfaces — it becomes three, and that file is the canonical documentation of the augmentation pattern. + - `.github/agents/docs-updater.agent.md`: its mapping of the model entity `BlockTune` → `docs/model.md`. + - Diagrams: `model-tree-structure.mmd`, `events-catalog.mmd`, `architecture-overview.mmd`. diff --git a/openspec/changes/plugin-block-data/specs/collaboration-manager/spec.md b/openspec/changes/plugin-block-data/specs/collaboration-manager/spec.md new file mode 100644 index 00000000..620e0b6e --- /dev/null +++ b/openspec/changes/plugin-block-data/specs/collaboration-manager/spec.md @@ -0,0 +1,44 @@ +## 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. + +#### Scenario: Local plugin data change becomes an operation +- **GIVEN** the local user changes `anchors.visible` on block 1 from `true` to `false` +- **WHEN** `CollaborationManager` handles the resulting event +- **THEN** it sends a `Modify` operation on `Index.pluginData(1, 'anchors', 'visible')` with `payload` `false` and `prevPayload` `true`, rather than logging an unknown event + +#### Scenario: Inverting a plugin data operation +- **GIVEN** a plugin data `Modify` operation with `payload` `false` and `prevPayload` `true` +- **WHEN** `inverse()` is called +- **THEN** it returns a `Modify` operation on the same index with `payload` `true` and `prevPayload` `false` + +#### Scenario: Transforming against a block insertion +- **GIVEN** a plugin data operation on block 2 and a concurrent block insertion at index 0 +- **WHEN** the plugin data operation is transformed against the insertion +- **THEN** its index targets block 3 + +#### Scenario: A plugin data operation as the against-operation +- **GIVEN** any pending or stacked operation and a plugin data `Modify` operation to transform it against +- **WHEN** the transformation runs — as it does for pending operations on the client, for the undo/redo stacks on every remote plugin data event, and for conflicting operations on the server +- **THEN** it completes and returns an operation, rather than throwing an unsupported-index error + +#### Scenario: A scalar payload +- **GIVEN** a plugin data change whose value is a boolean +- **WHEN** the operation is constructed +- **THEN** the payload type admits it, so scalar plugin data is representable in an operation + +#### Scenario: Transforming against removal of its block +- **GIVEN** a plugin data operation on block 2 and a concurrent removal of block 2 +- **WHEN** the plugin data operation is transformed against the removal +- **THEN** it becomes a `Neutral` operation + +#### Scenario: Two clients write the same key concurrently +- **GIVEN** clients A and B both write `anchors.visible` on block 1, and the server applies A before B +- **WHEN** B receives A's operation while its own write is still unsent +- **THEN** A's operation is transformed to `Neutral` on B, so B keeps the value the server will end up holding rather than being left on A's + +#### Scenario: Concurrent writes to different keys +- **GIVEN** a plugin data operation on `anchors.visible` and a concurrent one on `anchors.id` of the same block +- **WHEN** one is transformed against the other +- **THEN** it is returned unchanged, because the two do not describe the same value diff --git a/openspec/changes/plugin-block-data/specs/core/spec.md b/openspec/changes/plugin-block-data/specs/core/spec.md new file mode 100644 index 00000000..8a9dc3b1 --- /dev/null +++ b/openspec/changes/plugin-block-data/specs/core/spec.md @@ -0,0 +1,46 @@ +## ADDED Requirements + +### Requirement: v2 data conversion carries tune data into plugin data +`composeDataFromVersion2` SHALL map each v2 block's `tunes` map into the v3 block's `plugins` map, preserving each entry's key verbatim, so a v3 plugin that takes over a v2 tune's `name` finds its data. An entry whose v2 data is a plain object SHALL be copied key by key. An entry whose v2 data is a primitive or an array SHALL be stored under the single key `value`. A v2 block without `tunes`, or with an empty `tunes` map, SHALL produce no `plugins` entry. + +#### Scenario: Converting object tune data +- **GIVEN** a v2 block with `tunes: { anchors: { id: 'intro' } }` +- **WHEN** it is converted to v3 +- **THEN** the resulting block init carries `plugins: { anchors: { id: 'intro' } }` + +#### Scenario: Converting non-object tune data +- **GIVEN** a v2 block with `tunes: { alignment: 'left' }` +- **WHEN** it is converted +- **THEN** the resulting entry is `plugins: { alignment: { value: 'left' } }` + +#### Scenario: Block without tunes +- **GIVEN** a v2 block with no `tunes` key, or with `tunes: {}` +- **WHEN** it is converted +- **THEN** the resulting block init has no `plugins` key + +#### Scenario: Tune with no registered plugin +- **GIVEN** a v2 block carrying tune data whose name matches no plugin registered in this editor +- **WHEN** the document is converted and loaded +- **THEN** the entry is still present in the block's `plugins` and survives serialization, per the plugin data store's preservation rule + +## MODIFIED Requirements + +### Requirement: EditorAPI surface +The system SHALL expose an `EditorAPI` aggregating `BlocksAPI` (insert/insertMany/delete/move/render/clear/getBlocksCount/getPluginData/updatePluginData), `SelectionAPI` (applyInlineTool, selectedBlocks), `DocumentAPI` (serialized data, onUpdate, insertData/removeData/modifyData, undo/redo), and `TextAPI` (insert/remove/format/unformat/getFragments/get) to tools, plugins, and adapters. + +#### Scenario: Deleting with no block selected +- **GIVEN** no block is currently selected/no caret is set +- **WHEN** `BlocksAPI.delete()` or `move()` is called without an explicit index +- **THEN** it throws an error ("No block selected to delete" / "No block selected to move") + +#### Scenario: Splitting or converting with an unknown tool +- **GIVEN** a `splitBlock`/`convertBlock` call references a `dataKey` that doesn't exist, or a source/target tool that isn't registered +- **WHEN** the operation is attempted +- **THEN** it throws an error identifying the missing key or tool + +#### Scenario: Inserting a block with plugin data +- **GIVEN** `BlocksAPI.insert` is called with both `data` and `plugins: { anchors: { id: 'intro' } }` +- **WHEN** the block is added to the model +- **THEN** the serialized block carries both its tool data and that plugin data, each under its own key + +Implemented in `src/api/index.ts`, `src/api/BlocksAPI.ts`, `src/api/SelectionAPI.ts`, `src/api/DocumentAPI/DocumentAPI.ts`, `src/api/TextAPI.ts`, `src/components/BlockManager.ts`, validated by co-located `.spec.ts`/`.integration.spec.ts` files. diff --git a/openspec/changes/plugin-block-data/specs/model-types/spec.md b/openspec/changes/plugin-block-data/specs/model-types/spec.md new file mode 100644 index 00000000..70b195b8 --- /dev/null +++ b/openspec/changes/plugin-block-data/specs/model-types/spec.md @@ -0,0 +1,69 @@ +## MODIFIED Requirements + +### Requirement: Nominal identifier types +The system SHALL provide nominal (branded) types for `BlockId`, `BlockToolName`, `PluginDataName`, `DataKey`, and `InlineToolName` so that structurally identical primitives (e.g. two different kinds of string IDs) are not interchangeable at the type level. + +#### Scenario: Generating a block id +- **GIVEN** a new block is being created +- **WHEN** `generateBlockId()` is called +- **THEN** it returns a 21-character URL-safe random `BlockId`, generated via `crypto.getRandomValues` + +Implemented in `src/Nominal.ts`, `src/BlockId.ts`, `src/PluginData.ts`, `src/DataKey.ts`, `src/InlineTool.ts`. + +### Requirement: Document and block serialization shapes +The system SHALL define the serialized shapes for blocks, text nodes, and documents (`BlockData`, `BlockNodeInit`, `BlockNodeSerialized`, `TextNodeSerialized`, `EditorDocumentSerialized`, `ChangeData`) so `model` and `sdk` agree on wire/storage format. A block's per-plugin data SHALL be carried under the optional `plugins` key as a record of `PluginDataSerialized` keyed by plugin data name. + +#### Scenario: Distinguishing child node types +- **GIVEN** a block's data tree contains both plain values and text nodes +- **WHEN** a data node is serialized +- **THEN** it is tagged with the hidden discriminator property `$t` (`NODE_TYPE_HIDDEN_PROP`) set to a `BlockChildType` (`Value` or `Text`) so consumers can distinguish node kinds without inspecting shape + +#### Scenario: Serializing plugin data +- **GIVEN** a block carrying data for plugin `anchors` +- **WHEN** it is serialized +- **THEN** the data appears under `plugins.anchors`, and no `tunes` key is produced + +Implemented in `src/BlockNode.ts`, `src/Text.ts`, `src/Value.ts`, `src/EditorDocument.ts`, `src/ChangeData.ts`, `src/BlockChildType.ts`, `src/PluginData.ts`. + +### Requirement: Index — composite document location pointer +The system SHALL provide an abstract `IndexBase` class and one concrete subclass per pointer kind — `DocumentIndex`, `PropertyIndex`, `BlockIndex`, `PluginDataIndex`, `DataIndex`, `TextIndex` — each carrying only the fields structurally valid for that kind (e.g. `PluginDataIndex` always has `pluginName`+`pluginKey`, `PropertyIndex` never carries block-related fields), a `kind` discriminant (`IndexKind`) for narrowing, and immutable `with*` copy methods (`withBlockIndex`/`withTextRange`/`withDocumentId`) that return a new instance. The abstract `Index` class exposes static factory methods (`Index.document`/`property`/`block`/`pluginData`/`data`/`text`) and `Index.parse`, and overrides `Symbol.hasInstance` so `value instanceof Index` is true for any `IndexBase` instance even though concrete classes extend `IndexBase` directly. + +#### Scenario: Constructing an index of a given kind +- **GIVEN** a location needs to be pointed to +- **WHEN** the corresponding `Index.*` factory (or a concrete class constructor) is called +- **THEN** it returns an instance of the matching subclass whose `kind` and fields are fixed by the constructor signature, so invalid field combinations (e.g. a plugin name without a plugin key, or a property name combined with a block index) cannot be constructed for that subclass + +#### Scenario: Composite text selections +- **GIVEN** a selection spans multiple disjoint text ranges (e.g. across blocks) +- **WHEN** a `TextIndex` is constructed with more than one segment +- **THEN** `isComposite` is true, `isTextIndex` is false, `blockIndex`/`dataKey`/`textRange`/`documentId` are `undefined` (only meaningful for a single-segment instance), and `getTextSegments()` expands it back into one single-segment `TextIndex` per segment; constructing a `TextIndex` with zero segments throws + +#### Scenario: Parsing a serialized index +- **GIVEN** a JSON string produced by `IndexBase#serialize()` +- **WHEN** `Index.parse` is called +- **THEN** it parses the JSON and dispatches on its `k` discriminator field (`doc`/`prop`/`block`/`plugin`/`data`/`text`/`composite`) to reconstruct the matching concrete instance, and throws if the value isn't a JSON object with a string `k` field or `k` is unrecognized + +#### Scenario: Serializing a plugin data index +- **GIVEN** `Index.pluginData(1, 'anchors', 'id')` +- **WHEN** it is serialized +- **THEN** the result is `{"k":"plugin","b":1,"plugin":"anchors","key":"id"}`, and `Index.parse` of that string returns an equal `PluginDataIndex` + +#### Scenario: Resolving a partial index accumulated during event bubbling +- **GIVEN** a leaf node (text/value/plugin data) dispatches an event carrying only its locally-known fields as a `PartialIndex`, which parent nodes progressively complete via `withBlockIndex`/`withDocumentId` as the event bubbles up +- **WHEN** `PartialIndex#resolve()` is called once all context has been attached +- **THEN** it returns the concrete `IndexBase` subclass matching the accumulated fields, throwing a specific error naming the missing/conflicting field (e.g. `PluginDataIndex requires pluginKey`, `DataIndex cannot be combined with pluginName`, `PropertyIndex cannot be combined with block-related fields`) when the fields don't resolve to a valid index; `PartialIndex` itself throws on `serialize()`, so it must always be resolved before leaving `model` + +Implemented in `src/Index/IndexBase.ts`, `src/Index/index.ts` (factory/parse), `src/Index/DocumentIndex.ts`, `src/Index/PropertyIndex.ts`, `src/Index/BlockIndex.ts`, `src/Index/PluginDataIndex.ts`, `src/Index/DataIndex.ts`, `src/Index/TextIndex.ts`, `src/Index/PartialIndex.ts`, validated by `src/Index/Index.spec.ts`. + +### Requirement: Base document event and event bus +The system SHALL provide a `BaseDocumentEvent` base class carrying `{ index, action, data, userId }` that fires under the `EventType.Changed` DOM event type, concrete event subclasses for each kind of document mutation (block/data/text add/remove/modify, plugin data/property modification), and a thin `EventBus` (`EventTarget` subclass) used to dispatch them. + +#### Scenario: Emitting a document mutation event +- **GIVEN** a block, text, value, or plugin data node is added, removed, or modified +- **THEN** the corresponding concrete event (e.g. `DataNodeAddedEvent`, `TextFormattedEvent`, `BlockAddedEvent`, `PropertyModifiedEvent`, `PluginDataModifiedEvent`) is dispatched as `EventType.Changed`, carrying an `EventAction` (`Added`/`Removed`/`Modified`) and the affected `Index` + +#### Scenario: Emitting a caret event +- **GIVEN** a caret is added, removed, or updated +- **THEN** the corresponding caret event (`CaretManagerCaretAddedEvent`, `CaretManagerCaretRemovedEvent`, `CaretManagerCaretUpdatedEvent`) is dispatched as `EventType.CaretManagerUpdated`, carrying the serialized `Caret` + +Implemented in `src/BaseDocumentEvent.ts`, `src/EventBus.ts`, `src/EventType.ts`, `src/EventAction.ts`, `src/EventMap.ts`, `src/events/*`. diff --git a/openspec/changes/plugin-block-data/specs/model/spec.md b/openspec/changes/plugin-block-data/specs/model/spec.md new file mode 100644 index 00000000..0353503f --- /dev/null +++ b/openspec/changes/plugin-block-data/specs/model/spec.md @@ -0,0 +1,56 @@ +## RENAMED Requirements + +- FROM: `### Requirement: Value nodes and block tunes` +- TO: `### Requirement: Value nodes and plugin data` + +## MODIFIED Requirements + +### Requirement: BlockNode data tree +The system SHALL provide `BlockNode` representing a single block's data tree (nested value/text nodes, arrays, and objects) plus its per-plugin `PluginDataNode`s, supporting creation/removal/lookup of data nodes, text insert/remove/format/unformat, plugin-data/value updates, and text content extraction. Updating plugin data for a plugin name the block has no entry for SHALL create that entry rather than throw. + +#### Scenario: Creating a data node at an existing key +- **GIVEN** a block already has a data node at a given key +- **WHEN** `createDataNode` is called for that same key +- **THEN** it throws `AlreadyExistingKeyError` + +#### Scenario: Creating a data node within an array path +- **GIVEN** a block has an array of data nodes at a path +- **WHEN** `createDataNode` targets an index within that array +- **THEN** existing entries at or after that index are shifted rather than the operation erroring + +#### Scenario: Updating plugin data for a new plugin name +- **GIVEN** a block with no plugin data entry named `anchors` +- **WHEN** `updatePluginData('anchors', { id: 'intro' })` is called +- **THEN** a `PluginDataNode` named `anchors` is created, its event listener is attached before any value is set, and a `PluginDataModifiedEvent` bubbles from the block with `previous` `undefined` + +#### Scenario: Plugin data events carry the acting user +- **GIVEN** a plugin data change made in a user context +- **WHEN** the event bubbles from the `PluginDataNode` through the `BlockNode` +- **THEN** its `userId` is taken from the active context, like value-node events, rather than a placeholder + +Implemented in `src/entities/BlockNode/index.ts`, validated by its co-located `.spec.ts`. + +### Requirement: Value nodes and plugin data +The system SHALL provide `ValueNode` for leaf non-text data storage and `PluginDataNode` for per-block data owned by a plugin, both participating in the block's event-emitting data tree. A `PluginDataNode` SHALL hold a flat key/value record, SHALL emit one `PluginDataModifiedEvent` per changed key, and SHALL delete a key when it is set to `undefined`. + +#### Scenario: Modifying a value node +- **GIVEN** a `ValueNode` holding a leaf value within a block +- **WHEN** its value is updated +- **THEN** a `ValueModifiedEvent` is emitted carrying the previous and new value + +#### Scenario: Removing a plugin data key +- **GIVEN** a `PluginDataNode` holding `{ id: 'intro' }` +- **WHEN** `id` is updated to `undefined` +- **THEN** a `PluginDataModifiedEvent` is emitted with `previous` `'intro'` and `value` `undefined`, and the node's serialized form no longer contains `id` + +Implemented in `src/entities/ValueNode`, `src/entities/PluginDataNode`. + +## ADDED Requirements + +### Requirement: Generic modification of plugin data +`EditorDocument.modifyData` SHALL apply a `Modified` change addressed by a `PluginDataIndex` by setting that plugin's key on the indexed block to the change's `value`, so undo/redo and remote operations can replay plugin data changes through the generic index-based entry point. + +#### Scenario: Replaying a plugin data change by index +- **GIVEN** a block at index 1 whose `anchors` plugin data has `visible: true` +- **WHEN** `modifyData(Index.pluginData(1, 'anchors', 'visible'), { value: false, previous: true })` is called +- **THEN** the block's `anchors.visible` becomes `false` and a `PluginDataModifiedEvent` is emitted with that index diff --git a/openspec/changes/plugin-block-data/specs/plugin-block-data/spec.md b/openspec/changes/plugin-block-data/specs/plugin-block-data/spec.md new file mode 100644 index 00000000..70671a29 --- /dev/null +++ b/openspec/changes/plugin-block-data/specs/plugin-block-data/spec.md @@ -0,0 +1,167 @@ +## ADDED Requirements + +### Requirement: Per-block plugin data store +Each block SHALL be able to hold data owned by plugins, stored as a map from a plugin data name (by convention the owning plugin's static `name`) to a flat record of string keys and JSON-serializable values. The store SHALL be serialized under the block's `plugins` key, and a block without plugin data SHALL serialize without a `plugins` entry for that plugin. + +A write that would leave the stored data as it is — the value a key already holds, or the removal of a key that is not present — SHALL emit no event, and so SHALL produce neither an operation for collaborators nor an undo step. Plugins re-apply their current state routinely, and an entry that undoes nothing is worse than no entry at all. + +Plugin names and the keys within an entry are document data, not identifiers the editor chooses, so neither SHALL be able to collide with `Object.prototype`. A key arriving from a stored document SHALL be held as data whatever it is called, `__proto__` included; a key the entry does not hold SHALL read as absent rather than as an inherited member, both when asking for a plugin's entry and when reading a key within one. + +What `getPluginData` and the serialized document hand back SHALL be detached from the store, so that changing it does not change the document. Reading an entry, editing it and passing it back to `updatePluginData` is the obvious way to use the two together, and over a live record the no-op rule above turns it into silent loss: the document has already changed, so the write that should have announced it emits nothing. + +#### Scenario: A block with no plugin data +- **GIVEN** a block that has no plugin data at all +- **WHEN** it is serialized +- **THEN** its `plugins` value is an empty map rather than being absent, matching how the store serializes today + +#### Scenario: Block initialized with plugin data +- **GIVEN** a block is inserted with `plugins: { anchors: { id: "intro" } }` +- **WHEN** the document is serialized +- **THEN** the block's serialized form contains `plugins: { anchors: { id: "intro" } }` + +#### Scenario: Writing plugin data for the first time +- **GIVEN** a block that has no data for plugin `anchors` +- **WHEN** plugin data `{ id: "intro" }` is written for `anchors` on that block +- **THEN** the entry is created with that value instead of an error being thrown, and a `PluginDataModifiedEvent` is emitted for key `id` with `previous` `undefined` and `value` `"intro"` + +#### Scenario: Updating one key keeps the others +- **GIVEN** a block with `plugins.anchors` equal to `{ id: "intro", visible: true }` +- **WHEN** `{ visible: false }` is written for `anchors` +- **THEN** the entry becomes `{ id: "intro", visible: false }`, and exactly one `PluginDataModifiedEvent` is emitted, for key `visible` + +#### Scenario: Removing the last key drops the entry +- **GIVEN** a block with `plugins.anchors` equal to `{ id: "intro" }` +- **WHEN** `{ id: undefined }` is written for `anchors` +- **THEN** the key is removed, and the serialized block no longer contains an `anchors` entry under `plugins` + +#### Scenario: Writing the value a key already holds +- **GIVEN** a block with `plugins.anchors` equal to `{ visible: true }` +- **WHEN** `{ visible: true }` is written for `anchors` again +- **THEN** the data is unchanged and no `PluginDataModifiedEvent` is emitted + +#### Scenario: Removing a key that is not there +- **GIVEN** a block whose `anchors` entry has no `visible` key +- **WHEN** `{ visible: undefined }` is written for `anchors` +- **THEN** the data is unchanged and no `PluginDataModifiedEvent` is emitted + +#### Scenario: Reading an entry whose keys were all removed +- **GIVEN** a block whose `anchors` entry existed and then had every key removed +- **WHEN** its plugin data is read +- **THEN** `undefined` is returned, the same as for an entry that never existed + +#### Scenario: A plugin name that collides with an object-prototype member +- **GIVEN** plugin data is written for a plugin named `__proto__` or `toString` +- **WHEN** it is written and read back, and the document is serialized and re-loaded +- **THEN** the entry is stored and returned as ordinary data, with no prototype of the store affected and no silent loss + +#### Scenario: An empty plugin name +- **WHEN** plugin data is written for an empty plugin name +- **THEN** it throws, rather than creating an unaddressable entry + +#### Scenario: Unknown plugin data is preserved +- **GIVEN** a document whose block carries a `plugins` entry for a plugin that is not registered in this editor +- **WHEN** the document is loaded and serialized again +- **THEN** that plugin's entry is preserved verbatim + +### Requirement: Plugin data API +The system SHALL expose `BlocksAPI.getPluginData({ block, plugin })` and `BlocksAPI.updatePluginData({ block, plugin, data, userId? })`, where `block` is a block index or id. `updatePluginData` SHALL merge the given keys into the plugin's entry, attributing the change to `userId` or, when omitted, to the configured user. Each changed key SHALL be recorded as its own modification, so a call that writes several keys is not a single undo step. `BlocksAPI.insert` and `insertMany` SHALL accept an initial `plugins` map per block. + +#### Scenario: Reading plugin data +- **GIVEN** a block with id `b1` whose `plugins.anchors` is `{ id: "intro" }` +- **WHEN** `api.blocks.getPluginData({ block: "b1", plugin: "anchors" })` is called +- **THEN** it returns `{ id: "intro" }` + +#### Scenario: Reading absent plugin data +- **WHEN** `getPluginData` is called for a plugin that has no entry on the block +- **THEN** it returns `undefined` + +#### Scenario: A plugin named after a member of Object.prototype +- **GIVEN** a block that has no entry for a plugin named `toString` +- **WHEN** `getPluginData({ block: 0, plugin: "toString" })` is called +- **THEN** it returns `undefined`, rather than the function the prototype would answer with + +#### Scenario: A key named __proto__ in a stored document +- **GIVEN** a document whose `plugins.anchors` holds a `__proto__` key +- **WHEN** it is loaded and serialized again +- **THEN** the key is still there, because it was held as data rather than reaching a prototype setter + +#### Scenario: The first write to a key named after a member of Object.prototype +- **GIVEN** an entry that holds no `toString` key +- **WHEN** `toString` is written for the first time +- **THEN** the change records no previous value, so undoing it removes the key rather than restoring an inherited function + +#### Scenario: Editing what was read +- **GIVEN** `getPluginData` returned a plugin's entry +- **WHEN** the caller changes a key on it and passes it to `updatePluginData` +- **THEN** the document is unchanged until that call, which records the change as its own modification + +#### Scenario: Writing plugin data +- **WHEN** `api.blocks.updatePluginData({ block: 0, plugin: "anchors", data: { id: "intro" } })` is called +- **THEN** the block at index 0 carries `plugins.anchors.id === "intro"`, and the emitted event's `userId` is the configured user + +#### Scenario: Unknown block +- **WHEN** `getPluginData` or `updatePluginData` references a block index or id that does not exist +- **THEN** it throws — naming the id when an id was given, or reporting an out-of-bounds index when an index was given + +#### Scenario: Writing several keys at once +- **WHEN** `updatePluginData` is called with two keys in `data` +- **THEN** both are applied, two modifications are recorded, and a single undo reverts only the last one + +### Requirement: Plugin data survives block restructuring +Block operations that relocate or transform a block SHALL keep its plugin data consistent: `move` SHALL preserve it, `convert` SHALL carry it over to the converted block, and `split` SHALL leave it on the original block and create the new block without plugin data. + +#### Scenario: Moving a block +- **GIVEN** a block carrying plugin data +- **WHEN** it is moved to another index +- **THEN** the block at the new index carries the same plugin data + +#### Scenario: Converting a block +- **GIVEN** a block carrying plugin data +- **WHEN** it is converted to another block tool +- **THEN** the resulting block carries the same plugin data + +#### Scenario: Splitting a block +- **GIVEN** a block carrying plugin data +- **WHEN** it is split at a caret offset +- **THEN** the original block keeps its plugin data, and the newly inserted block has none + +### Requirement: Plugin data changes are undoable +A plugin data change SHALL be recorded by local undo/redo like any other document modification. Undoing it SHALL restore the previous value, including removing a key that did not exist before the change. + +#### Scenario: Undoing a first write +- **GIVEN** a block with no `anchors` data, then `updatePluginData` writes `{ id: "intro" }` for `anchors` +- **WHEN** `api.document.undo()` is called +- **THEN** the block serializes without an `anchors` entry, and `api.document.redo()` restores `{ id: "intro" }` + +#### Scenario: Undoing an update +- **GIVEN** `plugins.anchors.visible` changed from `true` to `false` +- **WHEN** undo is performed +- **THEN** `visible` is `true` again + +#### Scenario: A write that changes nothing adds no undo step +- **GIVEN** `plugins.anchors.visible` is `true` and a plugin writes `{ visible: true }` again +- **WHEN** undo is performed +- **THEN** it reverts whatever the user did before that write, because the no-op write recorded nothing of its own + +### Requirement: Plugin data changes are collaborative +A local plugin data change SHALL be sent to collaborators as a `Modify` operation on a `PluginDataIndex`, and a received one SHALL be applied to the local model. Plugin data operations SHALL be transformed against concurrent block insertions and removals so they keep targeting the same block. + +#### Scenario: Remote client receives a plugin data change +- **GIVEN** two clients editing the same document +- **WHEN** client A writes `{ visible: false }` for `anchors` on a block +- **THEN** client B's model reflects `visible: false` for that block + +#### Scenario: Concurrent block insertion above +- **GIVEN** client A writes plugin data for the block at index 2 while client B concurrently inserts a block at index 0 +- **WHEN** both operations are applied on both clients +- **THEN** the plugin data change lands on the same logical block (index 3 after B's insertion) on both clients + +#### Scenario: Removing a key reaches collaborators +- **GIVEN** client A removes the `visible` key of a block's `anchors` data +- **WHEN** the operation is serialized, sent, and applied on client B +- **THEN** B's block no longer has that key — a removal carries no value, so it SHALL survive a round trip through JSON, where a key holding `undefined` does not + +#### Scenario: Target block removed concurrently +- **GIVEN** client A writes plugin data for a block that client B concurrently removes +- **WHEN** A's operation is transformed against B's removal +- **THEN** it becomes a no-op rather than modifying a different block diff --git a/openspec/changes/plugin-block-data/specs/sdk/spec.md b/openspec/changes/plugin-block-data/specs/sdk/spec.md new file mode 100644 index 00000000..24cf06d8 --- /dev/null +++ b/openspec/changes/plugin-block-data/specs/sdk/spec.md @@ -0,0 +1,26 @@ +## MODIFIED Requirements + +### Requirement: Augmentable plugin type maps +The system SHALL declare three empty, augmentable interfaces — `EditorjsPluginApiMap` (plugin id → public API type), `ToolPluginOptionsMap` (plugin id → tool-directed options type), and `EditorjsPluginDataMap` (plugin id → the shape of the per-block data that plugin stores) — that plugin packages extend via module augmentation of `@editorjs/sdk`. `PluginId` SHALL include the keys of all three maps. `BlocksAPI.getPluginData`/`updatePluginData` SHALL resolve their data type from `EditorjsPluginDataMap` for a declared id, and SHALL fall back to `Record` for an id absent from it, using a non-distributive conditional so the `string & {}` member of `PluginId` does not widen a declared id's type. + +#### Scenario: Plugin package augments the api and options maps +- **GIVEN** a plugin package declares `declare module '@editorjs/sdk'` augmenting `EditorjsPluginApiMap` and `ToolPluginOptionsMap` under its `name` +- **WHEN** a consumer's compilation includes that package's types +- **THEN** `api.plugins.` and `options.plugins.` are both fully typed with no cast + +#### Scenario: No augmentation present +- **GIVEN** no plugin package has augmented any of the three interfaces +- **WHEN** `@editorjs/sdk` is compiled on its own +- **THEN** all three are empty and `Partial<...>` of them permits no keys, so the base package remains self-consistent + +#### Scenario: Plugin package declares its block data shape +- **GIVEN** a plugin package augments `EditorjsPluginDataMap` with `{ anchors: { id: string } }` +- **WHEN** a consumer calls `api.blocks.getPluginData({ plugin: 'anchors' })` +- **THEN** the result is typed `{ id: string } | undefined`, and `updatePluginData({ plugin: 'anchors', data: { id: 1 } })` is a compile error + +#### Scenario: Plugin data for an undeclared id +- **GIVEN** a plugin that has not augmented `EditorjsPluginDataMap` +- **WHEN** `getPluginData({ plugin: 'whatever' })` is called +- **THEN** the result is typed `Record | undefined` rather than `never`, so an undeclared plugin still compiles + +Implemented in `src/index.ts` (the map declarations, `PluginId`, `PluginsAPI`, `ToolPluginOptions`), `src/api/BlocksAPI.ts`, validated by `src/pluginTypeMaps.spec.ts`. diff --git a/openspec/changes/plugin-block-data/tasks.md b/openspec/changes/plugin-block-data/tasks.md new file mode 100644 index 00000000..12e0dbc0 --- /dev/null +++ b/openspec/changes/plugin-block-data/tasks.md @@ -0,0 +1,70 @@ +## 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 + +## 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 + +## 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 + +## 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 + +## 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` + +## 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 +- [ ] 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 + +## 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 + +## 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` diff --git a/openspec/changes/remove-block-tunes/.openspec.yaml b/openspec/changes/remove-block-tunes/.openspec.yaml new file mode 100644 index 00000000..563fab5a --- /dev/null +++ b/openspec/changes/remove-block-tunes/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-09-21 diff --git a/openspec/changes/remove-block-tunes/design.md b/openspec/changes/remove-block-tunes/design.md new file mode 100644 index 00000000..760b327e --- /dev/null +++ b/openspec/changes/remove-block-tunes/design.md @@ -0,0 +1,37 @@ +## Context + +The Block Tune tool kind is spread across `sdk` and `core`: +- `ToolType.Tune`, `BlockTune`/`BlockTuneConstructor`/`BlockTuneOptions`/`BlockTuneData`, `BlockTuneFacade`, and `ToolsCollection#blockTunes` in `sdk`. +- The `use()` branch, `getAll(ToolType.Tune)`, `ToolsFactory`'s Tune case and `ToolsManager#blockTunes` in `core`. +- A `tunes` member on the `BlockTool` contract. + +No tune is functional on `main`: nothing renders them and nothing connects them to the Model. Every tune use case is covered by a plain plugin — `plugin-block-data` gives such a plugin per-block storage and `block-settings-ui` gives it a menu — but neither has to land before the dead kind can go. + +## Goals / Non-Goals + +**Goals:** +- Remove the tune tool kind and every code path that registers, prepares or collects tunes. +- Leave no dangling references in docs or specs. + +**Non-Goals:** +- A compatibility shim for v2 third-party tunes. None exists today, and one can be written later as a plugin that adapts a v2 tune to block settings and plugin data if there is demand. + +## Decisions + +### D1. Delete outright rather than deprecate +v3 is pre-1.0 and the tune path is non-functional, so a deprecation cycle would only keep dead code alive. Every removed export is listed in the proposal, for the PR description — the repo keeps no changelog files. + +### D2. Drop the tool's `tunes` option with no replacement in the contract +The option is `BlockToolOptionKey.Tunes`, surfaced as `BlockToolFacade#enabledBlockTunes`. Nothing reads that getter today, so removing it breaks no behavior — but it is v2's per-tool allow-list ("enable these tunes for this tool"), and deleting it removes that integrator control with no replacement. That is deliberate: per-tool filtering now lives in the providers, which receive `tool` in their context and can opt out. If integrators ask for the allow-list back, it returns through `tool-plugin-options` as `options.plugins['block-settings']`, the existing channel for tool → plugin configuration, rather than as a member of the tool contract. + +### D3. The model layer keeps its own renaming change +`BlockTuneName`, `BlockTuneSerialized` and `createBlockTuneName` are model-types names that `sdk` re-exports. They are renamed by `plugin-block-data`. This change removes only the tool kind, so its compile-time assertions enumerate tool-kind names explicitly instead of asserting that the string "tune" is gone from `sdk`. + +## Risks / Trade-offs + +- **[Removing the extension point before its replacement lands]** → accepted. A tune cannot render or store anything on `main`, so there is no working behavior to lose in the window before `block-settings-ui` lands. +- **[Leftover references]** → `shortcuts-plugin` is the one package that breaks, and it is named in the tasks. The workspace-wide search is scoped to the tool-kind symbols, because the model layer legitimately keeps its own (renamed) tune vocabulary until `plugin-block-data` lands. + +## Migration Plan + +Land whenever convenient — nothing sequences before it. Close PR #157 with links to the three changes. Rollback is reverting the PR. diff --git a/openspec/changes/remove-block-tunes/proposal.md b/openspec/changes/remove-block-tunes/proposal.md new file mode 100644 index 00000000..648961ff --- /dev/null +++ b/openspec/changes/remove-block-tunes/proposal.md @@ -0,0 +1,50 @@ +## Why + +The Block Tune tool kind is dead weight. A registered tune gets a `BlockTuneFacade` built and sorted into `ToolsManager.blockTunes`, and then nothing ever reads it: no adapter, no rendering, no core wiring. Keeping it leaves a second, half-wired way to build what plugins now do, and it is the extension point PR #157 grew an adapter and a manager around. + +This is one of three changes that replace the Block Tune entity with plugins (see the review on [PR #157](https://github.com/editor-js/document-model/pull/157)): +- `plugin-block-data`: the data layer. +- `block-settings-ui`: the UI surfaces. +- **`remove-block-tunes`** (this change): deleting the old entity. + +It depends on neither of the others. Because the tune kind is non-functional, deleting it breaks no working feature, and its spec deltas (`sdk`, `core`) touch no requirement the other two changes touch. `plugin-block-data` renames the *model's* tune vocabulary; this change removes the *tool kind*. + +## What Changes + +- **SDK — remove the tune tool kind.** Delete `ToolType.Tune`, `BlockTune`, `BlockTuneConstructor`, `BlockTuneConstructorOptions`, `BlockTuneOptions`, `BlockTuneData`, and `BlockTuneFacade`, plus everything that references them: + - `BaseToolFacade#isTune()` and `ToolsCollection#blockTunes` (its only consumer). + - `BlockTuneConstructor` from the public `ToolConstructable` union and `BlockTuneFacade` from `ToolFacadeClass`. + - `ToolTypeToOptions[ToolType.Tune]`, the `ToolStaticOptions` member, and the `BlockTuneOptions` re-exports. + - `BlockToolOptionKey.Tunes` and its `BlockToolOptions` member — `tunes` is a tool *option*, not a constructor member. + - `UserToolOptions.EnabledBlockTunes`, `BlockToolFacade#enabledBlockTunes` and `BlockToolFacade#tunes`. + - The `./BlockTune.js` export from the entities barrel. + + **BREAKING** for anything that registers a tune through `core.use()` or sets a tool's `tunes` option. +- **Core — remove tune registration.** Remove the Tune branch from `Core#use`, the `getAll(ToolType.Tune)` preparation step, the Tune case in `ToolsFactory`, and `ToolsManager#blockTunes`. +- **"Tune" becomes a UI term only.** A former tune is written as a plugin that uses the block-settings API and plugin data. +- **`shortcuts-plugin` cleanup.** Its dead `#processBlockTune(_tool: BlockTuneFacade)` method and the `BlockTuneFacade` import go with the facade. +- **Close PR #157** as superseded by these three changes. + +## Capabilities + +### New Capabilities + +_None._ + +### Modified Capabilities + +- `sdk`: the `Tool and tune contracts` requirement becomes `Tool contracts` with no tune kind. `ToolsCollection` drops `blockTunes`. +- `core`: tool registration and validation no longer has a tune path. + +## Impact + +- **Packages:** `sdk`, `core`, and `shortcuts-plugin` (it imports `BlockTuneFacade`). `playground` has no tune references. +- **Out of scope:** the model layer's tune vocabulary (`BlockTuneName`, `BlockTuneSerialized`, `createBlockTuneName` and their `sdk` re-exports) is renamed by `plugin-block-data`, not here. A workspace-wide grep for `tunes` hits those legitimately. +- **Public API (breaking, pre-1.0):** the removed exports listed above. +- **Order:** independent. It can land before, after, or alongside the other two changes. +- **Docs to update:** + - `docs/plugins.md`: the "Block Tune" row, and line 5, which advertises the SDK as re-exporting a `BlockTune` contract. + - `docs/README.md`: the `BlockTune` contract mention. + - `docs/diagrams/plugin-lifecycle-flow.mmd`: `ToolType.Tune` binding and `prepareTools(..., blockTunes)`. + - The `shortcuts-plugin` spec's reserved-work note: "block tunes" → "block settings items". + - `openspec/specs/sdk/spec.md`'s **Purpose** preamble ("interfaces for block tools, inline tools, block tunes, and plugins"). It sits outside any `### Requirement:` block, so the mechanical `openspec archive` fold will not touch it — edit it by hand in the same PR, like a new capability's Purpose. diff --git a/openspec/changes/remove-block-tunes/specs/core/spec.md b/openspec/changes/remove-block-tunes/specs/core/spec.md new file mode 100644 index 00000000..893e3b09 --- /dev/null +++ b/openspec/changes/remove-block-tunes/specs/core/spec.md @@ -0,0 +1,16 @@ +## MODIFIED Requirements + +### Requirement: Tool registration and validation +The system SHALL validate configured tools via `ToolsManager`, calling each tool's static `prepare()`, and sorting tools into `available`/`unavailable` collections exposed as `blockTools`/`inlineTools`. `Core#use` SHALL accept block tools, inline tools, adapter plugins, and generic plugins; there SHALL be no separate Block Tune registration path. + +#### Scenario: Rejecting a malformed tool +- **GIVEN** a configured tool is neither a constructor function nor an object with a `class` property +- **WHEN** `ToolsManager` validates the configuration +- **THEN** it throws an error naming the offending tool and describing the required shape + +#### Scenario: A former tune is registered as a plugin +- **GIVEN** a class implementing `EditorjsPlugin` that does what a Block Tune used to do +- **WHEN** it is registered via `core.use()` +- **THEN** it is instantiated with the other plugins and never appears in `ToolsManager`'s collections + +Implemented in `src/tools/ToolsManager.ts`, `src/tools/ToolsFactory.ts`, validated by `src/index.spec.ts` and co-located `.spec.ts` files. diff --git a/openspec/changes/remove-block-tunes/specs/sdk/spec.md b/openspec/changes/remove-block-tunes/specs/sdk/spec.md new file mode 100644 index 00000000..4e3cfd86 --- /dev/null +++ b/openspec/changes/remove-block-tunes/specs/sdk/spec.md @@ -0,0 +1,55 @@ +## RENAMED Requirements + +- FROM: `### Requirement: Tool and tune contracts` +- TO: `### Requirement: Tool contracts` + +## MODIFIED Requirements + +### Requirement: Tool contracts +The system SHALL define the static/instance contracts that block tools and inline tools must satisfy: `BaseTool`/`BaseToolConstructor` (common `name`, `options`, `prepare()`, `reset()`), `BlockTool`/`BlockToolConstructor` (adds `toolbox`, `shortcut`, `inlineToolbar`, `conversionConfig`, `canBeSplit`), and `InlineTool`/`InlineToolConstructor` (adds `isActive`, `getFormattingOptions`, `createWrapper`, `getToolbarConfig`). The SDK SHALL NOT define a Block Tune tool kind: per-block settings and per-block data are provided by plugins (see `block-settings` and `plugin-block-data`), and `ToolType` SHALL have no `Tune` member. `ToolConfig` SHALL be an SDK-owned contract (not a re-exported passthrough from `@editorjs/editorjs`), kept formally distinct from `ToolOptions`: `options` describes core/plugin-facing wiring available before any block instance exists, while `ToolConfig` describes tool-author-facing user data resolved per tool registration. A tool's static `options` SHALL be either a plain options object or a synchronous factory taking the tool's `ToolConfig` and returning that options object; the facade SHALL resolve the factory exactly once, at construction, and serve every option-reading getter from that resolved value without writing it back onto the tool class. + +#### Scenario: Options and config merging in a tool facade +- **GIVEN** a tool class has static `options` (and optionally `options.config` typed as `ToolConfig`) +- **WHEN** the tool is registered via `use(Tool, options)` with overriding options +- **THEN** the facade's `options` getter merges the tool's resolved static options with `use()`-time options, with `use()`-time keys taking precedence, and the `config` getter merges similarly, injecting `defaultPlaceholder` only when `isDefault` is true and no `placeholder` key is already present + +#### Scenario: Resolving static options from a config factory +- **GIVEN** a tool class declares `static options` as a function of its `ToolConfig` rather than as a plain object +- **WHEN** its facade is constructed for a registration made via `use(Tool, { config })` +- **THEN** the function is invoked exactly once with the `config` supplied at `use()` time, its returned options object becomes the tool's resolved static options for that facade, and the tool class's own `options` property is left untouched + +#### Scenario: Deriving a toolbox entry from a config value +- **GIVEN** a block tool's `options` factory computes `toolbox` entries from a field of the config it receives +- **WHEN** the facade's `toolbox` getter is read +- **THEN** the entries reflect the config supplied at `use()` time, and any explicit `use()`-time `toolbox` override is merged on top using the existing array/object positional-merge algorithm, with a `use()`-time `toolbox: false` still hiding the tool from the toolbox + +#### Scenario: Isolating factory-derived options per facade instance +- **GIVEN** two `Core` instances each register the same tool class through `use()` with a different `config` +- **WHEN** each instance's facade resolves the tool's `options` factory +- **THEN** each facade holds its own resolved options and neither instance's derived values are observable from the other + +#### Scenario: Text content conversion without config +- **GIVEN** a block tool has no `conversionConfig` +- **WHEN** `exportTextContent`/`importTextContent` is called on its facade +- **THEN** it throws a descriptive error stating the tool does not have export/import configuration + +#### Scenario: Text content conversion with a keypath +- **GIVEN** a block tool's `conversionConfig` specifies a dot-notation string key (including nested array paths, e.g. `items.0.text`) +- **WHEN** `exportTextContent`/`importTextContent` is called +- **THEN** the value at that keypath is read/written, producing or consuming a `TextNodeSerialized` value tagged with the hidden `Text` block-child-type marker + +#### Scenario: No tune tool kind +- **WHEN** the SDK's public exports are inspected +- **THEN** there is no `BlockTune`, `BlockTuneConstructor`, `BlockTuneOptions`, `BlockTuneFacade`, or `ToolType.Tune`, and `BlockToolConstructor` has no `tunes` member + +Implemented in `src/entities/BaseTool.ts`, `BlockTool.ts`, `InlineTool.ts`, `src/tools/facades/{BaseToolFacade,BlockToolFacade,InlineToolFacade}.ts`, validated by `src/tools/facades/BaseToolFacade.spec.ts`. + +### Requirement: Tools collection +The system SHALL provide a `ToolsCollection` (a `Map` subclass) exposing filtered `blockTools`/`inlineTools` views over registered tool facades. + +#### Scenario: Filtering registered facades by kind +- **GIVEN** a `ToolsCollection` containing a mix of block tool and inline tool facades +- **WHEN** `blockTools` or `inlineTools` is accessed +- **THEN** each getter returns only the facades matching that kind + +Implemented in `src/tools/ToolsCollection.ts`, validated by its co-located `.spec.ts`. diff --git a/openspec/changes/remove-block-tunes/tasks.md b/openspec/changes/remove-block-tunes/tasks.md new file mode 100644 index 00000000..b79330e8 --- /dev/null +++ b/openspec/changes/remove-block-tunes/tasks.md @@ -0,0 +1,26 @@ +## 1. Guard the removal with tests + +- [ ] 1.1 Add type-level assertions (`@ts-expect-error`) that these no longer exist: `ToolType.Tune`, the `BlockTune*` entity exports, `BlockTuneFacade`, `BlockToolOptionKey.Tunes`, `BlockToolOptions['tunes']`, `UserToolOptions.EnabledBlockTunes` and `BlockToolFacade#enabledBlockTunes`. Enumerate tool-kind names only — the model-layer `BlockTuneName`/`BlockTuneSerialized` re-exports belong to `plugin-block-data` +- [ ] 1.2 Write a failing `ToolsCollection` spec case: the collection should expose only `blockTools`/`inlineTools`. Also write a `Core`/`ToolsManager` case: a plugin that contributes block settings items should be instantiated as a plugin and absent from the tool collections + +## 2. Remove from SDK + +- [ ] 2.1 Delete `sdk/src/entities/BlockTune.ts` and `sdk/src/tools/facades/BlockTuneFacade.ts` (with its spec), and remove their exports +- [ ] 2.2 Remove `ToolType.Tune`, `BaseToolFacade#isTune()` and `ToolsCollection#blockTunes` (its only consumer) +- [ ] 2.3 Remove `BlockTuneConstructor` from `ToolConstructable`, `BlockTuneFacade` from `ToolFacadeClass` (and its export), `ToolTypeToOptions[ToolType.Tune]`, the `ToolStaticOptions` member, the `BlockTuneOptions` re-exports in `BaseTool.ts`/`BaseToolFacade.ts`, and the `./BlockTune.js` line in the entities barrel +- [ ] 2.4 Remove `BlockToolOptionKey.Tunes` and its `BlockToolOptions` member, `UserToolOptions.EnabledBlockTunes`, `BlockToolFacade#enabledBlockTunes` and `BlockToolFacade#tunes` + +## 3. Remove from Core and dependents + +- [ ] 3.1 Remove the Tune branch from `Core#use`, the `getAll(ToolType.Tune)` step in tool preparation, the Tune case in `ToolsFactory`, and `ToolsManager#blockTunes` +- [ ] 3.2 Remove `#processBlockTune` and the `BlockTuneFacade` import from `packages/plugins/shortcuts-plugin/src/index.ts` +- [ ] 3.3 Grep the workspace for the removed tool-kind symbols (not the bare word `tunes`, which the model layer still uses until `plugin-block-data` lands), fix any leftovers, and confirm `yarn build` is clean + +## 4. Docs and wrap-up + +- [ ] 4.1 Update `docs/plugins.md` (the "Block Tune" table row and the SDK re-export list on line 5), `docs/README.md` (drop the `BlockTune` contract mention) and `docs/diagrams/plugin-lifecycle-flow.mmd` (drop the `ToolType.Tune` binding and `blockTunes`) +- [ ] 4.2 Hand-edit the **Purpose** preamble of `openspec/specs/sdk/spec.md` to drop "block tunes" — the mechanical archive fold only rewrites `### Requirement:` blocks +- [ ] 4.3 Change the `shortcuts-plugin` spec's reserved-work note from "block tunes" to "block settings items" +- [ ] 4.4 Run `yarn lint` and `yarn test`. Fix any regressions +- [ ] 4.5 Comment on PR #157 linking `plugin-block-data`, `block-settings-ui` and `remove-block-tunes` as its replacement +- [ ] 4.6 Run `openspec validate remove-block-tunes --type change` and confirm it passes diff --git a/openspec/specs/editorjs-bundle/spec.md b/openspec/specs/editorjs-bundle/spec.md index 1656c411..dee9e9ed 100644 --- a/openspec/specs/editorjs-bundle/spec.md +++ b/openspec/specs/editorjs-bundle/spec.md @@ -1,7 +1,7 @@ # editorjs-bundle Specification ## Purpose -`@editorjs/editorjs` is the batteries-included entry point for Editor.js: its default export `EditorJS` composes the headless `@editorjs/core` engine with `DOMAdapters`, `CollaborationManager`, a default set of tools (paragraph, bold, italic, link) and plugins (clipboard, shortcuts), and the default UI, so a caller can get a fully functional editor from configuration alone. It auto-initializes from the constructor, exposes an `isReady` promise, and accepts a v2-style `config.tools` map merged over the defaults with override-by-name. +`@editorjs/editorjs` is the batteries-included entry point for Editor.js: its default export `EditorJS` composes the headless `@editorjs/core` engine with `DOMAdapters`, `CollaborationManager`, a default set of tools (paragraph, bold, italic, link) and plugins (clipboard, shortcuts, default block settings), and the default UI, so a caller can get a fully functional editor from configuration alone. It auto-initializes from the constructor, exposes an `isReady` promise, and accepts a v2-style `config.tools` map merged over the defaults with override-by-name. ## Requirements ### Requirement: Batteries-included editor entry point The system SHALL provide `@editorjs/editorjs`, a package whose default export is an `EditorJS` class that composes `@editorjs/core` with a default set of tools, plugins, infrastructure, and UI so that a caller can construct a fully functional editor from configuration alone. diff --git a/openspec/specs/sdk/spec.md b/openspec/specs/sdk/spec.md index cf0cbc8f..6a51a0c5 100644 --- a/openspec/specs/sdk/spec.md +++ b/openspec/specs/sdk/spec.md @@ -2,7 +2,7 @@ ## Purpose -`@editorjs/sdk` is the shared-contracts package that tools, plugins, and adapters depend on. It provides type-only interfaces for block tools, inline tools, block tunes, and plugins; the concrete `BlockToolAdapter` base class bridging model events to per-block DOM adapters; the `EventBus`/typed event class hierarchy; and the `EditorAPI` surface passed into tools and plugins. It has no dependency on `@editorjs/core` or `@editorjs/model` directly, letting tool authors depend only on this package. +`@editorjs/sdk` is the shared-contracts package that tools, plugins, and adapters depend on. It provides type-only interfaces for block tools, inline tools, and plugins; the concrete `BlockToolAdapter` base class bridging model events to per-block DOM adapters; the `EventBus`/typed event class hierarchy; and the `EditorAPI` surface passed into tools and plugins. It has no dependency on `@editorjs/core` or `@editorjs/model` directly, letting tool authors depend only on this package. ## Requirements ### Requirement: Typed EventBus for channel:name events The system SHALL re-export `EventBus` (a thin `EventTarget` subclass defined in `@editorjs/model-types`) and augment `EventTarget`/`addEventListener`/`removeEventListener` typings so listeners are typed by a `` `${Channel}:${Name}` `` event-type template. diff --git a/openspec/specs/shortcuts-plugin/spec.md b/openspec/specs/shortcuts-plugin/spec.md index eb72e9a2..57e009c0 100644 --- a/openspec/specs/shortcuts-plugin/spec.md +++ b/openspec/specs/shortcuts-plugin/spec.md @@ -52,7 +52,7 @@ The system SHALL provide a `ShortcutsPlugin` (an `EditorjsPlugin` with `name` `s - **WHEN** `destroy()` is called - **THEN** it clears the registered shortcuts so subsequent keydowns dispatch nothing -Shortcuts for block tools and block tunes (a `shortcuts` map under `options.plugins.shortcuts`) are reserved for future work and not yet implemented. +Shortcuts for block tools and block settings items (a `shortcuts` map under `options.plugins.shortcuts`) are reserved for future work and not yet implemented. Implemented in `src/index.ts`, validated by its co-located `.spec.ts`. diff --git a/openspec/specs/ui/spec.md b/openspec/specs/ui/spec.md index 84e2baed..3cd0e525 100644 --- a/openspec/specs/ui/spec.md +++ b/openspec/specs/ui/spec.md @@ -4,7 +4,12 @@ `@editorjs/ui` is the default rendering shell for Editor.js: a set of `EditorjsPlugin` implementations that subscribe to the core `EventBus` to render DOM and dispatch their own `ui:*` events so the pieces can wire themselves together. It owns no document state — it renders what `core` (`BlockManager`/`SelectionManager`, etc.) reports, and forwards user interaction back through `EditorAPI`. -**Note**: `src/Blocks/Blocks.spec.ts` and `src/lifecycle.spec.ts` cover teardown and active/replacement-instance controls. The remaining scenarios below are derived from source and are not all covered by these tests. +**Note**: `src/Blocks/Blocks.spec.ts` and `src/lifecycle.spec.ts` cover teardown and +active/replacement-instance controls, and `src/BlockSettings/BlockSettings.spec.ts` and +`src/Toolbar/Toolbar.spec.ts` cover the block settings menu and the toolbar wiring that hosts +it. The remaining scenarios below are derived from the event-wiring logic in source rather than +confirmed by unit tests, though the toolbar's accessibility behaviour is additionally asserted +end to end by `packages/editorjs/e2e`. ## Requirements ### Requirement: Shell assembly The system SHALL provide `EditorjsUI` as the top-level shell that creates the editor wrapper in the holder element and reactively assembles the Toolbar, InlineToolbar, and Blocks elements into it as each announces its own `*:rendered` event, without holding direct references to those components. diff --git a/packages/plugins/default-block-settings-plugin/dist/index.d.ts b/packages/plugins/default-block-settings-plugin/dist/index.d.ts new file mode 100644 index 00000000..7ab2afcd --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/dist/index.d.ts @@ -0,0 +1,34 @@ +import type { EditorjsPlugin, EditorjsPluginParams } from '@editorjs/sdk'; +import { PluginType } from '@editorjs/sdk'; +/** + * Supplies the default entries of the block settings menu -- Move up, Move down and Delete -- + * as an ordinary plugin registered with the `block-settings` API. + * + * Nothing here is privileged: this is the reference example of what used to be a "block tune", + * written the way any third-party plugin would write it. + */ +export declare class DefaultBlockSettingsPlugin implements EditorjsPlugin { + #private; + /** + * Registers with `core.use` under {@link PluginType.Plugin} + */ + static readonly type = PluginType.Plugin; + /** + * Identifier the editor registers this plugin under + */ + static readonly name = "default-block-settings"; + /** + * DefaultBlockSettingsPlugin class constructor + * @param params - plugin parameters + */ + constructor({ api, eventBus }: EditorjsPluginParams); + /** + * Takes the provider back out of the menu. + * + * The ready listener goes too: the bus outlives the plugin, and a plugin destroyed before + * the editor finished starting would otherwise register a provider afterwards -- one nothing + * holds the unregister function for + */ + destroy(): void; +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/plugins/default-block-settings-plugin/dist/index.d.ts.map b/packages/plugins/default-block-settings-plugin/dist/index.d.ts.map new file mode 100644 index 00000000..93e420f0 --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,cAAc,EACd,oBAAoB,EAErB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAiB,UAAU,EAAE,MAAM,eAAe,CAAC;AAU1D;;;;;;GAMG;AACH,qBAAa,0BAA2B,YAAW,cAAc;;IAC/D;;OAEG;IACH,gBAAuB,IAAI,qBAAqB;IAEhD;;OAEG;IACH,gBAAuB,IAAI,4BAA4B;IAiBvD;;;OAGG;gBACS,EAAE,GAAG,EAAE,QAAQ,EAAE,EAAE,oBAAoB;IAOnD;;;;;;OAMG;IACI,OAAO,IAAI,IAAI;CA6HvB"} \ No newline at end of file diff --git a/packages/plugins/default-block-settings-plugin/dist/index.js b/packages/plugins/default-block-settings-plugin/dist/index.js new file mode 100644 index 00000000..dd93e21b --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/dist/index.js @@ -0,0 +1,159 @@ +import { CoreEventType, PluginType } from '@editorjs/sdk'; +import { IconChevronDown, IconChevronUp, IconCross, IconTrash } from '@codexteam/icons'; +/** + * Order the provider registers at, which puts its items after every other provider's. + * The built-in actions belong at the bottom of the menu + */ +const DEFAULT_SETTINGS_ORDER = 1000; +/** + * Supplies the default entries of the block settings menu -- Move up, Move down and Delete -- + * as an ordinary plugin registered with the `block-settings` API. + * + * Nothing here is privileged: this is the reference example of what used to be a "block tune", + * written the way any third-party plugin would write it. + */ +export class DefaultBlockSettingsPlugin { + /** + * Registers with `core.use` under {@link PluginType.Plugin} + */ + static type = PluginType.Plugin; + /** + * Identifier the editor registers this plugin under + */ + static name = 'default-block-settings'; + /** + * EditorAPI instance used to move and delete blocks + */ + #api; + /** + * Event bus the ready listener is attached to + */ + #eventBus; + /** + * Removes the provider again, once it has been registered + */ + #unregister; + /** + * DefaultBlockSettingsPlugin class constructor + * @param params - plugin parameters + */ + constructor({ api, eventBus }) { + this.#api = api; + this.#eventBus = eventBus; + this.#eventBus.addEventListener(`core:${CoreEventType.Ready}`, this.#handleReady); + } + /** + * Takes the provider back out of the menu. + * + * The ready listener goes too: the bus outlives the plugin, and a plugin destroyed before + * the editor finished starting would otherwise register a provider afterwards -- one nothing + * holds the unregister function for + */ + destroy() { + this.#eventBus.removeEventListener(`core:${CoreEventType.Ready}`, this.#handleReady); + this.#unregister?.(); + this.#unregister = undefined; + } + /** + * Registers once the editor is ready + */ + #handleReady = () => { + this.#register(); + }; + /** + * Registers the provider, unless the editor runs without a block settings menu. + * + * The lookup is deliberately late and optional: `api.plugins` is per editor instance, so a + * headless `Core` that never registered `BlockSettingsUI` simply has no entry here and this + * plugin stays inert rather than failing to initialise + */ + #register() { + const blockSettings = this.#api.plugins['block-settings']; + if (blockSettings === undefined) { + return; + } + this.#unregister = blockSettings.register(context => this.#items(context), { order: DEFAULT_SETTINGS_ORDER }); + } + /** + * Builds the items for one block + * @param context - the block the menu is being built for + */ + #items({ blockId, blockIndex }) { + const lastIndex = this.#api.blocks.getBlocksCount() - 1; + return [ + { + name: 'move-up', + title: 'Move up', + icon: IconChevronUp, + closeOnActivate: true, + /** + * A snapshot from when the menu was built, unlike the action below. Going stale + * only greys an item out, while a stale index would move the wrong block + */ + isDisabled: blockIndex <= 0, + onActivate: () => this.#move(blockId, -1), + }, + { + name: 'move-down', + title: 'Move down', + icon: IconChevronDown, + closeOnActivate: true, + isDisabled: blockIndex >= lastIndex, + onActivate: () => this.#move(blockId, 1), + }, + { + name: 'delete', + title: 'Delete', + icon: IconTrash, + /** + * Deletion asks first. The item turns into its own confirmation, and only that + * confirmation carries the handler -- which is why this item has no `onActivate` + */ + confirmation: { + name: 'delete-confirm', + title: 'Click to delete', + icon: IconCross, + closeOnActivate: true, + onActivate: () => this.#delete(blockId), + }, + }, + ]; + } + /** + * Moves the block one position in the given direction. + * + * The position is resolved from the id now rather than taken from the context: the menu may + * have been open while a collaborator inserted a block above the target, or while an undo ran + * @param blockId - id of the block to move + * @param offset - -1 to move up, 1 to move down + */ + #move(blockId, offset) { + const fromIndex = this.#api.blocks.getIndexById(blockId); + /** + * The block is gone -- removed by a collaborator or an undo while the menu was open. + * The lookup reports -1 rather than throwing, so there is nothing to recover from + */ + if (fromIndex === -1) { + return; + } + const toIndex = fromIndex + offset; + if (toIndex < 0 || toIndex > this.#api.blocks.getBlocksCount() - 1) { + return; + } + this.#api.blocks.move({ + fromIndex, + toIndex, + }); + } + /** + * Deletes the block, by id rather than by position + * @param blockId - id of the block to delete + */ + #delete(blockId) { + if (this.#api.blocks.getIndexById(blockId) === -1) { + return; + } + this.#api.blocks.delete({ block: blockId }); + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/plugins/default-block-settings-plugin/dist/index.js.map b/packages/plugins/default-block-settings-plugin/dist/index.js.map new file mode 100644 index 00000000..a8fbffe1 --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAGxF;;;GAGG;AACH,MAAM,sBAAsB,GAAG,IAAI,CAAC;AAEpC;;;;;;GAMG;AACH,MAAM,OAAO,0BAA0B;IACrC;;OAEG;IACI,MAAM,CAAU,IAAI,GAAG,UAAU,CAAC,MAAM,CAAC;IAEhD;;OAEG;IACI,MAAM,CAAU,IAAI,GAAG,wBAAwB,CAAC;IAEvD;;OAEG;IACM,IAAI,CAAY;IAEzB;;OAEG;IACM,SAAS,CAAW;IAE7B;;OAEG;IACH,WAAW,CAA2B;IAEtC;;;OAGG;IACH,YAAY,EAAE,GAAG,EAAE,QAAQ,EAAwB;QACjD,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;QAChB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;QAE1B,IAAI,CAAC,SAAS,CAAC,gBAAgB,CAAC,QAAQ,aAAa,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;IACpF,CAAC;IAED;;;;;;OAMG;IACI,OAAO;QACZ,IAAI,CAAC,SAAS,CAAC,mBAAmB,CAAC,QAAQ,aAAa,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;QAErF,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC;QACrB,IAAI,CAAC,WAAW,GAAG,SAAS,CAAC;IAC/B,CAAC;IAED;;OAEG;IACH,YAAY,GAAG,GAAS,EAAE;QACxB,IAAI,CAAC,SAAS,EAAE,CAAC;IACnB,CAAC,CAAC;IAEF;;;;;;OAMG;IACH,SAAS;QACP,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC;QAE1D,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YAChC,OAAO;QACT,CAAC;QAED,IAAI,CAAC,WAAW,GAAG,aAAa,CAAC,QAAQ,CACvC,OAAO,CAAC,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,EAC/B,EAAE,KAAK,EAAE,sBAAsB,EAAE,CAClC,CAAC;IACJ,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,EAAE,OAAO,EAAE,UAAU,EAAwB;QAClD,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,cAAc,EAAE,GAAG,CAAC,CAAC;QAExD,OAAO;YACL;gBACE,IAAI,EAAE,SAAS;gBACf,KAAK,EAAE,SAAS;gBAChB,IAAI,EAAE,aAAa;gBACnB,eAAe,EAAE,IAAI;gBAErB;;;mBAGG;gBACH,UAAU,EAAE,UAAU,IAAI,CAAC;gBAC3B,UAAU,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;aAC1C;YACD;gBACE,IAAI,EAAE,WAAW;gBACjB,KAAK,EAAE,WAAW;gBAClB,IAAI,EAAE,eAAe;gBACrB,eAAe,EAAE,IAAI;gBACrB,UAAU,EAAE,UAAU,IAAI,SAAS;gBACnC,UAAU,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;aACzC;YACD;gBACE,IAAI,EAAE,QAAQ;gBACd,KAAK,EAAE,QAAQ;gBACf,IAAI,EAAE,SAAS;gBAEf;;;mBAGG;gBACH,YAAY,EAAE;oBACZ,IAAI,EAAE,gBAAgB;oBACtB,KAAK,EAAE,iBAAiB;oBACxB,IAAI,EAAE,SAAS;oBACf,eAAe,EAAE,IAAI;oBACrB,UAAU,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;iBACxC;aACF;SACF,CAAC;IACJ,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,OAAgB,EAAE,MAAc;QACpC,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QAEzD;;;WAGG;QACH,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,CAAC;YACrB,OAAO;QACT,CAAC;QAED,MAAM,OAAO,GAAG,SAAS,GAAG,MAAM,CAAC;QAEnC,IAAI,OAAO,GAAG,CAAC,IAAI,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,cAAc,EAAE,GAAG,CAAC,EAAE,CAAC;YACnE,OAAO;QACT,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC;YACpB,SAAS;YACT,OAAO;SACR,CAAC,CAAC;IACL,CAAC;IAED;;;OAGG;IACH,OAAO,CAAC,OAAgB;QACtB,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;YAClD,OAAO;QACT,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IAC9C,CAAC"} \ No newline at end of file