or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

commands.mdconfiguration.mddata-management.mdeditor-lifecycle.mdindex.mdplugins.mduser-interface.md
tile.json

editor-lifecycle.mddocs/

Editor Lifecycle

Core editor creation, destruction, and state management operations for controlling the ClassicEditor instance lifecycle.

Capabilities

Editor Creation

Creates and initializes a new ClassicEditor instance with optional configuration.

/**
 * Creates a new ClassicEditor instance
 * @param sourceElementOrData - HTML element to replace or initial data string
 * @param config - Optional configuration to override defaults
 * @returns Promise resolving to editor instance
 */
static create(
  sourceElementOrData: HTMLElement | string, 
  config?: EditorConfig
): Promise<ClassicEditor>;

Usage Examples:

import ClassicEditor from "@ckeditor/ckeditor5-build-classic";

// Create from DOM element
const editor = await ClassicEditor.create(
  document.querySelector('#editor')
);

// Create with initial data
const editor = await ClassicEditor.create(
  '<p>Initial content</p>',
  {
    toolbar: {
      items: ['bold', 'italic', 'link']
    }
  }
);

// Create with extensive configuration
const editor = await ClassicEditor.create(
  document.querySelector('#editor'),
  {
    toolbar: {
      items: [
        'undo', 'redo', '|',
        'heading', '|', 
        'bold', 'italic', '|',
        'link', 'uploadImage', 'insertTable'
      ]
    },
    image: {
      toolbar: ['imageTextAlternative', 'toggleImageCaption']
    },
    table: {
      contentToolbar: ['tableColumn', 'tableRow', 'mergeTableCells']
    },
    language: 'en'
  }
);

Editor Destruction

Destroys the editor instance and cleans up all resources.

/**
 * Destroys the editor instance and cleans up resources
 * @returns Promise that resolves when destruction is complete
 */
destroy(): Promise<unknown>;

Usage Example:

// Clean destruction
await editor.destroy();

// With source element update
editor.config.set('updateSourceElementOnDestroy', true);
await editor.destroy(); // Updates original element with current content

Editor Focus

Sets focus to the editor's editable area.

/**
 * Moves focus to the editor's editable area
 */
focus(): void;

Usage Example:

// Focus the editor
editor.focus();

// Focus after other operations
editor.setData('<p>New content</p>');
editor.focus();

State Management

Monitor and query the current editor state.

/**
 * Current editor state
 */
readonly state: 'initializing' | 'ready' | 'destroyed';

/**
 * Unique identifier for this editor instance
 */
readonly id: string;

/**
 * Whether the editor is in read-only mode
 */
readonly isReadOnly: boolean;

Usage Examples:

// Check editor state
if (editor.state === 'ready') {
  editor.setData('<p>Editor is ready</p>');
}

// Get editor ID
console.log('Editor ID:', editor.id);

// Check read-only status
if (!editor.isReadOnly) {
  editor.execute('bold');
}

Read-only Mode Control

Enable and disable read-only mode with lock-based system.

/**
 * Enables read-only mode with a specific lock identifier
 * @param lockId - Unique identifier for this read-only lock
 */
enableReadOnlyMode(lockId: string | symbol): void;

/**
 * Disables read-only mode for a specific lock identifier
 * @param lockId - Lock identifier to remove
 */
disableReadOnlyMode(lockId: string | symbol): void;

Usage Examples:

// Enable read-only mode
const lockId = Symbol('maintenance-mode');
editor.enableReadOnlyMode(lockId);

// Disable read-only mode
editor.disableReadOnlyMode(lockId);

// Multiple locks example
const lock1 = 'user-permissions';
const lock2 = 'network-offline';

editor.enableReadOnlyMode(lock1);
editor.enableReadOnlyMode(lock2);

// Editor remains read-only until both locks are removed
editor.disableReadOnlyMode(lock1);
console.log(editor.isReadOnly); // true - lock2 still active

editor.disableReadOnlyMode(lock2);
console.log(editor.isReadOnly); // false - all locks removed

Source Element Access

Access the original HTML element the editor was created from.

/**
 * Original HTML element (if editor was created from an element)
 */
readonly sourceElement?: HTMLElement;

/**
 * Updates the source element with current editor data
 * @param data - Optional data to set, defaults to current editor data
 */
updateSourceElement(data?: string): void;

Usage Example:

// Access original element
if (editor.sourceElement) {
  console.log('Original element:', editor.sourceElement.tagName);
}

// Update source element
editor.updateSourceElement(); // Uses current editor data
editor.updateSourceElement('<p>Custom data</p>'); // Uses provided data

Static Properties

Built-in Plugins List

/**
 * Array of all plugin constructors included in this build
 */
static readonly builtinPlugins: Array<PluginConstructor>;

Default Configuration

/**
 * Default configuration object for this editor build
 */
