Skip to content

feat(core): add editor destroy lifecycle - #196

Merged
gohabereg merged 15 commits into
mainfrom
feat/editor-destroy-lifecycle
Nov 18, 2026
Merged

gohabereg merged 15 commits into
mainfrom
feat/editor-destroy-lifecycle

Conversation

@gohabereg

@gohabereg gohabereg commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

Why

First implementation step of the editor-destroy OpenSpec change (spec PR #195, the base of this one). Adds the editor teardown lifecycle and the API changes it needs; the adapters/UI/plugins side follows in a stacked PR.

What Changes

  • Core#destroy(): plugins in reverse construction order (destroy?.() + PluginRegistry.unregister), then UndoRedoManager, SelectionManager, BlockRenderer, the adapter (destroy?.(), made required in the next PR along with DOMAdapters.destroy()), and last ToolsManager. Each step runs through a helper that logs and continues. Services resolved in initialize() are recorded in #services, so teardown never constructs one. A second call is a no-op because instances and services are cleared. use()/initialize() throw afterwards. Core's onModelUpdate model listener goes through a controller that destroy() aborts, so a model the integrator kept no longer reaches the callback after teardown.
  • Interrupted initialize() rejects with a DOMException named AbortError instead of booting the document or dispatching core:ready. ToolsManager owns an AbortController that its destroy() aborts. Its preparation queue checks that signal before and after each tool's prepare(). Tools still queued are never prepared, and a tool whose prepare() settles after destroy is never created, registered or announced with ToolLoaded. A prepare() already running can't be interrupted, because it takes no signal, so its result is dropped.
  • EditorJS#destroy() delegates to Core. The bundle attaches reportUnlessAborted() to its ready promise: AbortError is ignored and other init errors are logged, so nothing is reported as an unhandled rejection. Awaiting isReady still rejects.
  • BlockRenderer keeps each block's tool instance and destroys it on block removal and on teardown. A render that settles after teardown dispatches nothing.
  • Tool contracts: optional destroy() on BlockTool/InlineTool, called once per instance by its owner:
    • Block tools: BlockRenderer owns each per-block instance.
    • Inline tools: InlineToolFacade.create() returns one cached instance per tool, shared by formatting, selection, validation and the inline toolbar. None of those consumers destroys it. The facade's new destroy() does, once and only if the instance was ever created, and ToolsManager.destroy() calls it for every inline tool, logging a throwing hook and moving on to the next.
  • Listeners through AbortController: onUpdate/onCaretUpdate subscribe through their own controller (signatures unchanged). UndoRedoManager, SelectionManager and BlockRenderer abort one controller each. BlockToolAdapter owns its controller and exposes protected signal to subclasses. EditorJSModel's typed addEventListener overloads accept options.
  • OpenSpec: the spec revisions behind these fixes (D3, D4, D7, and the new core and sdk scenarios) are in docs(openspec): propose editor-destroy #195 and merged into this branch. This PR only checks off their tasks.

Verification

  • Full workspace build, lint and tests pass.
  • Mutation testing on every line this PR adds (Stryker scoped to the diff, -w): all mutants killed in core, and in sdk/editorjs via an ad-hoc run (those packages have no Stryker config). model changes are type-only. The packages' own yarn test:mutations pass.
  • Tests cover:
    • teardown order, including inline tools after the adapter; error logging; idempotency
    • destroy before and during initialization, including tools still queued and a prepare() that settles after destroy
    • late renders
    • tool instance destruction: each shared inline instance destroyed exactly once, and never by SelectionManager or ToolsManager validation
    • the AbortError handling, including that it is not left unhandled
    • onModelUpdate after destroy

Notes

  • ToolsManager's inline-tool render check is pinned by tests as-is; removing it is tracked on the board ("Remove inverted inline tool render check in ToolsManager").
  • The integration tasks (real DOM, several editors per page) are covered by the e2e suite in feat: implement destroy() in adapters and plugins #207.

Stack

  1. docs(openspec): propose editor-destroy #195 spec
  2. This PR
  3. feat: implement destroy() in adapters and plugins #207 adapters, plugins, e2e tests and the archive (stacked on this one)

🤖 Generated with Claude Code

gohabereg and others added 4 commits October 6, 2026 18:13
Add the editor-destroy change: Core/EditorJS destroy() lifecycle,
optional destroy() on tools, required destroy() on the adapter plugin,
and a repo-wide rule that listeners are released through AbortController
(owned by SDK base classes where they exist).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Core#destroy(): destroys plugins in reverse construction order and
  unregisters their public APIs, then UndoRedoManager, SelectionManager,
  BlockRenderer and the adapter. Idempotent, safe before and during
  initialize(), never mutates the model. use()/initialize() throw after it.
- EditorJS#destroy() delegates to Core.
- BlockRenderer keeps each block's tool instance and destroys it on block
  removal and on teardown; a render settling after teardown is dropped.
- Optional destroy() on BlockTool/InlineTool; throwaway inline tool
  instances (SelectionManager, ToolsManager validation) are destroyed
  right after use.
- Listeners are released through AbortController: onUpdate/onCaretUpdate
  subscribe through their own controller, BlockToolAdapter owns one and
  exposes a protected signal to subclasses, core services abort theirs
  on destroy. Model addEventListener overloads accept options.

Part of the editor-destroy OpenSpec change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Cover teardown error logging, services that were never resolved, an
  adapter without destroy(), and blocks removed without a tracked tool.
- Cover ToolsManager inline tool validation around the destroyed
  validation instance.
- Drop the redundant destroyed guard in Core.destroy(): clearing plugin
  instances and services already makes a second call a no-op.
- Drop { once: true } on the BlockToolAdapter abort listener: a signal
  aborts only once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tError

- Core.initialize() rejects with a DOMException named AbortError when
  destroy() runs while tools are being prepared, instead of resolving.
- The EditorJS bundle handles its own ready promise: an AbortError is
  ignored, any other initialization error is logged, so neither is
  reported as an unhandled rejection. Awaiting isReady still rejects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Unit Tests

Package Coverage Delta
@editorjs/shortcuts-plugin 100% 0% ⚪️
@editorjs/collaboration-manager 87.58% 0% ⚪️
@editorjs/clipboard-plugin 66.66% 0% ⚪️
@editorjs/dom-adapters 86.95% 0% ⚪️
@editorjs/editorjs 100% 0% ⚪️
@editorjs/ot-server 20% 0% ⚪️
@editorjs/model 98.61% 0% ⚪️
@editorjs/core 81.37% +3.32% 🟢
@editorjs/model-types N/A N/A
@editorjs/ui 71.15% 0% ⚪️
@editorjs/default-block-settings-plugin 100% 0% ⚪️

Mutation Tests

Package Mutation score Dashboard URL
@editorjs/shortcuts-plugin No files to mutate found.
@editorjs/clipboard-plugin No files to mutate found.
@editorjs/dom-adapters No files to mutate found.
@editorjs/model NaN% Dashboard
@editorjs/collaboration-manager No files to mutate found.
@editorjs/core 75.92% 🟡 Dashboard
@editorjs/default-block-settings-plugin No files to mutate found.

gohabereg and others added 3 commits October 6, 2026 18:30
#174 now covers teardown for every UI plugin (listeners, holders,
popovers, the EditorjsUI wrapper, pending inline toolbar config). Drop
the ui delta and the UI tasks; keep only InlineToolbarUI destroying its
inline tool instances, done after #174 lands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* The document model is left untouched, so no removal reaches undo history or collaboration.
* Safe to call more than once and while {@link initialize} is pending. After it, `use()` and `initialize()` throw
*/
public destroy(): void {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

destroy() never releases the onModelUpdate listener registered in the constructor.

It is this.#model.addEventListener(EventType.Changed, ...) with no signal, and teardown does not call removeEventListener for it. The other listeners in this PR are tied to an AbortController and aborted here. This one stays for as long as the model is reachable.

destroy() does not mutate the model, so the callback does not run during teardown itself. It does run on any later change: something still holding api, or a collaboration op that arrives after unmount. The integrator passed that callback and then unmounted, so it fires into a tree that is already gone.

Abort it from here, same as the service listeners.

Comment thread packages/core/src/index.ts Resolved
gohabereg and others added 2 commits November 4, 2026 18:38
…cade

InlineToolFacade.create() hands the same cached instance to every
consumer, but ToolsManager's validation and SelectionManager destroyed
it after each use, so a tool with a destroy() hook was torn down at
startup and after every formatting action, and then used again.

- InlineToolFacade.destroy() destroys the shared instance once, dropping
  it before the hook runs.
- ToolsManager.destroy() destroys every inline tool facade; a throwing
  hook is logged and the remaining tools are still destroyed.
- Core.destroy() calls it last, after the adapter, since the adapter and
  the UI use the instances until then.
- Validation and SelectionManager.applyInlineTool no longer destroy the
  instance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Core registered its onModelUpdate model listener without a way to remove
it. An integrator that kept the model it was handed could still reach
the callback after teardown. The listener now uses Core's own controller,
which destroy() aborts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
gohabereg and others added 4 commits November 4, 2026 23:59
Review on #196 found that the tool preparation queue kept running after
destroy(). Tools still queued were prepared, and a tool whose prepare()
settled after teardown was created and announced. D4 now describes the
fix: ToolsManager owns an AbortController that destroy() aborts, and
each queued job checks it before and after prepare(). A prepare()
already running can't be interrupted, so its result is dropped.

The core scenario for a destroy during a pending initialize() covers
it, and task 6.5 tracks the implementation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review on #195 pointed out that InlineToolFacade.create() returns one
cached instance per tool. Formatting, selection, validation and the
inline toolbar all share it, so the cleanup D7 proposed would destroy
tools still in use, several times over.

- Design: D7 is rewritten. Each inline tool's facade owns its shared
  instance, and ToolsManager destroys it once, as the last step of
  teardown. Both rejected alternatives are explained. D3 gains the
  ToolsManager step and D5 the FormattingAdapter change. The context
  table and the #174 risk are updated.
- Specs: the SDK teardown hook requirement states the rule, with a
  facade scenario. Core gains a scenario for shared inline instances
  destroyed last, once each. The dom-adapters formatting scenario no
  longer destroys them.
- The proposal and tasks 4.3, 4.4, 5.4 and 7.2 are updated to match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The tool preparation queue kept running after destroy(). Tools still
queued were prepared, and a tool whose prepare() settled after teardown
was created, registered and announced with ToolLoaded. Its inline
instance then outlived ToolsManager.destroy().

ToolsManager now owns an AbortController that destroy() aborts. Each
queued job checks the signal before calling prepare() and again once it
settles. A prepare() already running can't be interrupted, since it
takes no signal, so its result is dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts:
#	openspec/changes/editor-destroy/tasks.md
@gohabereg
gohabereg force-pushed the feat/editor-destroy-lifecycle branch from a8c4898 to b17b8ea Compare November 5, 2026 00:00
Base automatically changed from feat/editor-destroy to main November 8, 2026 13:50
@neSpecc
neSpecc requested a balanced review from Copilot November 18, 2026 11:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved lifecycle bugs allow initialization and tool events after destruction, recursive teardown, and missed cleanup of plugin and tool instances.

8 open issues
What changed in this PR

Adds the core editor teardown lifecycle and supporting SDK APIs, implementing the first stage of the editor-destroy design from #195. Adapter/plugin cleanup and integration coverage follow in #207.

Changes:

  • Adds Core.destroy() and EditorJS.destroy(), ordered resource cleanup, and ownership of block and shared inline tool instances.
  • Uses abort signals for listener cleanup and interrupted tool preparation, with readiness rejection handling.
  • Adds lifecycle tests and OpenSpec requirements, design notes, and task tracking.
File Description
packages/​sdk/​src/​tools/​facades/​InlineToolFacade.ts Adds shared inline-instance teardown.
packages/​sdk/​src/​tools/​facades/​InlineToolFacade.spec.ts Tests singleton ownership and destruction.
packages/​sdk/​src/​entities/​ToolDestroy.spec.ts Tests optional tool teardown contracts.
packages/​sdk/​src/​entities/​InlineTool.ts Declares the optional destroy hook.
packages/​sdk/​src/​entities/​BlockToolAdapter.ts Adds an inherited abort signal for cleanup.
packages/​sdk/​src/​entities/​BlockToolAdapter.spec.ts Tests base and subclass listener cleanup.
packages/​sdk/​src/​entities/​BlockTool.ts Explicitly declares the destroy hook.
packages/​model/​src/​EditorJSModel.ts Allows options in typed listener registrations.
packages/​editorjs/​src/​reportUnlessAborted.ts Handles readiness rejections without swallowing them for callers.
packages/​editorjs/​src/​reportUnlessAborted.spec.ts Tests abort suppression and error logging.
packages/​editorjs/​src/​index.ts Exposes destroy and handles readiness failures.
packages/​editorjs/​src/​index.spec.ts Tests destroy delegation and readiness rejection behavior.
packages/​core/​src/​tools/​ToolsManager.ts Adds preparation cancellation and inline-tool teardown.
packages/​core/​src/​tools/​ToolsManager.spec.ts Tests tool cancellation, ownership, and teardown.
packages/​core/​src/​index.ts Tracks resources and implements ordered editor teardown.
packages/​core/​src/​index.spec.ts Tests teardown order, errors, and initialization interruption.
packages/​core/​src/​components/​UndoRedoManager.ts Uses an abort controller for listener cleanup.
packages/​core/​src/​components/​UndoRedoManager.spec.ts Updates cleanup tests for abort signals.
packages/​core/​src/​components/​SelectionManager.ts Adds caret-listener teardown.
packages/​core/​src/​components/​SelectionManager.spec.ts Tests cleanup and shared inline-tool ownership.
packages/​core/​src/​components/​BlockRenderer.ts Tracks and destroys block tools; suppresses renders after teardown.
packages/​core/​src/​components/​BlockRenderer.spec.ts Tests block cleanup and pending renders.
packages/​core/​src/​api/​SelectionAPI.ts Uses a controller per caret subscription.
packages/​core/​src/​api/​SelectionAPI.spec.ts Tests caret subscription cancellation.
packages/​core/​src/​api/​DocumentAPI/​DocumentAPI.ts Uses a controller per document subscription.
packages/​core/​src/​api/​DocumentAPI/​DocumentAPI.spec.ts Tests document subscription cancellation.
openspec/​changes/​editor-destroy/​tasks.md Tracks completed and deferred implementation tasks.
openspec/​changes/​editor-destroy/​specs/​sdk/​spec.md Defines tool and adapter teardown contracts.
openspec/​changes/​editor-destroy/​specs/​editorjs-bundle/​spec.md Defines bundle teardown and readiness behavior.
openspec/​changes/​editor-destroy/​specs/​dom-adapters/​spec.md Specifies adapter cleanup for the follow-up work.
openspec/​changes/​editor-destroy/​specs/​core/​spec.md Defines core teardown and block lifecycle requirements.
openspec/​changes/​editor-destroy/​specs/​architecture/​spec.md Establishes abort-controller listener cleanup rules.
openspec/​changes/​editor-destroy/​proposal.md Describes teardown goals and affected capabilities.
openspec/​changes/​editor-destroy/​design.md Documents ownership, ordering, and cancellation decisions.
openspec/​changes/​editor-destroy/​.openspec.yaml Adds OpenSpec change metadata.

Review effort: Balanced

this.#controller.abort();

for (const id of this.#blocks.keys()) {
this.#releaseBlock(id);
/**
* The renderer was destroyed while the block was rendering, so the block is already released
*/
if (this.#controller.signal.aborted) {
this.#iocContainer.get(UndoRedoManager);
this.#services.undoRedoManager = this.#iocContainer.get(UndoRedoManager);

this.#model.initializeDocument({ blocks });
Comment thread packages/core/src/index.ts Resolved
Comment on lines +393 to +394
this.#pluginInstances.push({ name: plugin.name,
instance });
Comment thread packages/core/src/tools/ToolsManager.ts Outdated
public destroy(): void {
this.#controller.abort();

const facades = new Set([...this.#availableTools.values(), ...this.#unavailableTools.values()]);
Comment on lines +174 to +176
if (signal.aborted) {
return;
}
Comment on lines +193 to +195
if (signal.aborted) {
return;
}

@neSpecc neSpecc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot's comments are valid — please address them, especially the remove-during-render race in BlockRenderer.

public destroy(): void {
const instance = this.#instance;

this.#instance = undefined;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After destroy() the next create() silently builds a fresh instance that nobody will ever destroy (e.g. a late listener firing after teardown). Maybe keep a #destroyed flag and throw or return early from create() once the facade is destroyed?

Comment thread packages/editorjs/src/index.ts Outdated
}

/**
* Tears the editor down: removes its DOM, closes the collaboration connection, and releases plugins and tools.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This says destroy() removes the DOM and closes the collaboration connection, but both land only in #207. If this merges first, the doc overpromises. Either soften it here or make sure #196 and #207 ship together.

gohabereg and others added 2 commits November 18, 2026 19:35
…ifecycle

# Conflicts:
#	openspec/changes/editor-destroy/tasks.md
#	packages/core/src/index.spec.ts
- BlockRenderer: after render() settles, it dispatches only if the
  instance is still the one tracked for its block. A block removed while
  rendering, or removed and added again as a move does, no longer
  publishes UI from a destroyed instance. A throwing block adapter is
  logged, so the remaining blocks are still released.
- Core.destroy() returns at once when already destroying, so a plugin
  whose destroy() calls it again no longer recurses.
- initialize() rejects with an AbortError when a plugin constructor
  destroys the editor (that plugin is destroyed, and no later plugin is
  constructed), and when onModelUpdate destroys it during document
  initialization, instead of dispatching core:ready.
- ToolsManager checks its signal for every tool, including those
  without prepare(), and when a prepare() rejects after destroy, so no
  fallback facade is built. It keeps every inline facade it creates in
  its own set, so a tool registered twice or a facade replaced after a
  failed validation still has its instance destroyed.
- InlineToolFacade.create() throws once the facade is destroyed, rather
  than building an instance nobody would destroy.
- EditorJS.destroy()'s comment no longer promises behaviour that depends
  on #207.

Design D3, D4 and D7, the core and sdk scenarios and the tasks are
updated to match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@gohabereg
gohabereg requested a review from neSpecc November 18, 2026 20:28
@gohabereg
gohabereg added this pull request to the merge queue Nov 18, 2026
Merged via the queue into main with commit 7565998 Nov 18, 2026
94 checks passed
@gohabereg
gohabereg deleted the feat/editor-destroy-lifecycle branch November 18, 2026 20:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants