diff --git a/.github/actions/base-coverage/action.yml b/.github/actions/base-coverage/action.yml index 3dc3b6de..a0499958 100644 --- a/.github/actions/base-coverage/action.yml +++ b/.github/actions/base-coverage/action.yml @@ -22,15 +22,27 @@ runs: fetch-depth: 0 submodules: true - - name: Check package exists on base ref + # A base-ref comparison only means something when the base ref can actually produce + # a coverage report. Two cases cannot: the package may not exist there yet, or it may + # exist without a test suite, which is the case for the PR that first adds one. The + # second needs its own check -- package.json is present, so the file test passes, and + # `yarn workspace ... test:coverage` then fails with "couldn't find a script". + - name: Check base ref can report coverage id: check shell: bash run: | - if [ -f "${{ inputs.working-directory }}/package.json" ]; then - echo "exists=true" >> "$GITHUB_OUTPUT" - else + if [ ! -f "${{ inputs.working-directory }}/package.json" ]; then echo "Package not present on base ref (new package), skipping base coverage" echo "exists=false" >> "$GITHUB_OUTPUT" + elif ! node -e " + const fs = require('fs'); + const pkg = JSON.parse(fs.readFileSync(process.argv[1] + '/package.json', 'utf8')); + process.exit(pkg.scripts && pkg.scripts['test:coverage'] ? 0 : 1); + " "${{ inputs.working-directory }}"; then + echo "Package has no test:coverage script on base ref (suite added in this PR), skipping base coverage" + echo "exists=false" >> "$GITHUB_OUTPUT" + else + echo "exists=true" >> "$GITHUB_OUTPUT" fi - name: Setup Node diff --git a/.github/workflows/default-block-settings-plugin.yml b/.github/workflows/default-block-settings-plugin.yml new file mode 100644 index 00000000..eb927d49 --- /dev/null +++ b/.github/workflows/default-block-settings-plugin.yml @@ -0,0 +1,20 @@ +name: Default block settings plugin check +on: + pull_request: + merge_group: + +permissions: + contents: read + pull-requests: write + issues: write + actions: read + +jobs: + package-check: + uses: ./.github/workflows/package-check.yml + with: + package-name: '@editorjs/default-block-settings-plugin' + working-directory: './packages/plugins/default-block-settings-plugin' + include-mutations: true + secrets: + stryker_dashboard_api_key: ${{ secrets.STRYKER_DASHBOARD_API_KEY }} diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml new file mode 100644 index 00000000..4f9bc02b --- /dev/null +++ b/.github/workflows/ui.yml @@ -0,0 +1,17 @@ +name: UI check +on: + pull_request: + merge_group: + +permissions: + contents: read + pull-requests: write + issues: write + actions: read + +jobs: + package-check: + uses: ./.github/workflows/package-check.yml + with: + package-name: '@editorjs/ui' + working-directory: './packages/ui' diff --git a/docs/events.md b/docs/events.md index 635923e2..40282acc 100644 --- a/docs/events.md +++ b/docs/events.md @@ -47,9 +47,24 @@ Dispatched on the IoC-managed `EventBus` (one instance per editor) with prefixed | `UndoCoreEvent` | `core:undo` | — | `DocumentAPI.undo()` or `BlocksUI` (Cmd/Ctrl+Z) | | `RedoCoreEvent` | `core:redo` | — | `DocumentAPI.redo()` or `BlocksUI` (Cmd/Ctrl+Shift+Z) | | `BeforeInputUIEvent` | `ui:before-input` | `{ data, inputType, targetRanges, isCrossInputSelection, isComposing }` | `BlocksUI` | +| `BlockSelectedUIEvent` | `ui:blocks:block-selected` | `{ block: HTMLElement, index }` | `BlocksUI`, on pointer enter and on the caret moving into another block | +| `BlockSettingsOpenUIEvent` | `ui:block-settings:open` | `{ index }` | anyone opening the menu programmatically | +| `BlockSettingsRenderedUIEvent` | `ui:block-settings:rendered` | `{ button: HTMLElement, blockSettings: HTMLElement }` | `BlockSettingsUI` | +| `BlockSettingsOpenedUIEvent` | `ui:block-settings:opened` | — | `BlockSettingsUI` | +| `BlockSettingsClosedUIEvent` | `ui:block-settings:closed` | — | `BlockSettingsUI` | `BlockAddedCoreEvent` carries the rendered `HTMLElement` in `detail.ui`, while the model-level `BlockAddedEvent` carries serialised data — they are complementary. +`BlockSettingsUI` owns both its menu and the button that opens it, and announces the two +together so a host can place them: `ToolbarUI` puts the button among its own controls and the +menu beside the toolbox popover. `ui:block-settings:open` is therefore not how the button works +— it is the way anything *else* opens the menu, naming the target block by index. + +`BlockSelectedUIEvent` is what "the selected block" means to the toolbar and to anything +mounted in it. It is dispatched for the pointer entering a block *and* for the caret moving +into one, so a control acting on the selected block still works for someone who never touches +a mouse. Repeats for the same block are not dispatched. + Use core/UI events for UI workflows and extension coordination. ## Adapter internals diff --git a/docs/plugins.md b/docs/plugins.md index cce3fb35..f8d5f4e0 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -28,7 +28,8 @@ Tools are registered via `core.use(ToolConstructor, options)` during setup. The | Inline Tool | `InlineTool` (from config `tools`) | Selection formatting actions | There is no Block Tune tool kind. What v2 called a tune is a UI plugin: it puts an item in the -block settings menu and stores its state as [per-block plugin data](#per-block-plugin-data). +[block settings menu](#block-settings) and stores its state as +[per-block plugin data](#per-block-plugin-data). ## Initialization sequence @@ -116,6 +117,66 @@ Merging is shallow **at the plugin-id level**: a slice supplied through `use()` const { shortcut } = toolFacade.pluginOptions('shortcuts') ?? {}; ``` +## Block settings + +The per-block settings menu — the thing v2 called "block tunes" — is no longer a kind of entity. +`BlockSettingsUI` renders the popover and the button that opens it, announcing both through +`ui:block-settings:rendered` for the toolbar to place, and owns no items of its own; a plugin +contributes to it by registering a *provider*: + +```ts +const unregister = api.plugins['block-settings']?.register(ctx => ({ + title: 'Anchor', + icon: IconLink, + isActive: Boolean(api.blocks.getPluginData({ block: ctx.blockId, plugin: 'anchors' })), + onActivate: () => setAnchor(ctx.blockId), +})); +``` + +A provider is asked again every time the menu opens, so an item's `isActive`, `isDisabled` and +`title` can be derived from current state rather than cached. Return `undefined` (or an empty +array) to contribute nothing for a given block — a provider that opts out adds no separator +either. Item behaviour comes entirely from the returned config — a `BlockSettingsMenuConfig`, which is +ui-kit's popover-item shape: `onActivate`, `closeOnActivate`, `children` for a submenu, or a +`confirmation` whose own handler runs on the second activation. It is deliberately not +`@editorjs/sdk`'s `MenuConfig`, which is the narrower shape inline tools return from +`getToolbarConfig`. + +The button that opens the menu is a toggle: activating it while the menu is open dismisses it. +It acts on the block the pointer is over, or — with no pointer involved — the one the caret is +in, so the menu is reachable from the keyboard alone. + +Contributions are concatenated in ascending `order` (default `0`, ties broken by registration +order), separated from one another. `@editorjs/default-block-settings-plugin` registers at +`order: 1000` so the built-in Move up / Move down / Delete sit last; it is the reference example +of a former "tune" written as a plain plugin, with no privileged path into the menu. + +### Resolve positions from `blockId`, not `blockIndex` + +The provider context carries both, but only `blockId` is durable: + +```ts +onActivate: () => { + const index = api.blocks.getIndexById(ctx.blockId); + + // The block may be gone — removed by a collaborator, or by an undo — while the menu was open. + if (index === -1) { + return; + } + + api.blocks.move({ fromIndex: index, toIndex: index - 1 }); +} +``` + +`ctx.blockIndex` is only true at the moment the menu was built. A menu can stay open while a +collaborator inserts a block above the target, or while an undo runs, and a handler acting on the +stale index then moves the wrong block. Deriving a *disabled state* from the index is fine, since +going stale only greys an item out — deriving an *action* from it is not. + +The menu is absent in a headless setup, which is why the lookup above is optional: a plugin +registered on a `Core` without `BlockSettingsUI` finds nothing under `api.plugins['block-settings']` +and should simply contribute nothing rather than fail. + ## Per-block plugin data A plugin stores its own data on a block through `api.blocks`, under a key that is by convention the @@ -310,6 +371,9 @@ Programmatic block management — delegates to `BlocksManager`. | `render(document)` | Re-initialize the document from serialised data | | `clear()` | Remove all blocks | | `getBlocksCount()` | Return the total number of blocks | +| `getIdByIndex(index)` | Id of the block at that index, or `undefined` | +| `getIndexById(id)` | Position of the block with that id, or `-1` | +| `getToolByIndex(index)` | Tool name of the block at that index, or `undefined` | | `getPluginData({ block, plugin })` | Read a plugin's per-block data, or `undefined` | | `updatePluginData({ block, plugin, data, userId? })` | Merge keys into a plugin's per-block data | diff --git a/openspec/changes/block-settings-ui/design.md b/openspec/changes/block-settings-ui/design.md index ef8018c7..ddc16861 100644 --- a/openspec/changes/block-settings-ui/design.md +++ b/openspec/changes/block-settings-ui/design.md @@ -44,12 +44,16 @@ type BlockSettingsProvider = (ctx: { blockId: BlockId; blockIndex: number; tool: 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. +2. The plugin follows `ui:blocks:block-selected` itself to know which block the button acts on, and stops following it for as long as the toolbar is holding its position -- while the menu is open, and while the toolbox 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 or the toolbox are open. + +The two halves of 2 and 3 have to agree, which is why the plugin tracks `ui:toolbox:opened`/`closed` as well. `ToolbarUI` owns where the button sits and this plugin owns what it acts on, so whenever one freezes the other must: a button left beside one block whose menu was built for another acts on the wrong block, and `Delete` is one of the items. *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`. +`BlockSettingsUI` resolves the target block's id with `api.blocks.getIdByIndex(index)` as each selection is reported, and keeps that id as the target, resolving the position back with `getIndexById` when the menu opens. So this change needs no new event or payload field from `core`. Keeping the position instead would go stale: a block inserted or removed above the target shifts every position below it, and none of the ways that happens -- a collaborator, an undo, a move -- reports a selection, so the button would quietly come to act on a different block. + +*Alternative considered:* give `ToolbarUI` the target index and pass it in `ui:block-settings:open`, so there is one owner rather than two components agreeing. Rejected for now because it moves the block the menu acts on back out of the plugin that owns the button, against the reasoning above; the duplicated flag is the smaller cost, and `ui:block-settings:open` stays available as the seam if that trade changes. 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. diff --git a/openspec/changes/block-settings-ui/specs/block-settings/spec.md b/openspec/changes/block-settings-ui/specs/block-settings/spec.md index 249254d0..05eab212 100644 --- a/openspec/changes/block-settings-ui/specs/block-settings/spec.md +++ b/openspec/changes/block-settings-ui/specs/block-settings/spec.md @@ -1,13 +1,18 @@ ## 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. +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. That announcement is made once and is not replayed, so the plugin SHALL be registered after whatever mounts it: a host registered later never hears it, and the button and the menu stay off the page with nothing reported. This ordering requirement SHALL be documented on the plugin. 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. Those SHALL be dispatched only when the state really changes: replacing the popover to show another block's items keeps the menu open throughout, so a rebuild SHALL report neither, and `aria-expanded` SHALL stay `"true"` across it. #### 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: Rebuilding the menu for another block +- **GIVEN** the menu is open for one block +- **WHEN** it is asked to open for another, which replaces the popover under it +- **THEN** the items become that block's, and neither `closed` nor `opened` is dispatched and `aria-expanded` stays `"true"`, because the menu never stopped being open + #### 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()` @@ -24,7 +29,7 @@ The system SHALL provide `BlockSettingsUI`, an `EditorjsPlugin` with static `nam - **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. +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. Where the open menu's own keyboard handling claims the key and suppresses the click the activation would otherwise produce, the dismissal SHALL happen on the keydown itself: no click arrives to carry it, and without that the menu cannot be dismissed from the button at all. 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 remember the block it acts on by identity rather than by position, because a block inserted or removed above it shifts every position below without any selection being reported, and resolve the position again when the menu opens. Once nothing is holding the target, the plugin SHALL take up whichever block the blocks plugin then reports as selected, rather than waiting for the next selection to be announced: the ones ignored while frozen are not announced again, so the button would go on acting on a block the caret has left -- which is what clicking into another block does, since the caret moves on mousedown while the popover only closes on the click. The plugin SHALL follow block selection to know which block the button acts on, and SHALL stop following it whenever the toolbar is holding its position — while the menu is open, and while the toolbox is open, since that popover renders inside the toolbar and moving it would carry the popover along. The button therefore stays beside one block for as long as either is open, and the block it acts on SHALL stay with it: a menu built for a block the button is not next to acts on the wrong one, and `Delete` is among its items. #### Scenario: The button is announced with the menu - **WHEN** `BlockSettingsUI` is constructed @@ -45,6 +50,31 @@ The button `BlockSettingsUI` announces SHALL carry the whole menu-button contrac - **WHEN** the button is activated again - **THEN** the menu closes, `aria-expanded` returns to `"false"`, and no second menu is built +#### Scenario: Clicking into another block while the menu is open +- **GIVEN** the menu is open for one block, and the caret is then placed in another, which is reported while the target is frozen +- **WHEN** the menu closes +- **THEN** the button acts on the block the caret reached, and the toolbar has moved to it, so the two still name the same block + +#### Scenario: A block is inserted above the target +- **GIVEN** the block at index 1 is the reported selection, and a block is then inserted above it by a collaborator, an undo or a move +- **WHEN** the button is activated +- **THEN** the menu is built for the block that was selected, at the position it now holds, rather than for whatever moved into index 1 + +#### Scenario: The target block is removed +- **GIVEN** the reported selection is a block that is then removed from the document +- **WHEN** the button is activated +- **THEN** no provider is asked and no menu opens, as for any position naming no block + +#### Scenario: The button is activated again from the keyboard +- **GIVEN** the menu was opened from the button, and the button holds focus +- **WHEN** Enter is pressed again, and the open menu's keyboard handling has already prevented the default so that no click follows +- **THEN** the menu closes and `aria-expanded` returns to `"false"`, rather than staying open with nothing left to dismiss it + +#### Scenario: A claimed key arrives with the menu closed +- **GIVEN** the menu is closed +- **WHEN** a key whose default was prevented elsewhere reaches the button +- **THEN** no provider is asked and no menu opens, because a dismissal is all that keydown stands in for + #### 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 @@ -55,6 +85,16 @@ The button `BlockSettingsUI` announces SHALL carry the whole menu-button contrac - **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 while the toolbox is open +- **GIVEN** the block at index 0 is selected and the toolbox is open, so the toolbar is holding its position beside that block +- **WHEN** another block is reported as selected, the toolbox closes, and the button is activated +- **THEN** the menu is built for the block the button is beside, not the one hovered while the toolbox was open + +#### Scenario: The target follows the selection again once the toolbox closes +- **GIVEN** the toolbox was open and has closed +- **WHEN** another block is reported as selected and the button is activated +- **THEN** the menu is built for that block, because the toolbar is following the selection again + #### 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 @@ -73,7 +113,7 @@ The settings popover SHALL carry an accessible name drawn from the UI package's - **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`). +`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, with `tool` absent when it could not be determined -- which means the editor's view of the block disagrees with the Model's, since the id and the tool are read from the same position -- so that a provider matching on a tool does not match, rather than being handed an empty name that matches nothing while looking like an answer 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`. Unregistering SHALL take effect from the next open, since providers are asked as the menu is built, so a menu already on screen keeps the items it was built with until it closes. 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: () => ... }))` @@ -111,18 +151,43 @@ The settings popover SHALL carry an accessible name drawn from the UI package's - **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. +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 its 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. The menu shows nothing until every provider has answered, so providers are expected to answer from what they already have: the timeout SHALL default to half a second, as a backstop rather than a budget, and a provider that genuinely needs longer SHALL say so at registration through `options.timeout` rather than every menu waiting on its account. This SHALL cover the callbacks a contributed item carries that the popover calls itself, at any depth of nested items and on an item's confirmation state, since they run after the provider has returned and outside anything it could be held to otherwise. `isActive`, which the popover reads as it renders, SHALL be resolved while the provider's items are collected, so a throw costs that provider's items as returning nothing does, rather than aborting the popover and with it every other provider's items. `onActivate`, which the popover calls on a click, SHALL instead be reported and go no further, because the popover honours `closeOnActivate` only after the handler returns and a throw escaping would abandon that along with the rest of the activation. 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: An item's isActive callback throws +- **GIVEN** two providers are registered and the first contributes an item whose `isActive` throws +- **WHEN** block settings open +- **THEN** the menu opens with the second provider's items alone and the failure is reported to the console, rather than no menu opening at all + +#### Scenario: An item's onActivate throws +- **GIVEN** an item whose `onActivate` throws, contributed by a provider +- **WHEN** it is activated +- **THEN** the failure is reported to the console and does not reach the popover, so the activation it would have abandoned, `closeOnActivate` among it, still runs + +#### Scenario: A nested item's isActive callback throws +- **GIVEN** a provider contributes an item whose nested child's `isActive` throws +- **WHEN** block settings open +- **THEN** that provider is skipped on the same terms, because nested items are rendered with their parent + +#### Scenario: An isActive callback that works +- **GIVEN** a provider contributes one item whose `isActive` returns `true` and one whose returns `false` +- **WHEN** block settings open +- **THEN** the first is shown as active and the second is not + #### 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 asks to be waited for +- **GIVEN** a provider registered with a `timeout` longer than the default, which answers within it +- **WHEN** block settings open +- **THEN** its items are shown, and nothing is reported -- while a provider that asked for less than it takes is skipped at the budget it asked for + #### Scenario: A provider never settles - **GIVEN** a provider returns a promise that never settles - **WHEN** block settings open and the timeout elapses 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 index 65d96ca1..200b27ce 100644 --- 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 @@ -1,7 +1,7 @@ ## 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. +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. Their titles SHALL come from a message catalogue of the plugin's own, as `@editorjs/ui` keeps its own strings, so that localising them is a change to one module rather than to every item it builds. 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 diff --git a/openspec/changes/block-settings-ui/specs/ui/spec.md b/openspec/changes/block-settings-ui/specs/ui/spec.md index 06b3dff1..101bffaa 100644 --- a/openspec/changes/block-settings-ui/specs/ui/spec.md +++ b/openspec/changes/block-settings-ui/specs/ui/spec.md @@ -1,7 +1,7 @@ ## 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. +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. Once both are closed it SHALL move to whichever block the blocks plugin then reports as selected, rather than waiting for the next selection: nothing announces the ones it held through, so the toolbar would otherwise be left beside a block the caret has gone from. 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 @@ -13,6 +13,11 @@ The system SHALL provide `ToolbarUI`, which renders a floating toolbar with a pl - **WHEN** the click is handled - **THEN** `ToolbarUI` dispatches a `ToolboxOpenUIEvent` +#### Scenario: The toolbar's own button does not submit a form +- **GIVEN** the editor is mounted inside a `
` +- **WHEN** the plus button is clicked +- **THEN** the toolbox opens and the form is not submitted, because the button is not a submit control + #### 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 @@ -23,10 +28,15 @@ The system SHALL provide `ToolbarUI`, which renders a floating toolbar with a pl - **WHEN** the pointer hovers a different block - **THEN** the toolbar does not move until settings close +#### Scenario: Catching up on the selection it held through +- **GIVEN** a block was reported as selected while the toolbar was holding its position +- **WHEN** the last of the Toolbox and block settings closes +- **THEN** the toolbar asks the blocks plugin which block is selected and moves to it, and with no block selected at all it stays where it is + 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. +`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, SHALL advertise the menu it controls via `aria-haspopup="menu"`, and SHALL declare itself a non-submitting control, so that an editor mounted inside a form is not posted when the toolbox is opened. 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 @@ -82,10 +92,24 @@ The pattern covers the **unmodified** arrow keys only. `ToolbarUI` SHALL ignore ### 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. +`BlocksUI` SHALL expose which block it treats as selected through its public API, as `api.plugins.blocksUI`, answering with the block's wrapper element and the position that block holds at the moment of asking. Selection reaches other plugins as a one-shot event, and one that ignores an announcement on purpose -- as the toolbar and the settings menu both do while a popover holds them -- has no other way to find out what it missed. The answer SHALL be nothing when no block has been reported, or when the block that was has since been removed, so that a caller is never handed a wrapper that has left the document. This is the UI's own notion of selection, not the model's, which `core:selection-changed` carries. + 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. +A repeat SHALL mean the same block at the same position, and either differing SHALL be dispatched. Adding or removing a block shifts the positions below it without the selection having moved, which makes each half necessary on its own: recognising the repeat by position alone lets the next block to land on that number read as already reported, so the caret arriving there is announced to nobody; recognising it by block alone hides that the block moved on the page, which the toolbar follows off this event and nothing else. + +#### Scenario: Asking which block is selected +- **GIVEN** a block has been reported as selected, and a block has since been inserted above it +- **WHEN** a plugin asks `api.plugins.blocksUI` for the selected block +- **THEN** it is given that same block and the position it holds now, not the one it held when it was reported + +#### Scenario: Asking before anything is selected, or after it is gone +- **GIVEN** no block has been reported as selected, or the one that was has been removed +- **WHEN** a plugin asks for the selected block +- **THEN** it is given nothing, rather than a wrapper that is no longer in the document + #### Scenario: Inserting a block wrapper at an index - **GIVEN** a `BlockAddedCoreEvent` with a valid index - **WHEN** `BlocksUI` processes it @@ -111,6 +135,16 @@ Only caret movement SHALL be filtered for repeats, because `selectionchange` fir - **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: A different block lands on the reported position +- **GIVEN** the caret was reported in a block, and a block above it is then removed, so the block below takes the position the caret's block held +- **WHEN** the caret moves into that block +- **THEN** `BlockSelectedUIEvent` is dispatched, because it is a different block however its position compares + +#### Scenario: A block is added above the caret +- **GIVEN** the caret is in a block, and a block is inserted above it, pushing it down the page +- **WHEN** the caret moves within that same block +- **THEN** `BlockSelectedUIEvent` is dispatched with its new position, because the toolbar tracks where the block is from this event alone + #### 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 diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index eab6903a..831ca5fe 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -15,17 +15,18 @@ ## 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 +- [x] 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` +- [x] 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` +- [x] 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 +- [x] 1.4 Point `vite.config.ts`'s `dts()` at `tsconfig.build.json` so declaration emit keeps excluding `*.spec.ts` +- [x] 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 + - `base-coverage` already skipped a package absent from the base ref, but `packages/ui/package.json` *is* there — only the script is missing, so the file test passed and `yarn workspace @editorjs/ui test:coverage` would have failed with "couldn't find a script". Its guard now also checks that the base ref declares `test:coverage`, which covers every future package that adds its first suite +- [x] 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: +- [x] 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>` +- [x] 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 @@ -34,18 +35,20 @@ - 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 +- [x] 2.3 Add a `UiComponentType.BlockSettings` member in `sdk` and declare it as `BlockSettingsUI`'s `static type` (`EditorjsPluginConstructor` requires an `EntityType` value) +- [x] 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) +- [x] 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 + - The menu is rebuilt from scratch on each open rather than edited in place. `removeItemByName` is ui-kit's only removal and a separator is constructed without params, so it has no name to be removed by; handing a fresh popover the whole item list is what guarantees the previous block's items leave the tree. The swap happens inside the plugin's own holder, so ui-kit's rendered DOM is never touched +- [x] 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) +- [x] 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: +- [x] 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 +- [x] 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 + - The string type-checked because the payload interface is empty, so every listener had been receiving `detail: 'ui:toolbox:open'`. The event name was never affected -- it comes from the class -- so nothing downstream had to change with it +- [x] 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 +- [x] 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 @@ -53,51 +56,85 @@ - `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` +- [x] 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: +- [x] 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` +- [x] 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 +- [x] 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 + - `@codexteam/icons` turned out to be a second runtime dependency: the items carry icons, and the package was resolving it through workspace hoisting alone, which would break a standalone install. Declared it, and widened the capability's requirement text, which had said `@editorjs/sdk` was the only one +- [x] 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 +- [x] 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 +- [x] 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 +- [x] 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 +- [x] 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 +- [x] 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) +- [x] 5.2 Run `yarn lint`, `yarn test`, and the e2e suite. Fix any regressions + - Clean: lint and build workspace-wide, 1,099 unit tests, and 92 e2e across Chromium and WebKit. The one `✘` in the e2e run is `aria.spec.ts`'s `test.fail()` case for the unfixed `focus: true` caret todo, which Playwright counts as passing - [ ] 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 +- [x] 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 +- [x] 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 +- [x] 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 +- [x] 6.4 Replace the two `api.document.data.blocks.length` reads in `DefaultBlockSettingsPlugin` with `api.blocks.getBlocksCount()`, for the same reason +- [x] 6.5 Rename the UI package's `MenuConfig` to `BlockSettingsMenuConfig`: `@editorjs/sdk` already exports an unrelated `MenuConfig`, and the two are not interchangeable +- [x] 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 +- [x] 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` +- [x] 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 +- [x] 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 +- [x] 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 +- [x] 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 +- [x] 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 +- [x] 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 +- [x] 8.4 Give the settings button `type="button"`, so an editor mounted inside a form is not submitted when the menu opens +- [x] 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 + +## 9. Review follow-ups (fourth round) + +- [x] 9.1 Write a failing `BlockSettings.spec.ts` case for a block hovered while the toolbox is open, then stop following block selection for as long as the toolbox holds the toolbar in place, as the open menu already does. The toolbar freezes on `#isToolboxOpen` because the toolbox popover renders inside it; nothing told the settings plugin, so the button stayed beside one block while its target moved to another — and `Delete` then removed the block the user was not pointing at +- [x] 9.2 Write a failing case for an item whose `isActive` throws, then call those callbacks inside the provider's own `try`/`catch` and hand ui-kit the resolved values. ui-kit reads `isActive` while it renders the item, which happens in `#renderPopover`, long after `#collectItems` has returned: the throw aborted the popover, so one bad callback cost every provider's items and the menu did not open at all. Resolved at any depth of nested items and on an item's confirmation state, which render the same way; nothing is lost by resolving early, since the popover is rebuilt on every open + +## 10. Review follow-ups (fifth round) + +- [x] 10.1 Write a failing `BlockSettings.spec.ts` case for an Enter whose default was prevented before it reached the button, then dismiss the menu from the keydown handler when that is so, and restore the e2e case 8.3 dropped. 8.3 found that ui-kit's flipper claims the key for the open menu and suppresses the click, and concluded the remaining half belonged upstream — which was wrong: the handler still receives the keydown, and `defaultPrevented` identifies exactly the activation that will produce no click, so the dismissal has somewhere to live. A real-browser probe confirms the shape in both Chromium and WebKit: focus stays on the button, the keydown reaches it with the default already prevented in the capture phase, and no click ever arrives. The click stays the primary path, so the pointer and open-from-keyboard behaviour is untouched, and the unit helper that dispatches a keydown and a click together keeps meaning what it did + +## 11. Review follow-ups (sixth round) + +- [x] 11.1 Write failing `BlockSettings.spec.ts` cases for a block inserted above the target and for the target being removed, then hold the target by block id and resolve its position when the menu opens. The target was a position, updated only by `ui:blocks:block-selected`, so a collaborator, an undo or a move inserting above it left the button acting on whichever block slid into that position -- with `Delete` among the items. `design.md` said the plugin resolves the id from the index it last saw; it is the other way round now, and `getIndexById` returning `-1` for a block that is gone lands in the existing "no block" path +- [x] 11.2 Write failing `Blocks.selection.spec.ts` cases for a block landing on the reported position and for one added above the caret, then recognise a repeat as the same block at the same position rather than the position alone. `#addBlock`/`#removeBlock` splice the block list without touching the recorded position, so after a removal the next block to take that number read as already reported and the caret arriving there was announced to nobody. Keeping the position in the comparison matters as much as adding the block: the toolbar takes its vertical position from this event and nothing else, so a block pushed down the page by an insert above it has to be re-announced even though the selection never moved +- [x] 11.3 Write failing `Toolbar.spec.ts` and `BlockSettings.spec.ts` cases for a selection arriving while the toolbar is held, then give `BlocksUI` a `publicApi` -- `api.plugins.blocksUI.getSelectedBlock()` -- and have both consumers ask it once nothing is holding them. `BlocksUI` announces a selection once and records it, and both consumers deliberately ignore selections while frozen, so the announcement was destroyed: clicking into another block moves the caret on mousedown while the popover closes on the click, leaving the toolbar and the target on the block the caret had left. The review suggested re-announcing from `BlocksUI` or resetting its deduplication, both of which make the producer track which consumers are busy; exposing the selection as readable state instead leaves that knowledge with the consumers, which is also what lets each keep its own rule for the frozen window. 11.2 is what makes the API writable at all: with a position for state there is no correct answer to give, and the position is resolved on each call so an insert above the reported block cannot leave it naming someone else's slot. Nothing is returned once that block is removed, which is also why `#removeBlock` needs no cleanup of its own +- [x] 11.4 Add `static name = 'blocksUI'` to `BlocksUI` and augment `EditorjsPluginApiMap` from its own module, as `BlockSettingsUI` does for `block-settings`. The 8.3 and 9.1 tests expected a skipped selection to be dropped; the invariant they were written for -- the button and the block it acts on naming the same block -- still holds, since both consumers now read the same answer +- [x] 11.5 Write a failing `BlockSettings.spec.ts` case for a menu rebuilt while open, then unsubscribe from the popover's `Closed` before destroying it. `PopoverDesktop.destroy()` hides before tearing down and hiding emits `Closed`, so the popover being replaced reported the menu as closed and open again on every rebuild, flipping `aria-expanded` with it. Worse since 11.3: the toolbar catches up with the selection on a `closed`, so a spurious one could move it mid-rebuild +- [x] 11.6 Write a failing `BlockSettings.spec.ts` case for an item whose `onActivate` throws, then wrap that callback where `isActive` is already resolved, at every depth and on the confirmation state. ui-kit calls the handler from its own click handler and honours `closeOnActivate` only after it returns (`e.handleClick(), ..., e.closeOnActivate === !0 && (this.hide(), ...)`), so a throw abandoned the rest of the activation. Wrapped rather than resolved, since unlike `isActive` it cannot be called early. Only the report is asserted: jsdom swallows a listener's exception, so neither the escape nor the abandoned close is observable there -- a first attempt to assert the menu still closes passed before the fix and was dropped as a false positive + +- [x] 11.7 Add `options.timeout` to `register`, defaulting to 500ms rather than the 2000ms the constant carried, and document on the provider type that the menu shows nothing until every provider has answered. The budget belongs with the provider it contains, not with the editor: a slow provider is a property of that provider. Both the longer and the shorter budget are covered by cases that fail when the option is ignored -- the shorter one has to answer inside the default, or it would be skipped either way + +- [x] 11.8 Document on `BlockSettingsUI` and in the spec that it has to be registered after whatever mounts it. `ui:block-settings:rendered` is dispatched once from the constructor and never replayed, so a host registered later never hears it and both elements stay off the page silently. Documented rather than fixed: `publicApi` is registered right after each plugin's constructor, so a `getElements()` for late mounting would work, but this is one instance of the general problem already on the board as "UI component registered before its parent never mounts", and fixing it here for this pair alone would leave the rest of it + +- [x] 11.9 Make `tool` optional on `BlockSettingsContext` instead of falling back to `''`. The id and the tool are read from the same position, so an undefined tool means the editor's view of the block disagrees with the Model's; an empty name matched no provider while looking like an answer. Not opening at all was the other option in the review, and was rejected: the block does exist, so refusing the menu turns a disagreement the user cannot see into one they cannot work around + +- [x] 11.10 Say on `register` and in the spec that unregistering takes effect from the next open, since providers are asked as the menu is built and one already on screen keeps the items it was built with + +- [x] 11.11 Move the item titles out of `#items` into a `messages.ts` of the plugin's own, as `@editorjs/ui` keeps its own strings. Plugin config was the other suggestion and is left open: a catalogue is where localisation would read from either way, and it needs no options plumbing to be worth having now. The plugin's own tests go on asserting the literal titles, since those are what a user reads + +- [x] 11.12 Give the toolbar's plus button `type="button"`, as the settings button already had. Both sit in the same container and an editor mounted inside a form was posted by whichever of them still defaulted to `submit` +- [x] 11.13 Rewrite the item walk over the `PopoverItemParams` union instead of a `Record`, as the review asked. One cast is left, on the confirmation state, since the walk returns the wide union while that field holds the base variant. Longer than the record form by half again -- five branches, two helpers, and a named patch type, because the lint config rejects an inline object return type -- but the wrapper's parameters are typed rather than `unknown[]`, a misspelled key no longer compiles, and the variants that forbid `onActivate` are honoured by the branching rather than written through a string key. The first draft dropped the `typeof` guard on `onActivate`: ui-kit optional-chains it, so an item without one at runtime is legal, and it would have been given a wrapper that throws on click +- [x] 11.14 Cover the fourth of the review's missing tests: the caret leaving the menu's block while it is open, and the menu then reopened from the keyboard rather than the pointer. The other three arrived with 11.1, 11.5 and 11.6 diff --git a/package.json b/package.json index 95a976bb..578e6e63 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "packages/plugins/*" ], "scripts": { - "build": "yarn workspaces foreach -At run build", + "build": "yarn workspaces foreach -A --topological-dev run build", "test": "yarn workspaces foreach -A run test", "lint": "yarn workspaces foreach -A run lint", "lint:fix": "yarn workspaces foreach -A run lint --fix", diff --git a/packages/core/src/api/BlocksAPI.integration.spec.ts b/packages/core/src/api/BlocksAPI.integration.spec.ts index a8bd5db4..fc847bc3 100644 --- a/packages/core/src/api/BlocksAPI.integration.spec.ts +++ b/packages/core/src/api/BlocksAPI.integration.spec.ts @@ -310,6 +310,37 @@ describe('BlocksAPI integration (real model, mocked tools)', () => { }); }); + describe('getToolByIndex()', () => { + it('should return the tool name of the block at that index', () => { + blocksAPI.insert({ type: 'paragraph' }); + blocksAPI.insert({ type: 'header' }); + + expect(blocksAPI.getToolByIndex(1)).toBe('header'); + }); + + it('should return undefined past the end of the document', () => { + blocksAPI.insert({ type: 'paragraph' }); + + expect(blocksAPI.getToolByIndex(1)).toBeUndefined(); + }); + + it('should return undefined for a negative index', () => { + blocksAPI.insert({ type: 'paragraph' }); + + expect(blocksAPI.getToolByIndex(-1)).toBeUndefined(); + }); + + it('should follow the block when it moves', () => { + blocksAPI.insert({ type: 'paragraph' }); + blocksAPI.insert({ type: 'header' }); + + blocksAPI.move({ toIndex: 0, + fromIndex: 1 }); + + expect(blocksAPI.getToolByIndex(0)).toBe('header'); + }); + }); + describe('render()', () => { it('should replace document content with the provided serialized data', () => { blocksAPI.insert({ type: 'paragraph' }); diff --git a/packages/core/src/api/BlocksAPI.ts b/packages/core/src/api/BlocksAPI.ts index 29afb914..9b00f59d 100644 --- a/packages/core/src/api/BlocksAPI.ts +++ b/packages/core/src/api/BlocksAPI.ts @@ -223,6 +223,15 @@ export class BlocksAPI implements BlocksApiInterface { this.#blocksManager.convertBlock(block as BlockIndexOrId, createDataKey(key), newType, userId, dataOverrides); } + /** + * Returns the name of the tool rendering the block at the given index, or undefined when no + * block is there + * @param index - index of the block + */ + public getToolByIndex(index: number): string | undefined { + return this.#blocksManager.getToolByIndex(index); + } + /** * Returns the per-block data stored by the given plugin, or undefined when it stores none * @param params - getPluginData parameters diff --git a/packages/core/src/components/BlockManager.ts b/packages/core/src/components/BlockManager.ts index 5d0fdaa7..6ca5d6f0 100644 --- a/packages/core/src/components/BlockManager.ts +++ b/packages/core/src/components/BlockManager.ts @@ -436,6 +436,19 @@ export class BlocksManager { }, blockIndex); } + /** + * Returns the name of the tool rendering the block at the given index, or undefined when the + * index names no block. Out of bounds reports rather than throws, matching `getIdByIndex` + * @param index - position of the block in the document + */ + public getToolByIndex(index: number): string | undefined { + if (index < 0 || index >= this.blocksCount) { + return undefined; + } + + return this.#model.getBlockSerialized(index).name; + } + /** * Returns the per-block data stored by the given plugin, or undefined when it stores none * @param blockIndexOrId - position of the block in the document, or its id diff --git a/packages/editorjs/e2e/tests/axe.spec.ts b/packages/editorjs/e2e/tests/axe.spec.ts index e3d4decb..e1394dd2 100644 --- a/packages/editorjs/e2e/tests/axe.spec.ts +++ b/packages/editorjs/e2e/tests/axe.spec.ts @@ -54,6 +54,19 @@ test('has no automatically detectable accessibility violations with the toolbox expect(await auditEditor(page)).toEqual([]); }); +test('has no automatically detectable accessibility violations with block settings open', async ({ page }) => { + // The settings menu is the one popover whose items are *not* native controls -- they are + // divs carrying role="menuitem", which is what the ARIA menu pattern calls for and what the + // toolbox does too. That makes every accessible name, state and role on them authored rather + // than inherited, so it is worth auditing the menu in its open state. + await page.getByRole('textbox', { name: 'Paragraph' }).first() + .hover(); + await page.getByRole('button', { name: 'Block settings' }).click(); + await expect(page.getByRole('menu', { name: 'Block settings' })).toBeVisible(); + + expect(await auditEditor(page)).toEqual([]); +}); + test('has no automatically detectable accessibility violations with the inline toolbar open', async ({ page }) => { await selectParagraphText(page); await expect(page.getByRole('toolbar', { name: 'Text formatting' })).toBeVisible(); diff --git a/packages/editorjs/e2e/tests/block-settings.spec.ts b/packages/editorjs/e2e/tests/block-settings.spec.ts new file mode 100644 index 00000000..9d085cb7 --- /dev/null +++ b/packages/editorjs/e2e/tests/block-settings.spec.ts @@ -0,0 +1,272 @@ +import { test, expect } from '@playwright/test'; +import { mountDocument } from '../support/editor.js'; + +/** The three entries the default block settings plugin contributes. */ +const DEFAULT_ITEM_COUNT = 3; + +/** Slack, in pixels, when checking the toolbar has lined up with a block. */ +const ALIGNMENT_TOLERANCE = 4; + +/** + * The toolbar follows whichever block the pointer is over, so a test opens settings for a + * particular block by hovering it first and then clicking the toolbar's settings button. + */ + +test.beforeEach(async ({ page }) => { + await mountDocument(page, '?text=Alpha&text=Beta'); +}); + +test.describe('opening the menu', () => { + test('opens the settings menu for the hovered block', async ({ page }) => { + const blocks = page.getByRole('textbox', { name: 'Paragraph' }); + + await blocks.nth(1).hover(); + await page.getByRole('button', { name: 'Block settings' }).click(); + + // Named from the message catalogue, the same way the toolbox menu is. + const menu = page.getByRole('menu', { name: 'Block settings' }); + + await expect(menu).toBeVisible(); + await expect(menu.getByRole('menuitem', { name: 'Move up' })).toBeVisible(); + await expect(menu.getByRole('menuitem', { name: 'Move down' })).toBeVisible(); + await expect(menu.getByRole('menuitem', { name: 'Delete' })).toBeVisible(); + }); + + test('reports the menu state on the button that owns it', async ({ page }) => { + const settingsButton = page.getByRole('button', { name: 'Block settings' }); + + await page.getByRole('textbox', { name: 'Paragraph' }).first() + .hover(); + + await expect(settingsButton).toHaveAttribute('aria-haspopup', 'menu'); + await expect(settingsButton).toHaveAttribute('aria-expanded', 'false'); + + await settingsButton.click(); + + await expect(settingsButton).toHaveAttribute('aria-expanded', 'true'); + + await page.keyboard.press('Escape'); + + await expect(settingsButton).toHaveAttribute('aria-expanded', 'false'); + + // The menu button pattern hands focus back to the button the menu was opened from. + await expect(settingsButton).toBeFocused(); + }); + + test('closes the menu when the button that opened it is clicked again', async ({ page }) => { + const settingsButton = page.getByRole('button', { name: 'Block settings' }); + const menu = page.getByRole('menu', { name: 'Block settings' }); + + await page.getByRole('textbox', { name: 'Paragraph' }).first() + .hover(); + + await settingsButton.click(); + await expect(menu).toBeVisible(); + + // The popover closes itself on this click before the button's own handler runs, so what + // this asserts is that the handler does not immediately re-open it -- which is what made + // the button look inert on every second click. + await settingsButton.click(); + + await expect(menu).toBeHidden(); + await expect(settingsButton).toHaveAttribute('aria-expanded', 'false'); + + await settingsButton.click(); + + await expect(menu).toBeVisible(); + }); + + test('opens for the caret block without the pointer ever entering one', async ({ page }) => { + const blocks = page.getByRole('textbox', { name: 'Paragraph' }); + const toolbar = page.getByRole('toolbar', { name: 'Block actions' }); + + // Block selection is dispatched on pointer enter, so nothing here may hover a block: this + // is the path a keyboard-only user takes, and the button used to open nothing at all. + await page.keyboard.press('Tab'); + + // Waited for rather than assumed: the arrow keys below are only caret moves once the + // editor actually holds focus, and pressing them early leaves the document untouched. + await expect(page.getByRole('group')).toBeFocused(); + + // Tab reaches the editor but places no caret in a block; an arrow key is what does. + await page.keyboard.press('ArrowDown'); + await page.keyboard.press('ArrowDown'); + await page.keyboard.type('!'); + + // Typing is what says where the caret actually is, rather than assuming the arrows put it + // there. The second block is the target, so the toolbar has somewhere visible to move to. + await expect(blocks).toHaveText(['Alpha', '!Beta']); + + // The browser delivers `selectionchange` on its own schedule, so the caret reaching the + // editor and the toolbar hearing about it are two different moments. Waiting for the + // toolbar to line up with the second block waits for the second -- and is itself the other + // half of what this fixes, the toolbar following a caret that no pointer led. + await expect.poll(async () => { + const toolbarBox = await toolbar.boundingBox(); + const blockBox = await blocks.nth(1).boundingBox(); + + if (toolbarBox === null || blockBox === null) { + return false; + } + + return Math.abs(toolbarBox.y - blockBox.y) < ALIGNMENT_TOLERANCE; + }).toBe(true); + + // `press` on the locator rather than `focus()` then `keyboard.press`: the two-step form + // races, and an Enter that arrives before focus lands goes to the editor as a new block. + await page.getByRole('button', { name: 'Block settings' }).press('Enter'); + + const menu = page.getByRole('menu', { name: 'Block settings' }); + + await expect(menu).toBeVisible(); + + // The caret is in the last block, so moving further down is what must be unavailable -- + // which is also what says the menu was built for that block and not some default. + await expect(menu.getByRole('menuitem', { name: 'Move down' })).toHaveAttribute('aria-disabled', 'true'); + await expect(menu.getByRole('menuitem', { name: 'Move up' })).not.toHaveAttribute('aria-disabled', 'true'); + }); +}); + +test.describe('presentation', () => { + test('highlights the whole row on hover, not just the label', async ({ page }) => { + await page.getByRole('textbox', { name: 'Paragraph' }).first() + .hover(); + await page.getByRole('button', { name: 'Block settings' }).click(); + + await expect(page.getByRole('menu', { name: 'Block settings' })).toBeVisible(); + + // Regression test for the item wrapper: rendering menu items as `button` — right for + // ui-kit's inline toolbar, wrong for a vertical menu — made each row shrink to its own + // label, so the hover highlight covered a ragged part of it. Measured in one pass in the + // page and after the webfont has settled, because one locator at a time reads the rows at + // different moments and a loading font moves the menu's width between them. + const widths = await page.evaluate(async () => { + await document.fonts.ready; + + // Scoped by name: the toolbox renders a `role="menu"` of its own, closed but present. + const menu = document.querySelector('[role="menu"][aria-label="Block settings"]'); + + return [...(menu?.querySelectorAll('[role="menuitem"]') ?? [])] + .map(item => item.getBoundingClientRect().width); + }); + + expect(widths).toHaveLength(DEFAULT_ITEM_COUNT); + expect(widths[0]).toBeGreaterThan(0); + + // Every row is as wide as the menu rather than as wide as its own label. Broken, these came + // out at roughly 90 / 108 / 76 px — one per label length. + expect(new Set(widths).size).toBe(1); + }); + + test('disables moving further at the document boundaries', async ({ page }) => { + await page.getByRole('textbox', { name: 'Paragraph' }).first() + .hover(); + await page.getByRole('button', { name: 'Block settings' }).click(); + + const menu = page.getByRole('menu', { name: 'Block settings' }); + + await expect(menu.getByRole('menuitem', { name: 'Move up' })).toBeDisabled(); + await expect(menu.getByRole('menuitem', { name: 'Move down' })).toBeEnabled(); + }); + + test('marks an unavailable action as disabled rather than hiding it', async ({ page }) => { + await page.getByRole('textbox', { name: 'Paragraph' }).first() + .hover(); + await page.getByRole('button', { name: 'Block settings' }).click(); + + // Exposed through aria-disabled, and still reachable by the arrow keys: the APG keeps + // disabled menu items focusable so they can be discovered rather than silently missing. + const moveUp = page.getByRole('menu', { name: 'Block settings' }).getByRole('menuitem', { name: 'Move up' }); + + await expect(moveUp).toHaveAttribute('aria-disabled', 'true'); + }); +}); + +test.describe('keyboard operation', () => { + test('is operable from the keyboard alone', async ({ page }) => { + const blocks = page.getByRole('textbox', { name: 'Paragraph' }); + + await blocks.first().hover(); + await page.getByRole('button', { name: 'Block settings' }).click(); + + const menu = page.getByRole('menu', { name: 'Block settings' }); + + await expect(menu).toBeVisible(); + + // The items are divs with role="menuitem", as the ARIA menu pattern calls for -- so nothing + // here is inherited from a native control. Arrow-key navigation, the roving tabindex and + // Enter activation are all ui-kit's, and this is what says they still hold for this menu. + await page.keyboard.press('ArrowDown'); + await page.keyboard.press('ArrowDown'); + + await expect(menu.getByRole('menuitem', { name: 'Move down' })).toBeFocused(); + + await page.keyboard.press('Enter'); + + await expect(blocks).toHaveText(['Beta', 'Alpha']); + await expect(menu).toBeHidden(); + }); + + test('is dismissed from its own button by a second Enter', async ({ page }) => { + const blocks = page.getByRole('textbox', { name: 'Paragraph' }); + + await blocks.first().hover(); + + const button = page.getByRole('button', { name: 'Block settings' }); + + await button.click(); + + const menu = page.getByRole('menu', { name: 'Block settings' }); + + await expect(menu).toBeVisible(); + await expect(button).toBeFocused(); + + // ui-kit's flipper claims this Enter for the open menu and prevents the default before the + // event reaches the button, so no click is produced and the plugin has to dismiss the menu + // from the keydown itself. Without that, the menu cannot be closed from the button at all. + await page.keyboard.press('Enter'); + + await expect(menu).toBeHidden(); + await expect(button).toHaveAttribute('aria-expanded', 'false'); + }); +}); + +test.describe('actions', () => { + test('moves a block up from the settings menu', async ({ page }) => { + const blocks = page.getByRole('textbox', { name: 'Paragraph' }); + + await expect(blocks).toHaveText(['Alpha', 'Beta']); + + await blocks.nth(1).hover(); + await page.getByRole('button', { name: 'Block settings' }).click(); + await page.getByRole('menuitem', { name: 'Move up' }).click(); + + await expect(blocks).toHaveText(['Beta', 'Alpha']); + }); + + test('deletes a block only after its confirmation is activated', async ({ page }) => { + const blocks = page.getByRole('textbox', { name: 'Paragraph' }); + + await blocks.nth(1).hover(); + await page.getByRole('button', { name: 'Block settings' }).click(); + await page.getByRole('menuitem', { name: 'Delete' }).click(); + + // The item becomes its own confirmation in place: same element, new title, new action. + await expect(blocks).toHaveText(['Alpha', 'Beta']); + + await page.getByRole('menuitem', { name: 'Click to delete' }).click(); + + await expect(blocks).toHaveText(['Alpha']); + }); + + test('abandons a pending deletion when the menu is dismissed', async ({ page }) => { + const blocks = page.getByRole('textbox', { name: 'Paragraph' }); + + await blocks.nth(1).hover(); + await page.getByRole('button', { name: 'Block settings' }).click(); + await page.getByRole('menuitem', { name: 'Delete' }).click(); + await page.keyboard.press('Escape'); + + await expect(blocks).toHaveText(['Alpha', 'Beta']); + }); +}); diff --git a/packages/editorjs/package.json b/packages/editorjs/package.json index d467e522..e963ba58 100644 --- a/packages/editorjs/package.json +++ b/packages/editorjs/package.json @@ -8,7 +8,7 @@ "type": "module", "scripts": { "build": "yarn build:dependencies && yarn clear && tsc --build tsconfig.build.json", - "build:dependencies": "yarn workspaces foreach -Rpt --from $npm_package_name --exclude $npm_package_name run build", + "build:dependencies": "yarn workspaces foreach -Rp --topological-dev --from $npm_package_name --exclude $npm_package_name run build", "build:declaration": "yarn build --emitDeclarationOnly", "lint": "eslint ./src ./e2e playwright.config.ts playwright.voiceover.config.ts", "lint:ci": "yarn lint --max-warnings 0", @@ -47,6 +47,7 @@ "@editorjs/clipboard-plugin": "workspace:^", "@editorjs/collaboration-manager": "workspace:^", "@editorjs/core": "workspace:^", + "@editorjs/default-block-settings-plugin": "workspace:^", "@editorjs/dom-adapters": "workspace:^", "@editorjs/inline-link": "workspace:^", "@editorjs/italic": "workspace:^", diff --git a/packages/editorjs/src/index.spec.ts b/packages/editorjs/src/index.spec.ts index 5e3166e4..4595b2b2 100644 --- a/packages/editorjs/src/index.spec.ts +++ b/packages/editorjs/src/index.spec.ts @@ -27,12 +27,23 @@ jest.unstable_mockModule('@editorjs/italic', () => ({ ItalicInlineTool: class It jest.unstable_mockModule('@editorjs/inline-link', () => ({ LinkInlineTool: class LinkInlineTool {} })); jest.unstable_mockModule('@editorjs/clipboard-plugin', () => ({ ClipboardPlugin: class ClipboardPlugin {} })); jest.unstable_mockModule('@editorjs/shortcuts-plugin', () => ({ ShortcutsPlugin: class ShortcutsPlugin {} })); +jest.unstable_mockModule('@editorjs/default-block-settings-plugin', () => ({ + /** + * The assertions below read `ctor.name`, and this plugin declares a static `name`, so + * what they see is its plugin id rather than the class name. The mock declares it too, + * otherwise the test would assert a name the real module never reports + */ + DefaultBlockSettingsPlugin: class DefaultBlockSettingsPlugin { + public static readonly name = 'default-block-settings'; + }, +})); jest.unstable_mockModule('@editorjs/ui', () => ({ EditorjsUI: class EditorjsUI {}, BlocksUI: class BlocksUI {}, InlineToolbarUI: class InlineToolbarUI {}, ToolbarUI: class ToolbarUI {}, ToolboxUI: class ToolboxUI {}, + BlockSettingsUI: class BlockSettingsUI {}, })); const { default: EditorJS } = await import('./index.js'); @@ -78,6 +89,20 @@ describe('EditorJS bundle', () => { expect(registered).toContain('ClipboardPlugin'); expect(registered).toContain('ShortcutsPlugin'); + expect(registered).toContain('default-block-settings'); + }); + + it('registers the default UI packages on the underlying Core', () => { + initialize.mockResolvedValue(undefined); + + void new EditorJS({} as any); + + const registered = use.mock.calls.map(([ctor]) => (ctor as { name: string }).name); + + expect(registered).toContain('EditorjsUI'); + expect(registered).toContain('ToolbarUI'); + expect(registered).toContain('ToolboxUI'); + expect(registered).toContain('BlockSettingsUI'); }); it('configures a user tool with the options it was registered with', () => { diff --git a/packages/editorjs/src/index.ts b/packages/editorjs/src/index.ts index 67281ee2..b94aa32e 100644 --- a/packages/editorjs/src/index.ts +++ b/packages/editorjs/src/index.ts @@ -9,7 +9,8 @@ import { ItalicInlineTool } from '@editorjs/italic'; import { LinkInlineTool } from '@editorjs/inline-link'; import { ClipboardPlugin } from '@editorjs/clipboard-plugin'; import { ShortcutsPlugin } from '@editorjs/shortcuts-plugin'; -import { EditorjsUI, BlocksUI, InlineToolbarUI, ToolbarUI, ToolboxUI } from '@editorjs/ui'; +import { DefaultBlockSettingsPlugin } from '@editorjs/default-block-settings-plugin'; +import { EditorjsUI, BlocksUI, BlockSettingsUI, InlineToolbarUI, ToolbarUI, ToolboxUI } from '@editorjs/ui'; import { mergeTools } from './mergeTools.js'; /** @@ -76,6 +77,7 @@ export default class EditorJS { */ this.#core.use(ClipboardPlugin); this.#core.use(ShortcutsPlugin); + this.#core.use(DefaultBlockSettingsPlugin); /** * Default tools merged with user-provided `config.tools` (user wins by name). @@ -92,6 +94,7 @@ export default class EditorJS { this.#core.use(InlineToolbarUI); this.#core.use(ToolbarUI); this.#core.use(ToolboxUI); + this.#core.use(BlockSettingsUI); this.#readyPromise = this.#core.initialize(); } diff --git a/packages/playground/package.json b/packages/playground/package.json index 1dc9f234..f7cf024d 100644 --- a/packages/playground/package.json +++ b/packages/playground/package.json @@ -9,7 +9,7 @@ "build": "yarn build:dependencies && vue-tsc && vite build", "build:declaration": "", "preview": "yarn build:dependencies && vite preview", - "build:dependencies": "yarn workspaces foreach -Rpt --from $npm_package_name --exclude $npm_package_name run build", + "build:dependencies": "yarn workspaces foreach -Rp --topological-dev --from $npm_package_name --exclude $npm_package_name run build", "dev:dependencies": "yarn workspaces foreach -Rp --from $npm_package_name --exclude $npm_package_name run dev", "lint": "eslint", "lint:ci": "yarn lint --max-warnings 0", diff --git a/packages/plugins/default-block-settings-plugin/.gitignore b/packages/plugins/default-block-settings-plugin/.gitignore new file mode 100644 index 00000000..854a697d --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/.gitignore @@ -0,0 +1,24 @@ +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/sdks +!.yarn/versions + +# Swap the comments on the following lines if you don't wish to use zero-installs +# Documentation here: https://yarnpkg.com/features/zero-installs +#!.yarn/cache +#.pnp.* + +# IDE +.idea/* + +node_modules/* +dist/* + +# tests +coverage/ +reports/ + +# stryker temp files +.stryker-tmp diff --git a/packages/plugins/default-block-settings-plugin/README.md b/packages/plugins/default-block-settings-plugin/README.md new file mode 100644 index 00000000..9ea7504e --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/README.md @@ -0,0 +1,32 @@ +# Default Block Settings Plugin + +Built-in Editor.js plugin supplying the default entries of the block settings menu: **Move up**, +**Move down** and **Delete**. + +It is an ordinary plugin, not a special kind of entity — the same `block-settings` API any other +plugin uses, registered at `order: 1000` so its items sit last in the menu. It is the reference +example of what used to be called a "block tune". + +## Behaviour + +- **Move up** / **Move down** call `api.blocks.move`. Each is disabled at the document boundary, + evaluated when the menu is built. +- **Delete** asks for confirmation first, and deletes by block id on the second activation. + +Every handler resolves the target block's current index from its id at activation time rather than +reusing the index the menu was built with. A menu can stay open while a collaborator inserts a +block above the target, or while an undo runs, and acting on the stale index would move the wrong +block. A disabled state can go stale the same way, but that only greys an item out. + +Without a registered `block-settings` plugin — a headless `Core`, for instance — it stays inert and +throws nothing. + +## Usage + +Registered for you by `@editorjs/editorjs`. A headless `Core` opts in: + +```ts +import { DefaultBlockSettingsPlugin } from '@editorjs/default-block-settings-plugin'; + +core.use(DefaultBlockSettingsPlugin); +``` diff --git a/packages/plugins/default-block-settings-plugin/eslint.config.mjs b/packages/plugins/default-block-settings-plugin/eslint.config.mjs new file mode 100644 index 00000000..0434f533 --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/eslint.config.mjs @@ -0,0 +1,39 @@ +import CodeX from 'eslint-config-codex'; + +export default [ + ...CodeX, + { + languageOptions: { + parserOptions: { + project: './tsconfig.eslint.json', + tsconfigRootDir: import.meta.dirname, + sourceType: 'module', + }, + }, + rules: { + 'n/no-unpublished-import': ['error', { + allowModules: [ + 'eslint-config-codex', + ], + ignoreTypeImport: true, + }], + 'n/no-missing-import': 'off', + '@typescript-eslint/unbound-method': 'off', + 'n/no-unsupported-features/node-builtins': ['error', { + version: '>=24.0.0', + ignores: [], + }], + }, + }, + { + files: ['**/*.spec.ts'], + rules: { + /** + * For test files allow dev dependencies imports + */ + 'n/no-unpublished-import': ['error', { + allowModules: ['@jest/globals', '@editorjs/ui'], + }], + }, + }, +]; diff --git a/packages/plugins/default-block-settings-plugin/jest.config.ts b/packages/plugins/default-block-settings-plugin/jest.config.ts new file mode 100644 index 00000000..8133bf5f --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/jest.config.ts @@ -0,0 +1,31 @@ +import type { JestConfigWithTsJest } from 'ts-jest'; + +export default { + preset: 'ts-jest', + testEnvironment: 'node', + testMatch: [ '/src/**/*.spec.ts' ], + extensionsToTreatAsEsm: [ '.ts' ], + moduleNameMapper: { + '^(\\.{1,2}/.*)\\.js$': '$1', + }, + coverageReporters: ['lcov', 'json-summary', 'text-summary'], + transform: { + '^.+\\.tsx?$': [ + 'ts-jest', + { + useESM: true, + }, + ], + '^.+\\.jsx?$': [ + 'babel-jest', + { + presets: [ + ['@babel/preset-env', { targets: { node: 'current' } }], + ], + }, + ], + }, + transformIgnorePatterns: [ + 'node_modules/(?!@editorjs)', + ], +} as JestConfigWithTsJest; diff --git a/packages/plugins/default-block-settings-plugin/package.json b/packages/plugins/default-block-settings-plugin/package.json new file mode 100644 index 00000000..b9add29a --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/package.json @@ -0,0 +1,45 @@ +{ + "name": "@editorjs/default-block-settings-plugin", + "version": "0.0.0", + "packageManager": "yarn@4.0.1", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "type": "module", + "scripts": { + "build:dependencies": "yarn workspaces foreach -Rp --topological-dev --from $npm_package_name --exclude $npm_package_name run build", + "build": "yarn build:dependencies && yarn clear && tsc --build tsconfig.build.json", + "build:declaration": "yarn build --emitDeclarationOnly", + "lint": "eslint ./src", + "lint:ci": "yarn lint --max-warnings 0", + "lint:fix": "yarn lint --fix", + "test": "node --experimental-vm-modules $(yarn bin jest)", + "test:coverage": "yarn test --coverage=true", + "test:mutations": "NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" stryker run", + "clear": "rm -rf dist && rm -f tsconfig.build.tsbuildinfo && rm -f tsconfig.tsbuildinfo" + }, + "devDependencies": { + "@babel/core": "^7.29.0", + "@babel/preset-env": "^7.29.2", + "@editorjs/ui": "workspace:^", + "@jest/globals": "^29.7.0", + "@stryker-mutator/core": "^7.0.2", + "@stryker-mutator/jest-runner": "^7.0.2", + "@stryker-mutator/typescript-checker": "^7.0.2", + "@types/eslint": "^9.6.1", + "@types/jest": "^29.5.12", + "@types/node": "^22.10.2", + "babel-jest": "^29.7.0", + "eslint": "^9.24.0", + "eslint-config-codex": "^2.0.3", + "eslint-plugin-import": "^2.31.0", + "jest": "^29.7.0", + "stryker-cli": "^1.0.2", + "ts-jest": "^29.2.5", + "ts-node": "^10.9.2", + "typescript": "^5.5.4" + }, + "dependencies": { + "@codexteam/icons": "^0.3.3", + "@editorjs/sdk": "workspace:^" + } +} diff --git a/packages/plugins/default-block-settings-plugin/src/index.spec.ts b/packages/plugins/default-block-settings-plugin/src/index.spec.ts new file mode 100644 index 00000000..3cd96262 --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/src/index.spec.ts @@ -0,0 +1,412 @@ +import { beforeEach, describe, expect, it, jest } from '@jest/globals'; +import type { BlockSettingsAPI, BlockSettingsContext, BlockSettingsProvider } from '@editorjs/ui'; +import type { EditorAPI, EditorjsPluginParams, EventBus } from '@editorjs/sdk'; +import { CoreEventType } from '@editorjs/sdk'; +import { DefaultBlockSettingsPlugin } from './index.js'; + +/** + * Params `api.blocks.move` is called with + */ +interface MoveParams { + /** Index the block is moved to */ + toIndex: number; + /** Index the block is moved from */ + fromIndex?: number; +} + +/** + * Params `api.blocks.delete` is called with + */ +interface DeleteParams { + /** Index or id of the block to remove */ + block?: number | string; +} + +/** + * Order the plugin is expected to register at, so its items sit last + */ +const EXPECTED_ORDER = 1000; + +/** + * A popover item as the plugin returns it, narrowed to what the tests read + */ +interface Item { + /** Displayed text */ + title?: string; + /** Machine-readable item name, which reaches the DOM as a data attribute */ + name?: string; + /** Whether activating the item closes the menu */ + closeOnActivate?: boolean; + /** Whether the item is greyed out */ + isDisabled?: boolean; + /** Activation handler, absent on an item with confirmation */ + onActivate?: () => void; + /** Nested params applied once the item is activated */ + confirmation?: { + /** Displayed text of the confirmation */ + title?: string; + /** Machine-readable name of the confirmation item */ + name?: string; + /** Whether activating the confirmation closes the menu */ + closeOnActivate?: boolean; + /** Handler that performs the confirmed action */ + onActivate?: () => void; + }; +} + +/** + * Stands up the plugin over a fake editor whose document is a list of block ids + * @param options - test options + * @param options.blockIds - ids of the blocks the fake document holds + * @param options.withBlockSettings - false to omit the block-settings plugin entirely + */ +function setup({ blockIds = ['b0', 'b1', 'b2'], withBlockSettings = true }: { + /** Ids of the blocks the fake document holds */ + blockIds?: string[]; + /** False to omit the block-settings plugin entirely */ + withBlockSettings?: boolean; +} = {}): { + /** Instance under test */ + plugin: DefaultBlockSettingsPlugin; + /** Fires `core:ready`, which is when the plugin registers */ + ready: () => void; + /** Invokes the registered provider for a block and returns its items */ + itemsFor: (blockId: string) => Promise; + /** The order the provider was registered with */ + registeredOrder: () => number | undefined; + /** Spy on `api.blocks.move` */ + move: jest.Mock<(params: MoveParams) => void>; + /** Spy on `api.blocks.delete` */ + remove: jest.Mock<(params?: DeleteParams) => void>; + /** Mutable list of block ids, so a test can change the document mid-menu */ + blocks: string[]; + } { + const blocks = [...blockIds]; + const move = jest.fn<(params: MoveParams) => void>(); + const remove = jest.fn<(params?: DeleteParams) => void>(); + + let provider: BlockSettingsProvider | undefined; + let order: number | undefined; + + const blockSettings: BlockSettingsAPI = { + register: (registered, options) => { + provider = registered; + order = options?.order; + + return () => { + provider = undefined; + }; + }, + close: () => {}, + }; + + const api = { + blocks: { + getIndexById: (id: string) => blocks.indexOf(id), + getBlocksCount: () => blocks.length, + move, + delete: remove, + }, + // eslint-disable-next-line @typescript-eslint/naming-convention -- the key is the plugin's `name`, which is kebab-case + plugins: withBlockSettings ? { 'block-settings': blockSettings } : {}, + } as unknown as EditorAPI; + + const listeners = new Map void>(); + const eventBus = { + addEventListener: (name: string, listener: () => void) => { + listeners.set(name, listener); + }, + removeEventListener: (name: string, listener: () => void) => { + if (listeners.get(name) === listener) { + listeners.delete(name); + } + }, + dispatchEvent: () => true, + } as unknown as EventBus; + + const plugin = new DefaultBlockSettingsPlugin({ + api, + eventBus, + } as EditorjsPluginParams); + + return { + plugin, + ready: () => listeners.get(`core:${CoreEventType.Ready}`)?.(), + registeredOrder: () => order, + itemsFor: async (blockId: string) => { + if (provider === undefined) { + throw new Error('no provider was registered'); + } + + const context: BlockSettingsContext = { + blockId: blockId as BlockSettingsContext['blockId'], + blockIndex: blocks.indexOf(blockId), + tool: 'paragraph', + }; + + const result = await provider(context); + + if (result === undefined) { + return []; + } + + return (Array.isArray(result) ? result : [result]) as Item[]; + }, + move, + remove, + blocks, + }; +} + +/** + * Finds an item by its title + * @param items - items to search + * @param title - title to look for + */ +function byTitle(items: Item[], title: string): Item { + const item = items.find(candidate => candidate.title === title); + + if (item === undefined) { + throw new Error(`no item titled ${title}`); + } + + return item; +} + +describe('DefaultBlockSettingsPlugin', () => { + let instance: ReturnType; + + beforeEach(() => { + instance = setup(); + }); + + describe('registration', () => { + it('should be named default-block-settings', () => { + expect(DefaultBlockSettingsPlugin.name).toBe('default-block-settings'); + }); + + it('should give every item a stable name, which reaches the DOM as a data attribute', async () => { + instance.ready(); + + const items = await instance.itemsFor('b1'); + + expect(items.map(item => item.name)).toEqual(['move-up', 'move-down', 'delete']); + expect(byTitle(items, 'Delete').confirmation?.name).toBe('delete-confirm'); + }); + + it('should close the menu once an action is taken', async () => { + instance.ready(); + + const items = await instance.itemsFor('b1'); + + expect(byTitle(items, 'Move up').closeOnActivate).toBe(true); + expect(byTitle(items, 'Move down').closeOnActivate).toBe(true); + + /** + * The delete item itself only reveals its confirmation, so it must *not* close; + * the confirmation is what closes the menu + */ + expect(byTitle(items, 'Delete').closeOnActivate).toBeUndefined(); + expect(byTitle(items, 'Delete').confirmation?.closeOnActivate).toBe(true); + }); + + it('should register its provider once the editor is ready', async () => { + instance.ready(); + + const items = await instance.itemsFor('b1'); + + expect(items.map(item => item.title)).toEqual(['Move up', 'Move down', 'Delete']); + }); + + it('should register last, so its items follow other providers', () => { + instance.ready(); + + expect(instance.registeredOrder()).toBe(EXPECTED_ORDER); + }); + + it('should not register before the editor is ready', async () => { + await expect(instance.itemsFor('b1')).rejects.toThrow('no provider was registered'); + }); + + it('should stay inert without a block-settings plugin', () => { + const headless = setup({ withBlockSettings: false }); + + expect(() => headless.ready()).not.toThrow(); + expect(() => headless.plugin.destroy()).not.toThrow(); + }); + + it('should take its provider back out of the menu when destroyed', async () => { + instance.ready(); + instance.plugin.destroy(); + + await expect(instance.itemsFor('b1')).rejects.toThrow('no provider was registered'); + }); + + it('should not register after it has been destroyed', async () => { + instance.plugin.destroy(); + + // The bus outlives the plugin. A plugin destroyed before the editor finished starting + // would otherwise register a provider nothing holds the unregister function for. + instance.ready(); + + await expect(instance.itemsFor('b1')).rejects.toThrow('no provider was registered'); + }); + }); + + describe('moving', () => { + it('should move a block up by one index', async () => { + instance.ready(); + + byTitle(await instance.itemsFor('b1'), 'Move up').onActivate?.(); + + expect(instance.move).toHaveBeenCalledWith({ + fromIndex: 1, + toIndex: 0, + }); + }); + + it('should move a block down by one index', async () => { + instance.ready(); + + byTitle(await instance.itemsFor('b1'), 'Move down').onActivate?.(); + + expect(instance.move).toHaveBeenCalledWith({ + fromIndex: 1, + toIndex: 2, + }); + }); + + it('should disable moving up for the first block', async () => { + instance.ready(); + + const items = await instance.itemsFor('b0'); + + expect(byTitle(items, 'Move up').isDisabled).toBe(true); + expect(byTitle(items, 'Move down').isDisabled).toBe(false); + }); + + it('should disable moving down for the last block', async () => { + instance.ready(); + + const items = await instance.itemsFor('b2'); + + expect(byTitle(items, 'Move down').isDisabled).toBe(true); + expect(byTitle(items, 'Move up').isDisabled).toBe(false); + }); + + it('should resolve the index again at activation, not reuse the one from build time', async () => { + instance.ready(); + + const moveUp = byTitle(await instance.itemsFor('b1'), 'Move up'); + + /** + * A collaborator inserts a block above the target while the menu is open, so `b1` + * is at index 2 by the time the item is activated + */ + instance.blocks.unshift('inserted'); + + moveUp.onActivate?.(); + + expect(instance.move).toHaveBeenCalledWith({ + fromIndex: 2, + toIndex: 1, + }); + }); + + it('should not move the first block up, even with a stale disabled state', async () => { + instance.ready(); + + /** + * Built while `b1` sat in the middle, so `isDisabled` is false -- then a collaborator + * removes the block above it and `b1` becomes first while the menu is still open. + * The greyed-out state is a snapshot, so the guard in the handler is what has to hold + */ + const moveUp = byTitle(await instance.itemsFor('b1'), 'Move up'); + + instance.blocks.splice(0, 1); + + moveUp.onActivate?.(); + + expect(instance.move).not.toHaveBeenCalled(); + }); + + it('should not move the last block down, even with a stale disabled state', async () => { + instance.ready(); + + const moveDown = byTitle(await instance.itemsFor('b1'), 'Move down'); + + instance.blocks.splice(instance.blocks.indexOf('b2'), 1); + + moveDown.onActivate?.(); + + expect(instance.move).not.toHaveBeenCalled(); + }); + + it('should do nothing when the target block is gone', async () => { + instance.ready(); + + const items = await instance.itemsFor('b1'); + + instance.blocks.splice(instance.blocks.indexOf('b1'), 1); + + expect(() => { + byTitle(items, 'Move up').onActivate?.(); + byTitle(items, 'Move down').onActivate?.(); + }).not.toThrow(); + + expect(instance.move).not.toHaveBeenCalled(); + }); + }); + + describe('deleting', () => { + it('should carry a confirmation instead of a direct handler', async () => { + instance.ready(); + + const remove = byTitle(await instance.itemsFor('b1'), 'Delete'); + + expect(remove.onActivate).toBeUndefined(); + expect(remove.confirmation).toBeDefined(); + }); + + it('should label the confirmation as the destructive step', async () => { + instance.ready(); + + const remove = byTitle(await instance.itemsFor('b1'), 'Delete'); + + /** + * The item becomes a different control in place -- same element, new title and new + * action -- so the confirmation needs wording of its own. ui-kit announces this title + * when the state flips, and an empty one would leave a screen reader user with no + * indication that the next activation deletes the block + */ + expect(remove.confirmation?.title).toBe('Click to delete'); + }); + + it('should delete by block id once the confirmation is activated', async () => { + instance.ready(); + + byTitle(await instance.itemsFor('b1'), 'Delete').confirmation?.onActivate?.(); + + expect(instance.remove).toHaveBeenCalledWith({ block: 'b1' }); + }); + + it('should not delete anything until the confirmation is activated', async () => { + instance.ready(); + + await instance.itemsFor('b1'); + + expect(instance.remove).not.toHaveBeenCalled(); + }); + + it('should do nothing when the target block is gone', async () => { + instance.ready(); + + const remove = byTitle(await instance.itemsFor('b1'), 'Delete'); + + instance.blocks.splice(instance.blocks.indexOf('b1'), 1); + + expect(() => remove.confirmation?.onActivate?.()).not.toThrow(); + expect(instance.remove).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/packages/plugins/default-block-settings-plugin/src/index.ts b/packages/plugins/default-block-settings-plugin/src/index.ts new file mode 100644 index 00000000..c91a20d1 --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/src/index.ts @@ -0,0 +1,195 @@ +import type { + BlockId, + EditorAPI, + EditorjsPlugin, + EditorjsPluginParams, + EventBus +} from '@editorjs/sdk'; +import { CoreEventType, PluginType } from '@editorjs/sdk'; +import { IconChevronDown, IconChevronUp, IconCross, IconTrash } from '@codexteam/icons'; +import { messages } from './messages.js'; +import type { BlockSettingsContext, BlockSettingsMenuConfig } from '@editorjs/ui'; + +/** + * 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 implements EditorjsPlugin { + /** + * Registers with `core.use` under {@link PluginType.Plugin} + */ + public static readonly type = PluginType.Plugin; + + /** + * Identifier the editor registers this plugin under + */ + public static readonly name = 'default-block-settings'; + + /** + * EditorAPI instance used to move and delete blocks + */ + readonly #api: EditorAPI; + + /** + * Event bus the ready listener is attached to + */ + readonly #eventBus: EventBus; + + /** + * Removes the provider again, once it has been registered + */ + #unregister: (() => void) | undefined; + + /** + * DefaultBlockSettingsPlugin class constructor + * @param params - plugin parameters + */ + constructor({ api, eventBus }: EditorjsPluginParams) { + 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 + */ + public destroy(): void { + this.#eventBus.removeEventListener(`core:${CoreEventType.Ready}`, this.#handleReady); + + this.#unregister?.(); + this.#unregister = undefined; + } + + /** + * Registers once the editor is ready + */ + #handleReady = (): void => { + 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(): void { + 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 }: BlockSettingsContext): BlockSettingsMenuConfig { + const lastIndex = this.#api.blocks.getBlocksCount() - 1; + + return [ + { + name: 'move-up', + title: messages.moveUp, + 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: messages.moveDown, + icon: IconChevronDown, + closeOnActivate: true, + isDisabled: blockIndex >= lastIndex, + onActivate: () => this.#move(blockId, 1), + }, + { + name: 'delete', + title: messages.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: messages.deleteConfirmation, + 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: BlockId, offset: number): void { + 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: BlockId): void { + if (this.#api.blocks.getIndexById(blockId) === -1) { + return; + } + + this.#api.blocks.delete({ block: blockId }); + } +} diff --git a/packages/plugins/default-block-settings-plugin/src/messages.ts b/packages/plugins/default-block-settings-plugin/src/messages.ts new file mode 100644 index 00000000..c5389c65 --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/src/messages.ts @@ -0,0 +1,20 @@ +/** + * Every user-facing string this plugin puts in the settings menu, in one place. + * + * Collected here for the same reason `@editorjs/ui` collects its own: localising them will mean + * sourcing them from the editor config instead, and that is a change to this module rather than + * to every item it builds. i18n itself stays out of scope; this is only the seam it attaches to. + */ +export const messages = { + /** Item that moves the block one position up */ + moveUp: 'Move up', + + /** Item that moves the block one position down */ + moveDown: 'Move down', + + /** Item that asks before deleting the block */ + delete: 'Delete', + + /** What the delete item becomes once activated, and what actually deletes on activation */ + deleteConfirmation: 'Click to delete', +}; diff --git a/packages/plugins/default-block-settings-plugin/stryker.conf.mjs b/packages/plugins/default-block-settings-plugin/stryker.conf.mjs new file mode 100644 index 00000000..9b1f4ca1 --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/stryker.conf.mjs @@ -0,0 +1,35 @@ +// @ts-check +/** @type {import('@stryker-mutator/api/core').PartialStrykerOptions} */ +const config = { + _comment: + "This config was generated using 'stryker init'. Please take a look at: https://stryker-mutator.io/docs/stryker-js/configuration/ for more information.", + packageManager: "yarn", + thresholds: { + break: 75, + }, + thresholds_comment: "Minimum required coverage. Increase once we're closer to 100%.", + clearTextReporter: { + allowEmojis: true, + }, + reporters: [ + "json", + "html", + "clear-text", + "progress", + "dashboard", + ], + testRunner: "jest", + testRunner_comment: + "Take a look at https://stryker-mutator.io/docs/stryker-js/jest-runner for information about the jest plugin.", + coverageAnalysis: "perTest", + tsconfigFile: "tsconfig.json", + checkers: ["typescript"], + timeoutMS: 10000, + mutate: ["./src/**/*.ts", "!./src/**/mocks/*.ts", "!./src/**/__mocks__/*.ts", "!./src/**/*.spec.ts"], + /* + * In some cases PRs might not have any unit-tests + */ + allowEmpty: true, +}; + +export default config; diff --git a/packages/plugins/default-block-settings-plugin/tsconfig.build.json b/packages/plugins/default-block-settings-plugin/tsconfig.build.json new file mode 100644 index 00000000..5b7ae0fc --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/tsconfig.build.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.json", + "exclude": [ + "node_modules/**/*", + "dist/**/*", + "**/*.spec.ts" + ], + "references": [ + { + "path": "../../sdk/tsconfig.build.json" + } + ] +} diff --git a/packages/plugins/default-block-settings-plugin/tsconfig.eslint.json b/packages/plugins/default-block-settings-plugin/tsconfig.eslint.json new file mode 100644 index 00000000..72ee87bc --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/tsconfig.eslint.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "types": ["node", "jest"] + }, + "extends": "./tsconfig.json", + "include": [ + "src/**/*", + "eslint.config.mjs", + "**/*.spec.ts", + "jest.config.ts", + "stryker.conf.mjs" + ], + "exclude": [ + "dist/**/*", + "node_modules/**/*" + ] +} diff --git a/packages/plugins/default-block-settings-plugin/tsconfig.json b/packages/plugins/default-block-settings-plugin/tsconfig.json new file mode 100644 index 00000000..8cc9fa49 --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "composite": true, + "target": "esnext", + "module": "esnext", + "moduleResolution": "bundler", + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "strict": true, + "skipLibCheck": true, + "rootDir": "src", + "outDir": "dist", + "declaration": true, + "declarationMap": true, + "sourceMap": true + }, + "include": ["src/**/*"], + "exclude": [ + "node_modules/**/*", + "dist/**/*" + ], + "references": [ + { + "path": "../../sdk/tsconfig.build.json" + } + ] +} diff --git a/packages/sdk/src/api/BlocksAPI.ts b/packages/sdk/src/api/BlocksAPI.ts index 896477bd..24f9364b 100644 --- a/packages/sdk/src/api/BlocksAPI.ts +++ b/packages/sdk/src/api/BlocksAPI.ts @@ -154,6 +154,16 @@ export interface BlocksAPI { */ getIdByIndex(index: number): BlockId | undefined; + /** + * Returns the name of the tool rendering the block at the given index, or undefined when no + * block is there. + * + * Exists so that a caller needing one scalar about one block is not pushed to + * `api.document.data`, which serializes the entire document to get there + * @param index - index of the block + */ + getToolByIndex(index: number): string | undefined; + /** * Returns serialized data for provided data key * @param params - getData parameters diff --git a/packages/sdk/src/entities/EntityType.ts b/packages/sdk/src/entities/EntityType.ts index 09aaf2ca..990e6da5 100644 --- a/packages/sdk/src/entities/EntityType.ts +++ b/packages/sdk/src/entities/EntityType.ts @@ -25,7 +25,12 @@ export enum UiComponentType { /** * Toolbar area wrapper. Includes Toolbox and Block Settings */ - Toolbar = 'toolbar' + Toolbar = 'toolbar', + + /** + * Per-block settings menu wrapper + */ + BlockSettings = 'block-settings' } /** diff --git a/packages/ui/eslint.config.mjs b/packages/ui/eslint.config.mjs index 1063eee3..0a6bb039 100644 --- a/packages/ui/eslint.config.mjs +++ b/packages/ui/eslint.config.mjs @@ -18,6 +18,7 @@ export default [ 'n/no-unpublished-import': ['error', { allowModules: [ 'eslint-config-codex', + '@jest/globals', ], ignoreTypeImport: true, }], @@ -32,4 +33,15 @@ export default [ }], }, }, + { + files: ['**/*.spec.ts'], + rules: { + /** + * For test files allow dev dependencies imports + */ + 'n/no-unpublished-import': ['error', { + allowModules: ['@jest/globals'], + }], + }, + }, ]; diff --git a/packages/ui/jest.config.ts b/packages/ui/jest.config.ts index da221cac..6f8210ab 100644 --- a/packages/ui/jest.config.ts +++ b/packages/ui/jest.config.ts @@ -2,11 +2,23 @@ import type { JestConfigWithTsJest } from 'ts-jest'; export default { preset: 'ts-jest', - testEnvironment: 'node', + + /** + * Unlike every other package in the workspace, `ui` renders DOM. The teardown suites get by + * with fake elements, but anything asserting on real markup or a document selection needs a + * browser-like environment, which is why `jest-environment-jsdom` is an explicit dependency. + */ + testEnvironment: 'jsdom', testMatch: [ '/src/**/*.spec.ts' ], extensionsToTreatAsEsm: [ '.ts' ], moduleNameMapper: { '^(\\.{1,2}/.*)\\.js$': '$1', + + /** + * CSS Modules hand back the class name itself, so an assertion on rendered markup reads as + * the class the source asked for. `@codexteam/ui`'s themes are imported for their side + * effects only, and Jest cannot parse the CSS behind them either. + */ '\\.pcss$': '/test/style.cjs', '^@codexteam/ui/styles(?:/.*)?$': '/test/style.cjs', }, @@ -18,5 +30,21 @@ export default { useESM: true, }, ], + '^.+\\.jsx?$': [ + 'babel-jest', + { + presets: [ + ['@babel/preset-env', { targets: { node: 'current' } }], + ], + }, + ], }, + + /** + * `@codexteam/*` joins `@editorjs/*` here: `@editorjs/ui-kit` is shipped as ESM and is + * imported directly by the components under test. + */ + transformIgnorePatterns: [ + 'node_modules/(?!@editorjs|@codexteam)', + ], } as JestConfigWithTsJest; diff --git a/packages/ui/package.json b/packages/ui/package.json index 3bf8e34f..43803b54 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -18,22 +18,27 @@ "dist" ], "scripts": { - "build": "vite build", - "build:declaration": "", + "build:dependencies": "yarn workspaces foreach -Rp --topological-dev --from $npm_package_name --exclude $npm_package_name run build", + "build": "yarn build:dependencies && vite build", + "build:declaration": "yarn build", "dev": "chokidar 'src/**/*' -c 'yarn build' --initial", "prebuild": "yarn clear", "lint": "eslint ./src", "lint:ci": "yarn lint --max-warnings 0", "lint:fix": "yarn lint --fix", "test": "node --experimental-vm-modules $(yarn bin jest)", + "test:coverage": "yarn test --coverage=true", "clear": "rm -rf ./dist && rm -f tsconfig.tsbuildinfo && rm -f tsconfig.tsbuildinfo.json" }, "devDependencies": { + "@babel/core": "^7.29.0", + "@babel/preset-env": "^7.29.2", "@editorjs/core": "workspace:^", "@editorjs/dom-adapters": "workspace:^", "@editorjs/paragraph": "workspace:^", "@jest/globals": "^29.7.0", "@types/jest": "^29.5.12", + "babel-jest": "^29.7.0", "chokidar-cli": "^3.0.0", "eslint": "^9.9.1", "eslint-config-codex": "^2.0.3", diff --git a/packages/ui/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts new file mode 100644 index 00000000..2c5c110c --- /dev/null +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -0,0 +1,1504 @@ +import { afterEach, beforeEach, describe, expect, it, jest } from '@jest/globals'; +import type { BlockId, CoreConfigValidated, EditorAPI } from '@editorjs/sdk'; +import { EventBus } from '@editorjs/sdk'; +import { BlockSettingsUI } from './BlockSettings.js'; +import { BlockSettingsOpenUIEvent } from './events/index.js'; +import type { BlockSettingsRenderedUIEventPayload } from './events/index.js'; +import { BlockSelectedUIEvent } from '../Blocks/events/index.js'; +import type { SelectedBlock } from '../Blocks/Blocks.js'; +import { ToolboxClosedUIEvent, ToolboxOpenedUIEvent } from '../Toolbox/events/index.js'; +import type { BlockSettingsProvider } from './BlockSettings.js'; + +/** + * Blocks the fake document is made of + */ +interface StubBlock { + /** Block id */ + id: string; + /** Tool name */ + name: string; +} + +const defaultBlocks: StubBlock[] = [ + { id: 'block-0', + name: 'paragraph' }, + { id: 'block-1', + name: 'paragraph' }, + { id: 'block-2', + name: 'image' }, +]; + +/** + * A position no block occupies, so `getIdByIndex` resolves to nothing + */ +const MISSING_BLOCK_INDEX = 99; + +/** How long the deliberately slow provider takes, so a stale build would land last. */ +const SLOW_PROVIDER_MS = 20; + +/** Long enough for both overlapping requests to have settled. */ +const BOTH_REQUESTS_SETTLED_MS = 50; + +/** Longer than the default budget, so a provider needing it has to ask. */ +const SLOW_PROVIDER_ASKED_FOR_MS = 900; + +/** Well past whatever the provider timeout is set to, advanced over on fake timers. */ +const PAST_PROVIDER_TIMEOUT_MS = 10_000; + +/** + * Lets the queued provider promises settle. Opening is asynchronous because a provider may + * return a promise, so nothing about the rendered menu can be asserted synchronously + */ +async function flush(): Promise { + await new Promise(resolve => setTimeout(resolve, 0)); +} + +/** + * Builds a plugin instance over a fake editor + * @param blocks - blocks the fake document consists of + */ +function setup(blocks: StubBlock[] = defaultBlocks): { + /** Instance under test */ + plugin: BlockSettingsUI; + /** Event bus the instance is wired to */ + eventBus: EventBus; + /** Element the plugin announced via its rendered event */ + element: HTMLElement; + /** Button the plugin announced via its rendered event */ + button: HTMLButtonElement; + /** Fake editor API */ + api: EditorAPI; + /** The mock backing `api.blocks.getIdByIndex` */ + getIdByIndex: jest.Mock<(index: number) => string | undefined>; + /** Reports a block as selected, as `BlocksUI` does: by event, and through its public API */ + select: (index: number) => void; +} { + const eventBus = new EventBus(); + const holder = document.createElement('div'); + + const getIdByIndex = jest.fn((index: number) => blocks[index]?.id); + + /** + * What the blocks plugin would answer with. Driven only through the selection helpers, so this + * fake cannot come to disagree with the events the plugin is given + */ + let selected: SelectedBlock | undefined; + + const api = { + blocks: { + getIdByIndex, + getIndexById: jest.fn((id: string) => blocks.findIndex(block => block.id === id)), + /** + * Read fresh each time, so a test can mutate the block list between opens + */ + getToolByIndex: jest.fn((index: number) => blocks[index]?.name), + }, + plugins: { + blocksUI: { + getSelectedBlock: () => selected, + }, + }, + } as unknown as EditorAPI; + + let element: HTMLElement | undefined; + let button: HTMLButtonElement | undefined; + + /** + * Captures the element the plugin announces, which is what the toolbar would mount + * @param event - the plugin's rendered event + */ + function captureElement(event: CustomEvent): void { + const detail = event.detail as BlockSettingsRenderedUIEventPayload; + + element = detail.blockSettings; + button = detail.button as HTMLButtonElement; + } + + eventBus.addEventListener('ui:block-settings:rendered', captureElement); + + const plugin = new BlockSettingsUI({ + api, + eventBus, + /** + * The plugin reads a single field off the config, so the rest of the validated + * shape is not worth standing up here + */ + config: { holder } as unknown as CoreConfigValidated, + }); + + if (element === undefined || button === undefined) { + throw new Error('BlockSettingsUI did not announce its element and button'); + } + + holder.appendChild(button); + holder.appendChild(element); + + /** + * Attached for real: jsdom only moves focus to elements that are in the document, and + * the popover's focus handling is part of what these tests assert + */ + document.body.appendChild(holder); + + return { + /** + * Reports a block as selected the way `BlocksUI` does: by event, and through its public API + * @param index - position of the block to report + */ + select: (index: number): void => { + const block = document.createElement('div'); + + selected = { block, + id: blocks[index]?.id as BlockId }; + + eventBus.dispatchEvent(new BlockSelectedUIEvent({ block, + index })); + }, + plugin, + eventBus, + element, + button, + api, + getIdByIndex, + }; +} + +/** + * Titles of the menu items currently rendered, in document order + * @param element - the plugin's root element + */ +function itemTitles(element: HTMLElement): string[] { + return [...element.querySelectorAll('[role="menuitem"]')].map(item => item.textContent?.trim() ?? ''); +} + +/** + * Number of separators currently rendered + * @param element - the plugin's root element + */ +function separatorCount(element: HTMLElement): number { + return element.querySelectorAll('.ce-popover-item-separator').length; +} + +/** + * Clicks a button the way a pointer does -- `HTMLElement.click()` dispatches only the click, + * and the menu button reads its state on `mousedown`, which a real click always sends first + * @param button - the menu button under test + */ +function clickButton(button: HTMLButtonElement): void { + button.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })); + button.click(); +} + +/** + * Activates the button the way Enter and Space do: a `keydown`, then a `click`, with no + * pointer events anywhere in between + * @param button - control to activate + */ +function activateFromKeyboard(button: HTMLButtonElement): void { + button.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', + bubbles: true })); + button.click(); +} + +/** + * Activates the button the way Enter does while the open menu's own keyboard handling owns the + * key: the default is prevented before the event reaches the button, so no click ever follows + * @param button - control to activate + */ +function activateFromKeyboardWithoutClick(button: HTMLButtonElement): void { + /** + * Claims the key the way ui-kit's flipper does, from a capture listener above the button + * @param event - the keydown on its way down to the button + */ + const claimTheKey = (event: Event): void => { + event.preventDefault(); + }; + + document.addEventListener('keydown', claimTheKey, { capture: true }); + + button.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', + bubbles: true, + cancelable: true })); + + document.removeEventListener('keydown', claimTheKey, { capture: true }); +} + +/** + * Asks the plugin to open settings for a block, then lets the providers settle + * @param eventBus - bus to dispatch on + * @param index - block position to open settings for + */ +async function open(eventBus: EventBus, index: number): Promise { + eventBus.dispatchEvent(new BlockSettingsOpenUIEvent({ index })); + + await flush(); +} + +describe('BlockSettingsUI', () => { + let instance: ReturnType; + + beforeEach(() => { + document.body.innerHTML = ''; + instance = setup(); + }); + + describe('plugin contract', () => { + it('should be named block-settings', () => { + expect(BlockSettingsUI.name).toBe('block-settings'); + }); + + it('should expose register and close as its public API', () => { + expect(typeof instance.plugin.publicApi.register).toBe('function'); + expect(typeof instance.plugin.publicApi.close).toBe('function'); + }); + }); + + describe('opening', () => { + it('should resolve the target block id from the reported index', async () => { + const provider = jest.fn(() => undefined); + + instance.plugin.publicApi.register(provider); + + await open(instance.eventBus, 1); + + expect(instance.getIdByIndex).toHaveBeenCalledWith(1); + expect(provider).toHaveBeenCalledWith(expect.objectContaining({ blockId: 'block-1' })); + }); + + it('should hand providers the block index and tool alongside its id', async () => { + const provider = jest.fn(() => undefined); + + instance.plugin.publicApi.register(provider); + + await open(instance.eventBus, 2); + + expect(provider).toHaveBeenCalledWith({ + blockId: 'block-2', + blockIndex: 2, + tool: 'image', + }); + }); + + /** + * Only reachable if the editor's view of the block disagrees with the Model's, since the id + * and the tool are read from the same position. An empty name would match no provider while + * looking like an answer + */ + it('should leave the tool out when it cannot be determined', async () => { + const provider = jest.fn(() => undefined); + + instance.plugin.publicApi.register(provider); + (instance.api.blocks.getToolByIndex as jest.Mock<(index: number) => string | undefined>) + .mockReturnValue(undefined); + + await open(instance.eventBus, 2); + + expect(provider).toHaveBeenCalledWith({ blockId: 'block-2', + blockIndex: 2 }); + }); + + it('should call providers again on every open, so items reflect current state', async () => { + let isActive = false; + const provider = jest.fn(() => ({ + title: 'Anchor', + isActive, + onActivate: () => {}, + })); + + instance.plugin.publicApi.register(provider); + + await open(instance.eventBus, 0); + expect(provider).toHaveBeenCalledTimes(1); + + instance.plugin.publicApi.close(); + isActive = true; + + await open(instance.eventBus, 0); + expect(provider).toHaveBeenCalledTimes(2); + expect(provider.mock.results[1].value).toMatchObject({ isActive: true }); + }); + + it('should render the items a provider returns', async () => { + instance.plugin.publicApi.register(() => ({ + title: 'Anchor', + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + + expect(itemTitles(instance.element)).toEqual(['Anchor']); + }); + + it('should invoke the handler of an activated item', async () => { + const onActivate = jest.fn(); + + instance.plugin.publicApi.register(() => ({ + title: 'Anchor', + onActivate, + })); + + await open(instance.eventBus, 0); + instance.element.querySelector('[role="menuitem"]')?.click(); + + expect(onActivate).toHaveBeenCalled(); + }); + + it('should accept a provider that returns a promise', async () => { + instance.plugin.publicApi.register(() => Promise.resolve({ + title: 'Async', + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + + expect(itemTitles(instance.element)).toEqual(['Async']); + }); + }); + + describe('ordering', () => { + it('should order contributions by order then registration, separating providers', async () => { + instance.plugin.publicApi.register(() => ({ + title: 'Last', + onActivate: () => {}, + }), { order: 1000 }); + instance.plugin.publicApi.register(() => ({ + title: 'First', + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + + expect(itemTitles(instance.element)).toEqual(['First', 'Last']); + expect(separatorCount(instance.element)).toBe(1); + }); + + it('should break ties by registration order', async () => { + instance.plugin.publicApi.register(() => ({ + title: 'Registered first', + onActivate: () => {}, + })); + instance.plugin.publicApi.register(() => ({ + title: 'Registered second', + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + + expect(itemTitles(instance.element)).toEqual(['Registered first', 'Registered second']); + }); + + it('should not emit a separator for a provider that contributes nothing', async () => { + instance.plugin.publicApi.register(ctx => (ctx.tool === 'image' + ? undefined + : { + title: 'Only for text', + onActivate: () => {}, + })); + instance.plugin.publicApi.register(() => ({ + title: 'Always', + onActivate: () => {}, + })); + + await open(instance.eventBus, 2); + + expect(itemTitles(instance.element)).toEqual(['Always']); + expect(separatorCount(instance.element)).toBe(0); + }); + + it('should treat an empty array as no contribution', async () => { + instance.plugin.publicApi.register(() => []); + instance.plugin.publicApi.register(() => ({ + title: 'Always', + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + + expect(itemTitles(instance.element)).toEqual(['Always']); + expect(separatorCount(instance.element)).toBe(0); + }); + }); + + describe('unregistering', () => { + it('should stop invoking a provider once it is unregistered', async () => { + const provider = jest.fn(() => ({ + title: 'Anchor', + onActivate: () => {}, + })); + + const unregister = instance.plugin.publicApi.register(provider); + + unregister(); + + await open(instance.eventBus, 0); + + expect(provider).not.toHaveBeenCalled(); + expect(itemTitles(instance.element)).toEqual([]); + }); + }); + + describe('events', () => { + it('should dispatch opened once the menu is populated', async () => { + const onOpened = jest.fn(); + + instance.eventBus.addEventListener('ui:block-settings:opened', onOpened); + instance.plugin.publicApi.register(() => ({ + title: 'Anchor', + onActivate: () => {}, + })); + + await open(instance.eventBus, 1); + + expect(onOpened).toHaveBeenCalledTimes(1); + }); + + it('should dispatch closed when closed through the public API', async () => { + const onClosed = jest.fn(); + + instance.eventBus.addEventListener('ui:block-settings:closed', onClosed); + instance.plugin.publicApi.register(() => ({ + title: 'Anchor', + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + instance.plugin.publicApi.close(); + + expect(onClosed).toHaveBeenCalledTimes(1); + }); + }); + + describe('nothing to show', () => { + it('should not open when every provider contributes nothing', async () => { + const onOpened = jest.fn(); + + instance.eventBus.addEventListener('ui:block-settings:opened', onOpened); + instance.plugin.publicApi.register(() => undefined); + + await open(instance.eventBus, 0); + + expect(onOpened).not.toHaveBeenCalled(); + expect(itemTitles(instance.element)).toEqual([]); + }); + + it('should not open when no provider is registered', async () => { + const onOpened = jest.fn(); + + instance.eventBus.addEventListener('ui:block-settings:opened', onOpened); + + await open(instance.eventBus, 0); + + expect(onOpened).not.toHaveBeenCalled(); + }); + + it('should do nothing when the index resolves to no block', async () => { + const provider = jest.fn(() => ({ + title: 'Anchor', + onActivate: () => {}, + })); + const onOpened = jest.fn(); + + instance.eventBus.addEventListener('ui:block-settings:opened', onOpened); + instance.plugin.publicApi.register(provider); + + await open(instance.eventBus, MISSING_BLOCK_INDEX); + + expect(provider).not.toHaveBeenCalled(); + expect(onOpened).not.toHaveBeenCalled(); + expect(itemTitles(instance.element)).toEqual([]); + }); + }); + + describe('a failing provider', () => { + let reportedErrors: jest.SpiedFunction; + + beforeEach(() => { + reportedErrors = jest.spyOn(console, 'error').mockImplementation(() => {}); + }); + + afterEach(() => { + reportedErrors.mockRestore(); + }); + + it('should skip a provider that throws and keep the rest of the menu', async () => { + instance.plugin.publicApi.register(() => { + throw new Error('third-party provider blew up'); + }); + instance.plugin.publicApi.register(() => ({ + title: 'Healthy', + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + + expect(itemTitles(instance.element)).toEqual(['Healthy']); + }); + + /** + * `isActive` is called not by this plugin but by ui-kit, as it renders the item -- long after the provider's own + * error handling has returned. Left there, a throwing callback aborts the popover and no menu opens at all + */ + it('should keep the rest of the menu when an isActive callback throws', async () => { + instance.plugin.publicApi.register(() => ({ + title: 'Faulty', + isActive: () => { + throw new Error('isActive blew up'); + }, + onActivate: () => {}, + })); + instance.plugin.publicApi.register(() => ({ + title: 'Healthy', + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + + expect(itemTitles(instance.element)).toEqual(['Healthy']); + expect(instance.button.getAttribute('aria-expanded')).toBe('true'); + }); + + it('should report an isActive failure as the provider failing', async () => { + instance.plugin.publicApi.register(() => ({ + title: 'Faulty', + isActive: () => { + throw new Error('isActive blew up'); + }, + onActivate: () => {}, + })); + instance.plugin.publicApi.register(() => ({ + title: 'Healthy', + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + + expect(reportedErrors).toHaveBeenCalledWith( + expect.stringContaining('provider failed'), + expect.any(Error) + ); + }); + + it('should keep the rest of the menu when a nested isActive callback throws', async () => { + instance.plugin.publicApi.register(() => ({ + title: 'Faulty parent', + children: { + items: [{ + title: 'Faulty child', + isActive: () => { + throw new Error('isActive blew up'); + }, + onActivate: () => {}, + }], + }, + })); + instance.plugin.publicApi.register(() => ({ + title: 'Healthy', + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + + expect(itemTitles(instance.element)).toEqual(['Healthy']); + }); + + it('should still honour an isActive callback that works', async () => { + instance.plugin.publicApi.register(() => [ + { title: 'Active', + isActive: () => true, + onActivate: () => {} }, + { title: 'Inactive', + isActive: () => false, + onActivate: () => {} }, + ]); + + await open(instance.eventBus, 0); + + const active = [...instance.element.querySelectorAll('[role="menuitem"]')] + .filter(item => item.classList.toString().includes('active')) + .map(item => item.textContent?.trim()); + + expect(active).toEqual(['Active']); + }); + + /** + * `onActivate` runs inside ui-kit's click handler, well after the provider returned. A throw + * there escapes into the popover, which abandons the rest of its activation sequence -- + * `closeOnActivate` among it, since that runs after the handler + */ + it('should report an onActivate that throws rather than let it escape', async () => { + instance.plugin.publicApi.register(() => ({ + title: 'Faulty', + closeOnActivate: true, + onActivate: () => { + throw new Error('onActivate blew up'); + }, + })); + + await open(instance.eventBus, 0); + instance.element.querySelector('[role="menuitem"]')?.click(); + + expect(reportedErrors).toHaveBeenCalledWith( + expect.stringContaining('failed on activation'), + expect.any(Error) + ); + }); + + it('should still invoke a handler that works', async () => { + const onActivate = jest.fn(); + + instance.plugin.publicApi.register(() => ({ title: 'Anchor', + onActivate })); + + await open(instance.eventBus, 0); + instance.element.querySelector('[role="menuitem"]')?.click(); + + expect(onActivate).toHaveBeenCalledTimes(1); + expect(reportedErrors).not.toHaveBeenCalled(); + }); + + it('should skip a provider whose promise rejects', async () => { + instance.plugin.publicApi.register(() => Promise.reject(new Error('async blow-up'))); + instance.plugin.publicApi.register(() => ({ + title: 'Healthy', + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + + expect(itemTitles(instance.element)).toEqual(['Healthy']); + }); + + it('should report the failure rather than swallowing it', async () => { + const failure = new Error('third-party provider blew up'); + + instance.plugin.publicApi.register(() => { + throw failure; + }); + + await open(instance.eventBus, 0); + + expect(reportedErrors).toHaveBeenCalledWith(expect.stringContaining('provider failed'), failure); + }); + + it('should skip a provider that never settles rather than never opening', async () => { + jest.useFakeTimers(); + + try { + instance.plugin.publicApi.register(() => new Promise(() => {})); + instance.plugin.publicApi.register(() => ({ + title: 'Healthy', + onActivate: () => {}, + })); + + instance.eventBus.dispatchEvent(new BlockSettingsOpenUIEvent({ index: 0 })); + + await jest.advanceTimersByTimeAsync(PAST_PROVIDER_TIMEOUT_MS); + + /** + * `Promise.all` has no floor of its own, so before the timeout this menu did not open + * at all -- and no later attempt could, because each one waited on the same provider + */ + expect(itemTitles(instance.element)).toEqual(['Healthy']); + expect(reportedErrors).toHaveBeenCalledWith( + expect.stringContaining('provider failed'), + expect.objectContaining({ message: expect.stringContaining('did not return') }) + ); + } finally { + jest.useRealTimers(); + } + }); + + /** + * The default is a backstop for providers that answer locally. One that genuinely needs + * longer says so at registration rather than every menu waiting on its account + */ + it('should wait as long as a provider asked to be waited for', async () => { + jest.useFakeTimers(); + + try { + instance.plugin.publicApi.register( + () => new Promise(resolve => setTimeout(() => resolve({ title: 'Slow', + onActivate: () => {} }), SLOW_PROVIDER_ASKED_FOR_MS)), + { timeout: SLOW_PROVIDER_ASKED_FOR_MS * 2 } + ); + + instance.eventBus.dispatchEvent(new BlockSettingsOpenUIEvent({ index: 0 })); + + await jest.advanceTimersByTimeAsync(SLOW_PROVIDER_ASKED_FOR_MS * 2); + + expect(itemTitles(instance.element)).toEqual(['Slow']); + expect(reportedErrors).not.toHaveBeenCalled(); + } finally { + jest.useRealTimers(); + } + }); + + it('should give up on a provider sooner when it asked for less', async () => { + jest.useFakeTimers(); + + try { + // Comfortably inside the default, so only the budget it asked for can cut it off. + instance.plugin.publicApi.register( + () => new Promise(resolve => setTimeout(() => resolve({ title: 'Slow', + onActivate: () => {} }), SLOW_PROVIDER_MS)), + { timeout: 1 } + ); + instance.plugin.publicApi.register(() => ({ title: 'Healthy', + onActivate: () => {} })); + + instance.eventBus.dispatchEvent(new BlockSettingsOpenUIEvent({ index: 0 })); + + await jest.advanceTimersByTimeAsync(SLOW_PROVIDER_ASKED_FOR_MS); + + expect(itemTitles(instance.element)).toEqual(['Healthy']); + } finally { + jest.useRealTimers(); + } + }); + + it('should not emit a separator for the provider it skipped', async () => { + instance.plugin.publicApi.register(() => { + throw new Error('blew up'); + }); + instance.plugin.publicApi.register(() => ({ + title: 'Healthy', + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + + expect(separatorCount(instance.element)).toBe(0); + }); + }); + + describe('superseded and empty requests', () => { + it('should close an open menu when the next request resolves to no block', async () => { + const onClosed = jest.fn(); + + instance.plugin.publicApi.register(() => ({ + title: 'Anchor', + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + expect(itemTitles(instance.element)).toEqual(['Anchor']); + + instance.eventBus.addEventListener('ui:block-settings:closed', onClosed); + + await open(instance.eventBus, MISSING_BLOCK_INDEX); + + expect(onClosed).toHaveBeenCalledTimes(1); + }); + + it('should close an open menu when every provider opts out of the next block', async () => { + const onClosed = jest.fn(); + + instance.plugin.publicApi.register(ctx => (ctx.tool === 'image' + ? undefined + : { + title: 'Only text', + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + expect(itemTitles(instance.element)).toEqual(['Only text']); + + instance.eventBus.addEventListener('ui:block-settings:closed', onClosed); + + await open(instance.eventBus, 2); + + // Left open, it would be showing block 0's settings while claiming to be block 2's. + expect(onClosed).toHaveBeenCalledTimes(1); + }); + + it('should abandon a build in flight when the menu is closed', async () => { + const onOpened = jest.fn(); + + instance.eventBus.addEventListener('ui:block-settings:opened', onOpened); + + instance.plugin.publicApi.register(async () => { + await new Promise(resolve => setTimeout(resolve, SLOW_PROVIDER_MS)); + + return { + title: 'Anchor', + onActivate: () => {}, + }; + }); + + instance.eventBus.dispatchEvent(new BlockSettingsOpenUIEvent({ index: 0 })); + + /** + * Closing lands inside the build window, where `#isOpen` is still false because the + * provider has not returned. A close that only looked at `#isOpen` did nothing here, and + * the menu then opened a moment after the caller had asked for it to be gone + */ + instance.plugin.publicApi.close(); + + await new Promise(resolve => setTimeout(resolve, BOTH_REQUESTS_SETTLED_MS)); + + expect(onOpened).not.toHaveBeenCalled(); + expect(itemTitles(instance.element)).toEqual([]); + }); + + it('should abandon a build in flight when the open menu is dismissed', async () => { + const onOpened = jest.fn(); + + instance.plugin.publicApi.register(async (ctx) => { + if (ctx.blockIndex === 1) { + await new Promise(resolve => setTimeout(resolve, SLOW_PROVIDER_MS)); + } + + return { + title: `For ${ctx.blockId}`, + onActivate: () => {}, + }; + }); + + await open(instance.eventBus, 0); + expect(itemTitles(instance.element)).toEqual(['For block-0']); + + instance.eventBus.addEventListener('ui:block-settings:opened', onOpened); + + // A replacement menu is requested, and its provider has not returned yet. + instance.eventBus.dispatchEvent(new BlockSettingsOpenUIEvent({ index: 1 })); + + /** + * Escape and a click outside reach `#handleClosed` straight from the popover, without + * passing through `#close()`. Only that path invalidated a pending build, so a dismissed + * menu came back as soon as the replacement's provider returned + */ + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', + bubbles: true })); + + await new Promise(resolve => setTimeout(resolve, BOTH_REQUESTS_SETTLED_MS)); + + expect(onOpened).not.toHaveBeenCalled(); + }); + + it('should abandon a build in flight when the selection moves to another block', async () => { + const onOpened = jest.fn(); + + instance.eventBus.addEventListener('ui:block-settings:opened', onOpened); + + instance.plugin.publicApi.register(async (ctx) => { + await new Promise(resolve => setTimeout(resolve, SLOW_PROVIDER_MS)); + + return { + title: `For ${ctx.blockId}`, + onActivate: () => {}, + }; + }); + + instance.eventBus.dispatchEvent(new BlockSettingsOpenUIEvent({ index: 0 })); + + /** + * `#isOpen` is still false while the providers run, so selection is still being followed. + * The build for block 0 would otherwise finish and put block 0's actions beside block 1 + */ + instance.eventBus.dispatchEvent(new BlockSelectedUIEvent({ + block: document.createElement('div'), + index: 1, + })); + + await new Promise(resolve => setTimeout(resolve, BOTH_REQUESTS_SETTLED_MS)); + + expect(onOpened).not.toHaveBeenCalled(); + expect(itemTitles(instance.element)).toEqual([]); + }); + + it('should let the newest request win when two overlap', async () => { + const onOpened = jest.fn(); + + instance.eventBus.addEventListener('ui:block-settings:opened', onOpened); + + /** + * Block 0's provider resolves a tick later than block 1's, so without a guard the + * stale build would land last and render the wrong block's menu + */ + instance.plugin.publicApi.register(async (ctx) => { + if (ctx.blockIndex === 0) { + await new Promise(resolve => setTimeout(resolve, SLOW_PROVIDER_MS)); + } + + return { + title: `For ${ctx.blockId}`, + onActivate: () => {}, + }; + }); + + instance.eventBus.dispatchEvent(new BlockSettingsOpenUIEvent({ index: 0 })); + instance.eventBus.dispatchEvent(new BlockSettingsOpenUIEvent({ index: 1 })); + + await new Promise(resolve => setTimeout(resolve, BOTH_REQUESTS_SETTLED_MS)); + + expect(itemTitles(instance.element)).toEqual(['For block-1']); + expect(onOpened).toHaveBeenCalledTimes(1); + }); + }); + + describe('its button', () => { + /** + * Reports a block as hovered, which is what the button opens settings for + * @param index - position of the block + */ + function selectBlock(index: number): void { + instance.select(index); + } + + /** + * Announces the toolbox as open, which is when the toolbar stops following the selection + */ + function openToolbox(): void { + instance.eventBus.dispatchEvent(new ToolboxOpenedUIEvent({})); + } + + /** + * Announces the toolbox as closed, releasing the toolbar + */ + function closeToolbox(): void { + instance.eventBus.dispatchEvent(new ToolboxClosedUIEvent({})); + } + + it('should announce a button alongside the menu', () => { + expect(instance.button.tagName).toBe('BUTTON'); + }); + + it('should not submit a form it happens to sit inside', () => { + /** + * A button defaults to `submit`, and an editor mounted inside a form would then post it + * on every click of this control + */ + expect(instance.button.type).toBe('button'); + }); + + it('should close the menu when activated again from the keyboard', async () => { + const onClosed = jest.fn(); + const provider = jest.fn(() => ({ title: 'Anchor', + onActivate: () => {} })); + + instance.plugin.publicApi.register(provider); + instance.eventBus.addEventListener('ui:block-settings:closed', onClosed); + + selectBlock(0); + + clickButton(instance.button); + await flush(); + + expect(instance.button.getAttribute('aria-expanded')).toBe('true'); + expect(provider).toHaveBeenCalledTimes(1); + + /** + * Enter and Space send a `click` with no `mousedown`, so the snapshot taken on pointer + * down says "closed" however long the menu has been open. Read only from that, the + * button built the menu a second time instead of dismissing it -- the toggle worked for + * a mouse and not for a keyboard + */ + activateFromKeyboard(instance.button); + await flush(); + + expect(instance.button.getAttribute('aria-expanded')).toBe('false'); + expect(onClosed).toHaveBeenCalledTimes(1); + expect(provider).toHaveBeenCalledTimes(1); + }); + + /** + * The menu's own keyboard handling claims Enter and prevents the click the activation would + * otherwise produce, so the keydown is the only thing the button gets to act on + */ + it('should close the menu from the keyboard when no click follows', async () => { + instance.plugin.publicApi.register(() => ({ title: 'Anchor', + onActivate: () => {} })); + + selectBlock(0); + clickButton(instance.button); + await flush(); + + expect(instance.button.getAttribute('aria-expanded')).toBe('true'); + + activateFromKeyboardWithoutClick(instance.button); + await flush(); + + expect(instance.button.getAttribute('aria-expanded')).toBe('false'); + }); + + it('should not re-open the menu when a prevented key arrives with it closed', async () => { + const provider = jest.fn(() => ({ title: 'Anchor', + onActivate: () => {} })); + + instance.plugin.publicApi.register(provider); + + selectBlock(0); + activateFromKeyboardWithoutClick(instance.button); + await flush(); + + expect(provider).not.toHaveBeenCalled(); + expect(instance.button.getAttribute('aria-expanded')).toBe('false'); + }); + + /** + * The route the review asked about: the caret leaves the block the menu belongs to, and the + * menu is reopened without a pointer ever being used + */ + it('should open for the skipped selection when reopened from the keyboard', async () => { + instance.plugin.publicApi.register(ctx => ({ + title: `For ${ctx.blockId}`, + onActivate: () => {}, + })); + + selectBlock(0); + clickButton(instance.button); + await flush(); + + selectBlock(2); + instance.plugin.publicApi.close(); + + activateFromKeyboard(instance.button); + await flush(); + + expect(itemTitles(instance.element)).toEqual(['For block-2']); + }); + + it('should open from the keyboard when the menu is closed', async () => { + instance.plugin.publicApi.register(() => ({ + title: 'Anchor', + onActivate: () => {}, + })); + + selectBlock(0); + + activateFromKeyboard(instance.button); + await flush(); + + expect(itemTitles(instance.element)).toEqual(['Anchor']); + expect(instance.button.getAttribute('aria-expanded')).toBe('true'); + }); + + it('should carry an accessible name and advertise the menu it controls', () => { + expect(instance.button.getAttribute('aria-label')).toBe('Block settings'); + expect(instance.button.getAttribute('aria-haspopup')).toBe('menu'); + expect(instance.button.getAttribute('aria-expanded')).toBe('false'); + }); + + it('should open the menu for the block it is following', async () => { + instance.plugin.publicApi.register(ctx => ({ + title: `For ${ctx.blockId}`, + onActivate: () => {}, + })); + + selectBlock(1); + clickButton(instance.button); + await flush(); + + expect(itemTitles(instance.element)).toEqual(['For block-1']); + }); + + it('should follow the menu state with aria-expanded', async () => { + instance.plugin.publicApi.register(() => ({ + title: 'Anchor', + onActivate: () => {}, + })); + + selectBlock(0); + clickButton(instance.button); + await flush(); + + expect(instance.button.getAttribute('aria-expanded')).toBe('true'); + + instance.plugin.publicApi.close(); + + expect(instance.button.getAttribute('aria-expanded')).toBe('false'); + }); + + it('should hold focus before the menu is asked to open', async () => { + instance.plugin.publicApi.register(() => ({ + title: 'Anchor', + onActivate: () => {}, + })); + + selectBlock(0); + clickButton(instance.button); + await flush(); + + // Safari leaves a clicked button unfocused, and the popover would then have nowhere + // to return focus to when it closes. + expect(document.activeElement).toBe(instance.button); + }); + + it('should close the menu it opened when activated again', async () => { + instance.plugin.publicApi.register(() => ({ + title: 'Anchor', + onActivate: () => {}, + })); + + selectBlock(0); + clickButton(instance.button); + await flush(); + + expect(instance.button.getAttribute('aria-expanded')).toBe('true'); + + // A menu button dismisses the menu it opened; without this the second click rebuilt it + // in place and left no way to close it from the control that advertises it. + clickButton(instance.button); + await flush(); + + expect(instance.button.getAttribute('aria-expanded')).toBe('false'); + }); + + it('should not rebuild the menu when it is being closed', async () => { + const provider = jest.fn(() => ({ + title: 'Anchor', + onActivate: () => {}, + })); + + instance.plugin.publicApi.register(provider); + + selectBlock(0); + clickButton(instance.button); + await flush(); + + expect(provider).toHaveBeenCalledTimes(1); + + clickButton(instance.button); + await flush(); + + expect(provider).toHaveBeenCalledTimes(1); + }); + + it('should open again after it was toggled closed', async () => { + instance.plugin.publicApi.register(() => ({ + title: 'Anchor', + onActivate: () => {}, + })); + + selectBlock(0); + clickButton(instance.button); + await flush(); + clickButton(instance.button); + await flush(); + clickButton(instance.button); + await flush(); + + expect(instance.button.getAttribute('aria-expanded')).toBe('true'); + expect(itemTitles(instance.element)).toEqual(['Anchor']); + }); + + it('should not re-target while its menu is open', async () => { + instance.plugin.publicApi.register(ctx => ({ + title: `For ${ctx.blockId}`, + onActivate: () => {}, + })); + + selectBlock(0); + clickButton(instance.button); + await flush(); + + // The menu belongs to block 0; a selection arriving now must not move it underneath. + selectBlock(2); + await flush(); + + expect(itemTitles(instance.element)).toEqual(['For block-0']); + }); + + /** + * Nothing announces that selection a second time, so dropping it left the button acting on a + * block the caret had already left -- which is what clicking into another block does, since + * the caret moves on mousedown and the popover only closes on the click + */ + it('should take the selection it skipped once its menu closes', async () => { + instance.plugin.publicApi.register(ctx => ({ + title: `For ${ctx.blockId}`, + onActivate: () => {}, + })); + + selectBlock(0); + clickButton(instance.button); + await flush(); + + selectBlock(2); + instance.plugin.publicApi.close(); + + clickButton(instance.button); + await flush(); + + expect(itemTitles(instance.element)).toEqual(['For block-2']); + }); + + /** + * The toolbar holds its position while the toolbox is open, so the button stays beside one block: a target that + * moved out from under it would open one block's actions next to another's, `Delete` among them + */ + /** + * The target was frozen while the toolbox held the toolbar, and the toolbar catches up with + * the same selection when the toolbox closes -- so both land on the block the caret reached, + * which is what keeps the button and the block it acts on the same one + */ + it('should take the selection it skipped once the toolbox closes', async () => { + instance.plugin.publicApi.register(ctx => ({ + title: `For ${ctx.blockId}`, + onActivate: () => {}, + })); + + selectBlock(0); + openToolbox(); + selectBlock(2); + closeToolbox(); + + clickButton(instance.button); + await flush(); + + expect(itemTitles(instance.element)).toEqual(['For block-2']); + }); + + it('should not rebuild the open menu when the toolbox closes under it', async () => { + instance.plugin.publicApi.register(ctx => ({ + title: `For ${ctx.blockId}`, + onActivate: () => {}, + })); + + selectBlock(0); + clickButton(instance.button); + await flush(); + + openToolbox(); + selectBlock(2); + closeToolbox(); + + // The menu is still open, so the target has not moved with the toolbox closing. + expect(itemTitles(instance.element)).toEqual(['For block-0']); + }); + + it('should follow the selection again once the toolbox closes', async () => { + instance.plugin.publicApi.register(ctx => ({ + title: `For ${ctx.blockId}`, + onActivate: () => {}, + })); + + selectBlock(0); + openToolbox(); + closeToolbox(); + selectBlock(2); + + clickButton(instance.button); + await flush(); + + expect(itemTitles(instance.element)).toEqual(['For block-2']); + }); + }); + + describe('rebuilding an open menu', () => { + /** + * `PopoverDesktop.destroy()` hides before it tears down, and hiding emits `Closed`. With the + * old popover still subscribed, replacing it reported the menu as closed and open again + */ + it('should not report the menu as closed while it is being replaced', async () => { + const closed: unknown[] = []; + + instance.eventBus.addEventListener('ui:block-settings:closed', event => closed.push(event)); + instance.plugin.publicApi.register(ctx => ({ + title: `For ${ctx.blockId}`, + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + + expect(closed).toHaveLength(0); + + await open(instance.eventBus, 1); + + expect(closed).toHaveLength(0); + expect(itemTitles(instance.element)).toEqual(['For block-1']); + expect(instance.button.getAttribute('aria-expanded')).toBe('true'); + }); + + it('should still report the menu as closed when it really closes', async () => { + const closed: unknown[] = []; + + instance.eventBus.addEventListener('ui:block-settings:closed', event => closed.push(event)); + instance.plugin.publicApi.register(() => ({ title: 'Anchor', + onActivate: () => {} })); + + await open(instance.eventBus, 0); + instance.plugin.publicApi.close(); + + expect(closed).toHaveLength(1); + expect(instance.button.getAttribute('aria-expanded')).toBe('false'); + }); + }); + + describe('a target the document moves', () => { + /** + * Reports a selection to a freshly built instance + * @param target - the instance under test + * @param index - block position to report as selected + */ + function select(target: ReturnType, index: number): void { + target.select(index); + } + + /** + * A collaborator, an undo or a move can insert above the selected block, and none of those + * report a selection -- so a target held as a position quietly comes to mean another block + */ + it('should open for the block that was selected, not the position it held', async () => { + const blocks = [...defaultBlocks]; + const target = setup(blocks); + + target.plugin.publicApi.register(ctx => ({ + title: `For ${ctx.blockId}`, + onActivate: () => {}, + })); + + select(target, 1); + + blocks.unshift({ id: 'block-new', + name: 'paragraph' }); + + clickButton(target.button); + await flush(); + + expect(itemTitles(target.element)).toEqual(['For block-1']); + }); + + it('should hand providers the position the block holds now', async () => { + const blocks = [...defaultBlocks]; + const target = setup(blocks); + const provider = jest.fn(() => undefined); + + target.plugin.publicApi.register(provider); + + select(target, 1); + + blocks.unshift({ id: 'block-new', + name: 'paragraph' }); + + clickButton(target.button); + await flush(); + + expect(provider).toHaveBeenCalledWith(expect.objectContaining({ blockId: 'block-1', + blockIndex: 2 })); + }); + + it('should not open when the selected block is gone', async () => { + const blocks = [...defaultBlocks]; + const target = setup(blocks); + const provider = jest.fn(() => ({ title: 'Anchor', + onActivate: () => {} })); + + target.plugin.publicApi.register(provider); + + select(target, 1); + + blocks.splice(1, 1); + + clickButton(target.button); + await flush(); + + expect(provider).not.toHaveBeenCalled(); + expect(target.button.getAttribute('aria-expanded')).toBe('false'); + }); + }); + + describe('destroy', () => { + it('should stop answering open requests', async () => { + const destroyed = setup(); + const provider = jest.fn(() => ({ title: 'Anchor', + onActivate: () => {} })); + + destroyed.plugin.publicApi.register(provider); + + destroyed.plugin.destroy(); + + await open(destroyed.eventBus, 0); + + // The bus outlives the plugin, so a listener left on it would keep building menus into + // a holder that is no longer on the page. + expect(provider).not.toHaveBeenCalled(); + }); + + it('should abandon a build in flight', async () => { + const destroyed = setup(); + const onOpened = jest.fn(); + + destroyed.eventBus.addEventListener('ui:block-settings:opened', onOpened); + + destroyed.plugin.publicApi.register(async () => { + await new Promise(resolve => setTimeout(resolve, SLOW_PROVIDER_MS)); + + return { + title: 'Anchor', + onActivate: () => {}, + }; + }); + + destroyed.eventBus.dispatchEvent(new BlockSettingsOpenUIEvent({ index: 0 })); + + // Dropping the listeners stops the next request, not the one already waiting. + destroyed.plugin.destroy(); + + await new Promise(resolve => setTimeout(resolve, BOTH_REQUESTS_SETTLED_MS)); + + expect(onOpened).not.toHaveBeenCalled(); + expect(itemTitles(destroyed.element)).toEqual([]); + }); + + it('should stop following block selection', () => { + const destroyed = setup(); + + destroyed.plugin.destroy(); + + expect(() => destroyed.eventBus.dispatchEvent(new BlockSelectedUIEvent({ + block: document.createElement('div'), + index: 1, + }))).not.toThrow(); + }); + + it('should take its button and menu off the page', () => { + const destroyed = setup(); + + destroyed.plugin.destroy(); + + expect(destroyed.button.isConnected).toBe(false); + expect(destroyed.element.isConnected).toBe(false); + }); + }); + + describe('accessibility', () => { + it('should name the menu from the message catalogue', async () => { + instance.plugin.publicApi.register(() => ({ + title: 'Anchor', + onActivate: () => {}, + })); + + await open(instance.eventBus, 0); + + const menu = instance.element.querySelector('[role="menu"]'); + + expect(menu?.getAttribute('aria-label')).toBe('Block settings'); + }); + + it('should leave no stale items in the accessibility tree when rebuilt smaller', async () => { + instance.plugin.publicApi.register(ctx => (ctx.tool === 'image' + ? { + title: 'Only one', + onActivate: () => {}, + } + : [ + { + title: 'One', + onActivate: () => {}, + }, + { + title: 'Two', + onActivate: () => {}, + }, + ])); + + await open(instance.eventBus, 0); + expect(itemTitles(instance.element)).toEqual(['One', 'Two']); + + instance.plugin.publicApi.close(); + await open(instance.eventBus, 2); + + expect(itemTitles(instance.element)).toEqual(['Only one']); + }); + }); +}); diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts new file mode 100644 index 00000000..3713ef52 --- /dev/null +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -0,0 +1,823 @@ +import { make } from '@editorjs/dom'; +import { IconMenuSmall } from '@codexteam/icons'; +import type { + BlockId, + CoreConfigValidated, + EditorAPI, + EditorjsPlugin, + EditorjsPluginParams, + EventBus +} from '@editorjs/sdk'; +import { UiComponentType } from '@editorjs/sdk'; +import type { PopoverItemDefaultBaseParams, PopoverItemParams } from '@editorjs/ui-kit'; +import { PopoverDesktop, PopoverEvent, PopoverItemType } from '@editorjs/ui-kit'; +import { messages } from '../messages.js'; +import ControlStyle from '../controls.module.pcss'; +import type { BlockSelectedUIEvent } from '../Blocks/events/index.js'; +import { + BlockSettingsClosedUIEvent, + BlockSettingsOpenedUIEvent, + BlockSettingsRenderedUIEvent +} from './events/index.js'; +import type { BlockSettingsOpenUIEvent } from './events/index.js'; + +/** + * Items a provider contributes to the block settings menu. + * + * A single item or a list of them, in the vocabulary `@editorjs/ui-kit` popovers already use. + * Named apart from `@editorjs/sdk`'s `MenuConfig`, which is a different, narrower shape for + * inline tools' toolbar config: + * an item's behaviour comes entirely from its own params (`onActivate`, `isActive`, + * `isDisabled`, `closeOnActivate`, `children`, or a `confirmation` whose handler runs on the + * second activation), so the menu itself interprets nothing. + */ +export type BlockSettingsMenuConfig = PopoverItemParams | PopoverItemParams[]; + +/** + * The block a provider is being asked about + */ +export interface BlockSettingsContext { + /** + * Id of the block the menu is being built for. + * + * Identifies the block for as long as it exists, which is why an item's handler should + * resolve the block's current position from it rather than reusing {@link blockIndex} + */ + blockId: BlockId; + + /** + * Position the block held at the moment the menu was built. + * + * Only valid then: the document may change while the menu is open, so a handler acting on + * this number can hit a different block than the user opened the menu on + */ + blockIndex: number; + + /** + * Name of the tool rendering the block, for providers that only apply to some tools. + * + * Absent when it could not be determined, which means the editor's own view of this block + * disagrees with the Model's -- the id resolved and the tool did not. A provider matching on + * a tool simply does not match, rather than being handed an empty name that matches nothing + * while looking like an answer + */ + tool?: string; +} + +/** + * A function asked for its menu items each time block settings open. + * + * Returning `undefined` or an empty list opts out for that block, contributing neither items + * nor a separator. + * + * Expected to answer from what it already has: the menu shows nothing until every provider has + * answered, and one that has not answered within its timeout is left out of it. A provider that + * genuinely needs longer than the default says so through `options.timeout`. + */ +export type BlockSettingsProvider = ( + context: BlockSettingsContext +) => BlockSettingsMenuConfig | undefined | Promise; + +/** + * Options a provider is registered with + */ +export interface BlockSettingsRegisterOptions { + /** + * Ascending sort key for this provider's contribution, defaulting to `0` with ties broken by + * registration order. The built-in settings sit last, at `1000` + */ + order?: number; + + /** + * How long this provider may take before the menu is built without it, in milliseconds. A backstop rather than a + * budget: the menu shows nothing until every provider has answered, so one that needs this is one worth noticing + */ + timeout?: number; +} + +/** + * Public API the Block settings plugin exposes as `api.plugins['block-settings']` + */ +export interface BlockSettingsAPI { + /** + * Registers a settings provider. + * + * Unregistering takes effect from the next open: providers are asked as the menu is built, so + * one already on screen keeps the items it was built with until it closes + * @param provider - called with the target block each time the menu opens + * @param options - registration options, `order` and `timeout` among them + * @returns a function that unregisters the provider + */ + register(provider: BlockSettingsProvider, options?: BlockSettingsRegisterOptions): () => void; + + /** + * Closes the menu if it is open + */ + close(): void; +} + +declare module '@editorjs/sdk' { + /* eslint-disable jsdoc/require-jsdoc -- interface members are documented on the types they alias */ + interface EditorjsPluginApiMap { + /** + * Block settings plugin's public API + */ + // eslint-disable-next-line @typescript-eslint/naming-convention -- the key is the plugin's `name`, which is kebab-case + 'block-settings': BlockSettingsAPI; + } + /* eslint-enable jsdoc/require-jsdoc */ +} + +/** + * How long one provider may take before the menu is built without it. + * + * Long enough that a provider reading something off the network still makes it, short enough + * that the menu is not simply unresponsive while one waits + */ +const PROVIDER_TIMEOUT_MS = 500; + +/** + * A registered provider together with what it was registered with + */ +interface Registration { + /** The provider itself */ + provider: BlockSettingsProvider; + /** Sort key */ + order: number; + /** Registration counter, used to keep equal orders in registration sequence */ + sequence: number; + /** How long this provider may take, in milliseconds */ + timeout: number; +} + +/** + * Takes the callbacks ui-kit will call on a contributed item out of harm's way: `isActive`, which it reads as it + * renders, and `onActivate`, which it calls on a click -- both long after the provider's own `try` has returned + * @param item - item as the provider returned it + */ +/** + * Signature ui-kit calls a contributed item's handler with + */ +type ItemActivate = (activated: PopoverItemParams, event?: PointerEvent) => void; + +/** + * The handler with its failures reported rather than left to escape + * @param activate - the handler the provider supplied + */ +function guarded(activate: ItemActivate): ItemActivate { + return (activated, event): void => { + try { + activate(activated, event); + } catch (error) { + console.error('[BlockSettingsUI] A block settings item failed on activation', error); + } + }; +} + +/** + * The resolved active state, shaped to be spread over the item it came from + */ +interface ActiveStatePatch { + /** + * What the item's `isActive` callback returned, absent when it carried none + */ + isActive?: boolean; +} + +/** + * The item's `isActive` resolved to the boolean it returns, as a patch to spread over the item + * @param item - item carrying it, if it carries one at all + */ +function resolvedActiveState(item: PopoverItemParams): ActiveStatePatch { + if (!('isActive' in item) || typeof item.isActive !== 'function') { + return {}; + } + + return { isActive: item.isActive() }; +} + +/** + * Takes the callbacks ui-kit will call on a contributed item out of harm's way: `isActive`, which it reads as it + * renders, and `onActivate`, which it calls on a click -- both long after the provider's own `try` has returned + * @param item - item as the provider returned it + */ +function withIsolatedCallbacks(item: PopoverItemParams): PopoverItemParams { + /** + * A separator carries no behaviour at all + */ + if ('type' in item && item.type === PopoverItemType.Separator) { + return item; + } + + if ('children' in item) { + return { + ...item, + ...resolvedActiveState(item), + children: { + ...item.children, + items: item.children.items?.map(withIsolatedCallbacks), + }, + }; + } + + if ('confirmation' in item) { + return { + ...item, + ...resolvedActiveState(item), + confirmation: withIsolatedCallbacks(item.confirmation) as PopoverItemDefaultBaseParams, + }; + } + + if ('onActivate' in item && typeof item.onActivate === 'function') { + return { + ...item, + ...resolvedActiveState(item), + onActivate: guarded(item.onActivate), + }; + } + + return { + ...item, + ...resolvedActiveState(item), + }; +} + +/** + * UI plugin that renders the per-block settings menu and the button that opens it, announcing + * both once for a host to mount. It owns no items of its own -- everything in the menu comes + * from registered providers, the built-in Move/Delete entries included. + * + * Register it after whatever mounts it. The announcement is made once, from the constructor, and + * is not replayed, so a host registered later never hears it and the button and menu stay off + * the page with nothing reported + */ +export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { + /** + * Plugin type + */ + public static readonly type = UiComponentType.BlockSettings; + + /** + * Plugin name -- keys `api.plugins['block-settings']` + */ + public static readonly name = 'block-settings'; + + /** + * API registering providers and closing the menu + */ + public readonly publicApi: BlockSettingsAPI; + + /** + * EditorAPI instance, used to resolve the target block + */ + #api: EditorAPI; + + /** + * EventBus instance to exchange events between components + */ + #eventBus: EventBus; + + /** + * Editor configuration + */ + #editorConfig: CoreConfigValidated; + + /** + * Stable element handed to the host. The popover inside it is replaced per open, + * so this is what stays mounted + */ + #holder: HTMLElement; + + /** + * The control that opens the menu. Owned here rather than by the toolbar: the button and + * the menu are one widget, and every piece of its menu-button contract -- the accessible + * name, `aria-haspopup`, the `aria-expanded` that has to track the menu's real state -- + * depends on state only this plugin has + */ + #button: HTMLButtonElement; + + /** + * The block the menu will be built for, as last reported by block selection. Held by id, not position: a block + * inserted or removed above it shifts every position below, and nothing reports that as a selection + */ + #selectedBlockId: BlockId | undefined; + + /** + * Whether the toolbox popover is open. The toolbar holds its position while it is, since that popover renders inside + * the toolbar -- so the button stays beside one block, and the block the menu acts on has to stay there with it + */ + #isToolboxOpen = false; + + /** + * Popover rendering the current menu, absent until the menu is first built + */ + #popover: PopoverDesktop | undefined; + + /** + * Whether the menu is open, as this plugin understands it. + * + * Tracked here rather than read back off the popover, whose own shown state is its business + * and does not reliably survive the click that opened the menu. This is the state the + * button's `aria-expanded` and the `opened`/`closed` events promise + */ + #isOpen = false; + + /** + * Whether the menu was open when the activation that is now in progress began. + * + * The popover closes itself from the click, and it gets there before this button's own + * handler -- so by `click` the menu is already gone, and a toggle reading the state then + * would see every second activation as a fresh open. The last moment the answer is still + * true is `mousedown` for a pointer, and the `keydown` of Enter or Space for a keyboard, + * which is why both are recorded here rather than only the first + */ + #wasOpenOnActivationStart = false; + + /** + * Registered providers + */ + readonly #registrations = new Set(); + + /** + * Incremented per registration so providers sharing an `order` keep their registration sequence + */ + #sequence = 0; + + /** + * Incremented on every open request. Building a menu is asynchronous, so a request that + * finishes after a newer one started has been superseded and must not render + */ + #openToken = 0; + + /** + * Index the request currently being built is for, or `null` when nothing is in flight. + * + * Providers may be asynchronous, so the block a menu is being built for can stop being the + * selected one before the menu exists + */ + #buildingFor: BlockId | null = null; + + /** + * BlockSettingsUI class constructor + * @param params - Plugin parameters + */ + constructor({ api, eventBus, config }: EditorjsPluginParams) { + this.#api = api; + this.#eventBus = eventBus; + this.#editorConfig = config; + + this.publicApi = { + register: (provider, options) => this.#register(provider, options), + close: () => this.#close(), + }; + + this.#holder = make('div'); + this.#button = make('button', ControlStyle['toolbar-button'], { + innerHTML: IconMenuSmall, + /** + * A button defaults to `submit`, and the editor's holder may sit inside a form, where + * opening the settings menu would submit it + */ + type: 'button', + }) as HTMLButtonElement; + + this.#renderButton(); + + this.#eventBus.dispatchEvent(new BlockSettingsRenderedUIEvent({ + button: this.#button, + blockSettings: this.#holder, + })); + + this.#eventBus.addEventListener('ui:blocks:block-selected', this.#handleBlockSelected); + this.#eventBus.addEventListener('ui:block-settings:open', this.#handleOpenRequest); + this.#eventBus.addEventListener('ui:toolbox:opened', this.#handleToolboxOpened); + this.#eventBus.addEventListener('ui:toolbox:closed', this.#handleToolboxClosed); + } + + /** + * Cleanup when plugin is destroyed + */ + public destroy(): void { + /** + * The bus outlives the plugin, so a listener left on it keeps this instance alive and + * answering: an open request after destroy would build a menu into a detached holder + */ + this.#eventBus.removeEventListener('ui:blocks:block-selected', this.#handleBlockSelected); + this.#eventBus.removeEventListener('ui:block-settings:open', this.#handleOpenRequest); + this.#eventBus.removeEventListener('ui:toolbox:opened', this.#handleToolboxOpened); + this.#eventBus.removeEventListener('ui:toolbox:closed', this.#handleToolboxClosed); + + /** + * Dropping the listeners stops new requests, but not one already waiting on its providers. + * That one would render into the holder removed just below + */ + this.#abandonPendingBuild(); + + this.#popover?.destroy(); + this.#popover = undefined; + this.#holder.remove(); + this.#button.remove(); + } + + /** + * Where the target sits now, or -1 when there is no target or the document no longer holds it. Resolved on + * demand rather than stored, so it cannot go stale between the selection and the open + */ + get #selectedBlockIndex(): number { + if (this.#selectedBlockId === undefined) { + return -1; + } + + return this.#api.blocks.getIndexById(this.#selectedBlockId); + } + + /** + * Follows block selection, except while the menu or the toolbox is open: whenever the toolbar holds its position, + * re-targeting here would leave the button and this target on different blocks + * @param event - the selection event + */ + #handleBlockSelected = (event: BlockSelectedUIEvent): void => { + if (this.#isOpen || this.#isToolboxOpen) { + return; + } + + const blockId = this.#api.blocks.getIdByIndex(event.detail.index); + + /** + * A build in flight was started for whichever block was selected at the time. Letting it + * finish after the selection has moved would open that block's actions beside this one, + * which is a menu that acts on a block the user is no longer pointing at + */ + if (this.#buildingFor !== null && this.#buildingFor !== blockId) { + this.#abandonPendingBuild(); + } + + this.#selectedBlockId = blockId; + }; + + /** + * Opens the menu for the block another component asked about + * @param event - the open request + */ + #handleOpenRequest = (event: BlockSettingsOpenUIEvent): void => { + void this.#open(event.detail.index); + }; + + /** + * Freezes the target for as long as the toolbox holds the toolbar in place + */ + #handleToolboxOpened = (): void => { + this.#isToolboxOpen = true; + }; + + /** + * Lets the target follow the selection again, from the next block reported + */ + #handleToolboxClosed = (): void => { + this.#isToolboxOpen = false; + this.#catchUpWithSelection(); + }; + + /** + * Targets the block the UI treats as selected now, so the button acts on the block the caret reached while the + * target was frozen: selection arrives as a one-shot event, and the ones ignored here are not repeated + */ + #catchUpWithSelection(): void { + /** + * Either state alone freezes the target, so this waits for both. While frozen the target has to stay with the + * button, which the toolbar is holding beside another block + */ + if (this.#isOpen || this.#isToolboxOpen) { + return; + } + + const selected = this.#api.plugins.blocksUI?.getSelectedBlock(); + + if (selected === undefined) { + return; + } + + this.#selectedBlockId = selected.id; + } + + /** + * Gives the button its menu-button semantics and wires it to the menu + */ + #renderButton(): void { + this.#button.setAttribute('aria-label', messages.blockSettingsButton); + this.#button.setAttribute('aria-haspopup', 'menu'); + this.#button.setAttribute('aria-expanded', 'false'); + + this.#button.addEventListener('mousedown', () => { + this.#wasOpenOnActivationStart = this.#isOpen; + }); + + /** + * Enter and Space send a `click` of their own, with no pointer events before it. Their + * `keydown` is where that activation starts, so it is the keyboard's `mousedown` + */ + this.#button.addEventListener('keydown', (event: KeyboardEvent) => { + if (event.key !== 'Enter' && event.key !== ' ') { + return; + } + + this.#wasOpenOnActivationStart = this.#isOpen; + + /** + * No click follows a key the open menu's own handling has claimed, so the toggle on it never runs: closing + * here is the only way left to dismiss the menu from the button that opened it + */ + if (this.#isOpen && event.defaultPrevented) { + this.#close(); + } + }); + + this.#button.addEventListener('click', () => { + /** + * The snapshot is the answer whenever the popover has already dismissed itself over this + * activation, which is the usual order. The live state covers the case where it has not + * got there yet, so the toggle does not depend on which of the two runs first + */ + const wasOpen = this.#wasOpenOnActivationStart || this.#isOpen; + + this.#wasOpenOnActivationStart = false; + + /** + * Safari leaves a clicked button unfocused, and the popover would then capture + * `document.body` as the element to restore focus to when it closes. Focusing the + * button that owns the menu is also what the WAI-ARIA menu button pattern asks for + */ + this.#button.focus(); + + /** + * A menu button dismisses the menu it opened. The popover has already closed itself by + * now, so there is usually nothing left to close -- what matters is not re-opening it, + * which is what made the button look inert on every second click + */ + if (wasOpen) { + this.#close(); + + return; + } + + void this.#open(this.#selectedBlockIndex); + }); + } + + /** + * Registers a provider and returns its unregister function + * @param provider - called with the target block each time the menu opens + * @param options - registration options + */ + #register(provider: BlockSettingsProvider, options?: BlockSettingsRegisterOptions): () => void { + const registration: Registration = { + provider, + order: options?.order ?? 0, + sequence: this.#sequence++, + timeout: options?.timeout ?? PROVIDER_TIMEOUT_MS, + }; + + this.#registrations.add(registration); + + return () => { + this.#registrations.delete(registration); + }; + } + + /** + * Closes the menu if it is open. + * + * `hide()` is asked first, so the popover tears down its own focus handling, and the + * bookkeeping is then run directly: a popover that has already dropped its shown state hides + * without emitting anything, which would leave the button advertising a menu that is gone + */ + #close(): void { + this.#abandonPendingBuild(); + + if (!this.#isOpen) { + return; + } + + this.#popover?.hide(); + + this.#handleClosed(); + } + + /** + * Records the menu as closed, once, whichever route closed it + */ + #handleClosed = (): void => { + /** + * Escape and a click outside reach this directly from the popover, without passing through + * `#close()`, so the two close paths have to abandon a build in flight alike. A menu can be + * mid-build rather than open -- `#isOpen` is only set once the providers have returned -- + * which is why this runs before the open-state guard below + */ + this.#abandonPendingBuild(); + + if (!this.#isOpen) { + return; + } + + this.#isOpen = false; + + this.#button.setAttribute('aria-expanded', 'false'); + + this.#eventBus.dispatchEvent(new BlockSettingsClosedUIEvent({})); + + this.#catchUpWithSelection(); + }; + + /** + * Discards whichever menu is still being built, so that it never reaches the screen. + * + * Bumping the token is what the build checks before rendering; `#buildingFor` goes with it, + * since there is no longer a block being built for + */ + #abandonPendingBuild(): void { + this.#openToken++; + this.#buildingFor = null; + } + + /** + * Builds the menu for a block and opens it, unless there is nothing to show + * @param index - position the opening request named + */ + async #open(index: number): Promise { + const token = ++this.#openToken; + + const blockId = this.#api.blocks.getIdByIndex(index); + + /** + * Nothing is selected, or the index is stale, so no provider is asked. Any menu still on + * screen was built for a different block, and leaving it open would present one block's + * settings as another's + */ + if (blockId === undefined) { + this.#close(); + + return; + } + + this.#buildingFor = blockId; + + const items = await this.#collectItems({ + blockId, + blockIndex: index, + tool: this.#api.blocks.getToolByIndex(index), + }); + + /** + * A newer request started while this one was waiting on its providers. That one owns the + * menu now, and rendering this result would replace it with a stale block's items + */ + if (token !== this.#openToken) { + return; + } + + this.#buildingFor = null; + + /** + * Every provider opted out of this block. Same reasoning as the missing block above: the + * menu does not open, and whatever was open closes rather than misrepresenting this block + */ + if (items.length === 0) { + this.#close(); + + return; + } + + this.#renderPopover(items); + + this.#popover?.show(); + + this.#isOpen = true; + this.#button.setAttribute('aria-expanded', 'true'); + + this.#eventBus.dispatchEvent(new BlockSettingsOpenedUIEvent({})); + } + + /** + * Asks every registered provider for its items and concatenates the contributions, + * separated from one another + * @param context - the block being asked about + */ + async #collectItems(context: BlockSettingsContext): Promise { + const ordered = [...this.#registrations].sort( + (a, b) => (a.order - b.order) || (a.sequence - b.sequence) + ); + + const contributions = await Promise.all( + ordered.map(async ({ provider, timeout }) => { + try { + const result = await this.#withTimeout(provider(context), timeout); + + if (result === undefined) { + return []; + } + + const items = Array.isArray(result) ? result : [result]; + + /** + * Inside the `try` on purpose: an `isActive` that throws is this provider failing, so it costs this + * provider's items rather than the whole menu + */ + return items.map(withIsolatedCallbacks); + } catch (error) { + /** + * Providers are third-party code and this is the one place all of it runs, so without + * isolation a single plugin throwing takes the whole menu down for every block. It + * contributes nothing instead, and the stack identifies which one it was + */ + console.error('[BlockSettingsUI] A block settings provider failed and was skipped', error); + + return []; + } + }) + ); + + return contributions + .filter(contribution => contribution.length > 0) + .reduce((items, contribution) => { + if (items.length > 0) { + items.push({ type: PopoverItemType.Separator }); + } + + return items.concat(contribution); + }, []); + } + + /** + * Rejects if a provider has not settled in time, so that the one waiting on it is skipped + * rather than holding up the menu. + * + * Without this the `Promise.all` over providers has no floor: a provider that never settles + * means the menu never opens, and never opens again either, because every later attempt waits + * on the same provider. A rejection instead lands in the same skip-and-log path as one that + * threw, which is the behaviour a plugin author already has to expect + * @param result - what the provider returned + * @param timeout - how long that provider may take, in milliseconds + */ + async #withTimeout( + result: BlockSettingsMenuConfig | undefined | Promise, + timeout: number + ): Promise { + let timer: ReturnType | undefined; + + try { + return await Promise.race([ + result, + new Promise((_resolve, reject) => { + timer = setTimeout( + () => reject(new Error(`A block settings provider did not return within ${timeout}ms`)), + timeout + ); + }), + ]); + } finally { + clearTimeout(timer); + } + } + + /** + * Replaces the popover inside the holder with one built for the given items. Rebuilt rather + * than edited in place because `removeItemByName` is ui-kit's only removal and a separator + * carries no name, so a fresh popover is what keeps the previous block's items out of the + * accessibility tree + * @param items - items the menu should consist of + */ + #renderPopover(items: PopoverItemParams[]): void { + /** + * `destroy()` hides before it tears down, and hiding emits `Closed`. Left subscribed, the + * popover being replaced would report the menu as closed and open again on every rebuild + */ + this.#popover?.off(PopoverEvent.Closed, this.#handleClosed); + this.#popover?.destroy(); + + /** + * The item wrapper is left at ui-kit's default: `wrapperTag: 'button'`, carried over from + * PR #157, is what ui-kit uses for its *inline* popover, where shrink-to-fit is the right + * width. In a vertical menu a form control does not stretch to its container, so each row + * came out as wide as its own label -- a partial hover highlight and the UA button font + */ + this.#popover = new PopoverDesktop({ + scopeElement: this.#editorConfig.holder, + searchable: false, + items, + + /** + * Names the menu for assistive technologies, matching the button that opens it + */ + messages: { + label: messages.blockSettingsMenu, + }, + }); + + this.#popover.on(PopoverEvent.Closed, this.#handleClosed); + + this.#holder.innerHTML = ''; + this.#holder.appendChild(this.#popover.getElement()); + } +} + +export * from './events/index.js'; diff --git a/packages/ui/src/BlockSettings/events/BlockSettingsBaseEvent.ts b/packages/ui/src/BlockSettings/events/BlockSettingsBaseEvent.ts new file mode 100644 index 00000000..814db33f --- /dev/null +++ b/packages/ui/src/BlockSettings/events/BlockSettingsBaseEvent.ts @@ -0,0 +1,15 @@ +import { UIEventBase } from '@editorjs/sdk'; + +/** + * Base event class for BlockSettings events + */ +export class BlockSettingsBaseEvent extends UIEventBase { + /** + * Constructor function + * @param name - name of a BlockSettings event + * @param payload - generic payload + */ + constructor(name: string, payload: Payload) { + super(`block-settings:${name}`, payload); + } +} diff --git a/packages/ui/src/BlockSettings/events/BlockSettingsClosedUIEvent.ts b/packages/ui/src/BlockSettings/events/BlockSettingsClosedUIEvent.ts new file mode 100644 index 00000000..533f5672 --- /dev/null +++ b/packages/ui/src/BlockSettings/events/BlockSettingsClosedUIEvent.ts @@ -0,0 +1,20 @@ +import { BlockSettingsBaseEvent } from './BlockSettingsBaseEvent.js'; + +/** + * Payload of the BlockSettingsClosedUIEvent - empty for now + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface BlockSettingsClosedUIEventPayload {} + +/** + * Class for event that is being fired after block settings have been closed + */ +export class BlockSettingsClosedUIEvent extends BlockSettingsBaseEvent { + /** + * BlockSettingsClosedUIEvent constructor function + * @param payload - BlockSettingsClosed event payload + */ + constructor(payload: BlockSettingsClosedUIEventPayload) { + super('closed', payload); + } +} diff --git a/packages/ui/src/BlockSettings/events/BlockSettingsOpenUIEvent.ts b/packages/ui/src/BlockSettings/events/BlockSettingsOpenUIEvent.ts new file mode 100644 index 00000000..330e5ef4 --- /dev/null +++ b/packages/ui/src/BlockSettings/events/BlockSettingsOpenUIEvent.ts @@ -0,0 +1,26 @@ +import { BlockSettingsBaseEvent } from './BlockSettingsBaseEvent.js'; + +/** + * Names the block whose settings should be shown + */ +export interface BlockSettingsOpenUIEventPayload { + /** + * Position of the block to show settings for, named by index because callers follow block + * selection by position. `BlockSettingsUI` resolves it to an id once the menu opens, and the + * providers' items work from that id afterwards + */ + readonly index: number; +} + +/** + * Class for event that is being fired when block settings should be opened + */ +export class BlockSettingsOpenUIEvent extends BlockSettingsBaseEvent { + /** + * BlockSettingsOpenUIEvent constructor function + * @param payload - BlockSettingsOpen event payload + */ + constructor(payload: BlockSettingsOpenUIEventPayload) { + super('open', payload); + } +} diff --git a/packages/ui/src/BlockSettings/events/BlockSettingsOpenedUIEvent.ts b/packages/ui/src/BlockSettings/events/BlockSettingsOpenedUIEvent.ts new file mode 100644 index 00000000..4166e5e3 --- /dev/null +++ b/packages/ui/src/BlockSettings/events/BlockSettingsOpenedUIEvent.ts @@ -0,0 +1,20 @@ +import { BlockSettingsBaseEvent } from './BlockSettingsBaseEvent.js'; + +/** + * Payload of the BlockSettingsOpenedUIEvent - empty for now + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface BlockSettingsOpenedUIEventPayload {} + +/** + * Class for event that is being fired after block settings have been opened + */ +export class BlockSettingsOpenedUIEvent extends BlockSettingsBaseEvent { + /** + * BlockSettingsOpenedUIEvent constructor function + * @param payload - BlockSettingsOpened event payload + */ + constructor(payload: BlockSettingsOpenedUIEventPayload) { + super('opened', payload); + } +} diff --git a/packages/ui/src/BlockSettings/events/BlockSettingsRenderedUIEvent.ts b/packages/ui/src/BlockSettings/events/BlockSettingsRenderedUIEvent.ts new file mode 100644 index 00000000..c7371465 --- /dev/null +++ b/packages/ui/src/BlockSettings/events/BlockSettingsRenderedUIEvent.ts @@ -0,0 +1,34 @@ +import { BlockSettingsBaseEvent } from './BlockSettingsBaseEvent.js'; + +/** + * Payload of the BlockSettingsRenderedUIEvent + * Carries the elements the plugin owns, for a host to mount + */ +export interface BlockSettingsRenderedUIEventPayload { + /** + * The control that opens the menu. + * + * Announced separately from the menu because a host has to place it among its own + * controls -- `ToolbarUI` puts it in its actions container, where it takes part in the + * toolbar's roving tabindex and so has to be a child of that container in its own right + */ + readonly button: HTMLElement; + + /** + * The element the menu renders into + */ + readonly blockSettings: HTMLElement; +} + +/** + * Class for event that is being fired after the block settings menu is rendered + */ +export class BlockSettingsRenderedUIEvent extends BlockSettingsBaseEvent { + /** + * BlockSettingsRenderedUIEvent constructor function + * @param payload - BlockSettingsRendered event payload + */ + constructor(payload: BlockSettingsRenderedUIEventPayload) { + super('rendered', payload); + } +} diff --git a/packages/ui/src/BlockSettings/events/index.ts b/packages/ui/src/BlockSettings/events/index.ts new file mode 100644 index 00000000..02ce2d61 --- /dev/null +++ b/packages/ui/src/BlockSettings/events/index.ts @@ -0,0 +1,5 @@ +export * from './BlockSettingsBaseEvent.js'; +export * from './BlockSettingsRenderedUIEvent.js'; +export * from './BlockSettingsOpenUIEvent.js'; +export * from './BlockSettingsOpenedUIEvent.js'; +export * from './BlockSettingsClosedUIEvent.js'; diff --git a/packages/ui/src/Blocks/Blocks.selection.spec.ts b/packages/ui/src/Blocks/Blocks.selection.spec.ts new file mode 100644 index 00000000..30b9d723 --- /dev/null +++ b/packages/ui/src/Blocks/Blocks.selection.spec.ts @@ -0,0 +1,339 @@ +import { beforeEach, describe, expect, it } from '@jest/globals'; +import type { EditorAPI, EditorjsPluginParams } from '@editorjs/sdk'; +import { BlockAddedCoreEvent, BlockRemovedCoreEvent, EventBus } from '@editorjs/sdk'; +import { BlocksUI } from './Blocks.js'; +import type { BlocksHolderRenderedUIEvent, BlockSelectedUIEvent } from './events/index.js'; + +/** Enough blocks to tell "moved to another one" from "stayed put". */ +const THREE_BLOCKS = 3; + +/** The smallest document where a second block exists to move to. */ +const TWO_BLOCKS = 2; + +/** + * Mounts `BlocksUI` over a bus and gives it `count` blocks, each holding its own text node. + * + * The blocks are attached to the document for real: the caret is found by asking which block + * contains the selection's anchor, and a detached node is in no selection + * @param count - how many blocks the document starts with + */ +function setup(count: number): { + /** Event bus the instance is wired to */ + eventBus: EventBus; + /** Instance under test */ + plugin: BlocksUI; + /** The text nodes the blocks were given, in document order */ + texts: Text[]; + /** Indexes reported through `ui:blocks:block-selected`, in order */ + selected: number[]; + /** Adds a block at a position, keeping the ids the fake API answers with in step */ + addBlockAt: (index: number) => void; + /** Removes the block at a position, keeping those ids in step */ + removeBlockAt: (index: number) => void; +} { + const eventBus = new EventBus(); + const selected: number[] = []; + + /** + * Ids of the blocks by position, as the model would hold them. Spliced alongside every add and + * removal, so `getIdByIndex` answers for the document the plugin actually has + */ + const ids: string[] = []; + + eventBus.addEventListener('ui:blocks:block-selected', (event: BlockSelectedUIEvent) => { + selected.push(event.detail.index); + }); + + /** + * Attached as soon as it is announced, and before any block is added: a selection can only + * be placed in nodes that are in the document + */ + eventBus.addEventListener('ui:blocks:rendered', (event: BlocksHolderRenderedUIEvent) => { + document.body.appendChild(event.detail.blocksHolder); + }); + + const plugin = new BlocksUI({ + eventBus, + api: { + blocks: { + getIdByIndex: (index: number) => ids[index], + }, + } as unknown as EditorAPI, + } as EditorjsPluginParams); + + const texts: Text[] = []; + + for (let index = 0; index < count; index++) { + const blockElement = document.createElement('div'); + const text = document.createTextNode(`Block ${index}`); + + blockElement.appendChild(text); + texts.push(text); + + ids.splice(index, 0, `block-${index}`); + + eventBus.dispatchEvent(new BlockAddedCoreEvent({ + tool: 'paragraph', + data: {}, + ui: blockElement, + index, + })); + } + + return { + /** + * Adds a block at a position, as the core would + * @param index - where the block appears + */ + addBlockAt: (index: number): void => { + const blockElement = document.createElement('div'); + + blockElement.appendChild(document.createTextNode('Inserted')); + ids.splice(index, 0, 'block-inserted'); + + eventBus.dispatchEvent(new BlockAddedCoreEvent({ tool: 'paragraph', + data: {}, + ui: blockElement, + index })); + }, + + /** + * Removes the block at a position, as the core would + * @param index - which block goes + */ + removeBlockAt: (index: number): void => { + ids.splice(index, 1); + + eventBus.dispatchEvent(new BlockRemovedCoreEvent({ tool: 'paragraph', + index })); + }, + eventBus, + plugin, + texts, + selected, + }; +} + +/** + * Moves the pointer into a block, the way hovering it does + * @param node - a text node inside the block being entered + */ +function hoverBlock(node: Text): void { + // BlocksUI wraps what it is given: wrapper > contents > the element handed to it > this text. + const wrapper = node.parentElement?.parentElement?.parentElement; + + wrapper?.dispatchEvent(new MouseEvent('mouseenter')); +} + +/** + * The wrapper `BlocksUI` built around the element it was handed + * @param node - a text node inside that element + */ +function wrapperOf(node: Text): HTMLElement { + // BlocksUI wraps what it is given: wrapper > contents > the element handed to it > this text. + const wrapper = node.parentElement?.parentElement?.parentElement; + + if (wrapper === null || wrapper === undefined) { + throw new Error('the block has no wrapper'); + } + + return wrapper; +} + +/** + * Puts the caret in a text node, the way clicking or arrowing into a block does + * @param node - text node to place the caret in + */ +function putCaretIn(node: Text): void { + const range = document.createRange(); + + range.setStart(node, 0); + range.collapse(true); + + const selection = document.getSelection(); + + selection?.removeAllRanges(); + selection?.addRange(range); + + document.dispatchEvent(new Event('selectionchange')); +} + +describe('BlocksUI', () => { + beforeEach(() => { + document.body.innerHTML = ''; + document.getSelection()?.removeAllRanges(); + }); + + describe('telling other plugins which block is selected', () => { + it('should answer with nothing before any block has been reported', () => { + const instance = setup(TWO_BLOCKS); + + expect(instance.plugin.publicApi.getSelectedBlock()).toBeUndefined(); + }); + + it('should answer with the reported block and its id', () => { + const instance = setup(THREE_BLOCKS); + + putCaretIn(instance.texts[1]); + + expect(instance.plugin.publicApi.getSelectedBlock()).toEqual({ + block: wrapperOf(instance.texts[1]), + id: 'block-1', + }); + }); + + /** + * The id is read through the position the block holds when asked, so a block added above the + * reported one does not leave the answer naming whoever took its old slot + */ + it('should still answer with that block once one is added above it', () => { + const instance = setup(TWO_BLOCKS); + + putCaretIn(instance.texts[1]); + instance.addBlockAt(0); + + expect(instance.plugin.publicApi.getSelectedBlock()?.id).toBe('block-1'); + }); + + /** + * The wrapper is still held after its block is removed, so without this the answer would be + * an element that has left the document + */ + it('should answer with nothing once the reported block is removed', () => { + const instance = setup(TWO_BLOCKS); + + putCaretIn(instance.texts[1]); + + instance.removeBlockAt(1); + + expect(instance.plugin.publicApi.getSelectedBlock()).toBeUndefined(); + }); + }); + + describe('reporting the selected block', () => { + it('should report the block the caret moved into', () => { + const instance = setup(THREE_BLOCKS); + + putCaretIn(instance.texts[2]); + + // Hover was the only source of selection, which left every control acting on "the + // selected block" doing nothing at all for a user who never moves a pointer. + expect(instance.selected).toEqual([2]); + }); + + it('should report each block the caret moves between', () => { + const instance = setup(THREE_BLOCKS); + + putCaretIn(instance.texts[0]); + putCaretIn(instance.texts[1]); + + expect(instance.selected).toEqual([0, 1]); + }); + + it('should not report the same block twice', () => { + const instance = setup(TWO_BLOCKS); + + putCaretIn(instance.texts[1]); + // `selectionchange` fires on every keystroke; only a move to another block is news. + putCaretIn(instance.texts[1]); + + expect(instance.selected).toEqual([1]); + }); + + /** + * A position recorded earlier goes stale when a block is removed above it: the next block to + * land on that number reads as "already reported", and the caret arriving there is announced + * to nobody + */ + it('should report a different block that lands on the reported position', () => { + const instance = setup(THREE_BLOCKS); + + putCaretIn(instance.texts[1]); + + // Removing the block above shifts the caret's block to 0 and the one below it to 1. + instance.removeBlockAt(0); + + putCaretIn(instance.texts[2]); + + expect(instance.selected).toEqual([1, 1]); + }); + + it('should report the block that takes the position of a removed one', () => { + const instance = setup(THREE_BLOCKS); + + putCaretIn(instance.texts[1]); + + instance.removeBlockAt(1); + + // Block 2 is block 1 now, and it is where the caret goes once the block under it is gone. + putCaretIn(instance.texts[2]); + + expect(instance.selected).toEqual([1, 1]); + }); + + /** + * The selection has not moved, but the block has: inserting above it pushes it down the page, + * and the toolbar takes its position from this event and from nothing else + */ + it('should report the caret block again when one is added above it', () => { + const instance = setup(TWO_BLOCKS); + + putCaretIn(instance.texts[1]); + + instance.addBlockAt(0); + + putCaretIn(instance.texts[1]); + + expect(instance.selected).toEqual([1, 2]); + }); + + it('should report a block the pointer re-enters, even if it was the last one reported', () => { + const { texts, selected } = setup(TWO_BLOCKS); + + hoverBlock(texts[0]); + hoverBlock(texts[1]); + hoverBlock(texts[0]); + hoverBlock(texts[1]); + + /** + * Pointer entry is not deduplicated, because `mouseenter` only fires on actually + * crossing into a block -- there is no repetition to suppress. Suppressing it stranded + * anything that had ignored the last announcement: the toolbar and the settings menu + * both ignore selection while the menu is open, so after dismissing a menu opened on + * another block, coming back to this one told them nothing and they kept acting on it + */ + expect(selected).toEqual([0, 1, 0, 1]); + }); + + it('should still report a repeated pointer entry after the caret reported the same block', () => { + const { texts, selected } = setup(TWO_BLOCKS); + + putCaretIn(texts[1]); + hoverBlock(texts[1]); + + expect(selected).toEqual([1, 1]); + }); + + it('should report nothing for a selection outside every block', () => { + const instance = setup(TWO_BLOCKS); + const outside = document.createTextNode('elsewhere'); + + document.body.appendChild(outside); + + putCaretIn(outside); + + expect(instance.selected).toEqual([]); + }); + + it('should stop listening once destroyed', () => { + const instance = setup(TWO_BLOCKS); + + instance.plugin.destroy(); + + putCaretIn(instance.texts[1]); + + // The listener is on `document`, which outlives every editor on the page. + expect(instance.selected).toEqual([]); + }); + }); +}); diff --git a/packages/ui/src/Blocks/Blocks.ts b/packages/ui/src/Blocks/Blocks.ts index 2566de5e..aad934ee 100644 --- a/packages/ui/src/Blocks/Blocks.ts +++ b/packages/ui/src/Blocks/Blocks.ts @@ -2,7 +2,7 @@ import type { EventBus, BlockAddedCoreEvent, BlockRemovedCoreEvent, CopyUIEventPayload, EditorjsPlugin, - EditorjsPluginParams, EditorAPI } from '@editorjs/sdk'; + EditorjsPluginParams, EditorAPI, BlockId } from '@editorjs/sdk'; import { CoreEventType, CopyUIEvent, @@ -15,18 +15,69 @@ import { isNativeInput, make } from '@editorjs/dom'; import { BlocksHolderRenderedUIEvent, BlockSelectedUIEvent } from './events/index.js'; import { blockCss, blocksCss } from './Blocks.const.js'; +/** + * A block the editor's UI treats as selected: its wrapper element, and the position it holds now + */ +export interface SelectedBlock { + /** + * Wrapper element of the block, which is what a caller positions against + */ + block: HTMLElement; + + /** + * Id of the block, which stays its own however the document moves around it + */ + id: BlockId; +} + +/** + * Public API the Blocks plugin exposes as `api.plugins.blocksUI` + */ +export interface BlocksUIAPI { + /** + * The block the UI treats as selected: the one last reported by the pointer entering it or by the caret moving + * into it. This is the UI's own notion, not the model's selection, which `core:selection-changed` carries + * @returns the block's element and id, or `undefined` when none has been reported or it has been removed + */ + getSelectedBlock(): SelectedBlock | undefined; +} + +declare module '@editorjs/sdk' { + /* eslint-disable jsdoc/require-jsdoc -- interface members are documented on the types they alias */ + interface EditorjsPluginApiMap { + /** + * Blocks plugin's public API + */ + blocksUI: BlocksUIAPI; + } + /* eslint-enable jsdoc/require-jsdoc */ +} + /** * Editor's main UI renderer for HTML environment * - renders the editor UI * - adds and removes blocks on the page * - handles user UI interactions */ -export class BlocksUI implements EditorjsPlugin { +export class BlocksUI implements EditorjsPlugin<'blocksUI'> { /** * Plugin type */ public static readonly type = UiComponentType.Blocks; + /** + * Plugin name -- keys `api.plugins.blocksUI` + */ + public static readonly name = 'blocksUI'; + + /** + * API telling other plugins which block the UI treats as selected. + * + * Exposed because selection reaches them as a one-shot event, and a plugin that ignores one on purpose -- as the + * toolbar and the settings menu both do while a popover holds them -- has no other way to find out what it missed + */ + public readonly publicApi: BlocksUIAPI; + /** * Blocks holder element */ @@ -37,6 +88,18 @@ export class BlocksUI implements EditorjsPlugin { */ #blocks: HTMLElement[] = []; + /** + * The block last announced as selected. Held as the element, because a position recorded earlier comes to name a + * different block once one is added or removed above it, and that block would then read as already announced + */ + #announcedBlock: HTMLElement | null = null; + + /** + * The position that block held when it was announced. A change means the block itself moved on the page, which + * the toolbar follows off this event and nothing else -- so it is news even though the selection stayed put + */ + #announcedIndex = -1; + /** * EventBus instance to exchange events between components */ @@ -61,6 +124,10 @@ export class BlocksUI implements EditorjsPlugin { this.#eventBus = params.eventBus; this.#api = params.api; + + this.publicApi = { + getSelectedBlock: () => this.#selectedBlock(), + }; this.#blocksHolder = this.#prepareBlocksHolder(); this.#eventBus.addEventListener(`core:${CoreEventType.BlockAdded}`, (event: BlockAddedCoreEvent) => { @@ -75,6 +142,8 @@ export class BlocksUI implements EditorjsPlugin { this.#removeBlock(index); }, { signal }); + document.addEventListener('selectionchange', this.#handleSelectionChange, { signal }); + this.#eventBus.dispatchEvent(new BlocksHolderRenderedUIEvent({ blocksHolder: this.#blocksHolder, })); @@ -253,7 +322,68 @@ export class BlocksUI implements EditorjsPlugin { */ #updateSelectedBlock(event: MouseEvent): void { const block = event.target as HTMLElement; - const index = this.#blocks.indexOf(block); + + /** + * Announced without deduplication, unlike a caret move. `mouseenter` only fires when the + * pointer actually crosses into a block, so there is no repetition here to suppress -- and + * suppressing it is wrong: a listener that ignored the last announcement, as the toolbar + * and the settings menu both do while the menu is open, would otherwise never hear that + * the pointer came back + */ + this.#announceSelectedBlock(block, this.#blocks.indexOf(block)); + } + + /** + * Reports the block the caret is in, so that "the selected block" means something to a user + * who never moves a pointer. + * + * Hover was the only source of selection, which left every control acting on the selected + * block -- the toolbar's settings button among them -- doing nothing at all from the + * keyboard. Read here rather than from the editor's own caret state because that is cleared + * the moment focus leaves the editable, which is exactly what reaching for a toolbar does + */ + #handleSelectionChange = (): void => { + const selection = document.getSelection(); + const anchor = selection?.anchorNode ?? null; + + if (anchor === null) { + return; + } + + const index = this.#blocks.findIndex(block => block.contains(anchor)); + + if (index === -1) { + return; + } + + this.#selectBlock(this.#blocks[index], index); + }; + + /** + * Announces the block to work on, unless it is the one already announced + * @param block - the block's wrapper element + * @param index - its position in the document + */ + #selectBlock(block: HTMLElement, index: number): void { + /** + * `selectionchange` fires for every caret move, most of which stay inside one block, so + * announcing each one would be noise. Pointer entry is announced unconditionally instead + */ + if (block === this.#announcedBlock && index === this.#announcedIndex) { + return; + } + + this.#announceSelectedBlock(block, index); + } + + /** + * Reports the selected block to everything that follows it + * @param block - element of the selected block + * @param index - position of the block in the document + */ + #announceSelectedBlock(block: HTMLElement, index: number): void { + this.#announcedBlock = block; + this.#announcedIndex = index; this.#eventBus.dispatchEvent(new BlockSelectedUIEvent({ block, @@ -261,6 +391,33 @@ export class BlocksUI implements EditorjsPlugin { })); } + /** + * The block last announced as selected, with its id read through the position it holds now rather than the one it + * held then. Nothing is returned once it has left the document, so a caller is never handed an orphaned wrapper + */ + #selectedBlock(): SelectedBlock | undefined { + if (this.#announcedBlock === null) { + return undefined; + } + + const index = this.#blocks.indexOf(this.#announcedBlock); + + if (index === -1) { + return undefined; + } + + const id = this.#api.blocks.getIdByIndex(index); + + if (id === undefined) { + return undefined; + } + + return { + block: this.#announcedBlock, + id, + }; + } + /** * Cleanup when plugin is destroyed */ @@ -278,6 +435,9 @@ export class BlocksUI implements EditorjsPlugin { * Detaching the holder takes the block wrappers inside it along */ this.#blocksHolder.remove(); + this.#blocks = []; + this.#announcedBlock = null; + this.#announcedIndex = -1; } } diff --git a/packages/ui/src/Toolbar/Toolbar.const.ts b/packages/ui/src/Toolbar/Toolbar.const.ts index 02a9b221..1c113649 100644 --- a/packages/ui/src/Toolbar/Toolbar.const.ts +++ b/packages/ui/src/Toolbar/Toolbar.const.ts @@ -5,5 +5,4 @@ const className = bem('toolbar'); export const css = { toolbar: className(), actions: className('actions'), - plusButton: className('plus-button'), }; diff --git a/packages/ui/src/Toolbar/Toolbar.module.pcss b/packages/ui/src/Toolbar/Toolbar.module.pcss index 07c97157..2e928316 100644 --- a/packages/ui/src/Toolbar/Toolbar.module.pcss +++ b/packages/ui/src/Toolbar/Toolbar.module.pcss @@ -1,34 +1,3 @@ -:root { - - --toolbar-button { - background: none; - border: none; - padding: 0; - - color: var(--base--text); - cursor: pointer; - width: 26px; - height: 26px; - border-radius: var(--radius-m); - display: inline-flex; - justify-content: center; - align-items: center; - user-select: none; - - @media (hover: hover) { - &:hover { - background-color: var(--accent--bg-primary); - } - } - - &--active { - background-color: var(--accent--bg-primary); - animation: bounceIn 0.75s 1; - animation-fill-mode: forwards; - } - } -} - .toolbar { position: absolute; left: 0; @@ -42,11 +11,7 @@ &__actions { position: absolute; right: 100%; - } - - &__plus-button { - @apply --toolbar-button; - - flex-shrink: 0; + display: flex; + align-items: center; } } diff --git a/packages/ui/src/Toolbar/Toolbar.spec.ts b/packages/ui/src/Toolbar/Toolbar.spec.ts new file mode 100644 index 00000000..b46d9a6b --- /dev/null +++ b/packages/ui/src/Toolbar/Toolbar.spec.ts @@ -0,0 +1,323 @@ +import { beforeEach, describe, expect, it, jest } from '@jest/globals'; +import type { BlockId, EditorAPI } from '@editorjs/sdk'; +import { EventBus } from '@editorjs/sdk'; +import { ToolbarUI } from './Toolbar.js'; +import type { ToolbarRenderedUIEventPayload } from './ToolbarRenderedUIEvent.js'; +import { BlockSelectedUIEvent } from '../Blocks/events/index.js'; +import type { SelectedBlock } from '../Blocks/Blocks.js'; +import { BlockSettingsClosedUIEvent, BlockSettingsOpenedUIEvent, BlockSettingsRenderedUIEvent } from '../BlockSettings/events/index.js'; +import { ToolboxClosedUIEvent, ToolboxOpenedUIEvent } from '../Toolbox/events/index.js'; +import { messages } from '../messages.js'; + +/** + * Builds a toolbar over a fake editor and mounts the element it announces + */ +function setup(): { + /** Instance under test */ + plugin: ToolbarUI; + /** Event bus the instance is wired to */ + eventBus: EventBus; + /** Element the instance announced */ + holder: HTMLElement; + /** Reports a block as selected, as `BlocksUI` does: by event, and through its public API */ + select: (block: HTMLElement, index: number) => void; +} { + const eventBus = new EventBus(); + + /** + * What the blocks plugin would answer with. Driven only through `select`, so this fake cannot + * come to disagree with the events the toolbar is given + */ + let selected: SelectedBlock | undefined; + + const api = { + blocks: {}, + plugins: { + blocksUI: { + getSelectedBlock: () => selected, + }, + }, + } as unknown as EditorAPI; + + let holder: HTMLElement | undefined; + + /** + * Captures the element the toolbar announces + * @param event - the toolbar's rendered event + */ + function captureHolder(event: CustomEvent): void { + holder = (event.detail as ToolbarRenderedUIEventPayload).toolbar; + } + + eventBus.addEventListener('ui:toolbar:rendered', captureHolder); + + const plugin = new ToolbarUI({ + api, + eventBus, + } as never); + + if (holder === undefined) { + throw new Error('ToolbarUI did not announce its element'); + } + + document.body.appendChild(holder); + + return { + /** + * Reports a block as selected the way `BlocksUI` does + * @param block - the block's wrapper element + * @param index - its position in the document + */ + select: (block: HTMLElement, index: number): void => { + selected = { block, + id: `block-${index}` as BlockId }; + + eventBus.dispatchEvent(new BlockSelectedUIEvent({ block, + index })); + }, + plugin, + eventBus, + holder, + }; +} + +/** + * The toolbar's own action buttons + * @param holder - the toolbar element + */ +function actionButtons(holder: HTMLElement): HTMLButtonElement[] { + return [...holder.querySelectorAll('[role="toolbar"] > button')]; +} + +/** + * Announces a block settings widget the way `BlockSettingsUI` does, so the toolbar mounts it + * @param eventBus - bus to dispatch on + * @returns the button and menu element that were announced + */ +function announceBlockSettings(eventBus: EventBus): { + /** The control that opens the menu */ + button: HTMLButtonElement; + /** The element the menu renders into */ + menu: HTMLElement; +} { + const button = document.createElement('button'); + const menu = document.createElement('div'); + + button.setAttribute('aria-label', messages.blockSettingsButton); + menu.dataset.testid = 'block-settings-menu'; + + eventBus.dispatchEvent(new BlockSettingsRenderedUIEvent({ + button, + blockSettings: menu, + })); + + return { + button, + menu, + }; +} + +/** + * Reports a block as hovered, which is what the toolbar follows + * @param instance - the instance under test + * @param index - position of the block + * @returns the block element reported as selected + */ +function selectBlock(instance: ReturnType, index: number): HTMLElement { + const block = document.createElement('div'); + + instance.select(block, index); + + return block; +} + +describe('ToolbarUI', () => { + let instance: ReturnType; + + beforeEach(() => { + document.body.innerHTML = ''; + instance = setup(); + }); + + describe('opening the toolbox', () => { + it('should dispatch the open event with an object payload', () => { + const onOpen = jest.fn(); + + instance.eventBus.addEventListener('ui:toolbox:open', onOpen); + + actionButtons(instance.holder)[0].click(); + + expect(onOpen).toHaveBeenCalledTimes(1); + expect((onOpen.mock.calls[0][0] as CustomEvent).detail).toEqual({}); + }); + }); + + describe('mounting an announced widget', () => { + it('should mount the announced menu element into its actions area', () => { + const { menu } = announceBlockSettings(instance.eventBus); + + expect(instance.holder.querySelector('[role="toolbar"] [data-testid="block-settings-menu"]')).toBe(menu); + }); + + it('should mount the announced button as a control of its own', () => { + const { button } = announceBlockSettings(instance.eventBus); + + // A child of the actions container in its own right, which is what puts it in the + // roving tabindex -- nested inside the menu element it would be invisible to it. + expect(actionButtons(instance.holder)).toContain(button); + }); + + it('should keep one tab stop after an announced button joins', () => { + announceBlockSettings(instance.eventBus); + + const buttons = actionButtons(instance.holder); + + expect(buttons).toHaveLength(2); + expect(buttons.filter(button => button.tabIndex === 0)).toHaveLength(1); + }); + + it('should not submit a form it happens to sit inside', () => { + const [plusButton] = actionButtons(instance.holder); + + expect(plusButton.getAttribute('type')).toBe('button'); + }); + + it('should let the arrow keys reach an announced button', () => { + const { button } = announceBlockSettings(instance.eventBus); + const [plusButton] = actionButtons(instance.holder); + + plusButton.focus(); + plusButton.dispatchEvent(new KeyboardEvent('keydown', { + key: 'ArrowRight', + bubbles: true, + })); + + expect(button.tabIndex).toBe(0); + expect(plusButton.tabIndex).toBe(-1); + }); + }); + + describe('repositioning', () => { + it('should not move while block settings are open', () => { + const moveTo = jest.spyOn(instance.plugin, 'moveTo'); + + instance.eventBus.dispatchEvent(new BlockSettingsOpenedUIEvent({})); + selectBlock(instance, 1); + + expect(moveTo).not.toHaveBeenCalled(); + }); + + /** + * Nothing announces that selection again, so dropping it stranded the toolbar beside a block + * the caret had left -- which is what clicking into another block does, since the caret moves + * on mousedown while the popover only closes on the click + */ + it('should make the move it skipped once block settings close', () => { + const moveTo = jest.spyOn(instance.plugin, 'moveTo'); + + instance.eventBus.dispatchEvent(new BlockSettingsOpenedUIEvent({})); + + const block = selectBlock(instance, 1); + + instance.eventBus.dispatchEvent(new BlockSettingsClosedUIEvent({})); + + expect(moveTo).toHaveBeenCalledTimes(1); + expect(moveTo).toHaveBeenCalledWith(block); + }); + + it('should make the move it skipped once the toolbox closes', () => { + const moveTo = jest.spyOn(instance.plugin, 'moveTo'); + + instance.eventBus.dispatchEvent(new ToolboxOpenedUIEvent({})); + + const block = selectBlock(instance, 1); + + instance.eventBus.dispatchEvent(new ToolboxClosedUIEvent({})); + + expect(moveTo).toHaveBeenCalledWith(block); + }); + + /** + * Either popover alone pins the position, so the catch-up waits for both to be gone + */ + it('should keep holding its position while the other popover is still open', () => { + const moveTo = jest.spyOn(instance.plugin, 'moveTo'); + + instance.eventBus.dispatchEvent(new ToolboxOpenedUIEvent({})); + instance.eventBus.dispatchEvent(new BlockSettingsOpenedUIEvent({})); + + const block = selectBlock(instance, 1); + + instance.eventBus.dispatchEvent(new ToolboxClosedUIEvent({})); + + expect(moveTo).not.toHaveBeenCalled(); + + instance.eventBus.dispatchEvent(new BlockSettingsClosedUIEvent({})); + + expect(moveTo).toHaveBeenCalledWith(block); + }); + + it('should not move when nothing was reported while it was held', () => { + const moveTo = jest.spyOn(instance.plugin, 'moveTo'); + + instance.eventBus.dispatchEvent(new BlockSettingsOpenedUIEvent({})); + instance.eventBus.dispatchEvent(new BlockSettingsClosedUIEvent({})); + + expect(moveTo).not.toHaveBeenCalled(); + }); + }); + + describe('destroy', () => { + it('should stop reacting to block selection', () => { + const moveTo = jest.spyOn(instance.plugin, 'moveTo'); + + instance.plugin.destroy(); + + selectBlock(instance, 1); + + // The bus outlives the toolbar, so a listener left on it would keep this instance alive + // and still moving an element that is no longer on the page. + expect(moveTo).not.toHaveBeenCalled(); + }); + + it('should stop mounting widgets announced afterwards', () => { + instance.plugin.destroy(); + + const { button } = announceBlockSettings(instance.eventBus); + + expect(button.isConnected).toBe(false); + }); + + it('should take its holder off the page', () => { + instance.plugin.destroy(); + + expect(instance.holder.isConnected).toBe(false); + }); + }); + + describe('roving tabindex', () => { + it('should keep exactly one action button in the tab order', () => { + announceBlockSettings(instance.eventBus); + + const buttons = actionButtons(instance.holder); + + expect(buttons.length).toBeGreaterThan(1); + expect(buttons.filter(button => button.tabIndex === 0)).toHaveLength(1); + expect(buttons.filter(button => button.tabIndex === -1)).toHaveLength(buttons.length - 1); + }); + + it('should wrap around a single control', () => { + const [plusButton] = actionButtons(instance.holder); + + plusButton.focus(); + plusButton.dispatchEvent(new KeyboardEvent('keydown', { + key: 'ArrowRight', + bubbles: true, + })); + + // With nothing else in the container the move lands back on the same control, which is + // what keeps a one-control toolbar a no-op rather than an error. + expect(plusButton.tabIndex).toBe(0); + }); + }); +}); diff --git a/packages/ui/src/Toolbar/Toolbar.ts b/packages/ui/src/Toolbar/Toolbar.ts index af005037..35e499d3 100644 --- a/packages/ui/src/Toolbar/Toolbar.ts +++ b/packages/ui/src/Toolbar/Toolbar.ts @@ -5,9 +5,11 @@ import { css } from './Toolbar.const.js'; import type { ToolboxRenderedUIEvent } from '../Toolbox/events/index.js'; import { IconPlus } from '@codexteam/icons'; import Style from './Toolbar.module.pcss'; +import ControlStyle from '../controls.module.pcss'; import { ToolbarRenderedUIEvent } from './ToolbarRenderedUIEvent.js'; import type { BlockSelectedUIEvent } from '../Blocks/events/index.js'; import { ToolboxOpenUIEvent } from '../Toolbox/events/index.js'; +import type { BlockSettingsRenderedUIEvent } from '../BlockSettings/events/index.js'; import { messages } from '../messages.js'; /** @@ -67,8 +69,13 @@ export class ToolbarUI implements EditorjsPlugin { #nodes: ToolbarNodes = { holder: make('div', Style[css.toolbar]) as HTMLDivElement, actions: make('div', Style[css.actions]) as HTMLDivElement, - plusButton: make('button', Style[css.plusButton], { + plusButton: make('button', ControlStyle['toolbar-button'], { innerHTML: IconPlus, + /** + * A button defaults to `submit`, and the editor's holder may sit inside a form, where + * opening the toolbox would submit it + */ + type: 'button', }) as HTMLButtonElement, }; @@ -77,6 +84,12 @@ export class ToolbarUI implements EditorjsPlugin { */ #isToolboxOpen = false; + /** + * True while the Block Settings menu is open. The menu was built for one particular block, + * so the toolbar has to stay on it until the menu closes + */ + #isBlockSettingsOpen = false; + /** * Constructor function * @param args - plugin parameters @@ -96,8 +109,10 @@ export class ToolbarUI implements EditorjsPlugin { this.#subscribeToToolboxEvents(); + this.#subscribeToBlockSettingsEvents(); + this.#eventBus.addEventListener(`ui:blocks:block-selected`, (event: BlockSelectedUIEvent) => { - if (this.#isToolboxOpen) { + if (this.#isToolboxOpen || this.#isBlockSettingsOpen) { return; } @@ -137,6 +152,21 @@ export class ToolbarUI implements EditorjsPlugin { this.#nodes.actions.appendChild(toolboxElement); } + /** + * Mounts the Block Settings widget: its button among the toolbar's own controls, where being + * a direct child is what puts it in `#controls` and so in the roving tabindex, and its menu + * alongside the toolbox popover. The tab stop is reassigned afterwards, since this arrives + * after the toolbar rendered and a button carrying no `tabindex` would be a second stop + * @param button - the control that opens the menu + * @param blockSettingsElement - the element the menu renders into + */ + #addBlockSettings(button: HTMLElement, blockSettingsElement: HTMLElement): void { + this.#nodes.actions.appendChild(button); + this.#nodes.actions.appendChild(blockSettingsElement); + + this.#updateRovingTabindex(this.#nodes.plusButton); + } + /** * Creates Toolbar HTML nodes */ @@ -207,6 +237,7 @@ export class ToolbarUI implements EditorjsPlugin { this.#eventBus.addEventListener(`ui:toolbox:closed`, () => { this.#isToolboxOpen = false; + this.#catchUpWithSelection(); this.#nodes.plusButton.setAttribute('aria-expanded', 'false'); }, { signal }); } @@ -215,7 +246,57 @@ export class ToolbarUI implements EditorjsPlugin { * Dispatches an event to Toolbox plugin to open the toolbox */ #openToolbox(): void { - this.#eventBus.dispatchEvent(new ToolboxOpenUIEvent('ui:toolbox:open')); + /** + * The constructor takes a payload, not an event name -- the name is the class's own + * business. A string satisfied the empty payload type, so this went unnoticed and + * shipped `detail: 'ui:toolbox:open'` to every listener + */ + this.#eventBus.dispatchEvent(new ToolboxOpenUIEvent({})); + } + + /** + * Subscribes to the Block Settings plugin's events + */ + #subscribeToBlockSettingsEvents(): void { + const { signal } = this.#listenersController; + + this.#eventBus.addEventListener(`ui:block-settings:rendered`, (event: BlockSettingsRenderedUIEvent) => { + this.#addBlockSettings(event.detail.button, event.detail.blockSettings); + }, { signal }); + + /** + * The menu was built for one block, so the toolbar holds its position until it closes. + * The button's own `aria-expanded` belongs to the plugin that owns the button + */ + this.#eventBus.addEventListener(`ui:block-settings:opened`, () => { + this.#isBlockSettingsOpen = true; + }, { signal }); + + this.#eventBus.addEventListener(`ui:block-settings:closed`, () => { + this.#isBlockSettingsOpen = false; + this.#catchUpWithSelection(); + }, { signal }); + } + + /** + * Moves to the block the UI treats as selected now, so a caret that left the block under the toolbar is followed + * once nothing is holding it: selection arrives as a one-shot event, and the ones skipped here are not repeated + */ + #catchUpWithSelection(): void { + /** + * Either popover alone pins the position, so this waits for both + */ + if (this.#isToolboxOpen || this.#isBlockSettingsOpen) { + return; + } + + const selected = this.#api.plugins.blocksUI?.getSelectedBlock(); + + if (selected === undefined) { + return; + } + + this.moveTo(selected.block); } /** diff --git a/packages/ui/src/controls.module.pcss b/packages/ui/src/controls.module.pcss new file mode 100644 index 00000000..ef0d2f58 --- /dev/null +++ b/packages/ui/src/controls.module.pcss @@ -0,0 +1,28 @@ +/** + * Styling shared by the icon buttons in the floating toolbar's actions container, which are not + * all rendered by the same component: `ToolbarUI` owns the plus button, `BlockSettingsUI` the + * settings button. A plain class rather than an `@apply` property set, because that resolves + * within one file's PostCSS pass and every component would have to repeat the declarations + */ +.toolbar-button { + background: none; + border: none; + padding: 0; + + color: var(--base--text); + cursor: pointer; + width: 26px; + height: 26px; + border-radius: var(--radius-m); + display: inline-flex; + justify-content: center; + align-items: center; + user-select: none; + flex-shrink: 0; + + @media (hover: hover) { + &:hover { + background-color: var(--accent--bg-primary); + } + } +} diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts index da438244..f88cdf9f 100644 --- a/packages/ui/src/index.ts +++ b/packages/ui/src/index.ts @@ -119,3 +119,4 @@ export * from './InlineToolbar/InlineToolbar.js'; export * from './Blocks/Blocks.js'; export * from './Toolbox/Toolbox.js'; export * from './Toolbar/Toolbar.js'; +export * from './BlockSettings/BlockSettings.js'; diff --git a/packages/ui/src/messages.ts b/packages/ui/src/messages.ts index bc4f4856..d971ff28 100644 --- a/packages/ui/src/messages.ts +++ b/packages/ui/src/messages.ts @@ -18,6 +18,15 @@ export const messages = { /** Accessible name of the toolbox menu. Deliberately matches the button that opens it */ addBlockMenu: 'Add block', + /** + * Accessible name of the block settings menu. Deliberately matches the button that opens it, + * the same way the toolbox menu matches the add-block button + */ + blockSettingsMenu: 'Block settings', + + /** Accessible name of the icon-only button that opens the block settings menu */ + blockSettingsButton: 'Block settings', + /** Accessible name of the inline formatting toolbar, distinguishing it from the block one */ inlineToolbar: 'Text formatting', diff --git a/packages/ui/vite.config.ts b/packages/ui/vite.config.ts index 52732d11..c20be1eb 100644 --- a/packages/ui/vite.config.ts +++ b/packages/ui/vite.config.ts @@ -9,6 +9,9 @@ import postcssApply from 'postcss-apply'; export default defineConfig({ plugins: [ + // `tsconfig.json` includes everything under `src`, which now matches the spec + // files too. `tsconfig.build.json` is the one that excludes them, so declaration + // emit must read that instead or `dist` grows `.d.ts` files for the tests. dts({ tsconfigPath: './tsconfig.build.json' }), // vite-plugin-css-injected-by-js caches injected CSS across rebuilds in a // persistent `vite build --watch` process, so edits always show up one diff --git a/yarn.lock b/yarn.lock index 05b73a8e..4f5a881b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2364,6 +2364,34 @@ __metadata: languageName: unknown linkType: soft +"@editorjs/default-block-settings-plugin@workspace:^, @editorjs/default-block-settings-plugin@workspace:packages/plugins/default-block-settings-plugin": + version: 0.0.0-use.local + resolution: "@editorjs/default-block-settings-plugin@workspace:packages/plugins/default-block-settings-plugin" + dependencies: + "@babel/core": "npm:^7.29.0" + "@babel/preset-env": "npm:^7.29.2" + "@codexteam/icons": "npm:^0.3.3" + "@editorjs/sdk": "workspace:^" + "@editorjs/ui": "workspace:^" + "@jest/globals": "npm:^29.7.0" + "@stryker-mutator/core": "npm:^7.0.2" + "@stryker-mutator/jest-runner": "npm:^7.0.2" + "@stryker-mutator/typescript-checker": "npm:^7.0.2" + "@types/eslint": "npm:^9.6.1" + "@types/jest": "npm:^29.5.12" + "@types/node": "npm:^22.10.2" + babel-jest: "npm:^29.7.0" + eslint: "npm:^9.24.0" + eslint-config-codex: "npm:^2.0.3" + eslint-plugin-import: "npm:^2.31.0" + jest: "npm:^29.7.0" + stryker-cli: "npm:^1.0.2" + ts-jest: "npm:^29.2.5" + ts-node: "npm:^10.9.2" + typescript: "npm:^5.5.4" + languageName: unknown + linkType: soft + "@editorjs/document-playground@workspace:packages/playground": version: 0.0.0-use.local resolution: "@editorjs/document-playground@workspace:packages/playground" @@ -2446,6 +2474,7 @@ __metadata: "@editorjs/clipboard-plugin": "workspace:^" "@editorjs/collaboration-manager": "workspace:^" "@editorjs/core": "workspace:^" + "@editorjs/default-block-settings-plugin": "workspace:^" "@editorjs/dom-adapters": "workspace:^" "@editorjs/inline-link": "workspace:^" "@editorjs/italic": "workspace:^" @@ -2689,6 +2718,8 @@ __metadata: version: 0.0.0-use.local resolution: "@editorjs/ui@workspace:packages/ui" dependencies: + "@babel/core": "npm:^7.29.0" + "@babel/preset-env": "npm:^7.29.2" "@codexteam/icons": "npm:^0.3.3" "@codexteam/ui": "npm:^0.2.2" "@editorjs/core": "workspace:^" @@ -2700,6 +2731,7 @@ __metadata: "@editorjs/ui-kit": "npm:^2.0.0" "@jest/globals": "npm:^29.7.0" "@types/jest": "npm:^29.5.12" + babel-jest: "npm:^29.7.0" chokidar-cli: "npm:^3.0.0" eslint: "npm:^9.9.1" eslint-config-codex: "npm:^2.0.3" @@ -4073,10 +4105,10 @@ __metadata: languageName: node linkType: hard -"@oxc-project/types@npm:=0.153.0": - version: 0.153.0 - resolution: "@oxc-project/types@npm:0.153.0" - checksum: b123d6c8ed40b683be9af3a976148d522c621421bbae2d5716d210cda7a858108daa4bad77450b780f63529f2c43bd00e4c179f5952ffb6abbaacebdc71e282f +"@oxc-project/types@npm:=0.154.0": + version: 0.154.0 + resolution: "@oxc-project/types@npm:0.154.0" + checksum: 543b06a3955f178214ff159092e3fe83a92355bc9e7e712f8992c15b5ad6149c854c495986df37a8295977ef5f27d30f36229546f913e67a72418bbade333bf3 languageName: node linkType: hard @@ -4121,107 +4153,107 @@ __metadata: languageName: node linkType: hard -"@rolldown/binding-android-arm-eabi@npm:1.2.13": - version: 1.2.13 - resolution: "@rolldown/binding-android-arm-eabi@npm:1.2.13" +"@rolldown/binding-android-arm-eabi@npm:1.2.14": + version: 1.2.14 + resolution: "@rolldown/binding-android-arm-eabi@npm:1.2.14" conditions: os=android & cpu=arm languageName: node linkType: hard -"@rolldown/binding-android-arm64@npm:1.2.13": - version: 1.2.13 - resolution: "@rolldown/binding-android-arm64@npm:1.2.13" +"@rolldown/binding-android-arm64@npm:1.2.14": + version: 1.2.14 + resolution: "@rolldown/binding-android-arm64@npm:1.2.14" conditions: os=android & cpu=arm64 languageName: node linkType: hard -"@rolldown/binding-darwin-arm64@npm:1.2.13": - version: 1.2.13 - resolution: "@rolldown/binding-darwin-arm64@npm:1.2.13" +"@rolldown/binding-darwin-arm64@npm:1.2.14": + version: 1.2.14 + resolution: "@rolldown/binding-darwin-arm64@npm:1.2.14" conditions: os=darwin & cpu=arm64 languageName: node linkType: hard -"@rolldown/binding-darwin-x64@npm:1.2.13": - version: 1.2.13 - resolution: "@rolldown/binding-darwin-x64@npm:1.2.13" +"@rolldown/binding-darwin-x64@npm:1.2.14": + version: 1.2.14 + resolution: "@rolldown/binding-darwin-x64@npm:1.2.14" conditions: os=darwin & cpu=x64 languageName: node linkType: hard -"@rolldown/binding-freebsd-x64@npm:1.2.13": - version: 1.2.13 - resolution: "@rolldown/binding-freebsd-x64@npm:1.2.13" +"@rolldown/binding-freebsd-x64@npm:1.2.14": + version: 1.2.14 + resolution: "@rolldown/binding-freebsd-x64@npm:1.2.14" conditions: os=freebsd & cpu=x64 languageName: node linkType: hard -"@rolldown/binding-linux-arm-gnueabihf@npm:1.2.13": - version: 1.2.13 - resolution: "@rolldown/binding-linux-arm-gnueabihf@npm:1.2.13" +"@rolldown/binding-linux-arm-gnueabihf@npm:1.2.14": + version: 1.2.14 + resolution: "@rolldown/binding-linux-arm-gnueabihf@npm:1.2.14" conditions: os=linux & cpu=arm languageName: node linkType: hard -"@rolldown/binding-linux-arm64-gnu@npm:1.2.13": - version: 1.2.13 - resolution: "@rolldown/binding-linux-arm64-gnu@npm:1.2.13" +"@rolldown/binding-linux-arm64-gnu@npm:1.2.14": + version: 1.2.14 + resolution: "@rolldown/binding-linux-arm64-gnu@npm:1.2.14" conditions: os=linux & cpu=arm64 & libc=glibc languageName: node linkType: hard -"@rolldown/binding-linux-arm64-musl@npm:1.2.13": - version: 1.2.13 - resolution: "@rolldown/binding-linux-arm64-musl@npm:1.2.13" +"@rolldown/binding-linux-arm64-musl@npm:1.2.14": + version: 1.2.14 + resolution: "@rolldown/binding-linux-arm64-musl@npm:1.2.14" conditions: os=linux & cpu=arm64 & libc=musl languageName: node linkType: hard -"@rolldown/binding-linux-ppc64-gnu@npm:1.2.13": - version: 1.2.13 - resolution: "@rolldown/binding-linux-ppc64-gnu@npm:1.2.13" +"@rolldown/binding-linux-ppc64-gnu@npm:1.2.14": + version: 1.2.14 + resolution: "@rolldown/binding-linux-ppc64-gnu@npm:1.2.14" conditions: os=linux & cpu=ppc64 & libc=glibc languageName: node linkType: hard -"@rolldown/binding-linux-s390x-gnu@npm:1.2.13": - version: 1.2.13 - resolution: "@rolldown/binding-linux-s390x-gnu@npm:1.2.13" +"@rolldown/binding-linux-s390x-gnu@npm:1.2.14": + version: 1.2.14 + resolution: "@rolldown/binding-linux-s390x-gnu@npm:1.2.14" conditions: os=linux & cpu=s390x & libc=glibc languageName: node linkType: hard -"@rolldown/binding-linux-x64-gnu@npm:1.2.13": - version: 1.2.13 - resolution: "@rolldown/binding-linux-x64-gnu@npm:1.2.13" +"@rolldown/binding-linux-x64-gnu@npm:1.2.14": + version: 1.2.14 + resolution: "@rolldown/binding-linux-x64-gnu@npm:1.2.14" conditions: os=linux & cpu=x64 & libc=glibc languageName: node linkType: hard -"@rolldown/binding-linux-x64-musl@npm:1.2.13": - version: 1.2.13 - resolution: "@rolldown/binding-linux-x64-musl@npm:1.2.13" +"@rolldown/binding-linux-x64-musl@npm:1.2.14": + version: 1.2.14 + resolution: "@rolldown/binding-linux-x64-musl@npm:1.2.14" conditions: os=linux & cpu=x64 & libc=musl languageName: node linkType: hard -"@rolldown/binding-openharmony-arm64@npm:1.2.13": - version: 1.2.13 - resolution: "@rolldown/binding-openharmony-arm64@npm:1.2.13" +"@rolldown/binding-openharmony-arm64@npm:1.2.14": + version: 1.2.14 + resolution: "@rolldown/binding-openharmony-arm64@npm:1.2.14" conditions: os=openharmony & cpu=arm64 languageName: node linkType: hard -"@rolldown/binding-win32-arm64-msvc@npm:1.2.13": - version: 1.2.13 - resolution: "@rolldown/binding-win32-arm64-msvc@npm:1.2.13" +"@rolldown/binding-win32-arm64-msvc@npm:1.2.14": + version: 1.2.14 + resolution: "@rolldown/binding-win32-arm64-msvc@npm:1.2.14" conditions: os=win32 & cpu=arm64 languageName: node linkType: hard -"@rolldown/binding-win32-x64-msvc@npm:1.2.13": - version: 1.2.13 - resolution: "@rolldown/binding-win32-x64-msvc@npm:1.2.13" +"@rolldown/binding-win32-x64-msvc@npm:1.2.14": + version: 1.2.14 + resolution: "@rolldown/binding-win32-x64-msvc@npm:1.2.14" conditions: os=win32 & cpu=x64 languageName: node linkType: hard @@ -12416,25 +12448,25 @@ __metadata: linkType: hard "rolldown@npm:~1.2.12": - version: 1.2.13 - resolution: "rolldown@npm:1.2.13" - dependencies: - "@oxc-project/types": "npm:=0.153.0" - "@rolldown/binding-android-arm-eabi": "npm:1.2.13" - "@rolldown/binding-android-arm64": "npm:1.2.13" - "@rolldown/binding-darwin-arm64": "npm:1.2.13" - "@rolldown/binding-darwin-x64": "npm:1.2.13" - "@rolldown/binding-freebsd-x64": "npm:1.2.13" - "@rolldown/binding-linux-arm-gnueabihf": "npm:1.2.13" - "@rolldown/binding-linux-arm64-gnu": "npm:1.2.13" - "@rolldown/binding-linux-arm64-musl": "npm:1.2.13" - "@rolldown/binding-linux-ppc64-gnu": "npm:1.2.13" - "@rolldown/binding-linux-s390x-gnu": "npm:1.2.13" - "@rolldown/binding-linux-x64-gnu": "npm:1.2.13" - "@rolldown/binding-linux-x64-musl": "npm:1.2.13" - "@rolldown/binding-openharmony-arm64": "npm:1.2.13" - "@rolldown/binding-win32-arm64-msvc": "npm:1.2.13" - "@rolldown/binding-win32-x64-msvc": "npm:1.2.13" + version: 1.2.14 + resolution: "rolldown@npm:1.2.14" + dependencies: + "@oxc-project/types": "npm:=0.154.0" + "@rolldown/binding-android-arm-eabi": "npm:1.2.14" + "@rolldown/binding-android-arm64": "npm:1.2.14" + "@rolldown/binding-darwin-arm64": "npm:1.2.14" + "@rolldown/binding-darwin-x64": "npm:1.2.14" + "@rolldown/binding-freebsd-x64": "npm:1.2.14" + "@rolldown/binding-linux-arm-gnueabihf": "npm:1.2.14" + "@rolldown/binding-linux-arm64-gnu": "npm:1.2.14" + "@rolldown/binding-linux-arm64-musl": "npm:1.2.14" + "@rolldown/binding-linux-ppc64-gnu": "npm:1.2.14" + "@rolldown/binding-linux-s390x-gnu": "npm:1.2.14" + "@rolldown/binding-linux-x64-gnu": "npm:1.2.14" + "@rolldown/binding-linux-x64-musl": "npm:1.2.14" + "@rolldown/binding-openharmony-arm64": "npm:1.2.14" + "@rolldown/binding-win32-arm64-msvc": "npm:1.2.14" + "@rolldown/binding-win32-x64-msvc": "npm:1.2.14" "@rolldown/pluginutils": "npm:^1.0.0" dependenciesMeta: "@rolldown/binding-android-arm-eabi": @@ -12469,7 +12501,7 @@ __metadata: optional: true bin: rolldown: ./bin/cli.mjs - checksum: 7e602afd9c851e1e4c26711030211ec36c538f57a59e5c84ea74167a98db14eeecc8741a8c3564bcce8b9377ec0c5502973acc823bca4788da25ad6f70283416 + checksum: 8573c260516eefed8266da2dced4fa0742c8c44dbc79d35f5cc43cf1cfdaa1afedca7ab31e1abcf733be598f1866d5f8047884826717f37a507e70b4a0e510a2 languageName: node linkType: hard