From 96c3a639a39eff9e9aedd7c1f0e58660b013d43f Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 9 Oct 2026 01:11:47 +0100 Subject: [PATCH 01/38] test(ui): give the package a Jest harness `@editorjs/ui` is the first package here that renders DOM, so it is also the first to need `jest-environment-jsdom` as an explicit dependency. Two module mappings make its sources loadable under Jest: `@codexteam/ui`'s side-effect theme imports become an empty module, and CSS Modules resolve to a proxy that answers each property with its own name, so an assertion on rendered markup names the class the source asked for. `@codexteam/*` joins `@editorjs/*` in `transformIgnorePatterns` because ui-kit ships as ESM. Declaration emit moves to `tsconfig.build.json`, the config that excludes `*.spec.ts`, so `dist` does not grow typings for the tests. The shared `base-coverage` action skipped a package missing from the base ref but not one present there without a test suite -- the case of any PR adding a first suite, this one included. It would have run `test:coverage` on the base ref and failed with "couldn't find a script", so its guard now also checks that the script exists. Co-Authored-By: Claude Opus 5 --- .github/actions/base-coverage/action.yml | 20 ++- .github/workflows/ui.yml | 10 ++ openspec/changes/block-settings-ui/tasks.md | 13 +- packages/ui/eslint.config.mjs | 12 ++ packages/ui/jest.config.ts | 30 ++++- packages/ui/package.json | 4 + packages/ui/vite.config.ts | 3 + yarn.lock | 141 ++++++++++---------- 8 files changed, 153 insertions(+), 80 deletions(-) create mode 100644 .github/workflows/ui.yml 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/ui.yml b/.github/workflows/ui.yml new file mode 100644 index 00000000..ef3c7680 --- /dev/null +++ b/.github/workflows/ui.yml @@ -0,0 +1,10 @@ +name: UI check +on: + pull_request: + +jobs: + package-check: + uses: ./.github/workflows/package-check.yml + with: + package-name: '@editorjs/ui' + working-directory: './packages/ui' diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index eab6903a..3903a363 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -15,12 +15,13 @@ ## 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 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..985ba2e4 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -26,14 +26,18 @@ "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/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..3f5a408b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2689,6 +2689,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 +2702,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 +4076,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 +4124,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 +12419,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 +12472,7 @@ __metadata: optional: true bin: rolldown: ./bin/cli.mjs - checksum: 7e602afd9c851e1e4c26711030211ec36c538f57a59e5c84ea74167a98db14eeecc8741a8c3564bcce8b9377ec0c5502973acc823bca4788da25ad6f70283416 + checksum: 8573c260516eefed8266da2dced4fa0742c8c44dbc79d35f5cc43cf1cfdaa1afedca7ab31e1abcf733be598f1866d5f8047884826717f37a507e70b4a0e510a2 languageName: node linkType: hard From 1ab4201d50c1673e9b71be175604a90f5748e704 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 9 Oct 2026 01:20:06 +0100 Subject: [PATCH 02/38] feat(ui): add the block settings menu plugin `BlockSettingsUI` renders the per-block settings popover and owns no items of its own: everything in the menu comes from providers registered through `api.plugins['block-settings'].register`, which are asked again on every open so items reflect current state. Contributions are concatenated by ascending `order` (ties in registration order) with a separator between providers, and a provider returning nothing contributes no separator either. Providers receive `blockId` as well as `blockIndex`, because the index is only true at the moment the menu was built -- an item's handler is expected to resolve the block's position from the id instead. Requesting settings for an index that resolves to no block invokes no provider and opens nothing. The menu is rebuilt rather than edited between opens. `removeItemByName` is the only removal ui-kit offers and a separator carries no name, so a fresh popover with the full item list is what keeps the previous block's items out of the accessibility tree. The swap happens inside the plugin's own holder element, so ui-kit's rendered DOM stays untouched. The event classes and the popover setup are ported from the BlockTunes work in PR #157. Co-authored-by: Betty Steger <244475+bettysteger@users.noreply.github.com> Co-Authored-By: Claude Opus 5 --- openspec/changes/block-settings-ui/tasks.md | 15 +- packages/sdk/src/entities/EntityType.ts | 7 +- .../src/BlockSettings/BlockSettings.spec.ts | 440 ++++++++++++++++++ .../ui/src/BlockSettings/BlockSettings.ts | 347 ++++++++++++++ .../events/BlockSettingsBaseEvent.ts | 15 + .../events/BlockSettingsClosedUIEvent.ts | 20 + .../events/BlockSettingsOpenUIEvent.ts | 28 ++ .../events/BlockSettingsOpenedUIEvent.ts | 25 + .../events/BlockSettingsRenderedUIEvent.ts | 25 + packages/ui/src/BlockSettings/events/index.ts | 5 + packages/ui/src/index.ts | 1 + packages/ui/src/messages.ts | 9 + 12 files changed, 929 insertions(+), 8 deletions(-) create mode 100644 packages/ui/src/BlockSettings/BlockSettings.spec.ts create mode 100644 packages/ui/src/BlockSettings/BlockSettings.ts create mode 100644 packages/ui/src/BlockSettings/events/BlockSettingsBaseEvent.ts create mode 100644 packages/ui/src/BlockSettings/events/BlockSettingsClosedUIEvent.ts create mode 100644 packages/ui/src/BlockSettings/events/BlockSettingsOpenUIEvent.ts create mode 100644 packages/ui/src/BlockSettings/events/BlockSettingsOpenedUIEvent.ts create mode 100644 packages/ui/src/BlockSettings/events/BlockSettingsRenderedUIEvent.ts create mode 100644 packages/ui/src/BlockSettings/events/index.ts diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index 3903a363..73388e44 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -25,8 +25,8 @@ ## 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 @@ -35,11 +35,12 @@ - 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 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/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts new file mode 100644 index 00000000..eaf0f58e --- /dev/null +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -0,0 +1,440 @@ +import { beforeEach, describe, expect, it, jest } from '@jest/globals'; +import type { 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 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; + +/** + * 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; + /** Fake editor API */ + api: EditorAPI; + /** The mock backing `api.blocks.getIdByIndex` */ + getIdByIndex: jest.Mock<(index: number) => string | undefined>; +} { + const eventBus = new EventBus(); + const holder = document.createElement('div'); + + const getIdByIndex = jest.fn((index: number) => blocks[index]?.id); + + const api = { + blocks: { + getIdByIndex, + getIndexById: jest.fn((id: string) => blocks.findIndex(block => block.id === id)), + }, + document: { + /** + * Read fresh each time, so a test can mutate the block list between opens + */ + get data() { + return { blocks }; + }, + }, + plugins: {}, + } as unknown as EditorAPI; + + let element: HTMLElement | 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 { + element = (event.detail as BlockSettingsRenderedUIEventPayload).blockSettings; + } + + 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) { + throw new Error('BlockSettingsUI did not announce its element'); + } + + holder.appendChild(element); + + return { + plugin, + eventBus, + element, + 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; +} + +/** + * 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', + }); + }); + + 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); + expect((onOpened.mock.calls[0][0] as CustomEvent).detail).toEqual({ blockId: 'block-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('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..4e4f120b --- /dev/null +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -0,0 +1,347 @@ +import { make } from '@editorjs/dom'; +import type { + BlockId, + CoreConfigValidated, + EditorAPI, + EditorjsPlugin, + EditorjsPluginParams, + EventBus +} from '@editorjs/sdk'; +import { UiComponentType } from '@editorjs/sdk'; +import type { PopoverItemParams } from '@editorjs/ui-kit'; +import { PopoverDesktop, PopoverEvent, PopoverItemType } from '@editorjs/ui-kit'; +import { messages } from '../messages.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: + * 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 MenuConfig = 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 + */ + 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. + */ +export type BlockSettingsProvider = ( + context: BlockSettingsContext +) => MenuConfig | undefined | Promise; + +/** + * Options a provider is registered with + */ +export interface BlockSettingsRegisterOptions { + /** + * Ascending sort key for this provider's contribution. Defaults to `0`, ties are broken by + * registration order. The built-in settings sit last, at `1000` + */ + order?: number; +} + +/** + * Public API the Block settings plugin exposes as `api.plugins['block-settings']` + */ +export interface BlockSettingsAPI { + /** + * Registers a settings provider + * @param provider - called with the target block each time the menu opens + * @param options - registration options, `order` 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 */ +} + +/** + * 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; +} + +/** + * UI plugin that renders the per-block settings menu. + * + * Mirrors {@link ToolboxUI}: it announces its element once so `ToolbarUI` can mount it, then + * builds and opens the menu whenever it receives `ui:block-settings:open`. It owns no items of + * its own -- everything in the menu comes from registered providers, the built-in Move/Delete + * entries included. + */ +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 `ToolbarUI`. The popover inside it is replaced per open, + * so this is what stays mounted + */ + #holder: HTMLElement; + + /** + * Popover rendering the current menu, absent until the menu is first built + */ + #popover: PopoverDesktop | undefined; + + /** + * Registered providers + */ + readonly #registrations = new Set(); + + /** + * Incremented per registration so providers sharing an `order` keep their registration sequence + */ + #sequence = 0; + + /** + * 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.#eventBus.dispatchEvent(new BlockSettingsRenderedUIEvent({ + blockSettings: this.#holder, + })); + + this.#eventBus.addEventListener('ui:block-settings:open', (event: BlockSettingsOpenUIEvent) => { + void this.#open(event.detail.index); + }); + } + + /** + * Cleanup when plugin is destroyed + */ + public destroy(): void { + this.#popover?.destroy(); + this.#popover = undefined; + this.#holder.remove(); + } + + /** + * 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++, + }; + + this.#registrations.add(registration); + + return () => { + this.#registrations.delete(registration); + }; + } + + /** + * Closes the menu if it is open. `hide()` emits the popover's own closed event, + * which is what dispatches `ui:block-settings:closed` + */ + #close(): void { + if (this.#popover?.isShown === true) { + this.#popover.hide(); + } + } + + /** + * 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 blockId = this.#api.blocks.getIdByIndex(index); + + /** + * Nothing is selected, or the index is stale. Providers are not asked about a block that + * is not there, and an opening request for one is simply dropped + */ + if (blockId === undefined) { + return; + } + + const items = await this.#collectItems({ + blockId, + blockIndex: index, + tool: this.#api.document.data.blocks[index]?.name ?? '', + }); + + if (items.length === 0) { + return; + } + + this.#renderPopover(items); + + this.#popover?.show(); + + this.#eventBus.dispatchEvent(new BlockSettingsOpenedUIEvent({ blockId })); + } + + /** + * 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 }) => { + const result = await provider(context); + + if (result === undefined) { + return []; + } + + return Array.isArray(result) ? result : [result]; + }) + ); + + return contributions + .filter(contribution => contribution.length > 0) + .reduce((items, contribution) => { + if (items.length > 0) { + items.push({ type: PopoverItemType.Separator }); + } + + return items.concat(contribution); + }, []); + } + + /** + * Replaces the popover inside the holder with one built for the given items. + * + * The menu is rebuilt rather than edited in place: `removeItemByName` is the only removal + * `@editorjs/ui-kit` offers, and a separator is constructed without params, so it has no name + * to be removed by. Handing a fresh popover the complete item list is what guarantees that + * the items of the previous block leave the accessibility tree. + * @param items - items the menu should consist of + */ + #renderPopover(items: PopoverItemParams[]): void { + this.#popover?.destroy(); + + 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, + }, + }, + { + [PopoverItemType.Default]: { wrapperTag: 'button' }, + } + ); + + this.#popover.on(PopoverEvent.Closed, () => { + this.#eventBus.dispatchEvent(new BlockSettingsClosedUIEvent({})); + }); + + 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..108565e9 --- /dev/null +++ b/packages/ui/src/BlockSettings/events/BlockSettingsOpenUIEvent.ts @@ -0,0 +1,28 @@ +import { BlockSettingsBaseEvent } from './BlockSettingsBaseEvent.js'; + +/** + * Names the block whose settings should be shown + */ +export interface BlockSettingsOpenUIEventPayload { + /** + * Position of the block to show settings for. + * + * An index rather than an id because the dispatcher is the toolbar, which follows block + * selection by position. `BlockSettingsUI` resolves it to an id once, when 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..d90a27ab --- /dev/null +++ b/packages/ui/src/BlockSettings/events/BlockSettingsOpenedUIEvent.ts @@ -0,0 +1,25 @@ +import type { BlockId } from '@editorjs/sdk'; +import { BlockSettingsBaseEvent } from './BlockSettingsBaseEvent.js'; + +/** + * Reports which block the menu that just opened was built for + */ +export interface BlockSettingsOpenedUIEventPayload { + /** + * Id of the block the opened menu was built for + */ + readonly blockId: BlockId; +} + +/** + * 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..4bd4bd3c --- /dev/null +++ b/packages/ui/src/BlockSettings/events/BlockSettingsRenderedUIEvent.ts @@ -0,0 +1,25 @@ +import { BlockSettingsBaseEvent } from './BlockSettingsBaseEvent.js'; + +/** + * Payload of the BlockSettingsRenderedUIEvent + * Contains the block settings HTML element + */ +export interface BlockSettingsRenderedUIEventPayload { + /** + * Block settings HTML element + */ + 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/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', From e2325b8ac9aa432fea0d102d172a7325ed942b85 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 9 Oct 2026 01:24:23 +0100 Subject: [PATCH 03/38] feat(ui): open block settings from the toolbar Adds the settings button beside the plus button, appended before the roving tabindex is initialized so the actions container keeps exactly one tab stop. It follows the same menu-button contract as the plus button: an accessible name from the message catalogue, `aria-haspopup="menu"`, an `aria-expanded` kept in sync with the menu's own events, and focus taken on click so the popover has somewhere to return it on close. The toolbar now also tracks the hovered block's index, not just its element, and holds position while the menu is open -- the menu was built for one block, so moving off it mid-interaction would leave the two pointing at different blocks. Fixes `ToolboxOpenUIEvent` being constructed with an event name instead of a payload. The empty payload interface accepted the string, so listeners had been receiving `detail: 'ui:toolbox:open'`; the event's name comes from the class and was never affected. Ported from PR #157. Co-authored-by: Betty Steger <244475+bettysteger@users.noreply.github.com> Co-Authored-By: Claude Opus 5 --- openspec/changes/block-settings-ui/tasks.md | 11 +- packages/ui/src/Toolbar/Toolbar.const.ts | 1 + packages/ui/src/Toolbar/Toolbar.module.pcss | 8 + packages/ui/src/Toolbar/Toolbar.spec.ts | 207 ++++++++++++++++++++ packages/ui/src/Toolbar/Toolbar.ts | 97 ++++++++- 5 files changed, 316 insertions(+), 8 deletions(-) create mode 100644 packages/ui/src/Toolbar/Toolbar.spec.ts diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index 73388e44..08924400 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -44,10 +44,11 @@ ## 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 @@ -55,7 +56,7 @@ - `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 diff --git a/packages/ui/src/Toolbar/Toolbar.const.ts b/packages/ui/src/Toolbar/Toolbar.const.ts index 02a9b221..658273ec 100644 --- a/packages/ui/src/Toolbar/Toolbar.const.ts +++ b/packages/ui/src/Toolbar/Toolbar.const.ts @@ -6,4 +6,5 @@ export const css = { toolbar: className(), actions: className('actions'), plusButton: className('plus-button'), + settingsButton: className('settings-button'), }; diff --git a/packages/ui/src/Toolbar/Toolbar.module.pcss b/packages/ui/src/Toolbar/Toolbar.module.pcss index 07c97157..0cab49f4 100644 --- a/packages/ui/src/Toolbar/Toolbar.module.pcss +++ b/packages/ui/src/Toolbar/Toolbar.module.pcss @@ -42,6 +42,8 @@ &__actions { position: absolute; right: 100%; + display: flex; + align-items: center; } &__plus-button { @@ -49,4 +51,10 @@ flex-shrink: 0; } + + &__settings-button { + @apply --toolbar-button; + + flex-shrink: 0; + } } diff --git a/packages/ui/src/Toolbar/Toolbar.spec.ts b/packages/ui/src/Toolbar/Toolbar.spec.ts new file mode 100644 index 00000000..20331ef0 --- /dev/null +++ b/packages/ui/src/Toolbar/Toolbar.spec.ts @@ -0,0 +1,207 @@ +import { beforeEach, describe, expect, it, jest } from '@jest/globals'; +import type { 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 { BlockSettingsClosedUIEvent, BlockSettingsOpenedUIEvent, BlockSettingsRenderedUIEvent } from '../BlockSettings/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; +} { + const eventBus = new EventBus(); + const api = { blocks: {} } 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 { + 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')]; +} + +/** + * The button that opens block settings + * @param holder - the toolbar element + */ +function settingsButton(holder: HTMLElement): HTMLButtonElement { + const button = actionButtons(holder).find( + candidate => candidate.getAttribute('aria-label') === messages.blockSettingsButton + ); + + if (button === undefined) { + throw new Error('the toolbar rendered no settings button'); + } + + return button; +} + +/** + * Reports a block as hovered, which is what the toolbar follows + * @param eventBus - bus to dispatch on + * @param index - position of the block + */ +function selectBlock(eventBus: EventBus, index: number): void { + eventBus.dispatchEvent(new BlockSelectedUIEvent({ + block: document.createElement('div'), + index, + })); +} + +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('settings button', () => { + it('should request settings for the block the toolbar is following', () => { + const onOpen = jest.fn(); + + instance.eventBus.addEventListener('ui:block-settings:open', onOpen); + + selectBlock(instance.eventBus, 2); + settingsButton(instance.holder).click(); + + expect(onOpen).toHaveBeenCalledTimes(1); + expect((onOpen.mock.calls[0][0] as CustomEvent).detail).toEqual({ index: 2 }); + }); + + it('should carry an accessible name and advertise the menu it controls', () => { + const button = settingsButton(instance.holder); + + expect(button.getAttribute('aria-label')).toBe(messages.blockSettingsButton); + expect(button.getAttribute('aria-haspopup')).toBe('menu'); + expect(button.getAttribute('aria-expanded')).toBe('false'); + }); + + it('should follow the menu state with aria-expanded', () => { + const button = settingsButton(instance.holder); + + instance.eventBus.dispatchEvent(new BlockSettingsOpenedUIEvent({ blockId: 'block-2' as never })); + expect(button.getAttribute('aria-expanded')).toBe('true'); + + instance.eventBus.dispatchEvent(new BlockSettingsClosedUIEvent({})); + expect(button.getAttribute('aria-expanded')).toBe('false'); + }); + + it('should hold focus before the menu is asked to open', () => { + const button = settingsButton(instance.holder); + let focusedAtDispatch: Element | null = null; + + instance.eventBus.addEventListener('ui:block-settings:open', () => { + focusedAtDispatch = document.activeElement; + }); + + selectBlock(instance.eventBus, 0); + button.click(); + + expect(focusedAtDispatch).toBe(button); + }); + }); + + describe('mounting the menu', () => { + it('should mount the announced popover element into its actions area', () => { + const popover = document.createElement('div'); + + popover.dataset.testid = 'block-settings-popover'; + + instance.eventBus.dispatchEvent(new BlockSettingsRenderedUIEvent({ blockSettings: popover })); + + expect(instance.holder.querySelector('[role="toolbar"] [data-testid="block-settings-popover"]')).toBe(popover); + }); + }); + + describe('repositioning', () => { + it('should not move while block settings are open', () => { + const moveTo = jest.spyOn(instance.plugin, 'moveTo'); + + instance.eventBus.dispatchEvent(new BlockSettingsOpenedUIEvent({ blockId: 'block-0' as never })); + selectBlock(instance.eventBus, 1); + + expect(moveTo).not.toHaveBeenCalled(); + + instance.eventBus.dispatchEvent(new BlockSettingsClosedUIEvent({})); + selectBlock(instance.eventBus, 1); + + expect(moveTo).toHaveBeenCalledTimes(1); + }); + }); + + describe('roving tabindex', () => { + it('should keep exactly one action button in the tab order', () => { + 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 move the tab stop with the arrow keys', () => { + const buttons = actionButtons(instance.holder); + + buttons[0].focus(); + buttons[0].dispatchEvent(new KeyboardEvent('keydown', { + key: 'ArrowRight', + bubbles: true, + })); + + expect(buttons[1].tabIndex).toBe(0); + expect(buttons[0].tabIndex).toBe(-1); + }); + }); +}); diff --git a/packages/ui/src/Toolbar/Toolbar.ts b/packages/ui/src/Toolbar/Toolbar.ts index af005037..e29f1d1b 100644 --- a/packages/ui/src/Toolbar/Toolbar.ts +++ b/packages/ui/src/Toolbar/Toolbar.ts @@ -3,11 +3,13 @@ import { UiComponentType } from '@editorjs/sdk'; import { make } from '@editorjs/dom'; import { css } from './Toolbar.const.js'; import type { ToolboxRenderedUIEvent } from '../Toolbox/events/index.js'; -import { IconPlus } from '@codexteam/icons'; +import { IconMenuSmall, IconPlus } from '@codexteam/icons'; import Style from './Toolbar.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 { BlockSettingsOpenUIEvent } from '../BlockSettings/events/index.js'; import { messages } from '../messages.js'; /** @@ -38,6 +40,11 @@ interface ToolbarNodes { * Plus button to open Toolbox popover */ plusButton: HTMLButtonElement; + + /** + * Settings button to open the Block Settings popover + */ + settingsButton: HTMLButtonElement; } /** @@ -70,6 +77,9 @@ export class ToolbarUI implements EditorjsPlugin { plusButton: make('button', Style[css.plusButton], { innerHTML: IconPlus, }) as HTMLButtonElement, + settingsButton: make('button', Style[css.settingsButton], { + innerHTML: IconMenuSmall, + }) as HTMLButtonElement, }; /** @@ -77,6 +87,20 @@ 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; + + /** + * Position of the block the toolbar is currently following. + * + * `-1` until a block is reported, which is what the settings request carries in that case: + * it resolves to no block, and `BlockSettingsUI` drops the request + */ + #selectedBlockIndex = -1; + /** * Constructor function * @param args - plugin parameters @@ -96,11 +120,15 @@ 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; } + this.#selectedBlockIndex = event.detail.index; + this.moveTo(event.detail.block); }, { signal }); } @@ -137,6 +165,14 @@ export class ToolbarUI implements EditorjsPlugin { this.#nodes.actions.appendChild(toolboxElement); } + /** + * Adds the Block Settings popover to the editor UI + * @param blockSettingsElement - block settings HTML element to add to the page + */ + #addBlockSettings(blockSettingsElement: HTMLElement): void { + this.#nodes.actions.appendChild(blockSettingsElement); + } + /** * Creates Toolbar HTML nodes */ @@ -146,6 +182,12 @@ export class ToolbarUI implements EditorjsPlugin { this.#nodes.holder.appendChild(this.#nodes.actions); this.#nodes.actions.appendChild(this.#nodes.plusButton); + /** + * Appended before the roving tabindex is initialized below, so that both buttons are + * already in the container when the single tab stop is assigned + */ + this.#nodes.actions.appendChild(this.#nodes.settingsButton); + /** * The actions container groups related controls. It is named because the inline toolbar * is a toolbar too, and the plus button is icon-only, so it needs a name of its own @@ -154,6 +196,7 @@ export class ToolbarUI implements EditorjsPlugin { this.#nodes.actions.setAttribute('aria-label', messages.blockActionsToolbar); this.#nodes.actions.setAttribute('aria-orientation', 'horizontal'); this.#nodes.plusButton.setAttribute('aria-label', messages.addBlockButton); + this.#nodes.settingsButton.setAttribute('aria-label', messages.blockSettingsButton); /** * role="toolbar" is a promise that the group is a single tab stop navigated with the arrow @@ -172,6 +215,23 @@ export class ToolbarUI implements EditorjsPlugin { this.#nodes.plusButton.setAttribute('aria-haspopup', 'menu'); this.#nodes.plusButton.setAttribute('aria-expanded', 'false'); + /** + * Same menu-button contract as the plus button: it owns the settings menu and reports + * whether that menu is currently open + */ + this.#nodes.settingsButton.setAttribute('aria-haspopup', 'menu'); + this.#nodes.settingsButton.setAttribute('aria-expanded', 'false'); + + this.#nodes.settingsButton.addEventListener('click', () => { + /** + * Focused for the same reason the plus button is: Safari leaves a clicked button + * unfocused, and the popover would then restore focus to `document.body` on close + */ + this.#nodes.settingsButton.focus(); + + this.#openBlockSettings(); + }); + this.#nodes.plusButton.addEventListener('click', () => { /** * Safari does not focus a button when it is clicked, so without this the toolbox @@ -215,7 +275,38 @@ 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 { + this.#eventBus.addEventListener(`ui:block-settings:rendered`, (event: BlockSettingsRenderedUIEvent) => { + this.#addBlockSettings(event.detail.blockSettings); + }); + + this.#eventBus.addEventListener(`ui:block-settings:opened`, () => { + this.#isBlockSettingsOpen = true; + this.#nodes.settingsButton.setAttribute('aria-expanded', 'true'); + }); + + this.#eventBus.addEventListener(`ui:block-settings:closed`, () => { + this.#isBlockSettingsOpen = false; + this.#nodes.settingsButton.setAttribute('aria-expanded', 'false'); + }); + } + + /** + * Asks the Block Settings plugin to open the menu for the block the toolbar is following + */ + #openBlockSettings(): void { + this.#eventBus.dispatchEvent(new BlockSettingsOpenUIEvent({ index: this.#selectedBlockIndex })); } /** From 41c200b5fdb2be961b4fd76f57d7e09a5da7d6b1 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 9 Oct 2026 01:30:52 +0100 Subject: [PATCH 04/38] feat(default-block-settings-plugin): move, move and delete as a plugin Move up, Move down and Delete become an ordinary plugin registered through the `block-settings` API at `order: 1000`, so the built-in entries sit last in the menu with no privileged path into it. This is the reference example of a former "block tune" written the way any third-party plugin would write it. Every handler resolves the block's current index from its id at activation. The menu can stay open while a collaborator inserts a block above the target or an undo runs, and acting on the index the menu was built with would move a different block. `isDisabled` is necessarily a build-time snapshot, so the handlers carry their own bounds check rather than trusting it -- a stale disabled state then only greys an item out. Delete asks first: the item turns into its own confirmation in place, and only the confirmation carries a handler. It deletes by id, not by position. The plugin looks `block-settings` up lazily at `core:ready` and stays inert when it is absent, which is what a headless Core gets. `destroy()` takes the provider back out of the menu. Behaviour and test cases ported from the internal tunes in PR #157, with the confirmation step they lacked. Co-authored-by: Betty Steger <244475+bettysteger@users.noreply.github.com> Co-Authored-By: Claude Opus 5 --- .../default-block-settings-plugin.yml | 20 + openspec/changes/block-settings-ui/tasks.md | 11 +- .../default-block-settings-plugin/.gitignore | 24 ++ .../default-block-settings-plugin/README.md | 32 ++ .../eslint.config.mjs | 39 ++ .../jest.config.ts | 31 ++ .../package.json | 44 ++ .../src/index.spec.ts | 402 ++++++++++++++++++ .../src/index.ts | 176 ++++++++ .../stryker.conf.mjs | 35 ++ .../tsconfig.build.json | 13 + .../tsconfig.eslint.json | 17 + .../tsconfig.json | 27 ++ 13 files changed, 866 insertions(+), 5 deletions(-) create mode 100644 .github/workflows/default-block-settings-plugin.yml create mode 100644 packages/plugins/default-block-settings-plugin/.gitignore create mode 100644 packages/plugins/default-block-settings-plugin/README.md create mode 100644 packages/plugins/default-block-settings-plugin/eslint.config.mjs create mode 100644 packages/plugins/default-block-settings-plugin/jest.config.ts create mode 100644 packages/plugins/default-block-settings-plugin/package.json create mode 100644 packages/plugins/default-block-settings-plugin/src/index.spec.ts create mode 100644 packages/plugins/default-block-settings-plugin/src/index.ts create mode 100644 packages/plugins/default-block-settings-plugin/stryker.conf.mjs create mode 100644 packages/plugins/default-block-settings-plugin/tsconfig.build.json create mode 100644 packages/plugins/default-block-settings-plugin/tsconfig.eslint.json create mode 100644 packages/plugins/default-block-settings-plugin/tsconfig.json 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/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index 08924400..503ea17c 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -60,17 +60,18 @@ ## 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 +- [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 - [ ] 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 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..5cb05afc --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/package.json @@ -0,0 +1,44 @@ +{ + "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": "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..ba7d84b6 --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/src/index.spec.ts @@ -0,0 +1,402 @@ +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), + move, + delete: remove, + }, + document: { + get data() { + return { blocks: blocks.map(id => ({ id, + name: 'paragraph' })) }; + }, + }, + // 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); + }, + 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'); + }); + }); + + 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..b67e5860 --- /dev/null +++ b/packages/plugins/default-block-settings-plugin/src/index.ts @@ -0,0 +1,176 @@ +import type { + BlockId, + EditorAPI, + EditorjsPlugin, + EditorjsPluginParams +} from '@editorjs/sdk'; +import { CoreEventType, PluginType } from '@editorjs/sdk'; +import { IconChevronDown, IconChevronUp, IconCross, IconTrash } from '@codexteam/icons'; +import type { BlockSettingsContext, MenuConfig } 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; + + /** + * 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; + + eventBus.addEventListener(`core:${CoreEventType.Ready}`, () => { + this.#register(); + }); + } + + /** + * Takes the provider back out of the menu + */ + public destroy(): void { + this.#unregister?.(); + this.#unregister = undefined; + } + + /** + * 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): MenuConfig { + const lastIndex = this.#api.document.data.blocks.length - 1; + + return [ + { + name: 'move-up', + title: 'Move up', + icon: IconChevronUp, + closeOnActivate: true, + + /** + * A snapshot from when the menu was built, unlike the action below. Going stale + * only greys an item out, while a stale index would move the wrong block + */ + isDisabled: blockIndex <= 0, + onActivate: () => this.#move(blockId, -1), + }, + { + name: 'move-down', + title: 'Move down', + icon: IconChevronDown, + closeOnActivate: true, + isDisabled: blockIndex >= lastIndex, + onActivate: () => this.#move(blockId, 1), + }, + { + name: 'delete', + title: 'Delete', + icon: IconTrash, + + /** + * Deletion asks first. The item turns into its own confirmation, and only that + * confirmation carries the handler -- which is why this item has no `onActivate` + */ + confirmation: { + name: 'delete-confirm', + title: 'Click to delete', + icon: IconCross, + closeOnActivate: true, + onActivate: () => this.#delete(blockId), + }, + }, + ]; + } + + /** + * Moves the block one position in the given direction. + * + * The position is resolved from the id now rather than taken from the context: the menu may + * have been open while a collaborator inserted a block above the target, or while an undo ran + * @param blockId - id of the block to move + * @param offset - -1 to move up, 1 to move down + */ + #move(blockId: 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.document.data.blocks.length - 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/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" + } + ] +} From fc7053fcab67991adbacc142492bbebadbcc7257 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 9 Oct 2026 01:37:21 +0100 Subject: [PATCH 05/38] feat(editorjs): ship the block settings menu in the bundle Registers `BlockSettingsUI` and `DefaultBlockSettingsPlugin` so a bundle user gets the settings menu without wiring anything. A headless `Core` still opts in. Adds the e2e suite for it, which exercises the whole round trip through the real bundle in Chromium and WebKit: opening the menu for a hovered block, the button's `aria-expanded` and focus return, the disabled state at the document boundary, moving a block, and that deletion needs its confirmation and is abandoned when the menu is dismissed. Documents the provider API in docs/plugins.md -- including why a handler must resolve the block's position from `blockId` rather than reusing `blockIndex` -- and the four `ui:block-settings:*` events in docs/events.md. Note that the bundle's spec assertions read `ctor.name`, which for a plugin declaring a static `name` is its plugin id rather than the class name; the test mock declares one too, so it asserts a name the real module actually reports. Co-Authored-By: Claude Opus 5 --- docs/events.md | 9 ++ docs/plugins.md | 56 ++++++++++- openspec/changes/block-settings-ui/tasks.md | 11 ++- .../editorjs/e2e/tests/block-settings.spec.ts | 96 +++++++++++++++++++ packages/editorjs/package.json | 1 + packages/editorjs/src/index.spec.ts | 25 +++++ packages/editorjs/src/index.ts | 5 +- yarn.lock | 29 ++++++ 8 files changed, 225 insertions(+), 7 deletions(-) create mode 100644 packages/editorjs/e2e/tests/block-settings.spec.ts diff --git a/docs/events.md b/docs/events.md index 635923e2..f0d40582 100644 --- a/docs/events.md +++ b/docs/events.md @@ -47,9 +47,18 @@ 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` | +| `BlockSettingsOpenUIEvent` | `ui:block-settings:open` | `{ index }` | `ToolbarUI` (settings button) | +| `BlockSettingsRenderedUIEvent` | `ui:block-settings:rendered` | `{ blockSettings: HTMLElement }` | `BlockSettingsUI` | +| `BlockSettingsOpenedUIEvent` | `ui:block-settings:opened` | `{ blockId }` | `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. +The block settings events form one round trip: the toolbar asks for a block *by index*, and +`BlockSettingsUI` answers with `opened` carrying the block *id* it resolved. Only the id is +durable — see [Block settings](plugins.md#block-settings) for why a menu item should resolve +positions from it rather than reusing the index it was built with. + Use core/UI events for UI workflows and extension coordination. ## Adapter internals diff --git a/docs/plugins.md b/docs/plugins.md index cce3fb35..beea070c 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,59 @@ 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 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, 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. + +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 diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index 503ea17c..99a3c043 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -72,14 +72,15 @@ - 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 - [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 -- [ ] 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.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 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..0c33553b --- /dev/null +++ b/packages/editorjs/e2e/tests/block-settings.spec.ts @@ -0,0 +1,96 @@ +import { test, expect } from '@playwright/test'; +import { mountDocument } from '../support/editor.js'; + +/** + * 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('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('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('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..91e627f2 100644 --- a/packages/editorjs/package.json +++ b/packages/editorjs/package.json @@ -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/yarn.lock b/yarn.lock index 3f5a408b..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:^" From c326a8b35d80a4c9fca93de2f7d1fddab6be7704 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 9 Oct 2026 01:49:24 +0100 Subject: [PATCH 06/38] fix(ui): let block settings rows fill the menu The menu items were configured with `wrapperTag: 'button'`, carried over from PR #157. That is what ui-kit uses for its *inline* popover, where items are horizontal toolbar buttons and shrinking to fit the label is right. A vertical menu's styles assume a block-level wrapper, and a form control does not stretch to its container the way a div does, so each row came out as wide as its own label -- roughly 90 / 108 / 76 px for Move up / Move down / Delete. The hover highlight then covered a ragged part of each row instead of the whole row, and the UA button font replaced the editor's (13.3px Arial for 15px InterVariable). Leaving the wrapper at ui-kit's default fixes all three. Items are still exposed as `menuitem` and still activated from the keyboard by ui-kit itself, so nothing is lost on the accessibility side. Guarded by an e2e test, since only a real layout engine sees this. It measures the rows in a single pass in the page and after the webfont has settled -- taken one locator at a time, the rows are measured at different moments and a font still loading moves the menu's width between them, which WebKit reported as several pixels of drift. Confirmed the test fails with the old wrapper restored. Co-Authored-By: Claude Opus 5 --- .../editorjs/e2e/tests/block-settings.spec.ts | 37 +++++++++++++++++++ .../ui/src/BlockSettings/BlockSettings.ts | 36 ++++++++++-------- 2 files changed, 57 insertions(+), 16 deletions(-) diff --git a/packages/editorjs/e2e/tests/block-settings.spec.ts b/packages/editorjs/e2e/tests/block-settings.spec.ts index 0c33553b..32e7e2d9 100644 --- a/packages/editorjs/e2e/tests/block-settings.spec.ts +++ b/packages/editorjs/e2e/tests/block-settings.spec.ts @@ -1,6 +1,9 @@ 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; + /** * 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. @@ -46,6 +49,40 @@ test('reports the menu state on the button that owns it', async ({ page }) => { await expect(settingsButton).toBeFocused(); }); +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. ui-kit renders menu items as block-level elements + // whose width fills the menu; configuring them as `button` instead — correct for its inline + // toolbar, where items sit in a row — made each one shrink to its own label, so the hover + // highlight covered a ragged part of the row. Only a real layout engine catches this, which + // is why it is asserted here rather than in the jsdom suite. + // + // Measured in one pass in the page, after the webfont has settled: taken one locator at a + // time, the rows are measured at different moments and a font still loading changes the + // menu's width between them, which WebKit reports as several pixels of drift. + 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(); diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index 4e4f120b..7fc84bfb 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -317,23 +317,27 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { #renderPopover(items: PopoverItemParams[]): void { this.#popover?.destroy(); - 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, - }, + /** + * The item wrapper is left at ui-kit's default. `wrapperTag: 'button'` -- which the port + * from PR #157 carried over -- is what ui-kit uses for its *inline* popover, where items + * are horizontal toolbar buttons and shrink-to-fit is the right width. A vertical menu's + * styles assume a block-level wrapper, and a form control does not stretch to its + * container the way a div does, so each row ended up as wide as its own label: the hover + * highlight covered part of the row, and the UA button font replaced the editor's. + * Items are still exposed as `menuitem` and activated from the keyboard by ui-kit itself. + */ + 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, }, - { - [PopoverItemType.Default]: { wrapperTag: 'button' }, - } - ); + }); this.#popover.on(PopoverEvent.Closed, () => { this.#eventBus.dispatchEvent(new BlockSettingsClosedUIEvent({})); From 6cc851042c0d602b458a73bd87b4519ef4dc7805 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 9 Oct 2026 01:54:55 +0100 Subject: [PATCH 07/38] test(editorjs): cover the block settings menu's accessibility The menu's items are divs carrying role="menuitem", which is what the ARIA menu pattern calls for and what the toolbox already does -- but it does mean every name, role and state on them is authored rather than inherited from a native control. Nothing was asserting that. Adds an axe audit of the menu in its open state, a keyboard-only walk through it (arrow keys, roving tabindex, Enter activating and closing), and an assertion that an unavailable action is exposed with aria-disabled while staying reachable by the arrow keys, as the APG asks. Co-Authored-By: Claude Opus 5 --- packages/editorjs/e2e/tests/axe.spec.ts | 13 +++++++ .../editorjs/e2e/tests/block-settings.spec.ts | 36 +++++++++++++++++++ 2 files changed, 49 insertions(+) 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 index 32e7e2d9..2a30366e 100644 --- a/packages/editorjs/e2e/tests/block-settings.spec.ts +++ b/packages/editorjs/e2e/tests/block-settings.spec.ts @@ -94,6 +94,42 @@ test('disables moving further at the document boundaries', async ({ page }) => { await expect(menu.getByRole('menuitem', { name: 'Move down' })).toBeEnabled(); }); +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('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('moves a block up from the settings menu', async ({ page }) => { const blocks = page.getByRole('textbox', { name: 'Paragraph' }); From 82b69e1e574e0e8729981f0b4a46b9a983fb30c9 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 9 Oct 2026 22:16:50 +0100 Subject: [PATCH 08/38] fix(ui): make the block settings menu robust to its own providers Three defects found reviewing the change, all from `BlockSettingsUI` trusting input it has no business trusting. A provider that threw took the whole menu down. Providers are third-party code and `#collectItems` ran all of them inside one `Promise.all`, so a single plugin's error rejected the lot, was discarded by the fire-and-forget call in the constructor, and left the menu failing to open for every block -- losing the entries of the plugins that did nothing wrong. Each provider is now isolated and a failure is reported the way `BlockRenderer` reports a tool that fails to render: it contributes nothing, and the stack says which one it was. A request that resolved to no block, or one every provider opted out of, returned without touching a menu that was already open. That menu had been built for a different block, so it stayed on screen presenting one block's settings as another's. Both paths now close it. Building a menu is asynchronous, so two overlapping requests raced and whichever finished last won. With an async provider the stale build could land second and render the wrong block, reporting a `blockId` nobody asked for. Each request now takes a token and abandons its result if a newer request has started. Each case is covered by a test that fails without the corresponding fix. Co-Authored-By: Claude Opus 5 --- .../src/BlockSettings/BlockSettings.spec.ts | 143 +++++++++++++++++- .../ui/src/BlockSettings/BlockSettings.ts | 46 +++++- 2 files changed, 183 insertions(+), 6 deletions(-) diff --git a/packages/ui/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts index eaf0f58e..6e8efff2 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.spec.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, jest } from '@jest/globals'; +import { afterEach, beforeEach, describe, expect, it, jest } from '@jest/globals'; import type { CoreConfigValidated, EditorAPI } from '@editorjs/sdk'; import { EventBus } from '@editorjs/sdk'; import { BlockSettingsUI } from './BlockSettings.js'; @@ -30,6 +30,12 @@ const defaultBlocks: StubBlock[] = [ */ 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; + /** * 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 @@ -397,6 +403,141 @@ describe('BlockSettingsUI', () => { }); }); + 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']); + }); + + 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 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 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); + expect((onOpened.mock.calls[0][0] as CustomEvent).detail).toEqual({ blockId: 'block-1' }); + }); + }); + describe('accessibility', () => { it('should name the menu from the message catalogue', async () => { instance.plugin.publicApi.register(() => ({ diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index 7fc84bfb..fd2a99de 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -177,6 +177,12 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { */ #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; + /** * BlockSettingsUI class constructor * @param params - Plugin parameters @@ -245,13 +251,17 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { * @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. Providers are not asked about a block that - * is not there, and an opening request for one is simply dropped + * is not there. Any menu still on screen was built for a different block, so leaving it + * open would show one block's settings while claiming to be another's */ if (blockId === undefined) { + this.#close(); + return; } @@ -261,7 +271,21 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { tool: this.#api.document.data.blocks[index]?.name ?? '', }); + /** + * 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; + } + + /** + * 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; } @@ -284,13 +308,25 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { const contributions = await Promise.all( ordered.map(async ({ provider }) => { - const result = await provider(context); + try { + const result = await provider(context); + + if (result === undefined) { + return []; + } + + return Array.isArray(result) ? result : [result]; + } catch (error) { + /** + * Providers are third-party code, and this is the one place all of it runs. Without + * isolation a single plugin throwing takes the whole menu down for every block -- + * including the entries of the plugins that did nothing wrong. It contributes + * nothing instead, and the stack identifies which one it was. + */ + console.error('[BlockSettingsUI] A block settings provider failed and was skipped', error); - if (result === undefined) { return []; } - - return Array.isArray(result) ? result : [result]; }) ); From 14908df0b9ecce61f813fadacf977e294e7439e8 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 9 Oct 2026 22:36:22 +0100 Subject: [PATCH 09/38] test(editorjs): group the block settings e2e tests The suite was nine top-level `test()` calls. Grouped into `test.describe` blocks -- opening the menu, presentation, keyboard operation, actions -- to match how `aria.spec.ts` groups its toolbox and inline toolbar cases, and the describe/it structure the unit suites already follow. No assertions changed. Co-Authored-By: Claude Opus 5 --- .../editorjs/e2e/tests/block-settings.spec.ts | 232 +++++++++--------- 1 file changed, 120 insertions(+), 112 deletions(-) diff --git a/packages/editorjs/e2e/tests/block-settings.spec.ts b/packages/editorjs/e2e/tests/block-settings.spec.ts index 2a30366e..74c7ae92 100644 --- a/packages/editorjs/e2e/tests/block-settings.spec.ts +++ b/packages/editorjs/e2e/tests/block-settings.spec.ts @@ -13,157 +13,165 @@ test.beforeEach(async ({ page }) => { await mountDocument(page, '?text=Alpha&text=Beta'); }); -test('opens the settings menu for the hovered block', async ({ page }) => { - const blocks = page.getByRole('textbox', { name: 'Paragraph' }); +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(); + 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' }); + // 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(); -}); + 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' }); + 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 page.getByRole('textbox', { name: 'Paragraph' }).first() + .hover(); - await expect(settingsButton).toHaveAttribute('aria-haspopup', 'menu'); - await expect(settingsButton).toHaveAttribute('aria-expanded', 'false'); + await expect(settingsButton).toHaveAttribute('aria-haspopup', 'menu'); + await expect(settingsButton).toHaveAttribute('aria-expanded', 'false'); - await settingsButton.click(); + await settingsButton.click(); - await expect(settingsButton).toHaveAttribute('aria-expanded', 'true'); + await expect(settingsButton).toHaveAttribute('aria-expanded', 'true'); - await page.keyboard.press('Escape'); + await page.keyboard.press('Escape'); - await expect(settingsButton).toHaveAttribute('aria-expanded', 'false'); + 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(); + // The menu button pattern hands focus back to the button the menu was opened from. + await expect(settingsButton).toBeFocused(); + }); }); -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. ui-kit renders menu items as block-level elements - // whose width fills the menu; configuring them as `button` instead — correct for its inline - // toolbar, where items sit in a row — made each one shrink to its own label, so the hover - // highlight covered a ragged part of the row. Only a real layout engine catches this, which - // is why it is asserted here rather than in the jsdom suite. - // - // Measured in one pass in the page, after the webfont has settled: taken one locator at a - // time, the rows are measured at different moments and a font still loading changes the - // menu's width between them, which WebKit reports as several pixels of drift. - 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); +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. ui-kit renders menu items as block-level elements + // whose width fills the menu; configuring them as `button` instead — correct for its inline + // toolbar, where items sit in a row — made each one shrink to its own label, so the hover + // highlight covered a ragged part of the row. Only a real layout engine catches this, which + // is why it is asserted here rather than in the jsdom suite. + // + // Measured in one pass in the page, after the webfont has settled: taken one locator at a + // time, the rows are measured at different moments and a font still loading changes the + // menu's width between them, which WebKit reports as several pixels of drift. + 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); }); - 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(); -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' }); - 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(); -}); + await expect(menu.getByRole('menuitem', { name: 'Move up' })).toBeDisabled(); + await expect(menu.getByRole('menuitem', { name: 'Move down' })).toBeEnabled(); + }); -test('is operable from the keyboard alone', async ({ page }) => { - const blocks = page.getByRole('textbox', { name: 'Paragraph' }); + 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(); - await blocks.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' }); - const menu = page.getByRole('menu', { name: 'Block settings' }); + await expect(moveUp).toHaveAttribute('aria-disabled', 'true'); + }); +}); - await expect(menu).toBeVisible(); +test.describe('keyboard operation', () => { + test('is operable from the keyboard alone', async ({ page }) => { + const blocks = page.getByRole('textbox', { name: 'Paragraph' }); - // 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 blocks.first().hover(); + await page.getByRole('button', { name: 'Block settings' }).click(); - await expect(menu.getByRole('menuitem', { name: 'Move down' })).toBeFocused(); + const menu = page.getByRole('menu', { name: 'Block settings' }); - await page.keyboard.press('Enter'); + await expect(menu).toBeVisible(); - await expect(blocks).toHaveText(['Beta', 'Alpha']); - await expect(menu).toBeHidden(); -}); + // 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'); -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(); + await expect(menu.getByRole('menuitem', { name: 'Move down' })).toBeFocused(); - // 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 page.keyboard.press('Enter'); - await expect(moveUp).toHaveAttribute('aria-disabled', 'true'); + await expect(blocks).toHaveText(['Beta', 'Alpha']); + await expect(menu).toBeHidden(); + }); }); -test('moves a block up from the settings menu', async ({ page }) => { - const blocks = page.getByRole('textbox', { name: 'Paragraph' }); +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 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 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']); -}); + 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' }); + 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(); + 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']); + // 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 page.getByRole('menuitem', { name: 'Click to delete' }).click(); - await expect(blocks).toHaveText(['Alpha']); -}); + await expect(blocks).toHaveText(['Alpha']); + }); -test('abandons a pending deletion when the menu is dismissed', async ({ page }) => { - const blocks = page.getByRole('textbox', { name: 'Paragraph' }); + 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 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']); + await expect(blocks).toHaveText(['Alpha', 'Beta']); + }); }); From 0d592973dfcfe23d5f4ccb9cd9b97879f71abfdd Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 9 Oct 2026 23:17:58 +0100 Subject: [PATCH 10/38] refactor(ui)!: let the block settings plugin own its button `ToolbarUI` was rendering the settings button, naming it, tracking its `aria-expanded`, following block selection on its behalf and dispatching `ui:block-settings:open` on click -- all of it state belonging to a plugin that may not even be registered. The button and the menu are one widget, so the plugin now builds both and announces them together through `ui:block-settings:rendered`; the toolbar only places them. The button is announced separately from the menu rather than wrapped inside it, because it has to be a child of the actions container in its own right for the toolbar's roving tabindex to see it. That arrives after the toolbar has rendered, so mounting reassigns the single tab stop -- a button carrying no `tabindex` would otherwise be a second one. `ui:block-settings:open` stops being how the button works and becomes the way anything else opens the menu. The toolbar keeps `opened`/`closed` for the one thing that is still its business: holding position while a menu built for one block is on screen. The `opened` event drops its `blockId` payload, which nothing consumed. BREAKING: `ui:block-settings:rendered` now carries `{ button, blockSettings }`, and `ui:block-settings:opened` carries nothing. Co-Authored-By: Claude Opus 5 --- docs/events.md | 14 +-- docs/plugins.md | 5 +- .../BlockSettings/BlockSettings.module.pcss | 28 +++++ .../src/BlockSettings/BlockSettings.spec.ts | 110 ++++++++++++++++- .../ui/src/BlockSettings/BlockSettings.ts | 61 ++++++++- .../events/BlockSettingsOpenedUIEvent.ts | 11 +- .../events/BlockSettingsRenderedUIEvent.ts | 13 +- packages/ui/src/Toolbar/Toolbar.const.ts | 1 - packages/ui/src/Toolbar/Toolbar.module.pcss | 6 - packages/ui/src/Toolbar/Toolbar.spec.ts | 116 +++++++++--------- packages/ui/src/Toolbar/Toolbar.ts | 77 +++--------- 11 files changed, 292 insertions(+), 150 deletions(-) create mode 100644 packages/ui/src/BlockSettings/BlockSettings.module.pcss diff --git a/docs/events.md b/docs/events.md index f0d40582..5919ac22 100644 --- a/docs/events.md +++ b/docs/events.md @@ -47,17 +47,17 @@ 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` | -| `BlockSettingsOpenUIEvent` | `ui:block-settings:open` | `{ index }` | `ToolbarUI` (settings button) | -| `BlockSettingsRenderedUIEvent` | `ui:block-settings:rendered` | `{ blockSettings: HTMLElement }` | `BlockSettingsUI` | -| `BlockSettingsOpenedUIEvent` | `ui:block-settings:opened` | `{ blockId }` | `BlockSettingsUI` | +| `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. -The block settings events form one round trip: the toolbar asks for a block *by index*, and -`BlockSettingsUI` answers with `opened` carrying the block *id* it resolved. Only the id is -durable — see [Block settings](plugins.md#block-settings) for why a menu item should resolve -positions from it rather than reusing the index it was built with. +`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. Use core/UI events for UI workflows and extension coordination. diff --git a/docs/plugins.md b/docs/plugins.md index beea070c..a01db8db 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -120,8 +120,9 @@ 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 owns no items of its own; a plugin contributes to it by -registering a *provider*: +`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 => ({ diff --git a/packages/ui/src/BlockSettings/BlockSettings.module.pcss b/packages/ui/src/BlockSettings/BlockSettings.module.pcss new file mode 100644 index 00000000..abd3f437 --- /dev/null +++ b/packages/ui/src/BlockSettings/BlockSettings.module.pcss @@ -0,0 +1,28 @@ +/** + * The button is rendered by this plugin but lives among the toolbar's controls, so it + * matches them. The declarations are repeated rather than shared because `@apply` of the + * toolbar's `--toolbar-button` property set resolves per file, and there is no shared + * partial for the two to draw on yet. + */ +.settings-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/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts index 6e8efff2..85850939 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.spec.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -4,6 +4,7 @@ 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 { BlockSettingsProvider } from './BlockSettings.js'; /** @@ -55,6 +56,8 @@ function setup(blocks: StubBlock[] = defaultBlocks): { 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` */ @@ -82,13 +85,17 @@ function setup(blocks: StubBlock[] = defaultBlocks): { } 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 { - element = (event.detail as BlockSettingsRenderedUIEventPayload).blockSettings; + const detail = event.detail as BlockSettingsRenderedUIEventPayload; + + element = detail.blockSettings; + button = detail.button as HTMLButtonElement; } eventBus.addEventListener('ui:block-settings:rendered', captureElement); @@ -103,16 +110,24 @@ function setup(blocks: StubBlock[] = defaultBlocks): { config: { holder } as unknown as CoreConfigValidated, }); - if (element === undefined) { - throw new Error('BlockSettingsUI did not announce its element'); + 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 { plugin, eventBus, element, + button, api, getIdByIndex, }; @@ -343,7 +358,6 @@ describe('BlockSettingsUI', () => { await open(instance.eventBus, 1); expect(onOpened).toHaveBeenCalledTimes(1); - expect((onOpened.mock.calls[0][0] as CustomEvent).detail).toEqual({ blockId: 'block-1' }); }); it('should dispatch closed when closed through the public API', async () => { @@ -534,7 +548,93 @@ describe('BlockSettingsUI', () => { expect(itemTitles(instance.element)).toEqual(['For block-1']); expect(onOpened).toHaveBeenCalledTimes(1); - expect((onOpened.mock.calls[0][0] as CustomEvent).detail).toEqual({ blockId: 'block-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.eventBus.dispatchEvent(new BlockSelectedUIEvent({ + block: document.createElement('div'), + index, + })); + } + + it('should announce a button alongside the menu', () => { + expect(instance.button.tagName).toBe('BUTTON'); + }); + + 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); + instance.button.click(); + 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); + instance.button.click(); + 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); + instance.button.click(); + 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 not re-target while its menu is open', async () => { + instance.plugin.publicApi.register(ctx => ({ + title: `For ${ctx.blockId}`, + onActivate: () => {}, + })); + + selectBlock(0); + instance.button.click(); + await flush(); + + // The menu belongs to block 0; hovering elsewhere must not move it underneath. + selectBlock(2); + instance.plugin.publicApi.close(); + instance.button.click(); + await flush(); + + expect(itemTitles(instance.element)).toEqual(['For block-0']); }); }); diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index fd2a99de..0f99d760 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -1,4 +1,5 @@ import { make } from '@editorjs/dom'; +import { IconMenuSmall } from '@codexteam/icons'; import type { BlockId, CoreConfigValidated, @@ -11,6 +12,8 @@ import { UiComponentType } from '@editorjs/sdk'; import type { PopoverItemParams } from '@editorjs/ui-kit'; import { PopoverDesktop, PopoverEvent, PopoverItemType } from '@editorjs/ui-kit'; import { messages } from '../messages.js'; +import Style from './BlockSettings.module.pcss'; +import type { BlockSelectedUIEvent } from '../Blocks/events/index.js'; import { BlockSettingsClosedUIEvent, BlockSettingsOpenedUIEvent, @@ -157,11 +160,27 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { #editorConfig: CoreConfigValidated; /** - * Stable element handed to `ToolbarUI`. The popover inside it is replaced per open, + * 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; + + /** + * Position of the block the menu will be built for, as last reported by block selection. + * + * Frozen while the menu is open: the menu belongs to one block, and re-targeting under it + * would leave the button and the open menu pointing at different blocks + */ + #selectedBlockIndex = -1; + /** * Popover rendering the current menu, absent until the menu is first built */ @@ -198,11 +217,25 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { }; this.#holder = make('div'); + this.#button = make('button', Style['settings-button'], { + innerHTML: IconMenuSmall, + }) as HTMLButtonElement; + + this.#renderButton(); this.#eventBus.dispatchEvent(new BlockSettingsRenderedUIEvent({ + button: this.#button, blockSettings: this.#holder, })); + this.#eventBus.addEventListener('ui:blocks:block-selected', (event: BlockSelectedUIEvent) => { + if (this.#popover?.isShown === true) { + return; + } + + this.#selectedBlockIndex = event.detail.index; + }); + this.#eventBus.addEventListener('ui:block-settings:open', (event: BlockSettingsOpenUIEvent) => { void this.#open(event.detail.index); }); @@ -215,6 +248,27 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { this.#popover?.destroy(); this.#popover = undefined; this.#holder.remove(); + this.#button.remove(); + } + + /** + * 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('click', () => { + /** + * 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(); + + void this.#open(this.#selectedBlockIndex); + }); } /** @@ -292,8 +346,9 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { this.#renderPopover(items); this.#popover?.show(); + this.#button.setAttribute('aria-expanded', 'true'); - this.#eventBus.dispatchEvent(new BlockSettingsOpenedUIEvent({ blockId })); + this.#eventBus.dispatchEvent(new BlockSettingsOpenedUIEvent({})); } /** @@ -376,6 +431,8 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { }); this.#popover.on(PopoverEvent.Closed, () => { + this.#button.setAttribute('aria-expanded', 'false'); + this.#eventBus.dispatchEvent(new BlockSettingsClosedUIEvent({})); }); diff --git a/packages/ui/src/BlockSettings/events/BlockSettingsOpenedUIEvent.ts b/packages/ui/src/BlockSettings/events/BlockSettingsOpenedUIEvent.ts index d90a27ab..4166e5e3 100644 --- a/packages/ui/src/BlockSettings/events/BlockSettingsOpenedUIEvent.ts +++ b/packages/ui/src/BlockSettings/events/BlockSettingsOpenedUIEvent.ts @@ -1,15 +1,10 @@ -import type { BlockId } from '@editorjs/sdk'; import { BlockSettingsBaseEvent } from './BlockSettingsBaseEvent.js'; /** - * Reports which block the menu that just opened was built for + * Payload of the BlockSettingsOpenedUIEvent - empty for now */ -export interface BlockSettingsOpenedUIEventPayload { - /** - * Id of the block the opened menu was built for - */ - readonly blockId: BlockId; -} +// 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 diff --git a/packages/ui/src/BlockSettings/events/BlockSettingsRenderedUIEvent.ts b/packages/ui/src/BlockSettings/events/BlockSettingsRenderedUIEvent.ts index 4bd4bd3c..c7371465 100644 --- a/packages/ui/src/BlockSettings/events/BlockSettingsRenderedUIEvent.ts +++ b/packages/ui/src/BlockSettings/events/BlockSettingsRenderedUIEvent.ts @@ -2,11 +2,20 @@ import { BlockSettingsBaseEvent } from './BlockSettingsBaseEvent.js'; /** * Payload of the BlockSettingsRenderedUIEvent - * Contains the block settings HTML element + * Carries the elements the plugin owns, for a host to mount */ export interface BlockSettingsRenderedUIEventPayload { /** - * Block settings HTML element + * 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; } diff --git a/packages/ui/src/Toolbar/Toolbar.const.ts b/packages/ui/src/Toolbar/Toolbar.const.ts index 658273ec..02a9b221 100644 --- a/packages/ui/src/Toolbar/Toolbar.const.ts +++ b/packages/ui/src/Toolbar/Toolbar.const.ts @@ -6,5 +6,4 @@ export const css = { toolbar: className(), actions: className('actions'), plusButton: className('plus-button'), - settingsButton: className('settings-button'), }; diff --git a/packages/ui/src/Toolbar/Toolbar.module.pcss b/packages/ui/src/Toolbar/Toolbar.module.pcss index 0cab49f4..c900d4fb 100644 --- a/packages/ui/src/Toolbar/Toolbar.module.pcss +++ b/packages/ui/src/Toolbar/Toolbar.module.pcss @@ -51,10 +51,4 @@ flex-shrink: 0; } - - &__settings-button { - @apply --toolbar-button; - - flex-shrink: 0; - } } diff --git a/packages/ui/src/Toolbar/Toolbar.spec.ts b/packages/ui/src/Toolbar/Toolbar.spec.ts index 20331ef0..c7b3c849 100644 --- a/packages/ui/src/Toolbar/Toolbar.spec.ts +++ b/packages/ui/src/Toolbar/Toolbar.spec.ts @@ -60,19 +60,31 @@ function actionButtons(holder: HTMLElement): HTMLButtonElement[] { } /** - * The button that opens block settings - * @param holder - the toolbar element + * 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 settingsButton(holder: HTMLElement): HTMLButtonElement { - const button = actionButtons(holder).find( - candidate => candidate.getAttribute('aria-label') === messages.blockSettingsButton - ); +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'); - if (button === undefined) { - throw new Error('the toolbar rendered no settings button'); - } + button.setAttribute('aria-label', messages.blockSettingsButton); + menu.dataset.testid = 'block-settings-menu'; - return button; + eventBus.dispatchEvent(new BlockSettingsRenderedUIEvent({ + button, + blockSettings: menu, + })); + + return { + button, + menu, + }; } /** @@ -108,61 +120,42 @@ describe('ToolbarUI', () => { }); }); - describe('settings button', () => { - it('should request settings for the block the toolbar is following', () => { - const onOpen = jest.fn(); - - instance.eventBus.addEventListener('ui:block-settings:open', onOpen); - - selectBlock(instance.eventBus, 2); - settingsButton(instance.holder).click(); + describe('mounting an announced widget', () => { + it('should mount the announced menu element into its actions area', () => { + const { menu } = announceBlockSettings(instance.eventBus); - expect(onOpen).toHaveBeenCalledTimes(1); - expect((onOpen.mock.calls[0][0] as CustomEvent).detail).toEqual({ index: 2 }); + expect(instance.holder.querySelector('[role="toolbar"] [data-testid="block-settings-menu"]')).toBe(menu); }); - it('should carry an accessible name and advertise the menu it controls', () => { - const button = settingsButton(instance.holder); + it('should mount the announced button as a control of its own', () => { + const { button } = announceBlockSettings(instance.eventBus); - expect(button.getAttribute('aria-label')).toBe(messages.blockSettingsButton); - expect(button.getAttribute('aria-haspopup')).toBe('menu'); - expect(button.getAttribute('aria-expanded')).toBe('false'); + // 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 follow the menu state with aria-expanded', () => { - const button = settingsButton(instance.holder); - - instance.eventBus.dispatchEvent(new BlockSettingsOpenedUIEvent({ blockId: 'block-2' as never })); - expect(button.getAttribute('aria-expanded')).toBe('true'); + it('should keep one tab stop after an announced button joins', () => { + announceBlockSettings(instance.eventBus); - instance.eventBus.dispatchEvent(new BlockSettingsClosedUIEvent({})); - expect(button.getAttribute('aria-expanded')).toBe('false'); - }); - - it('should hold focus before the menu is asked to open', () => { - const button = settingsButton(instance.holder); - let focusedAtDispatch: Element | null = null; - - instance.eventBus.addEventListener('ui:block-settings:open', () => { - focusedAtDispatch = document.activeElement; - }); - - selectBlock(instance.eventBus, 0); - button.click(); + const buttons = actionButtons(instance.holder); - expect(focusedAtDispatch).toBe(button); + expect(buttons).toHaveLength(2); + expect(buttons.filter(button => button.tabIndex === 0)).toHaveLength(1); }); - }); - describe('mounting the menu', () => { - it('should mount the announced popover element into its actions area', () => { - const popover = document.createElement('div'); + it('should let the arrow keys reach an announced button', () => { + const { button } = announceBlockSettings(instance.eventBus); + const [plusButton] = actionButtons(instance.holder); - popover.dataset.testid = 'block-settings-popover'; - - instance.eventBus.dispatchEvent(new BlockSettingsRenderedUIEvent({ blockSettings: popover })); + plusButton.focus(); + plusButton.dispatchEvent(new KeyboardEvent('keydown', { + key: 'ArrowRight', + bubbles: true, + })); - expect(instance.holder.querySelector('[role="toolbar"] [data-testid="block-settings-popover"]')).toBe(popover); + expect(button.tabIndex).toBe(0); + expect(plusButton.tabIndex).toBe(-1); }); }); @@ -170,7 +163,7 @@ describe('ToolbarUI', () => { it('should not move while block settings are open', () => { const moveTo = jest.spyOn(instance.plugin, 'moveTo'); - instance.eventBus.dispatchEvent(new BlockSettingsOpenedUIEvent({ blockId: 'block-0' as never })); + instance.eventBus.dispatchEvent(new BlockSettingsOpenedUIEvent({})); selectBlock(instance.eventBus, 1); expect(moveTo).not.toHaveBeenCalled(); @@ -184,6 +177,8 @@ describe('ToolbarUI', () => { 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); @@ -191,17 +186,18 @@ describe('ToolbarUI', () => { expect(buttons.filter(button => button.tabIndex === -1)).toHaveLength(buttons.length - 1); }); - it('should move the tab stop with the arrow keys', () => { - const buttons = actionButtons(instance.holder); + it('should wrap around a single control', () => { + const [plusButton] = actionButtons(instance.holder); - buttons[0].focus(); - buttons[0].dispatchEvent(new KeyboardEvent('keydown', { + plusButton.focus(); + plusButton.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true, })); - expect(buttons[1].tabIndex).toBe(0); - expect(buttons[0].tabIndex).toBe(-1); + // 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 e29f1d1b..90238cb9 100644 --- a/packages/ui/src/Toolbar/Toolbar.ts +++ b/packages/ui/src/Toolbar/Toolbar.ts @@ -3,13 +3,12 @@ import { UiComponentType } from '@editorjs/sdk'; import { make } from '@editorjs/dom'; import { css } from './Toolbar.const.js'; import type { ToolboxRenderedUIEvent } from '../Toolbox/events/index.js'; -import { IconMenuSmall, IconPlus } from '@codexteam/icons'; +import { IconPlus } from '@codexteam/icons'; import Style from './Toolbar.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 { BlockSettingsOpenUIEvent } from '../BlockSettings/events/index.js'; import { messages } from '../messages.js'; /** @@ -40,11 +39,6 @@ interface ToolbarNodes { * Plus button to open Toolbox popover */ plusButton: HTMLButtonElement; - - /** - * Settings button to open the Block Settings popover - */ - settingsButton: HTMLButtonElement; } /** @@ -77,9 +71,6 @@ export class ToolbarUI implements EditorjsPlugin { plusButton: make('button', Style[css.plusButton], { innerHTML: IconPlus, }) as HTMLButtonElement, - settingsButton: make('button', Style[css.settingsButton], { - innerHTML: IconMenuSmall, - }) as HTMLButtonElement, }; /** @@ -93,14 +84,6 @@ export class ToolbarUI implements EditorjsPlugin { */ #isBlockSettingsOpen = false; - /** - * Position of the block the toolbar is currently following. - * - * `-1` until a block is reported, which is what the settings request carries in that case: - * it resolves to no block, and `BlockSettingsUI` drops the request - */ - #selectedBlockIndex = -1; - /** * Constructor function * @param args - plugin parameters @@ -127,8 +110,6 @@ export class ToolbarUI implements EditorjsPlugin { return; } - this.#selectedBlockIndex = event.detail.index; - this.moveTo(event.detail.block); }, { signal }); } @@ -166,11 +147,22 @@ export class ToolbarUI implements EditorjsPlugin { } /** - * Adds the Block Settings popover to the editor UI - * @param blockSettingsElement - block settings HTML element to add to the page + * Mounts the Block Settings widget: its button among the toolbar's own controls, and its + * menu alongside the toolbox popover. + * + * The button has to be a child of the actions container in its own right, not wrapped in + * the menu's element -- that is what puts it in `#controls` and so into the toolbar's + * roving tabindex. The tab stop is reassigned afterwards because this arrives after the + * toolbar has already rendered, and a button carrying no `tabindex` would be a second + * stop next to the plus button + * @param button - the control that opens the menu + * @param blockSettingsElement - the element the menu renders into */ - #addBlockSettings(blockSettingsElement: HTMLElement): void { + #addBlockSettings(button: HTMLElement, blockSettingsElement: HTMLElement): void { + this.#nodes.actions.appendChild(button); this.#nodes.actions.appendChild(blockSettingsElement); + + this.#updateRovingTabindex(this.#nodes.plusButton); } /** @@ -182,12 +174,6 @@ export class ToolbarUI implements EditorjsPlugin { this.#nodes.holder.appendChild(this.#nodes.actions); this.#nodes.actions.appendChild(this.#nodes.plusButton); - /** - * Appended before the roving tabindex is initialized below, so that both buttons are - * already in the container when the single tab stop is assigned - */ - this.#nodes.actions.appendChild(this.#nodes.settingsButton); - /** * The actions container groups related controls. It is named because the inline toolbar * is a toolbar too, and the plus button is icon-only, so it needs a name of its own @@ -196,7 +182,6 @@ export class ToolbarUI implements EditorjsPlugin { this.#nodes.actions.setAttribute('aria-label', messages.blockActionsToolbar); this.#nodes.actions.setAttribute('aria-orientation', 'horizontal'); this.#nodes.plusButton.setAttribute('aria-label', messages.addBlockButton); - this.#nodes.settingsButton.setAttribute('aria-label', messages.blockSettingsButton); /** * role="toolbar" is a promise that the group is a single tab stop navigated with the arrow @@ -215,23 +200,6 @@ export class ToolbarUI implements EditorjsPlugin { this.#nodes.plusButton.setAttribute('aria-haspopup', 'menu'); this.#nodes.plusButton.setAttribute('aria-expanded', 'false'); - /** - * Same menu-button contract as the plus button: it owns the settings menu and reports - * whether that menu is currently open - */ - this.#nodes.settingsButton.setAttribute('aria-haspopup', 'menu'); - this.#nodes.settingsButton.setAttribute('aria-expanded', 'false'); - - this.#nodes.settingsButton.addEventListener('click', () => { - /** - * Focused for the same reason the plus button is: Safari leaves a clicked button - * unfocused, and the popover would then restore focus to `document.body` on close - */ - this.#nodes.settingsButton.focus(); - - this.#openBlockSettings(); - }); - this.#nodes.plusButton.addEventListener('click', () => { /** * Safari does not focus a button when it is clicked, so without this the toolbox @@ -288,27 +256,22 @@ export class ToolbarUI implements EditorjsPlugin { */ #subscribeToBlockSettingsEvents(): void { this.#eventBus.addEventListener(`ui:block-settings:rendered`, (event: BlockSettingsRenderedUIEvent) => { - this.#addBlockSettings(event.detail.blockSettings); + this.#addBlockSettings(event.detail.button, event.detail.blockSettings); }); + /** + * 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; - this.#nodes.settingsButton.setAttribute('aria-expanded', 'true'); }); this.#eventBus.addEventListener(`ui:block-settings:closed`, () => { this.#isBlockSettingsOpen = false; - this.#nodes.settingsButton.setAttribute('aria-expanded', 'false'); }); } - /** - * Asks the Block Settings plugin to open the menu for the block the toolbar is following - */ - #openBlockSettings(): void { - this.#eventBus.dispatchEvent(new BlockSettingsOpenUIEvent({ index: this.#selectedBlockIndex })); - } - /** * The toolbar's own controls, in the order the arrow keys walk them. * From 0e3140a7d235cb656852da74d8d5666c8e2e91f6 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 9 Oct 2026 23:31:08 +0100 Subject: [PATCH 11/38] refactor(ui): share the toolbar button styling The plus button and the settings button look the same but are rendered by different components, and `@apply --toolbar-button` resolves within a single file's PostCSS pass -- so moving the settings button into its own plugin had meant repeating the declarations. They now share one `.toolbar-button` class in `controls.module.pcss`, which is what the two genuinely have in common. Drops the property set's `--active` modifier along the way. Nothing ever added that class, and the `bounceIn` animation it referenced is not defined anywhere in the package. Verified in the browser as well as the suites: both buttons render identically at 26x26 from the one class, and exactly one of them holds the tab stop. Co-Authored-By: Claude Opus 5 --- .../BlockSettings/BlockSettings.module.pcss | 28 -------------- .../ui/src/BlockSettings/BlockSettings.ts | 4 +- packages/ui/src/Toolbar/Toolbar.const.ts | 1 - packages/ui/src/Toolbar/Toolbar.module.pcss | 37 ------------------- packages/ui/src/Toolbar/Toolbar.ts | 3 +- packages/ui/src/controls.module.pcss | 31 ++++++++++++++++ 6 files changed, 35 insertions(+), 69 deletions(-) delete mode 100644 packages/ui/src/BlockSettings/BlockSettings.module.pcss create mode 100644 packages/ui/src/controls.module.pcss diff --git a/packages/ui/src/BlockSettings/BlockSettings.module.pcss b/packages/ui/src/BlockSettings/BlockSettings.module.pcss deleted file mode 100644 index abd3f437..00000000 --- a/packages/ui/src/BlockSettings/BlockSettings.module.pcss +++ /dev/null @@ -1,28 +0,0 @@ -/** - * The button is rendered by this plugin but lives among the toolbar's controls, so it - * matches them. The declarations are repeated rather than shared because `@apply` of the - * toolbar's `--toolbar-button` property set resolves per file, and there is no shared - * partial for the two to draw on yet. - */ -.settings-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/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index 0f99d760..6b3e5a50 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -12,7 +12,7 @@ import { UiComponentType } from '@editorjs/sdk'; import type { PopoverItemParams } from '@editorjs/ui-kit'; import { PopoverDesktop, PopoverEvent, PopoverItemType } from '@editorjs/ui-kit'; import { messages } from '../messages.js'; -import Style from './BlockSettings.module.pcss'; +import ControlStyle from '../controls.module.pcss'; import type { BlockSelectedUIEvent } from '../Blocks/events/index.js'; import { BlockSettingsClosedUIEvent, @@ -217,7 +217,7 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { }; this.#holder = make('div'); - this.#button = make('button', Style['settings-button'], { + this.#button = make('button', ControlStyle['toolbar-button'], { innerHTML: IconMenuSmall, }) as HTMLButtonElement; 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 c900d4fb..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; @@ -45,10 +14,4 @@ display: flex; align-items: center; } - - &__plus-button { - @apply --toolbar-button; - - flex-shrink: 0; - } } diff --git a/packages/ui/src/Toolbar/Toolbar.ts b/packages/ui/src/Toolbar/Toolbar.ts index 90238cb9..e7d24499 100644 --- a/packages/ui/src/Toolbar/Toolbar.ts +++ b/packages/ui/src/Toolbar/Toolbar.ts @@ -5,6 +5,7 @@ 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'; @@ -68,7 +69,7 @@ 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, }) as HTMLButtonElement, }; diff --git a/packages/ui/src/controls.module.pcss b/packages/ui/src/controls.module.pcss new file mode 100644 index 00000000..f0dec69b --- /dev/null +++ b/packages/ui/src/controls.module.pcss @@ -0,0 +1,31 @@ +/** + * Styling shared by the icon buttons that sit in the floating toolbar's actions container. + * + * A plain class rather than a `--toolbar-button` property set applied with `@apply`: that + * resolves within one file's PostCSS pass, so every component rendering one of these buttons + * had to repeat the declarations. The buttons are not all rendered by the same component -- + * `ToolbarUI` owns the plus button, `BlockSettingsUI` owns the settings button -- so the one + * thing they genuinely share is this appearance. + */ +.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); + } + } +} From 053497c9a45e41470e6d4377f8260d418b09acb4 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 9 Oct 2026 23:52:29 +0100 Subject: [PATCH 12/38] docs: keep the block settings comments to two sentences Eleven comments added by this change ran to three or four. Same content, tightened: the plugin and provider docs, the rebuild-per-open and item-wrapper notes, the toolbar's mounting contract, the shared button stylesheet, the CSS Modules mock and the row-width regression test. Co-Authored-By: Claude Opus 5 --- .../editorjs/e2e/tests/block-settings.spec.ts | 14 +++--- .../ui/src/BlockSettings/BlockSettings.ts | 45 ++++++++----------- .../events/BlockSettingsOpenUIEvent.ts | 8 ++-- packages/ui/src/Toolbar/Toolbar.ts | 12 ++--- packages/ui/src/controls.module.pcss | 11 ++--- 5 files changed, 34 insertions(+), 56 deletions(-) diff --git a/packages/editorjs/e2e/tests/block-settings.spec.ts b/packages/editorjs/e2e/tests/block-settings.spec.ts index 74c7ae92..63ea9dd3 100644 --- a/packages/editorjs/e2e/tests/block-settings.spec.ts +++ b/packages/editorjs/e2e/tests/block-settings.spec.ts @@ -59,15 +59,11 @@ test.describe('presentation', () => { await expect(page.getByRole('menu', { name: 'Block settings' })).toBeVisible(); - // Regression test for the item wrapper. ui-kit renders menu items as block-level elements - // whose width fills the menu; configuring them as `button` instead — correct for its inline - // toolbar, where items sit in a row — made each one shrink to its own label, so the hover - // highlight covered a ragged part of the row. Only a real layout engine catches this, which - // is why it is asserted here rather than in the jsdom suite. - // - // Measured in one pass in the page, after the webfont has settled: taken one locator at a - // time, the rows are measured at different moments and a font still loading changes the - // menu's width between them, which WebKit reports as several pixels of drift. + // 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; diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index 6b3e5a50..1701d0a1 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -72,7 +72,7 @@ export type BlockSettingsProvider = ( */ export interface BlockSettingsRegisterOptions { /** - * Ascending sort key for this provider's contribution. Defaults to `0`, ties are broken by + * 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; @@ -121,12 +121,9 @@ interface Registration { } /** - * UI plugin that renders the per-block settings menu. - * - * Mirrors {@link ToolboxUI}: it announces its element once so `ToolbarUI` can mount it, then - * builds and opens the menu whenever it receives `ui:block-settings:open`. It owns no items of - * its own -- everything in the menu comes from registered providers, the built-in Move/Delete - * entries included. + * 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. */ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { /** @@ -309,9 +306,9 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { const blockId = this.#api.blocks.getIdByIndex(index); /** - * Nothing is selected, or the index is stale. Providers are not asked about a block that - * is not there. Any menu still on screen was built for a different block, so leaving it - * open would show one block's settings while claiming to be another's + * 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(); @@ -373,10 +370,9 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { return Array.isArray(result) ? result : [result]; } catch (error) { /** - * Providers are third-party code, and this is the one place all of it runs. Without - * isolation a single plugin throwing takes the whole menu down for every block -- - * including the entries of the plugins that did nothing wrong. It contributes - * nothing instead, and the stack identifies which one it was. + * 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); @@ -397,25 +393,20 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { } /** - * Replaces the popover inside the holder with one built for the given items. - * - * The menu is rebuilt rather than edited in place: `removeItemByName` is the only removal - * `@editorjs/ui-kit` offers, and a separator is constructed without params, so it has no name - * to be removed by. Handing a fresh popover the complete item list is what guarantees that - * the items of the previous block leave the accessibility tree. + * 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 { this.#popover?.destroy(); /** - * The item wrapper is left at ui-kit's default. `wrapperTag: 'button'` -- which the port - * from PR #157 carried over -- is what ui-kit uses for its *inline* popover, where items - * are horizontal toolbar buttons and shrink-to-fit is the right width. A vertical menu's - * styles assume a block-level wrapper, and a form control does not stretch to its - * container the way a div does, so each row ended up as wide as its own label: the hover - * highlight covered part of the row, and the UA button font replaced the editor's. - * Items are still exposed as `menuitem` and activated from the keyboard by ui-kit itself. + * 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, diff --git a/packages/ui/src/BlockSettings/events/BlockSettingsOpenUIEvent.ts b/packages/ui/src/BlockSettings/events/BlockSettingsOpenUIEvent.ts index 108565e9..330e5ef4 100644 --- a/packages/ui/src/BlockSettings/events/BlockSettingsOpenUIEvent.ts +++ b/packages/ui/src/BlockSettings/events/BlockSettingsOpenUIEvent.ts @@ -5,11 +5,9 @@ import { BlockSettingsBaseEvent } from './BlockSettingsBaseEvent.js'; */ export interface BlockSettingsOpenUIEventPayload { /** - * Position of the block to show settings for. - * - * An index rather than an id because the dispatcher is the toolbar, which follows block - * selection by position. `BlockSettingsUI` resolves it to an id once, when the menu opens, - * and the providers' items work from that id afterwards + * 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; } diff --git a/packages/ui/src/Toolbar/Toolbar.ts b/packages/ui/src/Toolbar/Toolbar.ts index e7d24499..8d7f8f38 100644 --- a/packages/ui/src/Toolbar/Toolbar.ts +++ b/packages/ui/src/Toolbar/Toolbar.ts @@ -148,14 +148,10 @@ export class ToolbarUI implements EditorjsPlugin { } /** - * Mounts the Block Settings widget: its button among the toolbar's own controls, and its - * menu alongside the toolbox popover. - * - * The button has to be a child of the actions container in its own right, not wrapped in - * the menu's element -- that is what puts it in `#controls` and so into the toolbar's - * roving tabindex. The tab stop is reassigned afterwards because this arrives after the - * toolbar has already rendered, and a button carrying no `tabindex` would be a second - * stop next to the plus button + * 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 */ diff --git a/packages/ui/src/controls.module.pcss b/packages/ui/src/controls.module.pcss index f0dec69b..ef0d2f58 100644 --- a/packages/ui/src/controls.module.pcss +++ b/packages/ui/src/controls.module.pcss @@ -1,11 +1,8 @@ /** - * Styling shared by the icon buttons that sit in the floating toolbar's actions container. - * - * A plain class rather than a `--toolbar-button` property set applied with `@apply`: that - * resolves within one file's PostCSS pass, so every component rendering one of these buttons - * had to repeat the declarations. The buttons are not all rendered by the same component -- - * `ToolbarUI` owns the plus button, `BlockSettingsUI` owns the settings button -- so the one - * thing they genuinely share is this appearance. + * 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; From aef43b1e8a203c80df7a742d0b7b1a701bd59054 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 10 Oct 2026 00:23:18 +0100 Subject: [PATCH 13/38] fix(ci): build type-only workspace dependencies before linting and testing Two packages here depend on another workspace for its *types* only, and neither the build order nor the CI jobs accounted for it. `@editorjs/default-block-settings-plugin` takes `@editorjs/ui` as a devDependency and imports from it with `import type`, so that `api.plugins['block-settings']` typechecks without a runtime coupling. The build scripts order by `--topological`, which sees dependencies but not devDependencies, and run in parallel -- so the plugin was free to build before `@editorjs/ui` had emitted anything. They now order by `--topological-dev`. `@editorjs/ui` had no way to build its workspace dependencies at all: its build is `vite build`, with none of the project references that make the tsc-built packages pull `@editorjs/sdk` along, and its `build:declaration` was empty. The new `ui.yml` workflow is what exposed this -- its lint and test jobs ran against an unbuilt `@editorjs/sdk`. It gets the `build:dependencies` script `@editorjs/editorjs` and the playground already use. Reproduced each failure locally by clearing every `dist` *and* `tsbuildinfo` -- with the latter left behind, `tsc --build` believes its output is current and emits nothing, which looks like a different bug entirely. From genuinely cold: build, lint and test all clean, 1111 tests. Co-Authored-By: Claude Opus 5 --- package.json | 2 +- packages/editorjs/package.json | 2 +- packages/playground/package.json | 2 +- packages/plugins/default-block-settings-plugin/package.json | 3 ++- packages/ui/package.json | 5 +++-- 5 files changed, 8 insertions(+), 6 deletions(-) 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/editorjs/package.json b/packages/editorjs/package.json index 91e627f2..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", 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/package.json b/packages/plugins/default-block-settings-plugin/package.json index 5cb05afc..b9add29a 100644 --- a/packages/plugins/default-block-settings-plugin/package.json +++ b/packages/plugins/default-block-settings-plugin/package.json @@ -6,7 +6,8 @@ "types": "dist/index.d.ts", "type": "module", "scripts": { - "build": "yarn clear && tsc --build tsconfig.build.json", + "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", diff --git a/packages/ui/package.json b/packages/ui/package.json index 985ba2e4..3951887a 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -18,8 +18,9 @@ "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:dependencies", "dev": "chokidar 'src/**/*' -c 'yarn build' --initial", "prebuild": "yarn clear", "lint": "eslint ./src", From ddaf36fd3651f5f3210a719b294e90e0ccde45b4 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 10 Oct 2026 01:35:31 +0100 Subject: [PATCH 14/38] fix(ui): make the block settings button reachable, dismissable and cheap MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three findings from reviewing this branch, plus the housekeeping around them. The button did nothing at all for a keyboard-only user. `BlockSelectedUIEvent` was dispatched on `mouseenter` and nowhere else, so with no pointer the plugin's target index stayed `-1` and activating a control that is reachable, named and `aria-haspopup`-annotated silently opened nothing. `BlocksUI` now also reports the block the caret moves into. Reading the editor's own caret state instead would not work: it is cleared the moment focus leaves the editable, which is exactly what reaching for a toolbar does. The button did not toggle. ui-kit closes the popover from a listener that runs before the button's own handler, so the handler saw a closed menu and re-opened it, and the menu could not be dismissed from the control that advertises it. The open state is now read on `mousedown` — the last moment the answer is still true — and tracked by the plugin rather than read back off the popover, whose shown state does not survive that click. Reading one block's tool name went through `api.document.data`, which serializes every block, every text node and every inline fragment tree, on every open of the menu. `BlocksAPI.getToolByIndex` replaces it, and the default plugin's two `document.data.blocks.length` reads become `getBlocksCount()`. Alongside: the UI package's `MenuConfig` becomes `BlockSettingsMenuConfig`, since `@editorjs/sdk` already exports a different type by that name and the two are not interchangeable; `BlockSettingsUI`, `DefaultBlockSettingsPlugin` and `ToolbarUI` drop their event bus listeners on `destroy`, the bus having outlived them; and `build:declaration` emits declarations again rather than only building dependencies. Co-Authored-By: Claude Opus 5 --- docs/events.md | 6 + docs/plugins.md | 15 +- .../src/api/BlocksAPI.integration.spec.ts | 31 +++ packages/core/src/api/BlocksAPI.ts | 9 + packages/core/src/components/BlockManager.ts | 13 ++ .../editorjs/e2e/tests/block-settings.spec.ts | 76 +++++++ .../src/index.spec.ts | 22 +- .../src/index.ts | 36 +++- packages/sdk/src/api/BlocksAPI.ts | 10 + packages/ui/package.json | 2 +- .../src/BlockSettings/BlockSettings.spec.ts | 122 ++++++++++- .../ui/src/BlockSettings/BlockSettings.ts | 127 +++++++++--- .../ui/src/Blocks/Blocks.selection.spec.ts | 189 ++++++++++++++++++ packages/ui/src/Blocks/Blocks.ts | 52 ++++- packages/ui/src/Toolbar/Toolbar.spec.ts | 28 +++ packages/ui/src/Toolbar/Toolbar.ts | 8 +- 16 files changed, 689 insertions(+), 57 deletions(-) create mode 100644 packages/ui/src/Blocks/Blocks.selection.spec.ts diff --git a/docs/events.md b/docs/events.md index 5919ac22..40282acc 100644 --- a/docs/events.md +++ b/docs/events.md @@ -47,6 +47,7 @@ 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` | @@ -59,6 +60,11 @@ together so a host can place them: `ToolbarUI` puts the button among its own con 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 a01db8db..f8d5f4e0 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -136,9 +136,15 @@ const unregister = api.plugins['block-settings']?.register(ctx => ({ 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, 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. +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 @@ -365,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/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/block-settings.spec.ts b/packages/editorjs/e2e/tests/block-settings.spec.ts index 63ea9dd3..9d3d341f 100644 --- a/packages/editorjs/e2e/tests/block-settings.spec.ts +++ b/packages/editorjs/e2e/tests/block-settings.spec.ts @@ -4,6 +4,9 @@ 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. @@ -49,6 +52,79 @@ test.describe('opening the menu', () => { // 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', () => { diff --git a/packages/plugins/default-block-settings-plugin/src/index.spec.ts b/packages/plugins/default-block-settings-plugin/src/index.spec.ts index ba7d84b6..3cd96262 100644 --- a/packages/plugins/default-block-settings-plugin/src/index.spec.ts +++ b/packages/plugins/default-block-settings-plugin/src/index.spec.ts @@ -103,15 +103,10 @@ function setup({ blockIds = ['b0', 'b1', 'b2'], withBlockSettings = true }: { const api = { blocks: { getIndexById: (id: string) => blocks.indexOf(id), + getBlocksCount: () => blocks.length, move, delete: remove, }, - document: { - get data() { - return { blocks: blocks.map(id => ({ id, - name: 'paragraph' })) }; - }, - }, // 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; @@ -121,6 +116,11 @@ function setup({ blockIds = ['b0', 'b1', 'b2'], withBlockSettings = true }: { 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; @@ -241,6 +241,16 @@ describe('DefaultBlockSettingsPlugin', () => { 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', () => { diff --git a/packages/plugins/default-block-settings-plugin/src/index.ts b/packages/plugins/default-block-settings-plugin/src/index.ts index b67e5860..189060cd 100644 --- a/packages/plugins/default-block-settings-plugin/src/index.ts +++ b/packages/plugins/default-block-settings-plugin/src/index.ts @@ -2,11 +2,12 @@ import type { BlockId, EditorAPI, EditorjsPlugin, - EditorjsPluginParams + EditorjsPluginParams, + EventBus } from '@editorjs/sdk'; import { CoreEventType, PluginType } from '@editorjs/sdk'; import { IconChevronDown, IconChevronUp, IconCross, IconTrash } from '@codexteam/icons'; -import type { BlockSettingsContext, MenuConfig } from '@editorjs/ui'; +import type { BlockSettingsContext, BlockSettingsMenuConfig } from '@editorjs/ui'; /** * Order the provider registers at, which puts its items after every other provider's. @@ -37,6 +38,11 @@ export class DefaultBlockSettingsPlugin implements EditorjsPlugin { */ readonly #api: EditorAPI; + /** + * Event bus the ready listener is attached to + */ + readonly #eventBus: EventBus; + /** * Removes the provider again, once it has been registered */ @@ -48,20 +54,32 @@ export class DefaultBlockSettingsPlugin implements EditorjsPlugin { */ constructor({ api, eventBus }: EditorjsPluginParams) { this.#api = api; + this.#eventBus = eventBus; - eventBus.addEventListener(`core:${CoreEventType.Ready}`, () => { - this.#register(); - }); + this.#eventBus.addEventListener(`core:${CoreEventType.Ready}`, this.#handleReady); } /** - * Takes the provider back out of the menu + * 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. * @@ -86,8 +104,8 @@ export class DefaultBlockSettingsPlugin implements EditorjsPlugin { * Builds the items for one block * @param context - the block the menu is being built for */ - #items({ blockId, blockIndex }: BlockSettingsContext): MenuConfig { - const lastIndex = this.#api.document.data.blocks.length - 1; + #items({ blockId, blockIndex }: BlockSettingsContext): BlockSettingsMenuConfig { + const lastIndex = this.#api.blocks.getBlocksCount() - 1; return [ { @@ -152,7 +170,7 @@ export class DefaultBlockSettingsPlugin implements EditorjsPlugin { const toIndex = fromIndex + offset; - if (toIndex < 0 || toIndex > this.#api.document.data.blocks.length - 1) { + if (toIndex < 0 || toIndex > this.#api.blocks.getBlocksCount() - 1) { return; } 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/ui/package.json b/packages/ui/package.json index 3951887a..43803b54 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -20,7 +20,7 @@ "scripts": { "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:dependencies", + "build:declaration": "yarn build", "dev": "chokidar 'src/**/*' -c 'yarn build' --initial", "prebuild": "yarn clear", "lint": "eslint ./src", diff --git a/packages/ui/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts index 85850939..ac3efa05 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.spec.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -72,14 +72,10 @@ function setup(blocks: StubBlock[] = defaultBlocks): { blocks: { getIdByIndex, getIndexById: jest.fn((id: string) => blocks.findIndex(block => block.id === id)), - }, - document: { /** * Read fresh each time, so a test can mutate the block list between opens */ - get data() { - return { blocks }; - }, + getToolByIndex: jest.fn((index: number) => blocks[index]?.name), }, plugins: {}, } as unknown as EditorAPI; @@ -149,6 +145,16 @@ 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(); +} + /** * Asks the plugin to open settings for a block, then lets the providers settle * @param eventBus - bus to dispatch on @@ -580,7 +586,7 @@ describe('BlockSettingsUI', () => { })); selectBlock(1); - instance.button.click(); + clickButton(instance.button); await flush(); expect(itemTitles(instance.element)).toEqual(['For block-1']); @@ -593,7 +599,7 @@ describe('BlockSettingsUI', () => { })); selectBlock(0); - instance.button.click(); + clickButton(instance.button); await flush(); expect(instance.button.getAttribute('aria-expanded')).toBe('true'); @@ -610,7 +616,7 @@ describe('BlockSettingsUI', () => { })); selectBlock(0); - instance.button.click(); + clickButton(instance.button); await flush(); // Safari leaves a clicked button unfocused, and the popover would then have nowhere @@ -618,6 +624,64 @@ describe('BlockSettingsUI', () => { 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}`, @@ -625,19 +689,57 @@ describe('BlockSettingsUI', () => { })); selectBlock(0); - instance.button.click(); + clickButton(instance.button); await flush(); // The menu belongs to block 0; hovering elsewhere must not move it underneath. selectBlock(2); instance.plugin.publicApi.close(); - instance.button.click(); + clickButton(instance.button); await flush(); expect(itemTitles(instance.element)).toEqual(['For block-0']); }); }); + 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 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(() => ({ diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index 1701d0a1..b3fa7cd4 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -24,12 +24,14 @@ 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: + * 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 MenuConfig = PopoverItemParams | PopoverItemParams[]; +export type BlockSettingsMenuConfig = PopoverItemParams | PopoverItemParams[]; /** * The block a provider is being asked about @@ -65,7 +67,7 @@ export interface BlockSettingsContext { */ export type BlockSettingsProvider = ( context: BlockSettingsContext -) => MenuConfig | undefined | Promise; +) => BlockSettingsMenuConfig | undefined | Promise; /** * Options a provider is registered with @@ -183,6 +185,25 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { */ #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 pointer went down on the button. + * + * The popover closes itself from the click that follows, 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 click as a fresh open. `mousedown` is the last moment + * the answer is still true + */ + #wasOpenOnPointerDown = false; + /** * Registered providers */ @@ -225,29 +246,48 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { blockSettings: this.#holder, })); - this.#eventBus.addEventListener('ui:blocks:block-selected', (event: BlockSelectedUIEvent) => { - if (this.#popover?.isShown === true) { - return; - } - - this.#selectedBlockIndex = event.detail.index; - }); - - this.#eventBus.addEventListener('ui:block-settings:open', (event: BlockSettingsOpenUIEvent) => { - void this.#open(event.detail.index); - }); + this.#eventBus.addEventListener('ui:blocks:block-selected', this.#handleBlockSelected); + this.#eventBus.addEventListener('ui:block-settings:open', this.#handleOpenRequest); } /** * 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.#popover?.destroy(); this.#popover = undefined; this.#holder.remove(); this.#button.remove(); } + /** + * Follows block selection, except while the menu is open -- re-targeting under an open menu + * would leave the button and the menu pointing at different blocks + * @param event - the selection event + */ + #handleBlockSelected = (event: BlockSelectedUIEvent): void => { + if (this.#isOpen) { + return; + } + + this.#selectedBlockIndex = event.detail.index; + }; + + /** + * 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); + }; + /** * Gives the button its menu-button semantics and wires it to the menu */ @@ -256,7 +296,15 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { this.#button.setAttribute('aria-haspopup', 'menu'); this.#button.setAttribute('aria-expanded', 'false'); + this.#button.addEventListener('mousedown', () => { + this.#wasOpenOnPointerDown = this.#isOpen; + }); + this.#button.addEventListener('click', () => { + const wasOpen = this.#wasOpenOnPointerDown; + + this.#wasOpenOnPointerDown = 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 @@ -264,6 +312,17 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { */ 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); }); } @@ -288,15 +347,37 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { } /** - * Closes the menu if it is open. `hide()` emits the popover's own closed event, - * which is what dispatches `ui:block-settings:closed` + * 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 { - if (this.#popover?.isShown === true) { - this.#popover.hide(); + if (!this.#isOpen) { + return; } + + this.#popover?.hide(); + + this.#handleClosed(); } + /** + * Records the menu as closed, once, whichever route closed it + */ + #handleClosed = (): void => { + if (!this.#isOpen) { + return; + } + + this.#isOpen = false; + + this.#button.setAttribute('aria-expanded', 'false'); + + this.#eventBus.dispatchEvent(new BlockSettingsClosedUIEvent({})); + }; + /** * Builds the menu for a block and opens it, unless there is nothing to show * @param index - position the opening request named @@ -319,7 +400,7 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { const items = await this.#collectItems({ blockId, blockIndex: index, - tool: this.#api.document.data.blocks[index]?.name ?? '', + tool: this.#api.blocks.getToolByIndex(index) ?? '', }); /** @@ -343,6 +424,8 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { this.#renderPopover(items); this.#popover?.show(); + + this.#isOpen = true; this.#button.setAttribute('aria-expanded', 'true'); this.#eventBus.dispatchEvent(new BlockSettingsOpenedUIEvent({})); @@ -421,11 +504,7 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { }, }); - this.#popover.on(PopoverEvent.Closed, () => { - this.#button.setAttribute('aria-expanded', 'false'); - - this.#eventBus.dispatchEvent(new BlockSettingsClosedUIEvent({})); - }); + this.#popover.on(PopoverEvent.Closed, this.#handleClosed); this.#holder.innerHTML = ''; this.#holder.appendChild(this.#popover.getElement()); 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..86cf82da --- /dev/null +++ b/packages/ui/src/Blocks/Blocks.selection.spec.ts @@ -0,0 +1,189 @@ +import { beforeEach, describe, expect, it } from '@jest/globals'; +import type { EditorAPI, EditorjsPluginParams } from '@editorjs/sdk'; +import { BlockAddedCoreEvent, 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[]; +} { + const eventBus = new EventBus(); + const selected: number[] = []; + + 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: {} 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); + + eventBus.dispatchEvent(new BlockAddedCoreEvent({ + tool: 'paragraph', + data: {}, + ui: blockElement, + index, + })); + } + + return { + 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')); +} + +/** + * 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('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]); + }); + + 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..338180fa 100644 --- a/packages/ui/src/Blocks/Blocks.ts +++ b/packages/ui/src/Blocks/Blocks.ts @@ -37,6 +37,12 @@ export class BlocksUI implements EditorjsPlugin { */ #blocks: HTMLElement[] = []; + /** + * Position of the block last announced as selected, so the same one is not announced twice. + * `selectionchange` fires on every keystroke, and only a move to another block is news + */ + #selectedBlockIndex = -1; + /** * EventBus instance to exchange events between components */ @@ -75,6 +81,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 +261,47 @@ export class BlocksUI implements EditorjsPlugin { */ #updateSelectedBlock(event: MouseEvent): void { const block = event.target as HTMLElement; - const index = this.#blocks.indexOf(block); + + this.#selectBlock(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 { + if (index === this.#selectedBlockIndex) { + return; + } + + this.#selectedBlockIndex = index; this.#eventBus.dispatchEvent(new BlockSelectedUIEvent({ block, @@ -278,6 +326,8 @@ export class BlocksUI implements EditorjsPlugin { * Detaching the holder takes the block wrappers inside it along */ this.#blocksHolder.remove(); + this.#blocks = []; + this.#selectedBlockIndex = -1; } } diff --git a/packages/ui/src/Toolbar/Toolbar.spec.ts b/packages/ui/src/Toolbar/Toolbar.spec.ts index c7b3c849..77c347b1 100644 --- a/packages/ui/src/Toolbar/Toolbar.spec.ts +++ b/packages/ui/src/Toolbar/Toolbar.spec.ts @@ -175,6 +175,34 @@ describe('ToolbarUI', () => { }); }); + describe('destroy', () => { + it('should stop reacting to block selection', () => { + const moveTo = jest.spyOn(instance.plugin, 'moveTo'); + + instance.plugin.destroy(); + + selectBlock(instance.eventBus, 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); diff --git a/packages/ui/src/Toolbar/Toolbar.ts b/packages/ui/src/Toolbar/Toolbar.ts index 8d7f8f38..5a27aa2d 100644 --- a/packages/ui/src/Toolbar/Toolbar.ts +++ b/packages/ui/src/Toolbar/Toolbar.ts @@ -252,9 +252,11 @@ export class ToolbarUI implements EditorjsPlugin { * 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. @@ -262,11 +264,11 @@ export class ToolbarUI implements EditorjsPlugin { */ this.#eventBus.addEventListener(`ui:block-settings:opened`, () => { this.#isBlockSettingsOpen = true; - }); + }, { signal }); this.#eventBus.addEventListener(`ui:block-settings:closed`, () => { this.#isBlockSettingsOpen = false; - }); + }, { signal }); } /** From 8ef03058b3d2fda632c0dfc2fa8528444f13a33c Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sat, 10 Oct 2026 02:09:16 +0100 Subject: [PATCH 15/38] docs(openspec): check off the block-settings-ui review follow-ups Co-Authored-By: Claude Opus 5 --- openspec/changes/block-settings-ui/tasks.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index 99a3c043..29631c4e 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -85,13 +85,13 @@ ## 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) From 8eb68ffd5b084a37687431c0b78cc52d6309ef85 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sun, 11 Oct 2026 21:52:13 +0100 Subject: [PATCH 16/38] fix(ui): stop one settings provider from taking the whole menu with it its own: a provider that never settles meant the menu never opened, and never opened again either, because every later attempt waited on the same provider. Each one now races a timeout, and the expiry lands in the same skip-and-log path as a provider that threw. A close arriving while the menu is still being built was also ignored, because #isOpen is only set once the providers have returned -- so the menu appeared a moment after the caller asked for it to be gone. #close() abandons the request in flight before looking at the open state. destroy() had the same hole: dropping the bus listeners stops the next request, not the one already waiting on a holder that is about to be removed. Co-Authored-By: Claude Opus 5 --- openspec/changes/block-settings-ui/tasks.md | 6 +- .../src/BlockSettings/BlockSettings.spec.ts | 86 +++++++++++++++++++ .../ui/src/BlockSettings/BlockSettings.ts | 53 +++++++++++- 3 files changed, 141 insertions(+), 4 deletions(-) diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index 29631c4e..4a2f2026 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -95,9 +95,9 @@ ## 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) diff --git a/packages/ui/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts index ac3efa05..54098c01 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.spec.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -37,6 +37,9 @@ const SLOW_PROVIDER_MS = 20; /** Long enough for both overlapping requests to have settled. */ const BOTH_REQUESTS_SETTLED_MS = 50; +/** 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 @@ -472,6 +475,34 @@ describe('BlockSettingsUI', () => { 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(); + } + }); + it('should not emit a separator for the provider it skipped', async () => { instance.plugin.publicApi.register(() => { throw new Error('blew up'); @@ -527,6 +558,35 @@ describe('BlockSettingsUI', () => { 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 let the newest request win when two overlap', async () => { const onOpened = jest.fn(); @@ -719,6 +779,32 @@ describe('BlockSettingsUI', () => { 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(); diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index b3fa7cd4..00a063bc 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -110,6 +110,14 @@ declare module '@editorjs/sdk' { /* 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 = 2000; + /** * A registered provider together with what it was registered with */ @@ -261,6 +269,12 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { this.#eventBus.removeEventListener('ui:blocks:block-selected', this.#handleBlockSelected); this.#eventBus.removeEventListener('ui:block-settings:open', this.#handleOpenRequest); + /** + * 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.#openToken++; + this.#popover?.destroy(); this.#popover = undefined; this.#holder.remove(); @@ -354,6 +368,13 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { * without emitting anything, which would leave the button advertising a menu that is gone */ #close(): void { + /** + * A menu can be mid-build rather than open, since `#isOpen` is only set once the providers + * have returned. Abandoning the request here is what keeps a menu from appearing moments + * after it was closed, and is why this runs before the open-state guard below + */ + this.#openToken++; + if (!this.#isOpen) { return; } @@ -444,7 +465,7 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { const contributions = await Promise.all( ordered.map(async ({ provider }) => { try { - const result = await provider(context); + const result = await this.#withTimeout(provider(context)); if (result === undefined) { return []; @@ -475,6 +496,36 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { }, []); } + /** + * 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 + */ + async #withTimeout( + result: BlockSettingsMenuConfig | undefined | Promise + ): 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 ${PROVIDER_TIMEOUT_MS}ms`)), + PROVIDER_TIMEOUT_MS + ); + }), + ]); + } 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 From baaec46ad269bfd82f2a2735a91ac02af4a21b66 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 16 Oct 2026 23:54:17 +0100 Subject: [PATCH 17/38] fix(ui): keep the settings menu pointing at the block it was built for Four ways the menu and the block it acts on could come apart. A build in flight was only abandoned by #close(). Escape and a click outside reach #handleClosed straight from the popover, so a menu dismissed while a replacement was being built came back as soon as that replacement's provider returned. Both close paths now abandon it, through one helper that destroy() uses too. Selection was still followed while a build was in flight, because #isOpen is only set once the providers return. The build for the block the user asked about would then finish and put its actions beside whichever block the pointer had moved to. A build remembers which block it is for and is abandoned when the selection leaves it. The toggle read a state captured on mousedown, which a keyboard activation never sets: Enter and Space send a click with no pointer events at all. Their keydown is where that activation starts, so it is recorded there as well, and the click reads the live state too so the toggle no longer depends on which of the popover's dismissal and this handler runs first. The button carried no type, so an editor mounted inside a form submitted it on every click of this control. BlocksUI deduplicated pointer entry along with caret moves. `mouseenter` only fires on actually crossing into a block, so there was no repetition to suppress -- and suppressing it stranded the toolbar and the settings menu, both of which ignore selection while the menu is open: after dismissing a menu opened on another block, returning to this one told them nothing and they kept acting on the old one. Caret moves are still deduplicated, since selectionchange fires for every one of them. Co-Authored-By: Claude Opus 5 --- .../src/BlockSettings/BlockSettings.spec.ts | 130 ++++++++++++++++++ .../ui/src/BlockSettings/BlockSettings.ts | 95 ++++++++++--- packages/ui/src/Blocks/Blocks.ts | 22 ++- 3 files changed, 229 insertions(+), 18 deletions(-) diff --git a/packages/ui/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts index 54098c01..2bd7d47e 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.spec.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -158,6 +158,17 @@ function clickButton(button: HTMLButtonElement): void { 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(); +} + /** * Asks the plugin to open settings for a block, then lets the providers settle * @param eventBus - bus to dispatch on @@ -587,6 +598,72 @@ describe('BlockSettingsUI', () => { 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(); @@ -633,6 +710,59 @@ describe('BlockSettingsUI', () => { 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); + }); + + 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'); diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index 00a063bc..778d2f3a 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -203,14 +203,15 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { #isOpen = false; /** - * Whether the menu was open when the pointer went down on the button. + * Whether the menu was open when the activation that is now in progress began. * - * The popover closes itself from the click that follows, 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 click as a fresh open. `mousedown` is the last moment - * the answer is still true + * 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 */ - #wasOpenOnPointerDown = false; + #wasOpenOnActivationStart = false; /** * Registered providers @@ -228,6 +229,14 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { */ #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: number | null = null; + /** * BlockSettingsUI class constructor * @param params - Plugin parameters @@ -245,6 +254,11 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { 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(); @@ -273,7 +287,7 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { * 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.#openToken++; + this.#abandonPendingBuild(); this.#popover?.destroy(); this.#popover = undefined; @@ -291,7 +305,18 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { return; } - this.#selectedBlockIndex = event.detail.index; + const { index } = event.detail; + + /** + * 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 !== index) { + this.#abandonPendingBuild(); + } + + this.#selectedBlockIndex = index; }; /** @@ -311,13 +336,30 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { this.#button.setAttribute('aria-expanded', 'false'); this.#button.addEventListener('mousedown', () => { - this.#wasOpenOnPointerDown = this.#isOpen; + 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; }); this.#button.addEventListener('click', () => { - const wasOpen = this.#wasOpenOnPointerDown; + /** + * 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.#wasOpenOnPointerDown = false; + this.#wasOpenOnActivationStart = false; /** * Safari leaves a clicked button unfocused, and the popover would then capture @@ -368,12 +410,7 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { * without emitting anything, which would leave the button advertising a menu that is gone */ #close(): void { - /** - * A menu can be mid-build rather than open, since `#isOpen` is only set once the providers - * have returned. Abandoning the request here is what keeps a menu from appearing moments - * after it was closed, and is why this runs before the open-state guard below - */ - this.#openToken++; + this.#abandonPendingBuild(); if (!this.#isOpen) { return; @@ -388,6 +425,14 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { * 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; } @@ -399,12 +444,26 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { this.#eventBus.dispatchEvent(new BlockSettingsClosedUIEvent({})); }; + /** + * 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; + + this.#buildingFor = index; + const blockId = this.#api.blocks.getIdByIndex(index); /** @@ -432,6 +491,8 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { 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 diff --git a/packages/ui/src/Blocks/Blocks.ts b/packages/ui/src/Blocks/Blocks.ts index 338180fa..aa1fe82c 100644 --- a/packages/ui/src/Blocks/Blocks.ts +++ b/packages/ui/src/Blocks/Blocks.ts @@ -262,7 +262,14 @@ export class BlocksUI implements EditorjsPlugin { #updateSelectedBlock(event: MouseEvent): void { const block = event.target as HTMLElement; - this.#selectBlock(block, 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)); } /** @@ -297,10 +304,23 @@ export class BlocksUI implements EditorjsPlugin { * @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 (index === this.#selectedBlockIndex) { 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.#selectedBlockIndex = index; this.#eventBus.dispatchEvent(new BlockSelectedUIEvent({ From 78e46152127dfb5ef085a6c527f82b6d702de827 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Fri, 16 Oct 2026 23:56:38 +0100 Subject: [PATCH 18/38] docs(openspec): check off the third-round block-settings-ui follow-ups Co-Authored-By: Claude Opus 5 --- openspec/changes/block-settings-ui/tasks.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index 4a2f2026..94ba8762 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -101,8 +101,8 @@ ## 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 From 4d1950ff83676dfaa132a16904e4a949225f0b8f Mon Sep 17 00:00:00 2001 From: gohabereg Date: Thu, 5 Nov 2026 01:19:24 +0000 Subject: [PATCH 19/38] fix(ui): keep the block settings target with the button `ToolbarUI` holds its position while the toolbox is open, because that popover renders inside it, but nothing told `BlockSettingsUI`. Hovering another block moved the target while the button stayed where it was, so the menu opened for a block it was not beside -- and `Delete` is one of the items it offers. The plugin now follows the toolbox's own events and stops tracking the selection for as long as the toolbar is holding its position, as it already did for its own open menu. Co-Authored-By: Claude Opus 5 --- .../src/BlockSettings/BlockSettings.spec.ts | 53 +++++++++++++++++++ .../ui/src/BlockSettings/BlockSettings.ts | 30 +++++++++-- 2 files changed, 80 insertions(+), 3 deletions(-) diff --git a/packages/ui/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts index 2bd7d47e..8f94ac5a 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.spec.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -5,6 +5,7 @@ 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 { ToolboxClosedUIEvent, ToolboxOpenedUIEvent } from '../Toolbox/events/index.js'; import type { BlockSettingsProvider } from './BlockSettings.js'; /** @@ -706,6 +707,20 @@ describe('BlockSettingsUI', () => { })); } + /** + * 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'); }); @@ -890,6 +905,44 @@ describe('BlockSettingsUI', () => { expect(itemTitles(instance.element)).toEqual(['For block-0']); }); + + /** + * 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 + */ + it('should not re-target while the toolbox is open', 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-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('destroy', () => { diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index 778d2f3a..ba857697 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -188,6 +188,12 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { */ #selectedBlockIndex = -1; + /** + * 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 */ @@ -270,6 +276,8 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { 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); } /** @@ -282,6 +290,8 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { */ 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. @@ -296,12 +306,12 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { } /** - * Follows block selection, except while the menu is open -- re-targeting under an open menu - * would leave the button and the menu pointing at different blocks + * 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) { + if (this.#isOpen || this.#isToolboxOpen) { return; } @@ -327,6 +337,20 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { 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; + }; + /** * Gives the button its menu-button semantics and wires it to the menu */ From d64a75da2b99c1b959e925a78f9215906002bc22 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Thu, 5 Nov 2026 01:19:45 +0000 Subject: [PATCH 20/38] fix(ui): isolate a throwing isActive to the provider that shipped it ui-kit calls `isActive` while it renders an item, which happens in `#renderPopover` -- long after the per-provider `try` in `#collectItems` has returned. One throwing callback aborted the whole popover, so every other provider's items went with it and no menu opened at all. Those callbacks are now called inside the provider's own error handling and ui-kit is handed the values they return, at any depth of nested items and on an item's confirmation state. A throw costs that provider's items, as returning nothing does. Nothing is lost by resolving early: ui-kit reads the value once per render, and the popover is rebuilt on every open. Co-Authored-By: Claude Opus 5 --- .../src/BlockSettings/BlockSettings.spec.ts | 86 +++++++++++++++++++ .../ui/src/BlockSettings/BlockSettings.ts | 46 +++++++++- 2 files changed, 130 insertions(+), 2 deletions(-) diff --git a/packages/ui/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts index 8f94ac5a..ffd0f0fe 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.spec.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -463,6 +463,92 @@ describe('BlockSettingsUI', () => { 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']); + }); + it('should skip a provider whose promise rejects', async () => { instance.plugin.publicApi.register(() => Promise.reject(new Error('async blow-up'))); instance.plugin.publicApi.register(() => ({ diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index ba857697..f3f8d569 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -9,7 +9,7 @@ import type { EventBus } from '@editorjs/sdk'; import { UiComponentType } from '@editorjs/sdk'; -import type { PopoverItemParams } from '@editorjs/ui-kit'; +import type { PopoverItemChildren, PopoverItemParams } from '@editorjs/ui-kit'; import { PopoverDesktop, PopoverEvent, PopoverItemType } from '@editorjs/ui-kit'; import { messages } from '../messages.js'; import ControlStyle from '../controls.module.pcss'; @@ -130,6 +130,42 @@ interface Registration { sequence: number; } +/** + * Replaces every `isActive` callback in an item tree with the boolean it returns: ui-kit calls them as it renders, + * long after the provider's own `try` has returned, and a throw there aborts the popover and every provider's items + * @param item - item as the provider returned it + */ +function withResolvedActiveState(item: PopoverItemParams): PopoverItemParams { + const resolved: Record = { ...item }; + + if (typeof resolved.isActive === 'function') { + resolved.isActive = (resolved.isActive as () => boolean)(); + } + + const children = resolved.children as PopoverItemChildren | undefined; + + /** + * Nested items render with their parent, so their callbacks are called just as early + */ + if (children?.items !== undefined) { + resolved.children = { + ...children, + items: children.items.map(withResolvedActiveState), + }; + } + + const confirmation = resolved.confirmation as PopoverItemParams | undefined; + + /** + * The confirmation state replaces the item's own params on activation and renders from them the same way + */ + if (confirmation !== undefined) { + resolved.confirmation = withResolvedActiveState(confirmation); + } + + return resolved as PopoverItemParams; +} + /** * 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 @@ -556,7 +592,13 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { return []; } - return Array.isArray(result) ? result : [result]; + 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(withResolvedActiveState); } catch (error) { /** * Providers are third-party code and this is the one place all of it runs, so without From b477577898dc6e38b37de10ef0f47ae8a73b8929 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Thu, 5 Nov 2026 01:19:45 +0000 Subject: [PATCH 21/38] docs(openspec): specify and check off the fourth-round block-settings-ui follow-ups The spec change for the stack is merged, so this round's delta specs land here, with the code that implements them, rather than in a spec PR of their own. `design.md` gains the reasoning for the plugin tracking the toolbox itself, and the single-owner alternative that was rejected. Co-Authored-By: Claude Opus 5 --- openspec/changes/block-settings-ui/design.md | 8 +++-- .../specs/block-settings/spec.md | 29 +++++++++++++++++-- openspec/changes/block-settings-ui/tasks.md | 5 ++++ 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/openspec/changes/block-settings-ui/design.md b/openspec/changes/block-settings-ui/design.md index ef8018c7..c5dfa4b2 100644 --- a/openspec/changes/block-settings-ui/design.md +++ b/openspec/changes/block-settings-ui/design.md @@ -44,13 +44,17 @@ 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`. +*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. ### D2. Built-in actions are a plugin package in `packages/plugins/` 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..e381ccd4 100644 --- a/openspec/changes/block-settings-ui/specs/block-settings/spec.md +++ b/openspec/changes/block-settings-ui/specs/block-settings/spec.md @@ -24,7 +24,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. 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 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 @@ -55,6 +55,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 @@ -111,13 +121,28 @@ 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 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. This SHALL cover the callbacks a contributed item carries that the popover calls as it renders — `isActive`, at any depth of nested items and on an item's confirmation state — which run after the provider has returned and outside anything it could be held to otherwise: a callback throwing there SHALL cost that provider's items, as returning nothing does, rather than aborting the popover and with it every other provider's items. 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: 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 diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index 94ba8762..ea3c9450 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -106,3 +106,8 @@ - [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 From bb431a414c645c15c797283718462e827112dde9 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sun, 8 Nov 2026 13:59:46 +0000 Subject: [PATCH 22/38] fix(ui): dismiss the block settings menu from a second Enter ui-kit's flipper claims Enter for the menu it owns and prevents the default before the event reaches the button, so the browser produces no `click` and the toggle that lives on it never runs. The menu could not be dismissed from the button that opened it at all. The keydown handler already received that key and only recorded the open state. It now closes the menu when the default has been prevented, which is exactly the activation that will produce no click. The click stays the primary path, so pointer activation and opening from the keyboard behave as before, and the unit helper that dispatches a keydown and a click together keeps meaning what it did. Confirmed in Chromium and WebKit: focus stays on the button, the keydown arrives with the default already prevented in the capture phase, and no click follows. The e2e case dropped when this was first found -- on the view that the remaining half belonged upstream -- comes back with it, and fails in both engines without the fix. A second case covers a claimed key arriving while the menu is closed: it must open nothing, since a dismissal is all that keydown stands in for. The suppression itself is still ui-kit's, and is on the board as "Flipper claims Enter aimed at the button that owns the popover". If that changes, this compensation becomes dead code and should go with its tests. Co-Authored-By: Claude Opus 5 --- .../editorjs/e2e/tests/block-settings.spec.ts | 23 ++++++++ .../src/BlockSettings/BlockSettings.spec.ts | 57 +++++++++++++++++++ .../ui/src/BlockSettings/BlockSettings.ts | 8 +++ 3 files changed, 88 insertions(+) diff --git a/packages/editorjs/e2e/tests/block-settings.spec.ts b/packages/editorjs/e2e/tests/block-settings.spec.ts index 9d3d341f..9d085cb7 100644 --- a/packages/editorjs/e2e/tests/block-settings.spec.ts +++ b/packages/editorjs/e2e/tests/block-settings.spec.ts @@ -206,6 +206,29 @@ test.describe('keyboard operation', () => { 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', () => { diff --git a/packages/ui/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts index ffd0f0fe..57feae38 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.spec.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -170,6 +170,29 @@ function activateFromKeyboard(button: HTMLButtonElement): void { 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 @@ -849,6 +872,40 @@ describe('BlockSettingsUI', () => { 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'); + }); + it('should open from the keyboard when the menu is closed', async () => { instance.plugin.publicApi.register(() => ({ title: 'Anchor', diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index f3f8d569..05871d51 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -409,6 +409,14 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { } 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', () => { From 97c8c973c805e84833b75864d56f94d0cd16303a Mon Sep 17 00:00:00 2001 From: gohabereg Date: Sun, 8 Nov 2026 13:59:46 +0000 Subject: [PATCH 23/38] docs(openspec): specify and check off the fifth-round block-settings-ui follow-ups The button requirement already promised the toggle holds however the button is activated. This says what that takes when the open menu's own keyboard handling claims the key. Co-Authored-By: Claude Opus 5 --- .../block-settings-ui/specs/block-settings/spec.md | 12 +++++++++++- openspec/changes/block-settings-ui/tasks.md | 4 ++++ 2 files changed, 15 insertions(+), 1 deletion(-) 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 e381ccd4..6f2f0ce7 100644 --- a/openspec/changes/block-settings-ui/specs/block-settings/spec.md +++ b/openspec/changes/block-settings-ui/specs/block-settings/spec.md @@ -24,7 +24,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 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. +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 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 +45,16 @@ 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: 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 diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index ea3c9450..e3587cb6 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -111,3 +111,7 @@ - [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 From f7cc9711cab883a8860f0acb7edde42cfbf41352 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Mon, 16 Nov 2026 19:37:22 +0000 Subject: [PATCH 24/38] fix(ui): hold the block settings target by id, not by position The target was a position, updated only by `ui:blocks:block-selected`. A block inserted or removed above it shifts every position below, and none of the ways that happens -- a collaborator, an undo, a move -- reports a selection, so the button quietly came to act on whichever block slid into that position, with `Delete` among the items it offers. The selection is recorded as a block id now, and the position resolved again when the menu opens. `getIndexById` returns -1 for a block that is gone, which lands in the existing "no block, do not open" path rather than needing one of its own. `#buildingFor` becomes an id for the same reason: comparing a position recorded when the build started against one reported now says nothing once the document has shifted underneath. Co-Authored-By: Claude Opus 5 --- openspec/changes/block-settings-ui/design.md | 2 +- .../specs/block-settings/spec.md | 12 ++- openspec/changes/block-settings-ui/tasks.md | 4 + .../src/BlockSettings/BlockSettings.spec.ts | 76 +++++++++++++++++++ .../ui/src/BlockSettings/BlockSettings.ts | 32 +++++--- 5 files changed, 113 insertions(+), 13 deletions(-) diff --git a/openspec/changes/block-settings-ui/design.md b/openspec/changes/block-settings-ui/design.md index c5dfa4b2..ddc16861 100644 --- a/openspec/changes/block-settings-ui/design.md +++ b/openspec/changes/block-settings-ui/design.md @@ -51,7 +51,7 @@ The two halves of 2 and 3 have to agree, which is why the plugin tracks `ui:tool *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. 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 6f2f0ce7..19c5f694 100644 --- a/openspec/changes/block-settings-ui/specs/block-settings/spec.md +++ b/openspec/changes/block-settings-ui/specs/block-settings/spec.md @@ -24,7 +24,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. 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 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. +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. 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 +45,16 @@ 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: 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 diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index e3587cb6..168e2334 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -115,3 +115,7 @@ ## 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 diff --git a/packages/ui/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts index 57feae38..de77376a 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.spec.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -1088,6 +1088,82 @@ describe('BlockSettingsUI', () => { }); }); + 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.eventBus.dispatchEvent(new BlockSelectedUIEvent({ + block: document.createElement('div'), + 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(); diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index 05871d51..4909341c 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -217,12 +217,10 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { #button: HTMLButtonElement; /** - * Position of the block the menu will be built for, as last reported by block selection. - * - * Frozen while the menu is open: the menu belongs to one block, and re-targeting under it - * would leave the button and the open menu pointing at different blocks + * 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 */ - #selectedBlockIndex = -1; + #selectedBlockId: BlockId | undefined; /** * Whether the toolbox popover is open. The toolbar holds its position while it is, since that popover renders inside @@ -277,7 +275,7 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { * Providers may be asynchronous, so the block a menu is being built for can stop being the * selected one before the menu exists */ - #buildingFor: number | null = null; + #buildingFor: BlockId | null = null; /** * BlockSettingsUI class constructor @@ -341,6 +339,18 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { 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 @@ -351,18 +361,18 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { return; } - const { index } = event.detail; + 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 !== index) { + if (this.#buildingFor !== null && this.#buildingFor !== blockId) { this.#abandonPendingBuild(); } - this.#selectedBlockIndex = index; + this.#selectedBlockId = blockId; }; /** @@ -530,8 +540,6 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { async #open(index: number): Promise { const token = ++this.#openToken; - this.#buildingFor = index; - const blockId = this.#api.blocks.getIdByIndex(index); /** @@ -545,6 +553,8 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { return; } + this.#buildingFor = blockId; + const items = await this.#collectItems({ blockId, blockIndex: index, From 46554378bf849c03f15e279f94a3f37bbcd34fe0 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Mon, 16 Nov 2026 19:50:10 +0000 Subject: [PATCH 25/38] fix(ui): recognise a repeated selection by block and position together `#addBlock`/`#removeBlock` splice the block list without touching the position last announced, so a position recorded earlier came to name a different block: after a removal, the next block to take that number read as already reported, and the caret arriving there was announced to nobody -- leaving the toolbar and the settings menu acting on a block the caret had left. A repeat now means the same block at the same position. Both halves carry weight. Comparing positions alone is the bug above. Comparing blocks alone hides that a block moved on the page: the toolbar takes its vertical position from this event and from nothing else, so a block pushed down by an insert above it has to be re-announced even though the selection never moved. The block is compared as the element rather than by id, because within `BlocksUI` the element is the block -- it holds the wrappers already, and the event carries them. Co-Authored-By: Claude Opus 5 --- .../block-settings-ui/specs/ui/spec.md | 12 ++++ openspec/changes/block-settings-ui/tasks.md | 1 + .../ui/src/Blocks/Blocks.selection.spec.ts | 58 ++++++++++++++++++- packages/ui/src/Blocks/Blocks.ts | 20 +++++-- 4 files changed, 84 insertions(+), 7 deletions(-) diff --git a/openspec/changes/block-settings-ui/specs/ui/spec.md b/openspec/changes/block-settings-ui/specs/ui/spec.md index 06b3dff1..9742e4c4 100644 --- a/openspec/changes/block-settings-ui/specs/ui/spec.md +++ b/openspec/changes/block-settings-ui/specs/ui/spec.md @@ -86,6 +86,8 @@ Selection SHALL be dispatched both when the pointer enters a block and when the 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: Inserting a block wrapper at an index - **GIVEN** a `BlockAddedCoreEvent` with a valid index - **WHEN** `BlocksUI` processes it @@ -111,6 +113,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 168e2334..f316f8f8 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -119,3 +119,4 @@ ## 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 diff --git a/packages/ui/src/Blocks/Blocks.selection.spec.ts b/packages/ui/src/Blocks/Blocks.selection.spec.ts index 86cf82da..d8716b4d 100644 --- a/packages/ui/src/Blocks/Blocks.selection.spec.ts +++ b/packages/ui/src/Blocks/Blocks.selection.spec.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it } from '@jest/globals'; import type { EditorAPI, EditorjsPluginParams } from '@editorjs/sdk'; -import { BlockAddedCoreEvent, EventBus } from '@editorjs/sdk'; +import { BlockAddedCoreEvent, BlockRemovedCoreEvent, EventBus } from '@editorjs/sdk'; import { BlocksUI } from './Blocks.js'; import type { BlocksHolderRenderedUIEvent, BlockSelectedUIEvent } from './events/index.js'; @@ -137,6 +137,62 @@ describe('BlocksUI', () => { 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.eventBus.dispatchEvent(new BlockRemovedCoreEvent({ tool: 'paragraph', + index: 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.eventBus.dispatchEvent(new BlockRemovedCoreEvent({ tool: 'paragraph', + index: 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]); + + const blockElement = document.createElement('div'); + + blockElement.appendChild(document.createTextNode('Inserted')); + + instance.eventBus.dispatchEvent(new BlockAddedCoreEvent({ tool: 'paragraph', + data: {}, + ui: blockElement, + index: 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); diff --git a/packages/ui/src/Blocks/Blocks.ts b/packages/ui/src/Blocks/Blocks.ts index aa1fe82c..f23bed40 100644 --- a/packages/ui/src/Blocks/Blocks.ts +++ b/packages/ui/src/Blocks/Blocks.ts @@ -38,10 +38,16 @@ export class BlocksUI implements EditorjsPlugin { #blocks: HTMLElement[] = []; /** - * Position of the block last announced as selected, so the same one is not announced twice. - * `selectionchange` fires on every keystroke, and only a move to another block is news + * 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 */ - #selectedBlockIndex = -1; + #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 @@ -308,7 +314,7 @@ export class BlocksUI implements EditorjsPlugin { * `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 (index === this.#selectedBlockIndex) { + if (block === this.#announcedBlock && index === this.#announcedIndex) { return; } @@ -321,7 +327,8 @@ export class BlocksUI implements EditorjsPlugin { * @param index - position of the block in the document */ #announceSelectedBlock(block: HTMLElement, index: number): void { - this.#selectedBlockIndex = index; + this.#announcedBlock = block; + this.#announcedIndex = index; this.#eventBus.dispatchEvent(new BlockSelectedUIEvent({ block, @@ -348,6 +355,7 @@ export class BlocksUI implements EditorjsPlugin { this.#blocksHolder.remove(); this.#blocks = []; - this.#selectedBlockIndex = -1; + this.#announcedBlock = null; + this.#announcedIndex = -1; } } From 479cc39ebfd864b9fbbba1814e5d467a85f78627 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Mon, 16 Nov 2026 21:14:32 +0000 Subject: [PATCH 26/38] feat(ui): tell other plugins which block the UI treats as selected Selection reaches other plugins as a one-shot `ui:blocks:block-selected` event, with nothing to ask afterwards. A plugin that ignores an announcement on purpose -- as the toolbar and the settings menu both do while a popover holds them -- had no way to find out what it missed. `BlocksUI` gains a `publicApi`, reachable as `api.plugins.blocksUI`, answering with the selected block's wrapper element and its id. The id is read through the position the block holds when asked, not the one it held when it was reported, so a block inserted above it cannot leave the answer naming whoever took its old slot. Nothing is answered once that block has been removed, so a caller is never handed a wrapper that has left the document -- which is also why removal needs no bookkeeping of its own. Named `blocksUI` rather than `blocks` to keep it apart from `api.blocks`, which is the core's block API and a different thing. Co-Authored-By: Claude Opus 5 --- .../ui/src/Blocks/Blocks.selection.spec.ts | 120 ++++++++++++++++-- packages/ui/src/Blocks/Blocks.ts | 86 ++++++++++++- 2 files changed, 191 insertions(+), 15 deletions(-) diff --git a/packages/ui/src/Blocks/Blocks.selection.spec.ts b/packages/ui/src/Blocks/Blocks.selection.spec.ts index d8716b4d..30b9d723 100644 --- a/packages/ui/src/Blocks/Blocks.selection.spec.ts +++ b/packages/ui/src/Blocks/Blocks.selection.spec.ts @@ -26,10 +26,20 @@ function setup(count: number): { 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); }); @@ -44,7 +54,11 @@ function setup(count: number): { const plugin = new BlocksUI({ eventBus, - api: {} as EditorAPI, + api: { + blocks: { + getIdByIndex: (index: number) => ids[index], + }, + } as unknown as EditorAPI, } as EditorjsPluginParams); const texts: Text[] = []; @@ -56,6 +70,8 @@ function setup(count: number): { blockElement.appendChild(text); texts.push(text); + ids.splice(index, 0, `block-${index}`); + eventBus.dispatchEvent(new BlockAddedCoreEvent({ tool: 'paragraph', data: {}, @@ -65,6 +81,32 @@ function setup(count: number): { } 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, @@ -83,6 +125,21 @@ function hoverBlock(node: Text): void { 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 @@ -107,6 +164,52 @@ describe('BlocksUI', () => { 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); @@ -148,8 +251,7 @@ describe('BlocksUI', () => { putCaretIn(instance.texts[1]); // Removing the block above shifts the caret's block to 0 and the one below it to 1. - instance.eventBus.dispatchEvent(new BlockRemovedCoreEvent({ tool: 'paragraph', - index: 0 })); + instance.removeBlockAt(0); putCaretIn(instance.texts[2]); @@ -161,8 +263,7 @@ describe('BlocksUI', () => { putCaretIn(instance.texts[1]); - instance.eventBus.dispatchEvent(new BlockRemovedCoreEvent({ tool: 'paragraph', - index: 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]); @@ -179,14 +280,7 @@ describe('BlocksUI', () => { putCaretIn(instance.texts[1]); - const blockElement = document.createElement('div'); - - blockElement.appendChild(document.createTextNode('Inserted')); - - instance.eventBus.dispatchEvent(new BlockAddedCoreEvent({ tool: 'paragraph', - data: {}, - ui: blockElement, - index: 0 })); + instance.addBlockAt(0); putCaretIn(instance.texts[1]); diff --git a/packages/ui/src/Blocks/Blocks.ts b/packages/ui/src/Blocks/Blocks.ts index f23bed40..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 */ @@ -73,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) => { @@ -336,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 */ From db492755f71b1fc87fbd465e1799643db256e68a Mon Sep 17 00:00:00 2001 From: gohabereg Date: Mon, 16 Nov 2026 21:14:33 +0000 Subject: [PATCH 27/38] fix(ui): follow the selection again once nothing is holding the toolbar Both the toolbar and the settings menu stop following selection while a popover holds them, and the announcements they ignore are never repeated. Clicking into another block moves the caret on mousedown while the popover only closes on the click, so both were left on the block the caret had left -- the toolbar drawn beside it, and the button acting on it with `Delete` among the items it offers. Each now asks `api.plugins.blocksUI` which block is selected once nothing is holding it. Reading a shared answer rather than each remembering what it skipped means they cannot come to disagree, and the frozen window stays each one's own rule: the toolbar waits for both popovers, the menu for both its own and the toolbox. The cases that expected a skipped selection to be dropped are updated. The invariant they were written for -- the button and the block it acts on naming the same block -- still holds, since both now read the same answer. Co-Authored-By: Claude Opus 5 --- .../specs/block-settings/spec.md | 7 +- .../block-settings-ui/specs/ui/spec.md | 19 ++- openspec/changes/block-settings-ui/tasks.md | 2 + .../src/BlockSettings/BlockSettings.spec.ts | 91 ++++++++++++--- .../ui/src/BlockSettings/BlockSettings.ts | 25 ++++ packages/ui/src/Toolbar/Toolbar.spec.ts | 108 ++++++++++++++++-- packages/ui/src/Toolbar/Toolbar.ts | 23 ++++ 7 files changed, 249 insertions(+), 26 deletions(-) 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 19c5f694..5df7610b 100644 --- a/openspec/changes/block-settings-ui/specs/block-settings/spec.md +++ b/openspec/changes/block-settings-ui/specs/block-settings/spec.md @@ -24,7 +24,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. 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. 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. +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 +45,11 @@ 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 diff --git a/openspec/changes/block-settings-ui/specs/ui/spec.md b/openspec/changes/block-settings-ui/specs/ui/spec.md index 9742e4c4..323d7deb 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 @@ -23,6 +23,11 @@ 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 @@ -82,12 +87,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 diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index f316f8f8..c77d273a 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -120,3 +120,5 @@ - [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 diff --git a/packages/ui/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts index de77376a..ebec61aa 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.spec.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -1,10 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, jest } from '@jest/globals'; -import type { CoreConfigValidated, EditorAPI } from '@editorjs/sdk'; +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'; @@ -66,12 +67,20 @@ function setup(blocks: StubBlock[] = defaultBlocks): { 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, @@ -81,7 +90,11 @@ function setup(blocks: StubBlock[] = defaultBlocks): { */ getToolByIndex: jest.fn((index: number) => blocks[index]?.name), }, - plugins: {}, + plugins: { + blocksUI: { + getSelectedBlock: () => selected, + }, + }, } as unknown as EditorAPI; let element: HTMLElement | undefined; @@ -124,6 +137,19 @@ function setup(blocks: StubBlock[] = defaultBlocks): { 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, @@ -810,10 +836,7 @@ describe('BlockSettingsUI', () => { * @param index - position of the block */ function selectBlock(index: number): void { - instance.eventBus.dispatchEvent(new BlockSelectedUIEvent({ - block: document.createElement('div'), - index, - })); + instance.select(index); } /** @@ -1040,20 +1063,47 @@ describe('BlockSettingsUI', () => { clickButton(instance.button); await flush(); - // The menu belongs to block 0; hovering elsewhere must not move it underneath. + // 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-0']); + 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 */ - it('should not re-target while the toolbox is open', async () => { + /** + * 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: () => {}, @@ -1067,6 +1117,24 @@ describe('BlockSettingsUI', () => { 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']); }); @@ -1095,10 +1163,7 @@ describe('BlockSettingsUI', () => { * @param index - block position to report as selected */ function select(target: ReturnType, index: number): void { - target.eventBus.dispatchEvent(new BlockSelectedUIEvent({ - block: document.createElement('div'), - index, - })); + target.select(index); } /** diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index 4909341c..34ca391a 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -395,8 +395,31 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { */ #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 */ @@ -520,6 +543,8 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { this.#button.setAttribute('aria-expanded', 'false'); this.#eventBus.dispatchEvent(new BlockSettingsClosedUIEvent({})); + + this.#catchUpWithSelection(); }; /** diff --git a/packages/ui/src/Toolbar/Toolbar.spec.ts b/packages/ui/src/Toolbar/Toolbar.spec.ts index 77c347b1..fc7b6035 100644 --- a/packages/ui/src/Toolbar/Toolbar.spec.ts +++ b/packages/ui/src/Toolbar/Toolbar.spec.ts @@ -1,10 +1,12 @@ import { beforeEach, describe, expect, it, jest } from '@jest/globals'; -import type { EditorAPI } from '@editorjs/sdk'; +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'; /** @@ -17,9 +19,25 @@ function setup(): { 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(); - const api = { blocks: {} } as unknown as EditorAPI; + + /** + * 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; @@ -45,6 +63,18 @@ function setup(): { 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, @@ -89,14 +119,16 @@ function announceBlockSettings(eventBus: EventBus): { /** * Reports a block as hovered, which is what the toolbar follows - * @param eventBus - bus to dispatch on + * @param instance - the instance under test * @param index - position of the block + * @returns the block element reported as selected */ -function selectBlock(eventBus: EventBus, index: number): void { - eventBus.dispatchEvent(new BlockSelectedUIEvent({ - block: document.createElement('div'), - index, - })); +function selectBlock(instance: ReturnType, index: number): HTMLElement { + const block = document.createElement('div'); + + instance.select(block, index); + + return block; } describe('ToolbarUI', () => { @@ -164,14 +196,68 @@ describe('ToolbarUI', () => { const moveTo = jest.spyOn(instance.plugin, 'moveTo'); instance.eventBus.dispatchEvent(new BlockSettingsOpenedUIEvent({})); - selectBlock(instance.eventBus, 1); + 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({})); - selectBlock(instance.eventBus, 1); 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(); }); }); @@ -181,7 +267,7 @@ describe('ToolbarUI', () => { instance.plugin.destroy(); - selectBlock(instance.eventBus, 1); + 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. diff --git a/packages/ui/src/Toolbar/Toolbar.ts b/packages/ui/src/Toolbar/Toolbar.ts index 5a27aa2d..b87c1958 100644 --- a/packages/ui/src/Toolbar/Toolbar.ts +++ b/packages/ui/src/Toolbar/Toolbar.ts @@ -232,6 +232,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 }); } @@ -268,9 +269,31 @@ export class ToolbarUI implements EditorjsPlugin { 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); + } + /** * The toolbar's own controls, in the order the arrow keys walk them. * From 4f9b89b8b191de0c425e0b265210b10ba79e301e Mon Sep 17 00:00:00 2001 From: gohabereg Date: Mon, 16 Nov 2026 21:20:02 +0000 Subject: [PATCH 28/38] fix(ui): stop a menu rebuild reporting itself as closed and reopened `PopoverDesktop.destroy()` hides before it tears down, and hiding emits `Closed`. The popover being replaced was still subscribed, so showing another block's items reported the menu as closed and open again, flipping `aria-expanded` with it, though the menu never stopped being open. Since the toolbar started catching up with the selection on a `closed`, a spurious one could also have moved it mid-rebuild. The subscription is dropped before the popover is destroyed. `destroy()` on the plugin itself is left as it was: there the menu really is closing. Co-Authored-By: Claude Opus 5 --- .../specs/block-settings/spec.md | 7 +++- openspec/changes/block-settings-ui/tasks.md | 1 + .../src/BlockSettings/BlockSettings.spec.ts | 40 +++++++++++++++++++ .../ui/src/BlockSettings/BlockSettings.ts | 5 +++ 4 files changed, 52 insertions(+), 1 deletion(-) 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 5df7610b..a8f03dfc 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. 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()` diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index c77d273a..c8a0be5b 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -122,3 +122,4 @@ - [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 diff --git a/packages/ui/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts index ebec61aa..9a10c4ed 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.spec.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -1156,6 +1156,46 @@ describe('BlockSettingsUI', () => { }); }); + 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 diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index 34ca391a..6ba76402 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -704,6 +704,11 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { * @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(); /** From 84af3cb3b9ccd30e323dfc4ce6812726f5551e42 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Mon, 16 Nov 2026 21:23:57 +0000 Subject: [PATCH 29/38] fix(ui): keep a throwing item handler out of the popover `onActivate` runs inside ui-kit's own click handler, which honours `closeOnActivate` only after the handler returns -- `e.handleClick(), ..., e.closeOnActivate === !0 && (this.hide(), ...)` -- so a throw escaping there abandoned the rest of the activation along with the close. The handler is wrapped where `isActive` was already resolved, at every depth of nested items and on an item's confirmation state. 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 can be observed there. That `closeOnActivate` resumes follows from the handler no longer being able to throw out, not from a test. Co-Authored-By: Claude Opus 5 --- .../specs/block-settings/spec.md | 7 +++- openspec/changes/block-settings-ui/tasks.md | 1 + .../src/BlockSettings/BlockSettings.spec.ts | 36 +++++++++++++++++++ .../ui/src/BlockSettings/BlockSettings.ts | 28 +++++++++++---- 4 files changed, 65 insertions(+), 7 deletions(-) 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 a8f03dfc..cb06abd0 100644 --- a/openspec/changes/block-settings-ui/specs/block-settings/spec.md +++ b/openspec/changes/block-settings-ui/specs/block-settings/spec.md @@ -151,7 +151,7 @@ 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. This SHALL cover the callbacks a contributed item carries that the popover calls as it renders — `isActive`, at any depth of nested items and on an item's confirmation state — which run after the provider has returned and outside anything it could be held to otherwise: a callback throwing there SHALL cost that provider's items, as returning nothing does, rather than aborting the popover and with it every other provider's items. 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 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. 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 @@ -163,6 +163,11 @@ Providers are third-party code, and the open menu is the one place all of it run - **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 diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index c8a0be5b..22c4f381 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -123,3 +123,4 @@ - [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 diff --git a/packages/ui/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts index 9a10c4ed..43bbdc45 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.spec.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -598,6 +598,42 @@ describe('BlockSettingsUI', () => { 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(() => ({ diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index 6ba76402..a874718b 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -131,17 +131,33 @@ interface Registration { } /** - * Replaces every `isActive` callback in an item tree with the boolean it returns: ui-kit calls them as it renders, - * long after the provider's own `try` has returned, and a throw there aborts the popover and every provider's items + * 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 withResolvedActiveState(item: PopoverItemParams): PopoverItemParams { +function withIsolatedCallbacks(item: PopoverItemParams): PopoverItemParams { const resolved: Record = { ...item }; if (typeof resolved.isActive === 'function') { resolved.isActive = (resolved.isActive as () => boolean)(); } + const activate = resolved.onActivate; + + /** + * Wrapped rather than resolved: this one runs on a click, inside ui-kit's own handler, which goes on to honour + * `closeOnActivate` after it returns -- so a throw escaping here abandons the rest of that sequence + */ + if (typeof activate === 'function') { + resolved.onActivate = (...args: unknown[]): void => { + try { + (activate as (...callArgs: unknown[]) => void)(...args); + } catch (error) { + console.error('[BlockSettingsUI] A block settings item failed on activation', error); + } + }; + } + const children = resolved.children as PopoverItemChildren | undefined; /** @@ -150,7 +166,7 @@ function withResolvedActiveState(item: PopoverItemParams): PopoverItemParams { if (children?.items !== undefined) { resolved.children = { ...children, - items: children.items.map(withResolvedActiveState), + items: children.items.map(withIsolatedCallbacks), }; } @@ -160,7 +176,7 @@ function withResolvedActiveState(item: PopoverItemParams): PopoverItemParams { * The confirmation state replaces the item's own params on activation and renders from them the same way */ if (confirmation !== undefined) { - resolved.confirmation = withResolvedActiveState(confirmation); + resolved.confirmation = withIsolatedCallbacks(confirmation); } return resolved as PopoverItemParams; @@ -641,7 +657,7 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { * 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(withResolvedActiveState); + return items.map(withIsolatedCallbacks); } catch (error) { /** * Providers are third-party code and this is the one place all of it runs, so without From 9d62a54c165731bf72397c65dd18eb67364ea8d2 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Mon, 16 Nov 2026 21:29:27 +0000 Subject: [PATCH 30/38] feat(ui)!: let a settings provider say how long it may take The timeout containing a slow provider was a module constant, so every provider shared one budget and a plugin needing longer had no way to ask. It is per registration now, through `options.timeout`, and the default drops from 2000ms to 500ms. A backstop rather than a budget: the menu shows nothing until every provider has answered, so a provider approaching half a second is one worth noticing, and the provider type now says so. The budget belongs with the provider it contains rather than with the editor, since a slow provider is a property of that provider. BREAKING CHANGE: a provider taking between 500ms and 2000ms is now left out of the menu unless it registers with a longer `timeout`. Co-Authored-By: Claude Opus 5 --- .../specs/block-settings/spec.md | 7 ++- openspec/changes/block-settings-ui/tasks.md | 2 + .../src/BlockSettings/BlockSettings.spec.ts | 51 +++++++++++++++++++ .../ui/src/BlockSettings/BlockSettings.ts | 27 +++++++--- 4 files changed, 80 insertions(+), 7 deletions(-) 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 cb06abd0..35aac33c 100644 --- a/openspec/changes/block-settings-ui/specs/block-settings/spec.md +++ b/openspec/changes/block-settings-ui/specs/block-settings/spec.md @@ -151,7 +151,7 @@ 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. 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. +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 @@ -183,6 +183,11 @@ Providers are third-party code, and the open menu is the one place all of it run - **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/tasks.md b/openspec/changes/block-settings-ui/tasks.md index 22c4f381..2a8b3090 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -124,3 +124,5 @@ - [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 diff --git a/packages/ui/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts index 43bbdc45..d27ba160 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.spec.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -39,6 +39,9 @@ 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; @@ -686,6 +689,54 @@ describe('BlockSettingsUI', () => { } }); + /** + * 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'); diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index a874718b..2a70962a 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -64,6 +64,10 @@ export interface BlockSettingsContext { * * 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 @@ -78,6 +82,12 @@ export interface BlockSettingsRegisterOptions { * 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; } /** @@ -116,7 +126,7 @@ declare module '@editorjs/sdk' { * 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 = 2000; +const PROVIDER_TIMEOUT_MS = 500; /** * A registered provider together with what it was registered with @@ -128,6 +138,8 @@ interface Registration { order: number; /** Registration counter, used to keep equal orders in registration sequence */ sequence: number; + /** How long this provider may take, in milliseconds */ + timeout: number; } /** @@ -510,6 +522,7 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { provider, order: options?.order ?? 0, sequence: this.#sequence++, + timeout: options?.timeout ?? PROVIDER_TIMEOUT_MS, }; this.#registrations.add(registration); @@ -643,9 +656,9 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { ); const contributions = await Promise.all( - ordered.map(async ({ provider }) => { + ordered.map(async ({ provider, timeout }) => { try { - const result = await this.#withTimeout(provider(context)); + const result = await this.#withTimeout(provider(context), timeout); if (result === undefined) { return []; @@ -691,9 +704,11 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { * 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 + result: BlockSettingsMenuConfig | undefined | Promise, + timeout: number ): Promise { let timer: ReturnType | undefined; @@ -702,8 +717,8 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { result, new Promise((_resolve, reject) => { timer = setTimeout( - () => reject(new Error(`A block settings provider did not return within ${PROVIDER_TIMEOUT_MS}ms`)), - PROVIDER_TIMEOUT_MS + () => reject(new Error(`A block settings provider did not return within ${timeout}ms`)), + timeout ); }), ]); From a1e68af563e5fbc79fd5ffd26020806473118394 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Mon, 16 Nov 2026 21:35:18 +0000 Subject: [PATCH 31/38] docs(ui): say that block settings must be registered after its host `ui:block-settings:rendered` is dispatched once from the constructor and never replayed, so a host registered after this plugin never hears it and the button and the menu stay off the page with nothing reported. Documented rather than fixed. `publicApi` is registered right after each plugin's constructor, so a getter for late mounting would work, but this is one instance of the general problem tracked on the board as "UI component registered before its parent never mounts", and solving it here for this one pair would leave the rest of it. Co-Authored-By: Claude Opus 5 --- .../changes/block-settings-ui/specs/block-settings/spec.md | 2 +- openspec/changes/block-settings-ui/tasks.md | 2 ++ packages/ui/src/BlockSettings/BlockSettings.ts | 4 ++++ 3 files changed, 7 insertions(+), 1 deletion(-) 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 35aac33c..4a857804 100644 --- a/openspec/changes/block-settings-ui/specs/block-settings/spec.md +++ b/openspec/changes/block-settings-ui/specs/block-settings/spec.md @@ -1,7 +1,7 @@ ## 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. 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. +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 diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index 2a8b3090..14954564 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -126,3 +126,5 @@ - [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 diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index 2a70962a..6344ffa0 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -198,6 +198,10 @@ function withIsolatedCallbacks(item: PopoverItemParams): PopoverItemParams { * 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'> { /** From ac6508d236ff71272860b6f8bac541d84f8de228 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Mon, 16 Nov 2026 21:37:19 +0000 Subject: [PATCH 32/38] fix(ui)!: leave the tool out of the provider context when it is unknown `tool` fell back to `''`, which matched no provider while looking like an answer. 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 -- worth showing in the type rather than papering over. Refusing to open was the other option: rejected, since the block does exist, and a menu that will not open turns a disagreement the user cannot see into one they cannot work around. BREAKING CHANGE: `BlockSettingsContext.tool` is optional, so a provider reading it as a string has to handle it being absent. Co-Authored-By: Claude Opus 5 --- .../specs/block-settings/spec.md | 2 +- openspec/changes/block-settings-ui/tasks.md | 2 ++ .../ui/src/BlockSettings/BlockSettings.spec.ts | 18 ++++++++++++++++++ packages/ui/src/BlockSettings/BlockSettings.ts | 11 ++++++++--- 4 files changed, 29 insertions(+), 4 deletions(-) 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 4a857804..d3f43a19 100644 --- a/openspec/changes/block-settings-ui/specs/block-settings/spec.md +++ b/openspec/changes/block-settings-ui/specs/block-settings/spec.md @@ -113,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`. 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: () => ... }))` diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index 14954564..c7cd9f48 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -128,3 +128,5 @@ - [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 diff --git a/packages/ui/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts index d27ba160..9ac6abbb 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.spec.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -278,6 +278,24 @@ describe('BlockSettingsUI', () => { }); }); + /** + * 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(() => ({ diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index 6344ffa0..267ea314 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -54,9 +54,14 @@ export interface BlockSettingsContext { blockIndex: number; /** - * Name of the tool rendering the block, for providers that only apply to some tools + * 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; + tool?: string; } /** @@ -616,7 +621,7 @@ export class BlockSettingsUI implements EditorjsPlugin<'block-settings'> { const items = await this.#collectItems({ blockId, blockIndex: index, - tool: this.#api.blocks.getToolByIndex(index) ?? '', + tool: this.#api.blocks.getToolByIndex(index), }); /** From e79eff988f3226c026ac143c154c42552246d067 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Mon, 16 Nov 2026 21:38:48 +0000 Subject: [PATCH 33/38] docs(ui): say when unregistering a settings provider takes effect Providers are asked as the menu is built, so a menu already on screen keeps the items it was built with until it closes. The existing behaviour, said out loud on `register` and in the spec. Co-Authored-By: Claude Opus 5 --- .../changes/block-settings-ui/specs/block-settings/spec.md | 2 +- openspec/changes/block-settings-ui/tasks.md | 2 ++ packages/ui/src/BlockSettings/BlockSettings.ts | 7 +++++-- 3 files changed, 8 insertions(+), 3 deletions(-) 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 d3f43a19..05eab212 100644 --- a/openspec/changes/block-settings-ui/specs/block-settings/spec.md +++ b/openspec/changes/block-settings-ui/specs/block-settings/spec.md @@ -113,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, 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`. 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: () => ... }))` diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index c7cd9f48..a538fa74 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -130,3 +130,5 @@ - [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 diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index 267ea314..edc06775 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -100,9 +100,12 @@ export interface BlockSettingsRegisterOptions { */ export interface BlockSettingsAPI { /** - * Registers a settings provider + * 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` among them + * @param options - registration options, `order` and `timeout` among them * @returns a function that unregisters the provider */ register(provider: BlockSettingsProvider, options?: BlockSettingsRegisterOptions): () => void; From 839dd52e3890740ffe11b20ee7555eb9a8679f63 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Mon, 16 Nov 2026 21:40:52 +0000 Subject: [PATCH 34/38] refactor(default-block-settings-plugin): collect the item titles in one module The titles were written inline where the items are built, while `@editorjs/ui` keeps its own user-facing strings in a catalogue. They live in a `messages.ts` of this package's own now, so localising them is a change to one module rather than to every item. 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. Co-Authored-By: Claude Opus 5 --- .../default-block-settings-plugin/spec.md | 2 +- openspec/changes/block-settings-ui/tasks.md | 2 ++ .../src/index.ts | 9 +++++---- .../src/messages.ts | 20 +++++++++++++++++++ 4 files changed, 28 insertions(+), 5 deletions(-) create mode 100644 packages/plugins/default-block-settings-plugin/src/messages.ts 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/tasks.md b/openspec/changes/block-settings-ui/tasks.md index a538fa74..fda02263 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -132,3 +132,5 @@ - [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 diff --git a/packages/plugins/default-block-settings-plugin/src/index.ts b/packages/plugins/default-block-settings-plugin/src/index.ts index 189060cd..c91a20d1 100644 --- a/packages/plugins/default-block-settings-plugin/src/index.ts +++ b/packages/plugins/default-block-settings-plugin/src/index.ts @@ -7,6 +7,7 @@ import type { } 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'; /** @@ -110,7 +111,7 @@ export class DefaultBlockSettingsPlugin implements EditorjsPlugin { return [ { name: 'move-up', - title: 'Move up', + title: messages.moveUp, icon: IconChevronUp, closeOnActivate: true, @@ -123,7 +124,7 @@ export class DefaultBlockSettingsPlugin implements EditorjsPlugin { }, { name: 'move-down', - title: 'Move down', + title: messages.moveDown, icon: IconChevronDown, closeOnActivate: true, isDisabled: blockIndex >= lastIndex, @@ -131,7 +132,7 @@ export class DefaultBlockSettingsPlugin implements EditorjsPlugin { }, { name: 'delete', - title: 'Delete', + title: messages.delete, icon: IconTrash, /** @@ -140,7 +141,7 @@ export class DefaultBlockSettingsPlugin implements EditorjsPlugin { */ confirmation: { name: 'delete-confirm', - title: 'Click to delete', + title: messages.deleteConfirmation, icon: IconCross, closeOnActivate: true, onActivate: () => this.#delete(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', +}; From 7664c08bdfad70e0b33eff8fc0395c8544e286a9 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Mon, 16 Nov 2026 21:42:22 +0000 Subject: [PATCH 35/38] fix(ui): stop the toolbar's plus button submitting a form The settings button declares itself non-submitting; the plus button beside it still defaulted to `submit`, so an editor mounted inside a form was posted when the toolbox was opened. Co-Authored-By: Claude Opus 5 --- openspec/changes/block-settings-ui/specs/ui/spec.md | 7 ++++++- openspec/changes/block-settings-ui/tasks.md | 2 ++ packages/ui/src/Toolbar/Toolbar.spec.ts | 6 ++++++ packages/ui/src/Toolbar/Toolbar.ts | 5 +++++ 4 files changed, 19 insertions(+), 1 deletion(-) diff --git a/openspec/changes/block-settings-ui/specs/ui/spec.md b/openspec/changes/block-settings-ui/specs/ui/spec.md index 323d7deb..101bffaa 100644 --- a/openspec/changes/block-settings-ui/specs/ui/spec.md +++ b/openspec/changes/block-settings-ui/specs/ui/spec.md @@ -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 @@ -31,7 +36,7 @@ The system SHALL provide `ToolbarUI`, which renders a floating toolbar with a pl 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 diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index fda02263..aa76a5ed 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -134,3 +134,5 @@ - [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` diff --git a/packages/ui/src/Toolbar/Toolbar.spec.ts b/packages/ui/src/Toolbar/Toolbar.spec.ts index fc7b6035..b46d9a6b 100644 --- a/packages/ui/src/Toolbar/Toolbar.spec.ts +++ b/packages/ui/src/Toolbar/Toolbar.spec.ts @@ -176,6 +176,12 @@ describe('ToolbarUI', () => { 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); diff --git a/packages/ui/src/Toolbar/Toolbar.ts b/packages/ui/src/Toolbar/Toolbar.ts index b87c1958..35e499d3 100644 --- a/packages/ui/src/Toolbar/Toolbar.ts +++ b/packages/ui/src/Toolbar/Toolbar.ts @@ -71,6 +71,11 @@ export class ToolbarUI implements EditorjsPlugin { actions: make('div', Style[css.actions]) as HTMLDivElement, 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, }; From d88683216bc96905e0dc86853dc9f5d9a56c89ba Mon Sep 17 00:00:00 2001 From: gohabereg Date: Mon, 16 Nov 2026 22:03:09 +0000 Subject: [PATCH 36/38] refactor(ui): walk the popover item union instead of a plain record The item walk went through `Record`, which dropped the types: the wrapper's parameters were `unknown[]`, a misspelled key would have compiled, and the variants that forbid `onActivate` were written through a string key regardless. It narrows the union now. Half again as long -- five branches, two helpers and a named patch type, the last because the lint config rejects an inline object return type -- and one cast is left on the confirmation state, since the walk returns the wide union while that field holds the base variant. The `typeof` guard on `onActivate` matters: ui-kit optional-chains it, so an item without one at runtime is legal, and without the guard it would be given a wrapper that throws on click. Co-Authored-By: Claude Opus 5 --- openspec/changes/block-settings-ui/tasks.md | 1 + .../ui/src/BlockSettings/BlockSettings.ts | 102 ++++++++++++------ 2 files changed, 72 insertions(+), 31 deletions(-) diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index aa76a5ed..61790d19 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -136,3 +136,4 @@ - [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 diff --git a/packages/ui/src/BlockSettings/BlockSettings.ts b/packages/ui/src/BlockSettings/BlockSettings.ts index edc06775..3713ef52 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.ts @@ -9,7 +9,7 @@ import type { EventBus } from '@editorjs/sdk'; import { UiComponentType } from '@editorjs/sdk'; -import type { PopoverItemChildren, PopoverItemParams } from '@editorjs/ui-kit'; +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'; @@ -155,51 +155,91 @@ interface Registration { * 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 { - const resolved: Record = { ...item }; - - if (typeof resolved.isActive === 'function') { - resolved.isActive = (resolved.isActive as () => boolean)(); - } +/** + * Signature ui-kit calls a contributed item's handler with + */ +type ItemActivate = (activated: PopoverItemParams, event?: PointerEvent) => void; - const activate = resolved.onActivate; +/** + * 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 { /** - * Wrapped rather than resolved: this one runs on a click, inside ui-kit's own handler, which goes on to honour - * `closeOnActivate` after it returns -- so a throw escaping here abandons the rest of that sequence + * What the item's `isActive` callback returned, absent when it carried none */ - if (typeof activate === 'function') { - resolved.onActivate = (...args: unknown[]): void => { - try { - (activate as (...callArgs: unknown[]) => void)(...args); - } catch (error) { - console.error('[BlockSettingsUI] A block settings item failed on activation', error); - } - }; + 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 {}; } - const children = resolved.children as PopoverItemChildren | undefined; + 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 { /** - * Nested items render with their parent, so their callbacks are called just as early + * A separator carries no behaviour at all */ - if (children?.items !== undefined) { - resolved.children = { - ...children, - items: children.items.map(withIsolatedCallbacks), + 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), + }, }; } - const confirmation = resolved.confirmation as PopoverItemParams | undefined; + if ('confirmation' in item) { + return { + ...item, + ...resolvedActiveState(item), + confirmation: withIsolatedCallbacks(item.confirmation) as PopoverItemDefaultBaseParams, + }; + } - /** - * The confirmation state replaces the item's own params on activation and renders from them the same way - */ - if (confirmation !== undefined) { - resolved.confirmation = withIsolatedCallbacks(confirmation); + if ('onActivate' in item && typeof item.onActivate === 'function') { + return { + ...item, + ...resolvedActiveState(item), + onActivate: guarded(item.onActivate), + }; } - return resolved as PopoverItemParams; + return { + ...item, + ...resolvedActiveState(item), + }; } /** From 09670a3edccb021d05877445ae0035b6533d8542 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Mon, 16 Nov 2026 22:15:40 +0000 Subject: [PATCH 37/38] test(ui): reopen the settings menu from the keyboard after the caret moved The last of the cases the review asked for: the caret leaves the block the open menu belongs to, and the menu is reopened without a pointer ever being used. The other three arrived with the fixes for the stale target, the rebuilt menu and the throwing handler. Co-Authored-By: Claude Opus 5 --- openspec/changes/block-settings-ui/tasks.md | 1 + .../src/BlockSettings/BlockSettings.spec.ts | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/openspec/changes/block-settings-ui/tasks.md b/openspec/changes/block-settings-ui/tasks.md index 61790d19..831ca5fe 100644 --- a/openspec/changes/block-settings-ui/tasks.md +++ b/openspec/changes/block-settings-ui/tasks.md @@ -137,3 +137,4 @@ - [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/packages/ui/src/BlockSettings/BlockSettings.spec.ts b/packages/ui/src/BlockSettings/BlockSettings.spec.ts index 9ac6abbb..2c5c110c 100644 --- a/packages/ui/src/BlockSettings/BlockSettings.spec.ts +++ b/packages/ui/src/BlockSettings/BlockSettings.spec.ts @@ -1034,6 +1034,29 @@ describe('BlockSettingsUI', () => { 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', From 29139a7a5f326089d736f145cf5f5fe710301384 Mon Sep 17 00:00:00 2001 From: gohabereg Date: Mon, 16 Nov 2026 22:25:40 +0000 Subject: [PATCH 38/38] ci(ui): limit the workflow's token permissions and run it in the merge queue CodeQL flagged the workflow this change adds for not restricting `GITHUB_TOKEN`, so the job inherited the repository default rather than the four scopes a package check needs (code-scanning alert 52). It now declares the same block as `default-block-settings-plugin.yml`, the sibling added by this same change, and gains the `merge_group` trigger it was also missing, so the UI package is checked in the merge queue as well as on a pull request. No `include-mutations`: `packages/ui` has no Stryker config. Co-Authored-By: Claude Opus 5 --- .github/workflows/ui.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index ef3c7680..4f9bc02b 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -1,6 +1,13 @@ name: UI check on: pull_request: + merge_group: + +permissions: + contents: read + pull-requests: write + issues: write + actions: read jobs: package-check: