Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
chore(skills): add CKEditor 5 plugin development skill
Elian Doranb4cceffaa98f
diff --git a/.claude/skills/ckeditor5-plugin-development/SKILL.md b/.claude/skills/ckeditor5-plugin-development/SKILL.mdnew file mode 100644index 0000000000..a4e899ed34--- /dev/null+++ b/.claude/skills/ckeditor5-plugin-development/SKILL.md@@ -0,0 +1,198 @@+---+name: ckeditor5-plugin-development+description: >-+ Write, extend, and review CKEditor 5 plugins. Use when building or reviewing a+ CKEditor 5 feature/plugin, or when working with the editing engine (model,+ view, schema, conversion/upcast-downcast), commands, the UI library+ (buttons, dropdowns, dialogs, balloons, toolbars), widgets (block/inline,+ toWidget, nested editables), keystrokes, localization (t()), or scaffolding a+ ckeditor5-* package. Covers the architecture, idiomatic patterns, code-style+ conventions, and a review checklist distilled from the official docs.+---++# CKEditor 5 plugin development++CKEditor 5 is **plugin-based**: every feature — even typing and `<p>` support — is a+plugin. Without plugins the editor is an empty API. This skill distills how to write+new plugins and review existing ones idiomatically.++## When to use this skill++Use it whenever the task involves a CKEditor 5 plugin/feature: creating one, extending+one, debugging editing behavior, or reviewing plugin code for correctness and+convention compliance. Trigger concepts include: model/view/schema, conversion+(upcast/downcast), `Command`, `editor.model.change()`, `ButtonView`/`componentFactory`,+widgets (`toWidget`), `ContextualBalloon`/`Dialog`, `editor.keystrokes`, `t()`+localization, or a `ckeditor5-*` npm package.++## The three pillars++1. **Core editor architecture** (`@ckeditor/ckeditor5-core`) — glue classes: `Editor`,+ `Plugin`, `Command`, plus the event/observable system.+2. **Editing engine** (`@ckeditor/ckeditor5-engine`) — the custom MVC data **model**, the+ **view** (virtual DOM), **schema**, and **conversion** between them. The biggest piece.+3. **UI library** (`@ckeditor/ckeditor5-ui`) — MVC views, templates, and components+ (buttons, dropdowns, dialogs, toolbars).++Mental model of the engine: there is **one model document** that is **converted** into two+views — the **editing view** (what the user sees/edits) and the **data view** (input/output+for `getData()`/`setData()`/paste). You almost always change the **model**; converters+render it to the view. Never hand-edit the view to represent model state.++```+data (HTML) ──upcast──▶ MODEL ──editing downcast──▶ editing view ──render──▶ DOM (contentEditable)+ │+ └────data downcast──────▶ data view ──▶ getData()/output HTML+```++## Plugin anatomy++A plugin implements `PluginInterface`; the easy way is to extend `Plugin`. A plain function+`function MyPlugin( editor ) {}` also works for trivial cases.++```js+import { Plugin } from 'ckeditor5';++export default class MyPlugin extends Plugin {+ // Dependencies — the editor loads these automatically before this plugin.+ static get requires() {+ return [ SomeDependency ];+ }++ // Stable name for editor.plugins.get( 'MyPlugin' ) and dependency wiring.+ // In TypeScript: return 'MyPlugin' as const;+ static get pluginName() {+ return 'MyPlugin';+ }++ init() {+ const editor = this.editor; // the editor that loaded this plugin+ // Register schema, converters, commands, UI, keystrokes, listeners…+ }++ afterInit() {+ // Runs after ALL plugins' init(). Use it when you depend on another+ // plugin's runtime state (e.g. registering a widget toolbar).+ }++ // init()/afterInit() may return a Promise. Plugin extends a base that provides+ // destroy() and this.listenTo()/this.stopListening() (auto-cleaned on destroy).+}+```++Key rules (from the official conventions):++- Every feature is a plugin; plugins are **highly granular** and should know **as little+ about other plugins as possible** (communicate via commands, events, and the schema).+- **Split editing from UI.** The standard pattern is three plugins:+ - `Feature` — the **glue** plugin: `static get requires() { return [ FeatureEditing, FeatureUI ]; }`+ - `FeatureEditing` — schema, conversion, commands (works headless / server-side).+ - `FeatureUI` — buttons, dropdowns, balloons registered in `componentFactory`.+ This enables reuse (someone can take your editing layer and write a different UI).+- Register UI in `editor.ui.componentFactory.add( 'name', locale => view )`, then the user+ adds `'name'` to their `toolbar` config.+- Make features self-configuring: pre-configure the schema and provide config defaults via+ `editor.config.define( 'feature', { … } )`, read with `editor.config.get( 'feature.key' )`.++## Minimal end-to-end example (inline text attribute)++A "highlight" feature = a `$text` attribute ↔ `<mark>` element, a command, a button, a+keystroke. This is the canonical shape for inline styling features.++```js+import { Plugin, Command, ButtonView } from 'ckeditor5';++class HighlightCommand extends Command {+ refresh() {+ const { document, schema } = this.editor.model;+ this.value = document.selection.getAttribute( 'highlight' );+ this.isEnabled = schema.checkAttributeInSelection( document.selection, 'highlight' );+ }+ execute() {+ const model = this.editor.model;+ const selection = model.document.selection;+ const newValue = !this.value;+ model.change( writer => {+ if ( !selection.isCollapsed ) {+ for ( const range of model.schema.getValidRanges( selection.getRanges(), 'highlight' ) ) {+ newValue ? writer.setAttribute( 'highlight', true, range )+ : writer.removeAttribute( 'highlight', range );+ }+ }+ newValue ? writer.setSelectionAttribute( 'highlight', true )+ : writer.removeSelectionAttribute( 'highlight' );+ } );+ }+}++export default class Highlight extends Plugin {+ init() {+ const editor = this.editor;++ // 1. Schema: allow the attribute on text.+ editor.model.schema.extend( '$text', { allowAttributes: 'highlight' } );++ // 2. Conversion: model attribute 'highlight' <-> view <mark>.+ editor.conversion.attributeToElement( { model: 'highlight', view: 'mark' } );++ // 3. Command.+ editor.commands.add( 'highlight', new HighlightCommand( editor ) );++ // 4. UI button, reactive to command state.+ editor.ui.componentFactory.add( 'highlight', locale => {+ const button = new ButtonView( locale );+ const command = editor.commands.get( 'highlight' );+ button.set( { label: editor.t( 'Highlight' ), withText: true, isToggleable: true, tooltip: true } );+ button.bind( 'isOn', 'isEnabled' ).to( command, 'value', 'isEnabled' );+ button.on( 'execute', () => { editor.execute( 'highlight' ); editor.editing.view.focus(); } );+ return button;+ } );++ // 5. Keystroke.+ editor.keystrokes.set( 'Ctrl+Alt+H', 'highlight' );+ }+}+```++The same five steps (schema → conversion → command → UI → keystroke) recur in almost every+feature. For elements/objects/widgets you `schema.register(...)` and use `elementToElement`+converters instead of `attributeToElement`; see `references/widgets.md`.++## Development workflow++- **Scaffold a distributable package** with the package generator (`npx ckeditor5-package-generator`).+ See `references/tooling-and-packaging.md`. For a quick local feature you can just add a+ plugin class to an existing project.+- **Always reach for the CKEditor 5 Inspector** while developing — it shows the live model,+ view, schema, commands, and selection. `import CKEditorInspector from '@ckeditor/ckeditor5-inspector'; CKEditorInspector.attach( editor );`+- **Change the model, not the DOM.** Wrap all model mutations in `editor.model.change( writer => … )`+ (one block = one undo step). Use `editor.editing.view.change()` only for view-only state+ (e.g. focus class) that the model does not represent.+- **Verify** with `editor.getData()` / `editor.setData()` and by exercising selection edge+ cases (collapsed vs. ranged, inside objects/limits).++## Reference map++Load the focused reference for the task at hand:++| File | Use it for |+|------|-----------|+| `references/architecture.md` | Model, view, schema, positions/ranges/selections, markers, the event/observable system, binding. The conceptual foundation. |+| `references/conversion.md` | Upcast/downcast pipelines, conversion helpers, custom (callback) converters, attribute/element/marker conversion, position mapping. |+| `references/commands.md` | `Command` patterns: `refresh()`/`execute()`, state (`value`/`isEnabled`), `forceDisabled()`, `affectsData`, command events. |+| `references/ui-and-localization.md` | Views & templates, component catalog (buttons, inputs, dropdowns, dialogs/modals, balloons, toolbars), icons, `componentFactory`, focus/keystroke management, and `t()` localization. |+| `references/widgets.md` | Block & inline widgets: `toWidget`/`toWidgetEditable`, nested editables, `insertObject`, widget toolbars, view↔model position mapping, custom properties. |+| `references/conventions.md` | Naming, file/CSS/BEM rules, imports, JSDoc/visibility, `CKEditorError`, TypeScript rules. For writing idiomatic code and reviewing. |+| `references/tooling-and-packaging.md` | Package generator, `ckeditor5-metadata.json`, build output/integration, custom editor creators, dev-repo setup, the Inspector. |+| `references/review-checklist.md` | A structured checklist for reviewing an existing plugin (architecture, schema, conversion, commands, UI, a11y, conventions). |+| `references/recipes.md` | Task-oriented how-tos: insert content, find/iterate nodes, custom observers, place caret, extend other plugins' UI, etc. |++## Quick review checklist (summary)++When reviewing a plugin, confirm: editing/UI split with a glue plugin; `static get requires()`+and `pluginName` present; schema registered/extended and the feature self-configures; symmetric+upcast + (data & editing) downcast converters; a `Command` whose `refresh()` sets `isEnabled`+correctly (disabled where the schema disallows it); UI bound to command state and refocusing the+editing view on execute; keyboard accessibility (keystrokes + `accessibility.addKeystrokeInfos`);+all user-facing strings wrapped in `t()`; model changes inside `model.change()`; cleanup of+trackers/handlers in `destroy()`. Full version: `references/review-checklist.md`.diff --git a/.claude/skills/ckeditor5-plugin-development/references/architecture.md b/.claude/skills/ckeditor5-plugin-development/references/architecture.mdnew file mode 100644index 0000000000..fc3747dc36--- /dev/null+++ b/.claude/skills/ckeditor5-plugin-development/references/architecture.md@@ -0,0 +1,235 @@+# Architecture: core, model, view, schema, events++The conceptual foundation. Read this before working on editing behavior.++## Editor classes++`Editor` (`module:core/editor/editor~Editor`) is the entry point that glues everything.+Editors are created with the **static async** `create()` (constructors are protected).+Built-in types: `ClassicEditor`, `InlineEditor`, `BalloonEditor`, `DecoupledEditor`; you may+implement your own (see `tooling-and-packaging.md` → custom editor creators).++Key properties:++- `editor.config` — configuration object (`config.define()`, `config.get('feature.key')`).+- `editor.plugins` / `editor.commands` — collections of loaded plugins / commands.+- `editor.model` — the data model (entry point to the engine).+- `editor.data` — the **data controller** (data pipeline: `getData`/`setData`, processors).+- `editor.editing` — the **editing controller** (editing pipeline; `editor.editing.view`).+- `editor.keystrokes` — `EditingKeystrokeHandler`; bind keystrokes to commands.+- `editor.ui` — UI controller (`editor.ui.componentFactory`, `editor.ui.view`).+- `editor.accessibility` — register keystroke info for the a11y help dialog.++Key methods: `create()`, `destroy()` (returns a Promise — `await` it), `execute( 'cmd', …args )`,+`setData()`/`getData()` (format controlled by the data processor — not necessarily HTML; e.g.+Markdown via a custom `DataProcessor`).++## The model++A DOM-like tree of **elements** and **text nodes** living in a `document` with `roots`,+`selection`, and change `history`. Unlike the DOM, **both elements and text nodes can have+attributes**. Access:++```js+editor.model; // Model+editor.model.document; // ModelDocument+editor.model.document.getRoot(); // root element+editor.model.document.selection; // ModelDocumentSelection+editor.model.schema; // ModelSchema+```++### Changing the model — always via the writer++Structure, selection, and node creation happen **only** through the `ModelWriter`, available+inside `model.change()` / `model.enqueueChange()`:++```js+editor.model.change( writer => {+ writer.insertText( 'foo', editor.model.document.selection.getFirstPosition() );+} );++editor.model.change( writer => {+ for ( const range of editor.model.document.selection.getRanges() ) {+ writer.setAttribute( 'bold', true, range );+ }+} );+```++- All changes in one `change()` block = **one undo step** (one `Batch`). Nested `change()`+ blocks fold into the **outermost** block's batch.+- Prefer high-level `model.insertContent()`, `model.insertObject()`, `model.deleteContent()`,+ `model.getSelectedContent()` — they respect the schema. Use the writer's low-level methods+ (`createElement`, `createText`, `insert`, `append`, `remove`, `setAttribute`,+ `setSelection`, `setSelectionAttribute`, `removeSelectionAttribute`) for precise edits.+- All structural changes are **operations** (Operational Transformation, for collaboration);+ batches are the unit of undo.++### Text vs. selection attributes++Inline styles (bold, italic, links, highlight) are stored as **text-node attributes**, not+nested elements:++```text+<p>Foo <strong>bar</strong></p> (DOM/view)+<paragraph>"Foo " "bar"(bold=true)</paragraph> (model)+```++The **selection** also has attributes (`selection.getAttribute('bold')`); a collapsed+selection with `bold=true` means newly typed text will be bold. Manage with+`writer.setSelectionAttribute()` / `removeSelectionAttribute()`.++### Indexes, offsets, positions, ranges, selections++- **Index** addresses a node within its parent; **offset** addresses a position.+- `ModelPosition` = a `path` (array of offsets). `ModelRange` = start + end positions.+- `ModelSelection` = one or more ranges + direction + attributes (you can create many).+- `ModelDocumentSelection` = the user's actual selection (one per document); changeable only+ via the writer; auto-updates as the structure changes.+- Useful selection APIs: `selection.isCollapsed`, `getFirstPosition()`, `getFirstRange()`,+ `getRanges()`, `getSelectedElement()`, `getSelectedBlocks()`, `hasAttribute()`,+ `getAttributes()`. Position helpers: `writer.createPositionAt(node, 0|'end'|offset)`,+ `findAncestor('name')`. Range helpers: `createRangeIn(element)`, `createRange(start, end)`,+ `getItems()`, `getWalker()`, `containsRange(range, loose)`, `isCollapsed`.++### Markers++A special, persistent kind of range managed by `MarkerCollection`, changed only via the+writer. Markers: sync over the network for collaboration; auto-update on structure changes;+can be downcast to the editing view (`markerToHighlight`, `markerToElement`) or to data+(`markerToData`) and upcast (`dataToMarker`). Ideal for comments, selections of other users,+and metadata attached to document ranges.++## The schema++`editor.model.schema` defines what the model may contain. It governs paste filtering,+where the selection may go, which features apply where, etc. **Plugins should pre-configure+the schema** so the feature works without the user reconfiguring anything.++Core operations:++```js+// Allow an attribute on existing items (inline features):+schema.extend( '$text', { allowAttributes: 'highlight' } );++// Register a new element:+schema.register( 'simpleBox', { inheritAllFrom: '$blockObject' } );+schema.register( 'placeholder', { inheritAllFrom: '$inlineObject', allowAttributes: [ 'name' ] } );+schema.register( 'simpleBoxTitle', { isLimit: true, allowIn: 'simpleBox', allowContentOf: '$block' } );+schema.register( 'simpleBoxDescription', { isLimit: true, allowIn: 'simpleBox', allowContentOf: '$root' } );+```++Definition properties: `inheritAllFrom`, `allowIn`, `allowChildren`, `allowContentOf`,+`allowAttributes`, `allowAttributesOf`, plus semantic flags `isObject`, `isInline`,+`isBlock`, `isLimit`, `isSelectable`, `isContent`. Common generic items: `$root`, `$block`,+`$text`, `$blockObject`, `$inlineObject`, `$documentFragment`.++Behavior that flags produce (observable in the block-widget feature):+- `isLimit` — element can't be split (Enter) or emptied/left by Backspace; good for titles.+- `isObject` / `$blockObject` / `$inlineObject` — selected/deleted/copied as a unit.++Custom checks for disallowing in specific contexts:++```js+schema.addChildCheck( ( context, childDefinition ) => {+ if ( context.endsWith( 'simpleBoxDescription' ) && childDefinition.name == 'simpleBox' ) {+ return false; // no nested boxes+ }+} );+schema.addAttributeCheck( context => {+ if ( context.endsWith( 'formName $text' ) ) return false; // no inline styles inside+} );+```++Query APIs used by features/commands: `schema.checkChild( context, child )`,+`checkAttribute( context, attr )`, `checkAttributeInSelection( selection, attr )`,+`getValidRanges( ranges, attr )`, `findAllowedParent( position, name )`,+`findOptimalInsertionRange()`. There is **no clean way to override** a feature's schema after+the fact short of replacing `editor.model.schema`; prefer composing features.++## The view++An abstract, DOM-like **virtual DOM** with two pipelines: the **editing view**+(`editor.editing.view`, a persistent `ViewDocument` rendered to `contentEditable`) and the+**data view** (detached structures used by the data pipeline; no document/controller). The+`ViewRenderer` tames `contentEditable`.++Six **semantic element types** convey meaning to converters/renderer:+- **ContainerElement** — block structure (`<p>`, `<h1>`, `<li>`, `<section>`).+- **AttributeElement** — inline styling (`<strong>`, `<a>`, `<code>`); similar ones auto-flatten.+- **EmptyElement** — must have no children (`<img>`).+- **UIElement** — non-data UI inlined in content; selection jumps over it; its events/content+ are filtered out.+- **RawElement** — opaque data container; children transparent to the editor.+- **EditableElement** — a nested editable region inside non-editable content (e.g. image caption).++Plus **custom properties** (`element.getCustomProperty(name)` / `writer.setCustomProperty()`),+non-rendered markers used e.g. by `toWidget()` and to tag elements as belonging to a feature.++**Non-semantic views** are produced directly from input data (paste/`setData`) and consist of+plain `ViewElement`s before upcasting.++### Changing the view++Don't change the view manually unless the model genuinely can't represent the cause (e.g.+focus, which is a view property). When you must, use the view's `change()` block:++```js+editor.editing.view.change( writer => {+ writer.insert( position, writer.createText( 'foo' ) );+} );+```++Two view writers: `ViewDowncastWriter` (in `change()` blocks, semantic view, used while+downcasting) and `ViewUpcastWriter` (for pre-processing input/pasted non-semantic views).++View positions are `{ parent, offset }` and behave more like model **indexes**; conversion of+DOM↔view positions is fiddly — prefer working with model positions.++### Observers++Observers turn native DOM events into safe, testable custom events fired on the+`ViewDocument`. Defaults include mutation, selection, focus, key, composition, arrow-keys.+Add your own with `view.addObserver( MyObserver )` (subclass `Observer`, or `DomEventObserver`+for a single DOM event — see `recipes.md` double-click example). Third-party packages should+**prefix custom view events** (e.g. `myApp:keydown`) to avoid collisions.++## Conversion (overview)++Three processes connect model and view (deep dive in `conversion.md`):+- **Data upcasting** — data view → model (load/paste). Data processor → view fragment → model.+- **Data downcasting** — model → data view → output (`getData`).+- **Editing downcasting** — model → editing view → DOM, continuously as the model changes.+ There is **no** "editing upcasting": features listen to view events and apply model changes.++## Event system & observables++The editor is event-based; most classes are `Emitter`s and/or `Observable`s (an Observable is+an Emitter). This decouples and extends code.++- Listen with `this.listenTo( emitter, 'event', cb, { priority } )`; `this.stopListening()`+ (auto-called in `Plugin#destroy()`). Priorities (`'highest'`…`'lowest'`, default `'normal'`)+ order listeners; `evt.stop()` halts propagation, `evt.return` sets the result.+- Many methods are **decorated** into events (e.g. `Command#execute` fires `execute`), so you+ can run code before/after or block by listening with high/low priority and `evt.stop()`.+- Observables expose **observable properties** via `set()`, firing `change:prop` and+ `set:prop` events:++```js+this.set( 'value', undefined );+command.on( 'change:value', ( evt, name, newVal, oldVal ) => {} );+```++- **Binding** mirrors one observable's properties to another (heavily used in UI):++```js+target.bind( 'foo' ).to( source ); // foo <- source.foo+target.bind( 'foo' ).to( source, 'bar' ); // foo <- source.bar+button.bind( 'isOn', 'isEnabled' ).to( command, 'value', 'isEnabled' );+dropdown.bind( 'isEnabled' ).toMany( buttons, 'isEnabled', ( ...vals ) => vals.some( Boolean ) );+```++- **Event delegation** re-fires one emitter's events from another:+ `childButton.delegate( 'execute' ).to( parentView, 'cancel' )`.++This decorate/observe/bind/delegate quartet is the backbone of how commands, UI, and features+stay in sync without tight coupling.diff --git a/.claude/skills/ckeditor5-plugin-development/references/commands.md b/.claude/skills/ckeditor5-plugin-development/references/commands.mdnew file mode 100644index 0000000000..fdf6d7ecca--- /dev/null+++ b/.claude/skills/ckeditor5-plugin-development/references/commands.md@@ -0,0 +1,117 @@+# Commands++A **command** = an **action** (`execute()`) + a **state** (observable properties, kept fresh+by `refresh()`). Commands encapsulate feature logic so UI, keystrokes, other plugins, and+`editor.execute()` can all trigger and observe it. Most editor features expose their behavior+as commands.++## Defining and registering++Extend `Command`; register in the editing plugin's `init()`:++```js+import { Command } from 'ckeditor5';++class MyCommand extends Command {+ refresh() { /* set this.isEnabled / this.value */ }+ execute( ...args ) { /* mutate the model */ }+}++// In the plugin:+editor.commands.add( 'myCommand', new MyCommand( editor ) );+editor.execute( 'myCommand', arg ); // run it+editor.commands.get( 'myCommand' ); // get it+```++By convention command names are **action + feature**: `insertTable`, `uploadImage`,+`addAbbreviation`, `toggleSimpleBoxSecret` — not `tableInsert`.++## `refresh()` — state++Called automatically on **every** model document change, so state is always current. Set the+observable properties here:++- `this.isEnabled` — whether the command can run **now** (commonly a schema check).+- `this.value` — feature-specific state (e.g. is the selection already highlighted; the+ current attribute object; `undefined`/`null` when not applicable).++```js+refresh() {+ const { document, schema } = this.editor.model;+ this.value = document.selection.getAttribute( 'highlight' );+ this.isEnabled = schema.checkAttributeInSelection( document.selection, 'highlight' );+}+```++Other typical enablement checks: `schema.checkChild( selection.focus.parent, 'placeholder' )`+for insertion, or `schema.findAllowedParent( selection.getFirstPosition(), 'simpleBox' ) !== null`.++## `execute()` — action++Always mutate inside `model.change( writer => … )`. Handle collapsed vs. ranged selection.+Conventions seen across official features:++- Accept an options object: `execute( { value } )`, `execute( { title, abbr } )`,+ `execute( options = {} )` for toggles.+- **Boolean attributes:** set `true` to enable, **remove** the attribute to disable (yields+ `undefined`) — don't store `false`. Toggle = `options.value === undefined ? !this.value : options.value`.+- Inserting objects: prefer `model.insertObject( element, null, null, { setSelection: 'on' } )`+ or `model.insertContent()` — they split/validate per schema. `insertContent()`/`insertObject()`+ return a range; grab `.end` to place the selection after the insert.+- Ranged attribute application: iterate `schema.getValidRanges( selection.getRanges(), attr )`+ and `writer.setAttribute()` each; then manage selection attributes.+- Preserve existing inline attributes when inserting text: collect with+ `toMap( selection.getAttributes() )`, add yours, pass to `writer.createText( text, attrs )`.++Inline-attribute toggle example (collapsed handling shown):++```js+execute() {+ const model = this.editor.model;+ const selection = model.document.selection;+ const newValue = !this.value;+ model.change( writer => {+ if ( !selection.isCollapsed ) {+ for ( const range of model.schema.getValidRanges( selection.getRanges(), 'highlight' ) ) {+ newValue ? writer.setAttribute( 'highlight', true, range )+ : writer.removeAttribute( 'highlight', range );+ }+ }+ newValue ? writer.setSelectionAttribute( 'highlight', true )+ : writer.removeSelectionAttribute( 'highlight' );+ } );+}+```++## Command events++`Command#execute` is **decorated** into an event, and `value`/`isEnabled` are observable.+Listen to react before/after or to block:++```js+this.listenTo( someCommand, 'execute', () => {} ); // after default action+this.listenTo( other, 'execute', evt => evt.stop(), { priority: 'high' } ); // block before it runs+command.on( 'change:value', ( evt, name, newVal, oldVal ) => {} );+```++## Disabling a command externally++Don't fight `refresh()`. Use the helper, which survives refreshes and stacks per-feature:++```js+const cmd = editor.commands.get( 'bold' );+cmd.forceDisabled( 'MyFeature' ); // stays disabled until cleared AND no one else holds it+cmd.clearForceDisabled( 'MyFeature' );+```++## Read-only mode and `affectsData`++Editor commands are blocked in read-only mode by default. If a command does **not** change+data and should stay enabled (and in other write-restricting modes), set `this.affectsData =+false` (default `true`, immutable for the editor's lifetime):++```js+class MyAlwaysEnabledCommand extends Command {+ constructor( editor ) { super( editor ); this.affectsData = false; }+}+```diff --git a/.claude/skills/ckeditor5-plugin-development/references/conventions.md b/.claude/skills/ckeditor5-plugin-development/references/conventions.mdnew file mode 100644index 0000000000..a60e26fef9--- /dev/null+++ b/.claude/skills/ckeditor5-plugin-development/references/conventions.md@@ -0,0 +1,99 @@+# Code-style conventions++The official CKEditor 5 conventions (enforced by custom ESLint rules). Use them both to write+idiomatic plugins and to review them. Items below note the enforcing ESLint rule where one exists.++## Naming++- Variables/functions/params: `lowerCamelCase`. Classes/mixins: `UpperCamelCase` (mixins end+ in `Mixin`). Global constants: `ALLCAPS`. Private members: `_` prefix (`this._balloon`,+ `_createButton()`).+- Methods are **verbs** (`execute`, `getNextNumber`); properties/variables are **nouns**.+ Booleans use an auxiliary-verb prefix: `isEnabled`, `hasChildren`, `canObserve`, `mustRefresh`.+- **Commands:** action + feature → `insertTable`, `uploadImage`, `addAbbreviation` (not+ `tableInsert`). **Buttons:** verb+noun or noun → `insertTable`, `bold`.+- **Plugins:** feature or feature+sub-feature, `UpperCamelCase` → `Bold`, `ImageResize`,+ `TableClipboard`.+- Acronyms: two-letter stay upper (`getUI`); longer follow camelCase position rules+ (`domError`/`DomError`, `getCKEditorError`). Proper names keep their casing (`CKEditorError`).+- Model/view names follow the feature, lowerCamelCase for elements (`simpleBox`,+ `simpleBoxTitle`, `placeholder`); attributes lowerCamelCase (`linkHref`, `highlight`).++## Files & CSS++- File names: **all lowercase, kebab-case**; a single code entity drops separators+ (`DataProcessor` → `dataprocessor.ts`). Descriptive multi-word test files may use dashes.+- CSS: **BEM**, all lowercase, mandatory `ck-` prefix. Block `ck-dialog`; element+ `ck-dialog__header` (double underscore); modifier `ck-dialog_hidden` /+ `ck-toolbar__group_collapsed` (single underscore); key-value `ck-dropdown-menu_theme_lark`.+ IDs follow the same rules with `ck-` prefix. CSS vars inside `.ck-content` must be+ `--ck-content-*` (`ck-content-variable-name`).++## Imports & modules++- Same package → **relative** paths (`import Position from './position';`). Other packages →+ by **package name / main entry** (`import { Table } from 'ckeditor5';`), never deep relative+ (`../../../ckeditor5-utils/src/...`) (`no-relative-imports`, `no-cross-package-imports`,+ `no-scoped-imports-within-package`).+- All imports include file extensions (`.ts`/`.js`/`.json`) (`require-file-extensions-in-imports`).+- In `@if CK_DEBUG` blocks use `require()`, not `import` (`use-require-for-debug-mode-imports`).+- Each TS file in `packages/*/src/` starts with a `@module path/file` JSDoc tag matching its+ location (`validate-module-tag`); the package `index.ts` uses `@module <package>`.++## Plugin specifics++- Provide `static get pluginName()` (TS: `return 'Name' as const;`) and `static get requires()`+ for dependencies.+- Plugin boolean flags: set required flags with the exact literal type/value+ (`static override get isFooPlugin(): true { return true; }`); never set them to `false` and+ never set disallowed flags (`ckeditor-plugin-flags`).++## Visibility & documentation++- Public by default. Mark `@protected` / `@private` in JSDoc. Protected members are reachable+ from tests (tests live in the same package) — that's the idiom for testability.+- TS non-public members get `@internal` so they're stripped from `.d.ts`+ (`non-public-members-as-internal`; needs `stripInternal: true`).+- Block comments `/** … */` are for JSDoc only; everything else uses line comments `//`,+ preceded by a blank line, capitalized, ending with a period, one space after `//`.++## Errors++Throw `CKEditorError` with a kebab id and a documenting `@error` JSDoc block explaining cause+and fix (`ckeditor-error-message`):++```js+/**+ * Why this happened and how to fix it.+ *+ * @error ckeditor5-example-error+ */+throw new CKEditorError( 'ckeditor5-example-error', this );+```++## TypeScript rules++- **No `enum`** — use `const X = { … } as const;` + `type X = typeof X[keyof typeof X]`+ (`no-enum`).+- Use `as const` where exact literal types matter (e.g. `pluginName`).+- Don't hardcode `'$root'`: check `node.is( 'rootElement' )` not `name === '$root'`+ (`no-literal-dollar-root`). (Exception: view listener `context: '$root'` for tree bubbling.)+- Pass explicit context to APIs that silently default to `$root`+ (`require-explicit-data-context`): `editor.data.parse( html, '$documentFragment' )`,+ `document.createRoot( '$inlineRoot' )`.++## Formatting++- **Tabs** for indentation (display as 4). LF endings, no trailing spaces. Lines ≤120 chars+ (hard max 140).+- Spaces inside `( … )` and around operators: `if ( a > b ) { c = ( d + e ) * 2; }`. No space+ for empty `()`. Single quotes for strings. Braces on the same line as the head.+- Multi-line calls: first param on a new line, one tab per param, closing paren at the+ statement's indentation.+- Class member order: constructor → getters/setters → iterators → public instance → public+ static → protected instance → protected static → private instance → private static.+- Getters must be fast, side-effect-free, non-throwing, and shouldn't allocate new instances+ each call (cache).+- Avoid >3 positional args (use an options object); extract complex conditions into named+ functions with early returns. Format only the code you actually touch (don't reflow+ unrelated code in a PR).diff --git a/.claude/skills/ckeditor5-plugin-development/references/conversion.md b/.claude/skills/ckeditor5-plugin-development/references/conversion.mdnew file mode 100644index 0000000000..8d01365888--- /dev/null+++ b/.claude/skills/ckeditor5-plugin-development/references/conversion.md@@ -0,0 +1,124 @@+# Conversion: upcast & downcast++Conversion connects the **model** and the **view**. For the editor the **model is the source+of truth**; HTML/data is just I/O. That is why helper names look "reversed": converting the+`<mark>` element ↔ `highlight` model attribute uses `attributeToElement` (you name the+**model** side first).++## Pipelines++- **Upcast** (`upcast`) — view → model. Used when loading data **and** when pasting.+- **Downcast** has two flavors:+ - **dataDowncast** — model → output HTML (`getData()`, copy).+ - **editingDowncast** — model → editing view shown in the UI (continuous).++Use the **same** representation for both downcasts when possible; split them when the editing+view needs extras the data must not have (widget handles, UI elements, `contentEditable`,+nested-editable wiring). Editing-only enhancements (`toWidget`, `toWidgetEditable`, UI+elements) belong in `editingDowncast` so `getData()` stays clean.++## Two ways to register converters++**Two-way helpers** on `editor.conversion` — concise, for simple symmetric conversions.+They register both upcast and (data+editing) downcast at once:++```js+editor.conversion.attributeToElement( { model: 'highlight', view: 'mark' } );+editor.conversion.elementToElement( { model: 'simpleBox', view: { name: 'section', classes: 'simple-box' } } );+editor.conversion.attributeToAttribute( { model: 'secret', view: { name: 'section', key: 'class', value: 'secret' } } );+```++**Pipeline-scoped** via `editor.conversion.for( pipeline )` — for asymmetric/custom cases.+The same `attributeToElement` example expanded:++```js+editor.conversion.for( 'upcast' ).elementToAttribute( { model: 'highlight', view: 'mark' } );+editor.conversion.for( 'dataDowncast' ).attributeToElement( { model: 'highlight', view: 'mark' } );+editor.conversion.for( 'editingDowncast' ).attributeToElement( { model: 'highlight', view: 'mark' } );+```++Note the directionality: **upcast** uses `elementTo…` helpers (view→model), **downcast** uses+`…ToElement` helpers (model→view).++## Helper catalog++Upcast helpers (`for('upcast')`): `elementToElement`, `elementToAttribute`,+`attributeToAttribute`, `dataToMarker`.+Downcast helpers (`for('dataDowncast'|'editingDowncast'|'downcast')`): `elementToElement`,+`elementToStructure`, `attributeToElement`, `attributeToAttribute`, `markerToElement`,+`markerToHighlight`, `markerToData`.++## Callback (custom) converters++When the value isn't a fixed string, pass a `view`/`model` **callback**. The 2nd arg is the+conversion API with a `writer` (a `ViewDowncastWriter` downcast / `ModelWriter` upcast),+`consumable`, etc.++Downcast — model attribute value into a view element with an attribute:++```js+conversion.for( 'downcast' ).attributeToElement( {+ model: 'abbreviation',+ view: ( modelAttributeValue, { writer } ) =>+ writer.createAttributeElement( 'abbr', { title: modelAttributeValue } )+} );+```++Upcast — read a view attribute into the model attribute value:++```js+conversion.for( 'upcast' ).elementToAttribute( {+ view: { name: 'abbr', attributes: [ 'title' ] },+ model: { key: 'abbreviation', value: viewElement => viewElement.getAttribute( 'title' ) }+} );+```++Element callbacks build view structure with the view writer (`createContainerElement`,+`createEditableElement`, `createEmptyElement`, `createText`, `createPositionAt`, `insert`,+`setCustomProperty`):++```js+conversion.for( 'editingDowncast' ).elementToElement( {+ model: 'placeholder',+ view: ( modelItem, { writer } ) => {+ const span = writer.createContainerElement( 'span', { class: 'placeholder' } );+ writer.insert( writer.createPositionAt( span, 0 ), writer.createText( `{${ modelItem.getAttribute( 'name' ) }}` ) );+ return toWidget( span, writer ); // editing-only widget wrapping+ }+} );+```++## View matching patterns (upcast)++The `view` matcher accepts a tag string or an object: `{ name, classes, attributes, styles }`.+`attributes` can be an array of names to require or a map of name→value. Be specific so you+don't greedily match unrelated elements.++## Consumables++Each view/model item is "consumed" once during conversion so multiple converters don't+double-process it. In advanced converters you manage this explicitly with `consumable.consume(+item, 'insert' | 'attribute:foo' | … )` and `consumable.test(...)`. Example: a `dataDowncast`+that flattens nested model elements into one view element consumes the children itself+(see `recipes.md` "single view element / multiple model elements").++## Position mapping (inline widgets / structural mismatch)++When the view has "more" content than the model (e.g. a `<placeholder>` model element renders+as `<span>{name}</span>`), some view positions can't auto-map to the model and you get+`model-nodelist-offset-out-of-bounds`. Fix with the ready-made utility:++```js+import { viewToModelPositionOutsideModelElement } from 'ckeditor5';++editor.editing.mapper.on( 'viewToModelPosition',+ viewToModelPositionOutsideModelElement( editor.model, v => v.hasClass( 'placeholder' ) ) );+```++This maps any position inside the view `<span>` to a position **outside** the model element.++## Where to go deeper++The official "Conversion deep dive" (`framework/deep-dive/conversion/*`) covers+`elementToStructure`, reconversion/triggers, marker conversion, and data processors. For+widget-specific conversion patterns see `widgets.md`.diff --git a/.claude/skills/ckeditor5-plugin-development/references/recipes.md b/.claude/skills/ckeditor5-plugin-development/references/recipes.mdnew file mode 100644index 0000000000..f520f26f70--- /dev/null+++ b/.claude/skills/ckeditor5-plugin-development/references/recipes.md@@ -0,0 +1,150 @@+# Recipes (task-oriented how-tos)++Common snippets from the official how-tos. All model mutations run inside+`editor.model.change( writer => … )`.++## Get the editor instance++```js+// In a function plugin:+function MyPlugin( editor ) { /* editor.* */ }++// From a DOM editable element:+const editor = document.querySelector( '.ck-editor__editable_inline' ).ckeditorInstance;+```++`CKEDITOR_VERSION` in the console reports the version. There is no global registry of+instances by default.++## Insert content++```js+// Text with an attribute (e.g. a link) at the selection:+editor.model.change( writer => {+ const pos = editor.model.document.selection.getFirstPosition();+ editor.model.insertContent( writer.createText( 'CKEditor 5 rocks!', { linkHref: 'https://ckeditor.com/' } ), pos );+} );++// Plain text:+editor.model.insertContent( writer.createText( 'Plain text' ), pos );++// A chunk of HTML → model fragment → insert:+const viewFragment = editor.data.processor.toView( '<p>A <a href="...">link</a>.</p>' );+const modelFragment = editor.data.toModel( viewFragment );+editor.model.insertContent( modelFragment );+```++`insertContent()` respects the schema; unconverted elements/attributes are dropped.++## Focus the editor / editing view++```js+editor.focus();+editor.editing.view.focus();+```++## Place the caret at start / end++```js+editor.model.change( writer => {+ writer.setSelection( writer.createPositionAt( editor.model.document.getRoot(), 0 ) ); // start+ writer.setSelection( writer.createPositionAt( editor.model.document.getRoot(), 'end' ) ); // end+} );+```++## Delete selected blocks++```js+const blocks = Array.from( editor.model.document.selection.getSelectedBlocks() );+editor.model.change( writer => {+ const range = writer.createRange(+ writer.createPositionAt( blocks[ 0 ], 0 ),+ writer.createPositionAt( blocks[ blocks.length - 1 ], 'end' )+ );+ editor.model.deleteContent( writer.createSelection( range ) );+} );+```++## Find / iterate specific elements++```js+// Remove all block images:+editor.model.change( writer => {+ const range = writer.createRangeIn( editor.model.document.getRoot() );+ const toRemove = [];+ for ( const { item } of range.getWalker() ) {+ if ( item.is( 'element', 'imageBlock' ) ) toRemove.push( item );+ }+ toRemove.forEach( item => writer.remove( item ) );+} );++// Collect unique link targets:+const links = new Set();+for ( const { type, item } of editor.model.createRangeIn( editor.model.document.getRoot() ).getWalker() ) {+ if ( type === 'text' && item.hasAttribute( 'linkHref' ) ) links.add( item.getAttribute( 'linkHref' ) );+}+```++`item.is(...)` is the canonical type check: `is('element', 'name')`, `is('$text')`,+`is('rootElement')`, `is('element')`, etc.++## Set an attribute on the editable DOM root++```js+editor.editing.view.change( writer => {+ writer.setAttribute( 'myAttribute', 'value', editor.editing.view.document.getRoot() );+} );+```++## Custom DOM-event observer (e.g. double-click)++```js+import { DomEventObserver } from 'ckeditor5';++class DoubleClickObserver extends DomEventObserver {+ constructor( view ) { super( view ); this.domEventType = 'dblclick'; }+ onDomEvent( domEvent ) { this.fire( domEvent.type, domEvent ); }+}++const view = editor.editing.view;+view.addObserver( DoubleClickObserver );+editor.listenTo( view.document, 'dblclick', ( evt, data ) => { /* … */ }, { context: 'a' } );+```++Check for an existing observer that already fires the DOM event before adding your own.++## Extend another plugin's UI (e.g. add a button to the link form)++```js+import { ButtonView, Plugin, LinkUI } from 'ckeditor5';++class InternalLink extends Plugin {+ init() {+ const linkUI = this.editor.plugins.get( LinkUI );+ const balloon = this.editor.plugins.get( 'ContextualBalloon' );+ this.listenTo( balloon, 'change:visibleView', ( evt, name, visibleView ) => {+ if ( visibleView === linkUI.formView ) {+ const button = new ButtonView( this.locale );+ button.set( { label: 'Internal link', withText: true, tooltip: true } );+ button.bind( 'isEnabled' ).to( this.editor.commands.get( 'link' ) );+ button.render();+ linkUI.formView.registerChild( button );+ linkUI.formView.element.insertBefore( button.element, linkUI.formView.saveButtonView.element );+ }+ } );+ }+}+```++## Widget: one view element ↔ multiple/nested model elements++Pattern from the how-tos for a form `<input>` ↔ `<forms><formName>…</formName></forms>`:+upcast builds a model sub-structure from a single view element; `editingDowncast` converts+each model element separately (outer → `toWidget`, inner → `toWidgetEditable`); `dataDowncast`+collapses the structure back into one view element, consuming the inner items so other+converters skip them. See the full snippet in `docs/framework/how-tos.md` and `widgets.md`.++## Framework-integration gotcha++Building large React apps may hit `JavaScript heap out of memory`; raise Node's heap:+`NODE_OPTIONS="--max-old-space-size=4096" npm run build`.diff --git a/.claude/skills/ckeditor5-plugin-development/references/review-checklist.md b/.claude/skills/ckeditor5-plugin-development/references/review-checklist.mdnew file mode 100644index 0000000000..c95fd66457--- /dev/null+++ b/.claude/skills/ckeditor5-plugin-development/references/review-checklist.md@@ -0,0 +1,82 @@+# Reviewing a CKEditor 5 plugin++A structured checklist for reviewing existing plugin code. Pair each item with the relevant+reference file when you need the "why". Flag deviations; not every item applies to every+plugin (e.g. a UI-only or editing-only plugin).++## Architecture & structure++- [ ] **Editing/UI split**: a glue plugin (`static get requires() { return [ XEditing, XUI ]; }`),+ with schema/conversion/commands in `*Editing` and UI in `*UI`. Single-file plugins are ok+ for trivial features but a split is expected for anything reusable.+- [ ] `static get pluginName()` present (TS: `as const`) and `static get requires()` declares+ real dependencies (e.g. `Widget`, `ContextualBalloon`, `WidgetToolbarRepository`).+- [ ] Init logic in `init()`; cross-plugin runtime wiring in `afterInit()`.+- [ ] Plugin knows little about other plugins — collaborates via commands/events/schema, not+ reaching into internals.+- [ ] Self-configuring: schema pre-configured; config defaults via `editor.config.define()`,+ read via `editor.config.get()`. No required manual schema setup pushed onto the user.++## Schema++- [ ] Inline features `schema.extend( '$text', { allowAttributes } )`; elements/objects use+ `schema.register()` with correct `inheritAllFrom` (`$blockObject` / `$inlineObject` /+ `$block`) and `allowIn` / `allowContentOf`.+- [ ] Semantic flags correct: `isLimit` for non-splittable editables, object types for atomic+ elements; `addChildCheck`/`addAttributeCheck` used to disallow invalid nesting/attrs.++## Conversion++- [ ] Symmetric coverage: an **upcast** plus **downcast**; editing vs. data downcast split+ only when needed (widget/UI extras go to `editingDowncast` so `getData()` stays clean).+- [ ] Correct helpers/direction (`elementTo…` upcast, `…ToElement` downcast); `attributeToElement`+ naming reflects model-first thinking.+- [ ] Custom callback converters use the provided `writer`; consumables handled in advanced+ converters; inline widgets register `viewToModelPositionOutsideModelElement` mapping.+- [ ] Everything rendered/round-tripped has a converter (un-converted elements/attributes are+ filtered out).++## Commands++- [ ] Logic lives in a `Command`, not inline in a button handler.+- [ ] `refresh()` sets `isEnabled` from a real schema check (disabled where the attribute/child+ isn't allowed) and `value` reflecting current state; no manual state fighting `refresh()`.+- [ ] `execute()` wraps mutations in `model.change()`; handles collapsed vs. ranged selection;+ uses `getValidRanges`/`insertObject`/`insertContent` rather than unsafe low-level writes.+- [ ] Boolean attributes set `true` / removed (never stored as `false`).+- [ ] External disabling via `forceDisabled()/clearForceDisabled()`; `affectsData=false` only+ for non-data commands that must stay enabled in read-only.++## UI++- [ ] Components registered in `editor.ui.componentFactory.add(name, locale => view)`; `locale`+ passed to constructors.+- [ ] Button/dropdown state **bound** to command (`bind('isOn','isEnabled').to(command,'value','isEnabled')`),+ not manually toggled.+- [ ] Handlers call `editor.editing.view.focus()` after executing.+- [ ] Custom views encapsulate their DOM (no direct `element.*` writes that collide with+ bindings); dropdowns/dialogs/balloons use the provided helpers; balloons clean up via+ `clickOutsideHandler` and remove themselves on hide.++## Accessibility++- [ ] Keyboard support: `editor.keystrokes.set()` for shortcuts; form views use `FocusTracker`+ + `KeystrokeHandler` + `FocusCycler`, and **destroy** them in `destroy()`.+- [ ] Shortcuts registered with `editor.accessibility.addKeystrokeInfos()` and shown in the+ button `keystroke` tooltip; labels set even when `withText` is false.+- [ ] Dialogs/modals always leave a way to close (don't trap Esc without an alternative).++## Localization++- [ ] All user-facing strings go through `t()` (named exactly `t` in JS; literal first arg).+ Reused strings from other packages use the `locale.t` alias, not `t()`.++## Conventions & hygiene++- [ ] Naming/imports/file names/CSS-BEM/JSDoc/TS rules per `conventions.md`; `CKEditorError`+ with `@error`.+- [ ] Listeners use `this.listenTo()` (auto-cleaned); any other resources cleaned in `destroy()`.+- [ ] `ckeditor5-metadata.json` updated for new public plugins/UI/HTML output (for distributable+ packages).+- [ ] Model is the source of truth — no view hacks standing in for model state (except genuine+ view-only state like focus).diff --git a/.claude/skills/ckeditor5-plugin-development/references/tooling-and-packaging.md b/.claude/skills/ckeditor5-plugin-development/references/tooling-and-packaging.mdnew file mode 100644index 0000000000..230cb741fd--- /dev/null+++ b/.claude/skills/ckeditor5-plugin-development/references/tooling-and-packaging.md@@ -0,0 +1,153 @@+# Tooling & packaging++How to scaffold, build, integrate, and debug a distributable CKEditor 5 plugin package.++## Package generator++Scaffold a publishable `ckeditor5-*` package:++```bash+npx ckeditor5-package-generator+```++Package name: `ckeditor5-<name>` or `@<scope>/ckeditor5-<name>` (chars `0-9 a-z - . _`).+Options: `--lang js|ts`, `--plugin-name <Name>`, `--global-name <CKName>` (UMD global),+`--package-manager npm|yarn|pnpm`, `--verbose`.++Generated layout:++```+src/ plugin code & public exports (index, *editing, *ui, command…)+sample/ local Vite sample app (npm run start)+tests/ Vitest unit tests+theme/ icons & CSS+lang/ translation context + *.po files+scripts/ helper scripts (translation sync)+ckeditor5-metadata.json+vite.config.[js|ts]+# TS only: src/augmentation.ts, tsconfig.json, tsconfig.build.json, typings/+```++npm scripts: `start` (Vite sample + live reload), `test`, `test:debug`, `lint`, `build`+(npm + browser outputs to `dist/`), `translations:synchronize`, `translations:validate`.++## TypeScript augmentation (`src/augmentation.ts`)++Register your plugin/config/commands into CKEditor's type maps so consumers get typing:++```ts+import type { MyPlugin } from './index.js';+declare module '@ckeditor/ckeditor5-core' {+ interface PluginsMap { [ MyPlugin.pluginName ]: MyPlugin; }+ // also augment EditorConfig (for config) and CommandsMap (for typed commands)+}+```++## Build output & integration++`npm run build` emits:++```+dist/index.js npm ESM entry (ckeditor5 is external)+dist/index.css CSS for npm consumers+dist/*.d.ts type declarations+dist/browser/index.es.js browser ESM (needs ckeditor5 provided via import map)+dist/browser/index.umd.js browser UMD (exposes the --global-name; needs CKEDITOR global)+dist/browser/index.css CSS for ZIP/CDN+```++Consume via npm:++```js+import { ClassicEditor, Essentials, Paragraph } from 'ckeditor5';+import { MyPlugin } from '<package>';+import 'ckeditor5/ckeditor5.css';+import '<package>/index.css';+ClassicEditor.create( { /* plugins: [ Essentials, Paragraph, MyPlugin ] */ } );+```++For browser (no bundler): use import maps with `dist/browser/index.es.js`, or UMD `<script>`+tags where the editor is on `CKEDITOR` and your plugin on its global name. CDN integration+follows the same browser patterns. (Note: CDN/commercial builds aren't GPL — they need a+commercial license key; the `'GPL'` key only works for self-hosted/source usage.)++## Package metadata (`ckeditor5-metadata.json`)++Lives at the package root; lets external tooling (CKEditor Builder, the plugins/HTML-output+pages) discover plugins, UI components, and HTML output. Document **major** plugins only (not+the internal editing/UI split classes).++```json+{+ "plugins": [ {+ "name": "Display Name",+ "className": "MyPlugin",+ "description": "Short description.",+ "docs": "path/to/docs.html",+ "path": "src/index.js",+ "requires": [ "OtherPlugin", [ "Plugin1", "Plugin2" ] ],+ "registeredToolbars": [ "myFeature.toolbar" ],+ "uiComponents": [+ { "name": "myButton", "type": "Button", "iconName": "IconBold", "toolbars": [ "toolbar" ] }+ ],+ "htmlOutput": [+ { "elements": "span", "classes": "my-class", "styles": "color", "attributes": "data-*", "implements": "$inlineObject", "isAlternative": false }+ ]+ } ]+}+```++Field notes: `requires` nested arrays mean "at least one of"; `uiComponents[].type` is+`Button` | `SplitButton` | `Dropdown`; `iconName` is an export from `@ckeditor/ckeditor5-icons`;+`htmlOutput.implements` lists an inherited pseudo-element; `isAlternative: true` marks config-+dependent (non-default) output.++## CKEditor 5 Inspector++Indispensable debugging tool — shows the live **model**, **view**, **schema**, **commands**,+and selection.++```bash+npm install --save-dev @ckeditor/ckeditor5-inspector+```++```js+import CKEditorInspector from '@ckeditor/ckeditor5-inspector';+ClassicEditor.create( /* … */ ).then( editor => {+ CKEditorInspector.attach( editor );+ // or named: CKEditorInspector.attach( { 'header-editor': editor } );+} );+```++There's also a bookmarklet that injects the inspector without code changes (won't work under a+strict CSP).++## Custom editor creator (advanced)++To build a non-standard editor, implement three classes:++- **Editor** — extends `Editor`. Protected constructor sets up roots/model; static async+ `create(config)` chains `initPlugins()` → `ui.init()` → `data.init()` → fire `ready` and+ resolve with the instance; `destroy()` caches data, destroys UI, restores DOM.+- **EditorUI** — extends `EditorUI`. `init()` renders the view, wires focus tracking, attaches+ editables to the editing view (`attachDomRoot()`), inits placeholder + toolbar+ (`_initToolbar()` → `addToolbar()`); `destroy()` calls `detachDomRoot()`.+- **EditorUIView** — extends `EditorUIView`. Builds the `ToolbarView` and one+ `InlineEditableUIView` per editable; `render()` registers children.++Helpers: `getDataFromElement()`, `setDataInElement()`, `enableViewPlaceholder()`. Most plugin+work never needs this — only when you need a fundamentally different editor shell (e.g. a+multiroot editor).++## Contributing to the ckeditor5 monorepo++Requires Node ≥ 24.11.0, pnpm ≥ 10.17.0, Git.++```bash+git clone https://github.com/ckeditor/ckeditor5.git && cd ckeditor5+pnpm install+pnpm run test -- -wcs --files=engine # watch + coverage + source-map, one package+pnpm run manual # manual test server+pnpm run docs && pnpm run docs:serve # build & serve docs+npm run clean-up-svg-icons path/to/*.svg # optimize icons (SVGO)+```diff --git a/.claude/skills/ckeditor5-plugin-development/references/ui-and-localization.md b/.claude/skills/ckeditor5-plugin-development/references/ui-and-localization.mdnew file mode 100644index 0000000000..8cd5656e06--- /dev/null+++ b/.claude/skills/ckeditor5-plugin-development/references/ui-and-localization.md@@ -0,0 +1,266 @@+# UI library & localization++The UI library (`@ckeditor/ckeditor5-ui`) is a small MVC: **Views** render DOM via+**Templates**, expose **observable** properties, and are organized into **collections** that+form the UI tree. Features talk to views through observables — never the native DOM directly.++## Views & templates++A `View` builds its DOM with `setTemplate()` and exposes observable state via `set()`:++```js+import { View } from 'ckeditor5';++class SimpleInputView extends View {+ constructor( locale ) {+ super( locale );+ const bind = this.bindTemplate; // bind observables → DOM+ this.set( { isEnabled: false, placeholder: '' } );+ this.setTemplate( {+ tag: 'input',+ attributes: {+ class: [ 'foo', bind.if( 'isEnabled', 'ck-enabled' ) ],+ placeholder: bind.to( 'placeholder' ),+ type: 'text'+ },+ on: { keydown: bind.to( 'input' ) } // DOM event → view 'input' event+ } );+ }+ setValue( v ) { this.element.value = v; } // owned DOM access lives in the view+}+```++Rules & best practices:+- **Always pass `locale`** to view/component constructors.+- A standalone view must be `render()`ed before injecting `view.element` into the DOM; child+ views added to a collection are rendered/destroyed by the editor automatically.+- **Encapsulate the DOM**: features set view observables or `bind()` to them; never write+ `view.element.placeholder = …` directly (it collides with bindings).+- Template supports `tag`, `attributes` (incl. `class` arrays, `style` objects),+ `children` (views/strings/collections), and `on` event bindings. `bind.to(prop)` /+ `bind.if(prop, value, callback)` wire observables; templates also forward DOM events.+- Create child collections with `this.createCollection([...])`; the UI tree has no depth limit.++## View collections & the UI tree++Each editor UI has a root view at `editor.ui.view`. A `BoxedEditorUIView` exposes `top`+(toolbar), `main` (editable), and inherited `body` (floating elements in `<body>`). Plugins+add views into these collections so they're managed (initialized/destroyed) with the editor:++```js+class MyPlugin extends Plugin {+ init() { this.editor.ui.top.add( new MyPluginView() ); }+}+```++## Registering toolbar components++Register every toolbar/UI component in the **component factory**; the user references the name+in their `toolbar` config:++```js+editor.ui.componentFactory.add( 'myButton', locale => {+ const button = new ButtonView( locale );+ button.set( { label: editor.t( 'My button' ), withText: true } );+ button.on( 'execute', () => { editor.execute( 'myCommand' ); editor.editing.view.focus(); } );+ return button;+} );+// user config: toolbar: [ 'myButton' ]+```++**Best practice:** on any user action (button/dropdown execute), call+`editor.editing.view.focus()` so the editor keeps focus.++## Component catalog++| Component | Purpose / key props |+|-----------|---------------------|+| `ButtonView` | `label`, `withText`, `icon`, `tooltip`, `tooltipPosition`, `isOn`, `isEnabled`, `isToggleable`, `keystroke`, `withKeystroke`, `class`; fires `execute`. |+| `SwitchButtonView` | Toggle button; flips `isOn`; bind to a toggle command's `value`/`isEnabled`. |+| `DropdownButtonView` / `SplitButtonView` | Dropdown trigger buttons; `SplitButtonView` exposes `actionView` (main region). |+| `DropdownView` | Created via `createDropdown(locale[, SplitButtonView])`; has `buttonView` + `panelView`. |+| `ToolbarView` | `items` collection; `isCompact`; `ToolbarSeparatorView`, `ToolbarLineBreakView` for layout. |+| `LabeledFieldView` | Input + label: `new LabeledFieldView(locale, createLabeledInputText | createLabeledInputNumber)`; `fieldView.element.value`. |+| `InputTextView` / `TextareaView` | Raw inputs; `TextareaView` has `minRows`, `maxRows`, `resize`. |+| `SearchTextView` / `AutocompleteView` | Search/filter UIs (filtered view must implement `.filter()`/`.focus()`). |+| `IconView` | SVG display; `iconView.content = IconBold`. |+| `SpinnerView` | Loading spinner; `isVisible`. |+| `BalloonPanelView` | Low-level floating panel (`.pin({target, positions})`). Usually use `ContextualBalloon`. |+| `View` + `setTemplate` | Arbitrary custom UI / dialog content. |++## Icons++Import from the bundle (sourced from `@ckeditor/ckeditor5-icons`) and assign to a view's+`icon`/`content`:++```js+import { IconBold, IconCheck, IconCancel, IconQuote } from 'ckeditor5';+button.set( { icon: IconBold } );+```++Custom icons: pass the full SVG XML string. For a recolorable icon, strip `fill`/`stroke`+attributes from the SVG.++## Dropdowns++Use `createDropdown` + the appropriate `add…ToDropdown` helper; don't compose from scratch+unless necessary. Default dropdowns auto-close on blur and on `execute`, and focus their panel+content for keyboard nav.++```js+import { createDropdown, addListToDropdown, addToolbarToDropdown, addMenuToDropdown,+ SplitButtonView, UIModel, Collection } from 'ckeditor5';++const dropdown = createDropdown( locale );+dropdown.buttonView.set( { label: 'Label', withText: true, tooltip: true, icon } );++// List dropdown+const items = new Collection();+items.add( { type: 'button', model: new UIModel( { label: 'Foo', withText: true, commandParam: 'foo' } ) } );+addListToDropdown( dropdown, items );+dropdown.on( 'execute', evt => editor.execute( 'cmd', { value: evt.source.commandParam } ) );++// Toolbar dropdown (split button)+const dd2 = createDropdown( locale, SplitButtonView );+addToolbarToDropdown( dd2, [ buttonA, buttonB ] );+dd2.bind( 'isEnabled' ).toMany( [ buttonA, buttonB ], 'isEnabled', ( ...e ) => e.some( Boolean ) );++// Menu dropdown+addMenuToDropdown( dropdown, editor.body.ui.view, [+ { id: 'menu_1', menu: 'Menu 1', children: [ { id: 'a', label: 'Item A' } ] },+ { id: 'top_a', label: 'Top Item A' }+] );+```++Even when `withText` is false, set `label` for screen readers.++## Contextual balloon++For floating forms/toolbars pinned to the selection, use the `ContextualBalloon` plugin+(only one visible view at a time). Pattern from the abbreviation feature:++```js+import { ContextualBalloon, clickOutsideHandler } from 'ckeditor5';++static get requires() { return [ ContextualBalloon ]; }++init() {+ this._balloon = this.editor.plugins.get( ContextualBalloon );+ this.formView = this._createFormView();+}+_showUI() {+ this._balloon.add( { view: this.formView, position: this._getBalloonPositionData() } );+ this.formView.focus();+}+_getBalloonPositionData() {+ const view = this.editor.editing.view;+ return { target: () => view.domConverter.viewRangeToDom( view.document.selection.getFirstRange() ) };+}+_hideUI() { this._balloon.remove( this.formView ); this.editor.editing.view.focus(); }++// Hide on outside click:+clickOutsideHandler( {+ emitter: formView,+ activator: () => this._balloon.visibleView === formView,+ contextElements: [ this._balloon.view.element ],+ callback: () => this._hideUI()+} );+```++A custom form view extends `View`, builds inputs via `LabeledFieldView`, groups children in a+collection, uses `submitHandler({ view: this })` in `render()` to turn native submit into a+`submit` event, delegates button events (`cancelButtonView.delegate('execute').to(this,'cancel')`),+and exposes a `focus()` method. Add `tabindex: '-1'` and the `ck` class to UI roots.++## Dialogs & modals++The `Dialog` plugin shows views in a dialog (`isModal: false`) or modal (`isModal: true`,+blocks page interaction). Only one open at a time.++```js+const dialog = editor.plugins.get( 'Dialog' );+dialog.show( {+ id: 'myDialog',+ isModal: true,+ title: 'My dialog',+ icon: IconPencil, // header icon (optional)+ hasCloseButton: true, // default true when icon/title present+ content: someView, // a View or collection of Views+ position: DialogViewPosition.EDITOR_BOTTOM_CENTER, // optional+ actionButtons: [+ { label: 'OK', class: 'ck-button-action', withText: true, onExecute: () => dialog.hide() },+ { label: 'Cancel', withText: true, onExecute: () => dialog.hide() }+ ],+ onShow: dlg => { /* set listeners/initial values */ },+ onHide: dlg => { /* reset state */ }+} );+dialog.hide();+```++- Lifecycle events: `show` / `show:[id]`, `hide` / `hide:[id]` (on the plugin), and the+ view's `close` event (`data.source === 'escKeyPress'`). Listen to customize position or+ block Esc — but **always leave a way to close**; never trap users.+- Action buttons support `onCreate(buttonView)` and `onExecute()`; bind button `isEnabled` to+ content state to require user actions.+- `dialog.view.updatePosition()` re-applies the configured default position.+- Full keyboard a11y: Ctrl+F6 moves focus editor↔dialog; Esc closes; Tab/Shift+Tab navigate.++## Focus & keystroke management++Build accessible UI with these utility classes (see the abbreviation level-3 feature):++- `FocusTracker` — observes elements and exposes observable `isFocused` / `focusedElement`.+ `focusTracker.add( view.element )`.+- `KeystrokeHandler` — runs actions for keystrokes within a scope. `keystrokes.listenTo(el)`;+ `keystrokes.set( 'Tab', ( data, cancel ) => { …; cancel(); }, { priority } )`. Each view+ typically owns one.+- `FocusCycler` — cycles focus across a collection of focusables (Tab/Shift+Tab):+ `new FocusCycler( { focusables, focusTracker, keystrokeHandler, actions: { focusPrevious: 'shift + tab', focusNext: 'tab' } } )`.+- **Destroy** `focusTracker` and `keystrokes` in the view's `destroy()` to avoid leaks.++Editor-level keystrokes bind to commands directly via `EditingKeystrokeHandler`:++```js+editor.keystrokes.set( 'Ctrl+Alt+H', 'highlight' ); // command name+editor.keystrokes.set( 'Ctrl+Alt+H', ( evt, cancel ) => { editor.execute( 'highlight' ); cancel(); } );+```++Register shortcuts in the a11y help dialog and the button tooltip:++```js+const t = editor.t;+editor.accessibility.addKeystrokeInfos( {+ keystrokes: [ { label: t( 'Highlight text' ), keystroke: 'Ctrl+Alt+H' } ]+} );+button.set( { /* … */ keystroke: 'Ctrl+Alt+H' } ); // shows in tooltip+```++Keys map to platform conventions automatically (e.g. `Ctrl` → `Cmd` on macOS).++## Localization with `t()`++Every user-facing string must pass through the `t()` function so it can be translated.++- Get it from the locale: `const { t } = editor.locale;` or `const t = editor.t;` or, in a+ view, `const t = this.t;`. (`editor.locale.t` is also `editor.t`.)+- **Static-analysis constraints:** in **JS files** the analyzer only recognizes a function+ named exactly `t()` — don't rename it or call `locale.t()` directly. In **TS files** direct+ `Locale#t()` calls (`editor.t()`, `locale.t()`, `this.t()`) are also recognized. The first+ arg must be a **string or object literal** — never a variable.++```js+t( 'Insert emoji' ); // simple+t( 'Insert %0 emoji', emojiName ); // placeholder; array also ok+t( { string: '%0 emoji', plural: '%0 emojis', id: 'N_EMOJIS' }, quantity ); // plural; first value = quantity+t( { string: '%0 emoji', id: 'ACTION_EMOJI' }, 'insert' ); // disambiguating id+```++- **Reuse a translation** from another package without creating a new source message by+ aliasing the locale function: `const translateVariableKey = editor.locale.t;`+ `translateVariableKey( 'Block quote' )` reuses; `t( 'Create a block quote' )` is a new message.+- Ship translations as `.po` files in `lang/translations/` (preferred for packages — bundles+ only needed languages), or at runtime via the `add()` helper / `window.CKEDITOR_TRANSLATIONS`+ (extend with `Object.assign` to avoid clobbering). New languages need a `getPluralForm()`.+- Limitations: language can't change at runtime without re-creating the editor; the webpack+ plugin bundles one language at a time. Third-party packages localizing via `.po` must+ override `sourceFilesPattern`/`packageNamePattern` so the build tool scans their code.diff --git a/.claude/skills/ckeditor5-plugin-development/references/widgets.md b/.claude/skills/ckeditor5-plugin-development/references/widgets.mdnew file mode 100644index 0000000000..f50942d8cd--- /dev/null+++ b/.claude/skills/ckeditor5-plugin-development/references/widgets.md@@ -0,0 +1,196 @@+# Widgets (block & inline)++A **widget** is a model element rendered in the editing view with widget behavior: clickable+to select, copy/paste/delete as a unit, hover/focus outlines, and optional **nested editable**+regions. The widget system lives partly in the engine and partly in `@ckeditor/ckeditor5-widget`.++Two flavors:+- **Block widget** — `inheritAllFrom: '$blockObject'` (e.g. a box, block image, table).+- **Inline widget** — `inheritAllFrom: '$inlineObject'` (text-like; lives where `$text` is+ allowed, e.g. a placeholder/merge-field).++Both follow the standard editing/UI/glue split (see SKILL.md). The editing plugin must+`static get requires() { return [ Widget ]; }` — without the `Widget` plugin the view gets+widget classes but no behavior (clicking won't select).++## Inline widget recipe (placeholder)++Model: `<placeholder name="time">` inside text. View/data: `<span class="placeholder">{time}</span>`.++```js+import { Plugin, Widget, toWidget, viewToModelPositionOutsideModelElement } from 'ckeditor5';++class PlaceholderEditing extends Plugin {+ static get requires() { return [ Widget ]; }+ init() {+ this._defineSchema();+ this._defineConverters();+ this.editor.commands.add( 'placeholder', new PlaceholderCommand( this.editor ) );+ // Map view positions inside the <span> to outside the model element (avoids+ // model-nodelist-offset-out-of-bounds when selecting the widget).+ this.editor.editing.mapper.on( 'viewToModelPosition',+ viewToModelPositionOutsideModelElement( this.editor.model, v => v.hasClass( 'placeholder' ) ) );+ this.editor.config.define( 'placeholderConfig', { types: [ 'date', 'first name', 'surname' ] } );+ }+ _defineSchema() {+ this.editor.model.schema.register( 'placeholder', {+ inheritAllFrom: '$inlineObject', // selectable, atomic, allowed where $text is; can carry text attrs+ allowAttributes: [ 'name' ]+ } );+ }+ _defineConverters() {+ const conversion = this.editor.conversion;+ conversion.for( 'upcast' ).elementToElement( {+ view: { name: 'span', classes: [ 'placeholder' ] },+ model: ( viewElement, { writer } ) =>+ writer.createElement( 'placeholder', { name: viewElement.getChild( 0 ).data.slice( 1, -1 ) } )+ } );+ conversion.for( 'editingDowncast' ).elementToElement( {+ model: 'placeholder',+ view: ( item, { writer } ) => toWidget( createView( item, writer ), writer )+ } );+ conversion.for( 'dataDowncast' ).elementToElement( {+ model: 'placeholder',+ view: ( item, { writer } ) => createView( item, writer ) // NO toWidget in data+ } );+ function createView( item, writer ) {+ const span = writer.createContainerElement( 'span', { class: 'placeholder' } );+ writer.insert( writer.createPositionAt( span, 0 ), writer.createText( `{${ item.getAttribute( 'name' ) }}` ) );+ return span;+ }+ }+}+```++Command inserts the object and selects it:++```js+class PlaceholderCommand extends Command {+ execute( { value } ) {+ const selection = this.editor.model.document.selection;+ this.editor.model.change( writer => {+ const ph = writer.createElement( 'placeholder', { ...Object.fromEntries( selection.getAttributes() ), name: value } );+ this.editor.model.insertObject( ph, null, null, { setSelection: 'on' } );+ } );+ }+ refresh() {+ const sel = this.editor.model.document.selection;+ this.isEnabled = this.editor.model.schema.checkChild( sel.focus.parent, 'placeholder' );+ }+}+```++UI is typically a `createDropdown` list of types read from config (see `ui-and-localization.md`).++## Block widget recipe (box with nested editables)++Model:++```text+<simpleBox>+ <simpleBoxTitle></simpleBoxTitle>+ <simpleBoxDescription></simpleBoxDescription>+</simpleBox>+```++Schema — the box is a `$blockObject`; children are `isLimit` editables with controlled content:++```js+schema.register( 'simpleBox', { inheritAllFrom: '$blockObject', allowAttributes: [ 'secret' ] } );+schema.register( 'simpleBoxTitle', { isLimit: true, allowIn: 'simpleBox', allowContentOf: '$block' } );+schema.register( 'simpleBoxDescription', { isLimit: true, allowIn: 'simpleBox', allowContentOf: '$root' } );+schema.addChildCheck( ( ctx, child ) => {+ if ( ctx.endsWith( 'simpleBoxDescription' ) && child.name == 'simpleBox' ) return false; // no nesting+} );+```++Conversion — split editing vs. data downcast; `toWidget()` on the container,+`toWidgetEditable()` on each nested editable (built with `createEditableElement`). Upcast and+dataDowncast stay plain so `getData()` is clean:++```js+conversion.for( 'upcast' ).elementToElement( { model: 'simpleBox', view: { name: 'section', classes: 'simple-box' } } );+conversion.for( 'dataDowncast' ).elementToElement( { model: 'simpleBox', view: { name: 'section', classes: 'simple-box' } } );+conversion.for( 'editingDowncast' ).elementToElement( {+ model: 'simpleBox',+ view: ( el, { writer } ) => {+ const section = writer.createContainerElement( 'section', { class: 'simple-box' } );+ writer.setCustomProperty( 'simpleBox', true, section ); // tag for widget detection+ return toWidget( section, writer, { label: 'simple box widget' } );+ }+} );+// title / description:+conversion.for( 'editingDowncast' ).elementToElement( {+ model: 'simpleBoxTitle',+ view: ( el, { writer } ) => toWidgetEditable( writer.createEditableElement( 'h1', { class: 'simple-box-title' } ), writer )+} );+```++`toWidget()` makes content non-editable (sets `contentEditable=false` + classes like+`ck-widget`); `toWidgetEditable()` makes a nested region editable again. They react to hover,+selection, and focus.++Insert command uses `model.insertObject()` (splits paragraphs as needed) and builds the+structure with the writer. **A nested editable needs at least one paragraph** to be editable:++```js+function createSimpleBox( writer ) {+ const box = writer.createElement( 'simpleBox' );+ const title = writer.createElement( 'simpleBoxTitle' );+ const desc = writer.createElement( 'simpleBoxDescription' );+ writer.append( title, box );+ writer.append( desc, box );+ writer.appendElement( 'paragraph', desc ); // required, see ckeditor5#1464+ return box;+}+// refresh(): isEnabled = schema.findAllowedParent( selection.getFirstPosition(), 'simpleBox' ) !== null;+```++## Widget attributes (e.g. a boolean toggle)++Add to schema (`allowAttributes: [ 'secret' ]`), convert with the two-way+`attributeToAttribute` helper (maps a CSS class ↔ model attribute in both pipelines), and+expose a `SwitchButtonView` bound to a toggle command:++```js+conversion.attributeToAttribute( { model: 'secret', view: { name: 'section', key: 'class', value: 'secret' } } );+```++Boolean-attribute convention: set `true` to enable, **remove** the attribute to disable.++## Widget contextual toolbar++Use `WidgetToolbarRepository` (register in `afterInit()`, because it depends on runtime state).+Items come from config; `getRelatedElement` decides when the toolbar shows by finding the+widget view element (detect via the custom property + `isWidget()`):++```js+import { Plugin, WidgetToolbarRepository } from 'ckeditor5';++class SimpleBoxToolbar extends Plugin {+ static get requires() { return [ WidgetToolbarRepository ]; }+ afterInit() {+ const editor = this.editor;+ editor.plugins.get( WidgetToolbarRepository ).register( 'simpleBoxToolbar', {+ items: editor.config.get( 'simpleBox.toolbar' ), // e.g. [ 'secretSimpleBox' ]+ getRelatedElement: getClosestSimpleBoxWidget+ } );+ }+}+// getRelatedElement walks the view from selection looking for an element where+// !!viewElement.getCustomProperty('simpleBox') && isWidget(viewElement).+```++This is the same mechanism images/tables use to show their contextual toolbars.++## Useful widget utilities++`toWidget`, `toWidgetEditable`, `isWidget`, `viewToModelPositionOutsideModelElement`,+`WidgetToolbarRepository`, plus engine helpers `model.insertObject`, `model.insertContent`,+`writer.setCustomProperty`, `selection.getSelectedElement()`, `position.findAncestor(name)`.++If you attach custom DOM event handlers inside a widget, wrap them in a container with the+`data-cke-ignore-events` attribute so the editor's default handlers skip them. Advanced+behaviors are covered by the engine's "widget internals" deep dive. There are also tutorials+for **data from an external source** and **using React in a widget** if your widget needs+async content or framework components.