static readonly defaultConfig: EditorConfig;

Editor Name

/**
 * Human-readable name identifying this editor type
 */
static readonly editorName: string; // 'ClassicEditor'

Usage Examples:

// Access built-in plugins
console.log('Built-in plugins:', ClassicEditor.builtinPlugins.length);

// View default configuration
console.log('Default toolbar:', ClassicEditor.defaultConfig.toolbar);

// Check editor type
console.log('Editor type:', ClassicEditor.editorName);

Event Handling

Lifecycle Events

/**
 * Listen for editor lifecycle events
 */
interface EditorEvents {
  'ready': () => void;
  'destroy': () => void;
  'change:state': (evt: EventInfo, propertyName: string, newValue: string, oldValue: string) => void;
  'change:isReadOnly': (evt: EventInfo, propertyName: string, newValue: boolean, oldValue: boolean) => void;
}

Usage Examples:

// Listen for ready event
editor.on('ready', () => {
  console.log('Editor is ready!');
});

// Listen for state changes
editor.on('change:state', (evt, propertyName, newValue, oldValue) => {
  console.log(`State changed from ${oldValue} to ${newValue}`);
});

// Listen for read-only mode changes
editor.on('change:isReadOnly', (evt, propertyName, newValue) => {
  console.log('Read-only mode:', newValue ? 'enabled' : 'disabled');
});

// Listen for destruction
editor.on('destroy', () => {
  console.log('Editor destroyed');
});

Event System APIs

ClassicEditor implements a comprehensive event system for handling editor events and managing event listeners.

Event Registration

Register event listeners with various options and behaviors.

/**
 * Registers an event listener
 * @param event - Event name to listen for
 * @param callback - Function to call when event fires
 * @param options - Optional configuration including priority
 */
on<TEvent extends BaseEvent>(
  event: string, 
  callback: (eventInfo: EventInfo, ...args: any[]) => void, 
  options?: { priority?: number }
): void;

/**
 * Registers a one-time event listener
 * @param event - Event name to listen for  
 * @param callback - Function to call when event fires (removed after first execution)
 * @param options - Optional configuration including priority
 */
once<TEvent extends BaseEvent>(
  event: string,
  callback: (eventInfo: EventInfo, ...args: any[]) => void,
  options?: { priority?: number }
): void;

/**
 * Removes event listeners
 * @param event - Event name to stop listening for
 * @param callback - Optional specific callback to remove (removes all if not specified)
 */
off(event: string, callback?: Function): void;

Usage Examples:

// Basic event listener
editor.on('ready', () => {
  console.log('Editor ready');
});

// Event listener with priority
editor.on('change:data', (evt) => {
  console.log('Data changed');
}, { priority: 'high' });

// One-time event listener
editor.once('focus', () => {
  console.log('First focus event');
});

// Remove specific listener
const listener = () => console.log('Test');
editor.on('test', listener);
editor.off('test', listener);

// Remove all listeners for an event
editor.off('change:data');

External Event Listening

Listen to events from other emitters and manage those connections.

/**
 * Listens to events from another emitter
 * @param emitter - Object to listen to
 * @param event - Event name to listen for
 * @param callback - Function to call when event fires
 * @param options - Optional configuration
 */
listenTo(
  emitter: Emitter, 
  event: string, 
  callback: Function, 
  options?: Object
): void;

/**
 * Stops listening to events from other emitters
 * @param emitter - Optional specific emitter to stop listening to
 * @param event - Optional specific event to stop listening for
 * @param callback - Optional specific callback to remove
 */
stopListening(emitter?: Emitter, event?: string, callback?: Function): void;

Usage Examples:

// Listen to document events
editor.listenTo(document, 'keydown', (evt, domEvent) => {
  if (domEvent.ctrlKey && domEvent.key === 's') {
    domEvent.preventDefault();
    // Save editor content
  }
});

// Listen to window events
editor.listenTo(window, 'beforeunload', () => {
  // Auto-save before page unload
});

// Stop listening to specific emitter
editor.stopListening(document);

// Stop all external listening
editor.stopListening();

Event Firing

Trigger custom events and control event propagation.

/**
 * Fires an event with optional data
 * @param eventOrInfo - Event name string or EventInfo object
 * @param args - Additional arguments to pass to listeners
 * @returns Return value from event listeners (if any)
 */
fire(eventOrInfo: string | EventInfo, ...args: any[]): unknown;

Usage Examples:

// Fire simple event
editor.fire('customEvent');

// Fire event with data
editor.fire('contentProcessed', { 
  processedAt: new Date(),
  wordCount: 1500 
});

// Fire event and use return value
const result = editor.fire('validateContent', content);
if (result === false) {
  console.log('Content validation failed');
}

Event Delegation

Delegate events from this editor to other emitters.

/**
 * Delegates specified events to another emitter
 * @param events - Event names to delegate
 */
