or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

content-features.mdcore.mdeditors.mdengine.mdindex.mdui.mdutils.md
tile.json

utils.mddocs/

Utilities

CKEditor 5 provides essential utilities for working with the editor, including collections, observables, DOM helpers, and development tools. These utilities form the foundation for many editor operations and plugin development.

Capabilities

Observable Collections

Observable collections with automatic change notifications and data binding support.

/**
 * Observable collection with automatic change notifications
 */
class Collection<T = any> {
  /**
   * Number of items in the collection
   */
  readonly length: number;

  /**
   * Adds an item to the collection
   * @param item - Item to add
   * @param index - Position to insert at (defaults to end)
   */
  add(item: T, index?: number): void;

  /**
   * Adds multiple items to the collection
   * @param items - Items to add
   * @param index - Position to start inserting at
   */
  addMany(items: Iterable<T>, index?: number): void;

  /**
   * Gets an item by index or identifier
   * @param idOrIndex - Item index or identifier
   * @returns Item or null if not found
   */
  get(idOrIndex: string | number): T | null;

  /**
   * Checks if the collection contains an item
   * @param itemOrId - Item or identifier to check
   * @returns True if item exists
   */
  has(itemOrId: T | string): boolean;

  /**
   * Gets the index of an item
   * @param itemOrId - Item or identifier
   * @returns Item index or -1 if not found
   */
  getIndex(itemOrId: T | string): number;

  /**
   * Removes an item from the collection
   * @param subject - Item, index, or identifier to remove
   * @returns Removed item
   */
  remove(subject: T | number | string): T;

  /**
   * Clears all items from the collection
   */
  clear(): void;

  /**
   * Maps collection items to a new array
   * @param callback - Mapping function
   * @param thisArg - Value to use as this
   * @returns Mapped array
   */
  map<U>(callback: (item: T, index: number) => U, thisArg?: any): U[];

  /**
   * Finds the first item matching a condition
   * @param callback - Search predicate
   * @param thisArg - Value to use as this
   * @returns Found item or undefined
   */
  find(callback: (item: T, index: number) => boolean, thisArg?: any): T | undefined;

  /**
   * Filters collection items
   * @param callback - Filter predicate
   * @param thisArg - Value to use as this
   * @returns Filtered array
   */
  filter(callback: (item: T, index: number) => boolean, thisArg?: any): T[];

  /**
   * Binds the collection to another observable
   * @param to - Target observable
   * @param filter - Filter function for items
   * @param callback - Transform function for items
   */
  bindTo<S>(
    to: Collection<S>,
    filter?: (item: S) => boolean,
    callback?: (item: S) => T
  ): void;

  /**
   * Iterator over collection items
   */
  [Symbol.iterator](): Iterator<T>;
}

Usage Example:

import { Collection } from 'ckeditor5';

// Create a collection
const items = new Collection();

// Add items
items.add('first');
items.add('second', 0); // Insert at beginning

// Listen for changes
items.on('add', (evt, item, index) => {
  console.log(`Added "${item}" at index ${index}`);
});

items.on('remove', (evt, item, index) => {
  console.log(`Removed "${item}" from index ${index}`);
});

// Work with items
const found = items.find(item => item.startsWith('f')); // 'first'
const mapped = items.map(item => item.toUpperCase()); // ['FIRST', 'SECOND']

Configuration Management

Type-safe configuration system with default values and nested property support.

/**
 * Configuration object with support for nested properties and defaults
 */
class Config {
  /**
   * Gets a configuration value
   * @param name - Configuration key (supports dot notation like 'foo.bar')
   * @returns Configuration value
   */
  get(name: string): unknown;

  /**
   * Sets a configuration value
   * @param name - Configuration key or object with multiple key-value pairs
   * @param value - Value to set (ignored if name is object)
   */
  set(name: string | object, value?: unknown): void;

  /**
   * Defines a configuration value with default
   * @param name - Configuration key or object with multiple defaults
   * @param value - Default value (ignored if name is object)
   */
  define(name: string | object, value?: unknown): void;

  /**
   * Iterator over configuration keys
   */
  names(): IterableIterator<string>;
}

Usage Example:

import { Config } from 'ckeditor5';

const config = new Config();

// Define defaults
config.define('toolbar.items', ['bold', 'italic']);
config.define('language', 'en');

// Set values
config.set('toolbar.shouldNotGroupWhenFull', true);
config.set({
  'image.styles': ['alignLeft', 'alignCenter'],
  'table.defaultHeadings.rows': 1
});

// Get values
const toolbarItems = config.get('toolbar.items'); // ['bold', 'italic']
const language = config.get('language'); // 'en'

Internationalization

Locale and translation utilities for multi-language support.

/**
 * Locale object providing internationalization functionality
 */
class Locale {
  /**
   * UI language code (e.g., 'en', 'de', 'fr')
   */
  readonly language: string;

  /**
   * Content language code
   */
  readonly contentLanguage: string;

  /**
   * UI language direction
   */
  readonly uiLanguageDirection: 'ltr' | 'rtl';

  /**
   * Content language direction
   */
  readonly contentLanguageDirection: 'ltr' | 'rtl';

  /**
   * Translates a message
   * @param message - Message to translate or message object
   * @param values - Values for message interpolation
   * @returns Translated message
   */
  t(message: string | LocaleTranslate, values?: string[]): string;
}

/**
 * Translation message interface
 */
interface LocaleTranslate {
  /**
   * Message string with placeholders
   */
  string: string;

  /**
   * Plural forms for different quantities
   */
  plural?: string;

  /**
   * Message ID for translation systems
   */
  id?: string;
}

/**
 * Adds a translation dictionary
 * @param language - Language code
 * @param translations - Translation dictionary
 */
function add(language: string, translations: Record<string, string | string[]>): void;

/**
 * Gets translation function for a language
 * @param language - Language code
 * @returns Translation function
 */
function _getTranslationFunction(language: string): (message: string, values?: string[]) => string;

Usage Example:

import { Locale, add } from 'ckeditor5';

// Add translations
add('de', {
  'Bold': 'Fett',
  'Italic': 'Kursiv',
  'Insert image': 'Bild einfügen'
});

// Create locale
const locale = new Locale('de');

// Translate messages
const boldLabel = locale.t('Bold'); // 'Fett'
const italicLabel = locale.t('Italic'); // 'Kursiv'

// Messages with placeholders
const withValues = locale.t('Inserted %0 items', ['5']); // 'Inserted 5 items'

Error Handling

Specialized error class with additional context and debugging information.

/**
 * CKEditor-specific error class with enhanced debugging information
 */
class CKEditorError extends Error {
  /**
   * Error context data
   */
  readonly context: Editor | null;

  /**
   * Additional error data
   */
  readonly data?: Record<string, any>;

  /**
   * Creates a CKEditor error
   * @param message - Error message
   * @param context - Editor context
   * @param data - Additional error data
   */
  constructor(
    message: string,
    context?: Editor | null,
    data?: Record<string, any>
  );

  /**
   * Checks if an error is a CKEditor error
   * @param error - Error to check
   * @returns True if CKEditor error
   */
  static isCKEditorError(error: Error): error is CKEditorError;

  /**
   * Rethrows an error as CKEditor error if needed
   * @param error - Error to rethrow
   * @param context - Editor context
   */
  static rethrowUnexpectedError(error: Error, context: Editor): never;
}

DOM Utilities

Helper functions for DOM manipulation and element handling.

/**
 * Gets the border widths of an element
 * @param element - DOM element
 * @returns Object with border widths
 */
function getBorderWidths(element: Element): {
  top: number;
  right: number;
  bottom: number;
  left: number;
};

/**
 * Gets the position of an element relative to another element or viewport
 * @param element - Target element
 * @param relativeToElement - Reference element (defaults to viewport)
 * @returns Position object
 */
function getPositionedAncestor(element: Element, relativeToElement?: Element): {
  top: number;
  left: number;
  right: number;
  bottom: number;
} | null;

/**
 * Checks if an element is visible in the viewport
 * @param element - Element to check
 * @param container - Container element (defaults to viewport)
 * @returns True if element is visible
 */
function isVisible(element: Element, container?: Element): boolean;

/**
 * Scrolls an element into view
 * @param element - Element to scroll to
 * @param options - Scroll options
 */
function scrollViewportToShowTarget(element: Element, options?: {
  target: Element;
  viewportOffset?: number;
}): void;

/**
 * Gets the window object for an element
 * @param element - DOM element
 * @returns Window object
 */
function getWindow(element: Element): Window;

/**
 * Checks if element is a text node
 * @param node - Node to check
 * @returns True if text node
 */
function isText(node: Node): node is Text;

/**
 * Checks if element is an element node
 * @param node - Node to check
 * @returns True if element node
 */
function isElement(node: Node): node is Element;

Keyboard Utilities

Utilities for handling keyboard events and key combinations.