delegate(...events: string[]): EmitterMixinDelegateChain;

/**
 * Stops delegating events to other emitters
 * @param event - Optional specific event to stop delegating
 * @param emitter - Optional specific emitter to stop delegating to
 */
stopDelegating(event?: string, emitter?: Emitter): void;

Usage Examples:

// Delegate events to another object
const eventTarget = new EventTarget();
editor.delegate('change:data', 'focus', 'blur').to(eventTarget);

// Stop delegating specific event
editor.stopDelegating('change:data');

// Stop all delegation
editor.stopDelegating();

Observable Properties

ClassicEditor supports observable properties with automatic change notifications and property binding.

Property Management

Set and manage observable properties with change notifications.

/**
 * Sets an observable property value
 * @param name - Property name to set
 * @param value - New property value
 */
set<K extends keyof this & string>(name: K, value: this[K]): void;

/**
 * Sets multiple observable properties at once
 * @param properties - Object with property names and values
 */
set(properties: Record<string, unknown>): void;

Usage Examples:

// Set single property
editor.set('customProperty', 'value');

// Set multiple properties
editor.set({
  theme: 'dark',
  autoSave: true,
  customData: { userId: 123 }
});

// Property changes fire events automatically
editor.on('change:customProperty', (evt, propertyName, newValue, oldValue) => {
  console.log(`${propertyName} changed from ${oldValue} to ${newValue}`);
});

Property Binding

Bind properties between objects for automatic synchronization.

/**
 * Creates property bindings to other observable objects
 * @param bindProperties - Array of property names to bind
 */
bind(bindProperties: string[]): BindChain;

/**
 * Removes property bindings
 * @param properties - Optional specific properties to unbind (unbinds all if not specified)
 */
unbind(properties?: string[]): void;

Usage Examples:

// Bind editor read-only state to external object
const appState = new Observable();
appState.set('editingDisabled', false);

editor.bind('isReadOnly').to(appState, 'editingDisabled');

// Now changing appState.editingDisabled automatically updates editor.isReadOnly
appState.set('editingDisabled', true);
console.log(editor.isReadOnly); // true

// Bind with transformation
editor.bind('customProperty').to(appState, 'theme', theme => `theme-${theme}`);

// Remove bindings
editor.unbind('isReadOnly');
editor.unbind(); // Remove all bindings

Method Decoration

Decorate methods to make them observable and fire events.

/**
 * Decorates a method to make it fire events before and after execution
 * @param methodName - Name of the method to decorate
 */
decorate(methodName: string): void;

Usage Examples:

// Decorate a custom method
editor.customMethod = function() {
  console.log('Custom method executed');
};

editor.decorate('customMethod');

// Now the method fires events
editor.on('set:customMethod', () => {
  console.log('Before customMethod execution');
});

editor.on('customMethod', () => {
  console.log('After customMethod execution');
});

editor.customMethod(); // Fires both events

Static Utility Classes

ClassicEditor provides access to utility classes for advanced use cases including watchdog functionality and context management.

Editor Watchdog

Access to the EditorWatchdog class for error recovery and editor restart functionality.

/**
 * EditorWatchdog class for automatic editor recovery
 */
static EditorWatchdog: typeof EditorWatchdog;

Usage Example:

// Access EditorWatchdog
const EditorWatchdog = ClassicEditor.EditorWatchdog;

// Create watchdog instance
const watchdog = new EditorWatchdog();

// Initialize with editor
await watchdog.create(document.querySelector('#editor'), {
  // Editor configuration
});

// Watchdog will automatically restart editor on crashes
watchdog.on('error', (error) => {
  console.log('Editor crashed, restarting...', error);
});

Context Watchdog

Access to the ContextWatchdog class for managing multiple editor instances.

/**
 * ContextWatchdog class for managing multiple editors
 */
static ContextWatchdog: typeof ContextWatchdog;

Usage Example:

// Access ContextWatchdog
const ContextWatchdog = ClassicEditor.ContextWatchdog;

// Create context watchdog for multiple editors
const watchdog = new ContextWatchdog();

// Add multiple editor items
await watchdog.add({
  editor1: {
    sourceElementOrData: document.querySelector('#editor1'),
    config: { /* config */ }
  },
  editor2: {
    sourceElementOrData: document.querySelector('#editor2'),
    config: { /* config */ }
  }
});

Context Class

Access to the Context class for shared editor context.

/**
 * Context class for shared editor functionality
 */
static Context: typeof Context;

Usage Example:

// Access Context class
const Context = ClassicEditor.Context;

// Create shared context
const context = await Context.create({
  // Shared configuration
});

// Use context with multiple editors
const editor1 = await ClassicEditor.create(document.querySelector('#editor1'), {
  context: context
});

const editor2 = await ClassicEditor.create(document.querySelector('#editor2'), {
  context: context
});