/**
 * Gets the key code for a keyboard event
 * @param event - Keyboard event
 * @returns Key code
 */
function getCode(event: KeyboardEvent): number;

/**
 * Parses a keystroke string into key information
 * @param keystroke - Keystroke string (e.g., 'Ctrl+B')
 * @returns Key information object
 */
function parseKeystroke(keystroke: string): {
  keyCode: number;
  altKey?: boolean;
  ctrlKey?: boolean;
  shiftKey?: boolean;
  metaKey?: boolean;
};

/**
 * Gets a keystroke string from a keyboard event
 * @param event - Keyboard event
 * @returns Keystroke string
 */
function getKeystrokeText(event: KeyboardEvent): string;

/**
 * Checks if a keyboard event matches a keystroke
 * @param event - Keyboard event
 * @param keystroke - Keystroke to match
 * @returns True if matches
 */
function isKeystrokeMatched(event: KeyboardEvent, keystroke: string): boolean;

Environment Detection

Utilities for detecting browser and environment capabilities.

/**
 * Environment detection object
 */
const env: {
  /**
   * Whether running on macOS
   */
  readonly isMac: boolean;

  /**
   * Whether running on Windows
   */
  readonly isWindows: boolean;

  /**
   * Whether running on Linux
   */
  readonly isLinux: boolean;

  /**
   * Whether running on Android
   */
  readonly isAndroid: boolean;

  /**
   * Whether running on iOS
   */
  readonly isiOS: boolean;

  /**
   * Whether running on mobile device
   */
  readonly isMobile: boolean;

  /**
   * Whether running on tablet
   */
  readonly isTablet: boolean;

  /**
   * Whether running in Safari browser
   */
  readonly isSafari: boolean;

  /**
   * Whether running in Chrome browser
   */
  readonly isChrome: boolean;

  /**
   * Whether running in Firefox browser
   */
  readonly isFirefox: boolean;

  /**
   * Whether running in Edge browser
   */
  readonly isEdge: boolean;

  /**
   * Browser version
   */
  readonly version: number;

  /**
   * Whether browser supports sticky positioning
   */
  readonly isSticky: boolean;

  /**
   * Whether touch events are supported
   */
  readonly isTouchDevice: boolean;
};

Utility Functions

General-purpose utility functions for common operations.

/**
 * Generates a unique identifier
 * @returns Unique ID string
 */
function uid(): string;

/**
 * Converts any value to an array
 * @param value - Value to convert
 * @returns Array containing the value(s)
 */
function toArray<T>(value: T | T[]): T[];

/**
 * Creates a deep clone of an object
 * @param obj - Object to clone
 * @returns Cloned object
 */
function clone<T>(obj: T): T;

/**
 * Checks if two values are equal (deep comparison)
 * @param a - First value
 * @param b - Second value
 * @returns True if equal
 */
function isEqual(a: any, b: any): boolean;

/**
 * Delays execution by one animation frame
 * @returns Promise that resolves after animation frame
 */
function delay(): Promise<void>;

/**
 * Checks if a value is a plain object
 * @param value - Value to check
 * @returns True if plain object
 */
function isPlainObject(value: any): value is Record<string, any>;

/**
 * Merges objects deeply
 * @param target - Target object
 * @param sources - Source objects
 * @returns Merged object
 */
function merge<T>(target: T, ...sources: Partial<T>[]): T;

/**
 * Converts a string to camelCase
 * @param string - String to convert
 * @returns CamelCase string
 */
function toCamelCase(string: string): string;

/**
 * Converts a string to kebab-case
 * @param string - String to convert
 * @returns Kebab-case string
 */
function toKebabCase(string: string): string;

Usage Examples:

import { 
  uid, 
  toArray, 
  clone, 
  isEqual, 
  env, 
  parseKeystroke 
} from 'ckeditor5';

// Generate unique IDs
const id1 = uid(); // 'e1234567'
const id2 = uid(); // 'e2345678'

// Convert values to arrays
const single = toArray('hello'); // ['hello']
const multiple = toArray(['a', 'b']); // ['a', 'b']

// Deep cloning
const original = { a: { b: 1 } };
const cloned = clone(original);
cloned.a.b = 2; // original.a.b is still 1

// Environment detection
if (env.isMac) {
  console.log('Running on macOS');
}

if (env.isMobile) {
  console.log('Mobile device detected');
}

// Keyboard handling
const keyInfo = parseKeystroke('Ctrl+Shift+B');
// { keyCode: 66, ctrlKey: true, shiftKey: true }