BodyCollection
This is a special ViewCollection dedicated to elements that are detached from the DOM structure of the editor, like floating panels, floating toolbars, dialogs, etc.
The body collection is available under the editor.ui.view.body property. Any plugin can add a view to this collection.
All views added to a body collection render in a dedicated DOM container (<div class="ck ck-body ...">...</div>). All body collection containers render in a common shared (<div class="ck-body-wrapper">...</div>) in the DOM to limit the pollution of the <body> element. The resulting DOM structure is as follows:
<body>
<!-- Content of the webpage... -->
<!-- The shared wrapper for all body collection containers. -->
<div class="ck-body-wrapper">
<!-- The container of the first body collection instance. -->
<div class="ck ck-body ...">
<!-- View elements belonging to the first body collection -->
</div>
<!-- The container of the second body collection instance. -->
<div class="ck ck-body ...">...</div>
<!-- More body collection containers for the rest of instances... -->
</div>
</body>Copy codeBy default, the editor.ui.view manages the life cycle of the editor.ui.view.body collection, attaching and detaching it when the editor gets created or destroyed.
Custom body collection instances
Even though most editor instances come with a built-in body collection (editor.ui.view.body), you can create your own instance of this class if you need to control their life cycle.
The life cycle of a custom body collection must be handled manually by the developer using the dedicated API:
- A body collection will render itself automatically in the DOM as soon as you call
attachToDom. - Calling
destroywill remove the collection from the DOM and destroy its views.
Note: The shared collection wrapper (<div class="ck-body-wrapper">...</div>) gets automatically removed from DOM when the last body collection is destroyed and does not require any special handling.
Properties
bodyCollectionContainer: HTMLElementreadonlymodule:ui/editorui/bodycollection~BodyCollection#bodyCollectionContainerThe element holding elements of the body collection. It is created on demand – the first time it is accessed or the collection is attached – and reused afterwards. Creating it does not attach it to the DOM (that happens in
attachToDom), so it is available for focus tracking and styling even while the collection is not mounted yet.first: T | nullreadonlyinheritedmodule:ui/editorui/bodycollection~BodyCollection#firstReturns the first item from the collection or null when collection is empty.
id?: stringinheritedmodule:ui/editorui/bodycollection~BodyCollection#idlast: T | nullreadonlyinheritedmodule:ui/editorui/bodycollection~BodyCollection#lastReturns the last item from the collection or null when collection is empty.
length: numberreadonlyinheritedmodule:ui/editorui/bodycollection~BodyCollection#lengthThe number of items available in the collection.
module:ui/editorui/bodycollection~BodyCollection#localeThe editor's locale instance. See the view locale property.
mountTarget: ShadowRoot | HTMLElement | undefinedreadonlymodule:ui/editorui/bodycollection~BodyCollection#mountTargetThe mount target (element or shadow root) the collection is currently attached to, or
undefinedbeforeattachToDomis called or afterunmountFromDomordestroy._bodyCollectionContainer?: HTMLElementprivatemodule:ui/editorui/bodycollection~BodyCollection#_bodyCollectionContainerThe element holding elements of the body collection.
_mountTarget?: ShadowRoot | HTMLElementprivatemodule:ui/editorui/bodycollection~BodyCollection#_mountTargetThe mount target the
_bodyCollectionContaineris currently attached to (through the shared wrapper): thedocument.bodyfor editors in the light DOM, or aShadowRoot(or a configured element) for editors living inside a shadow root. Tracked so the collection can be re-mounted into a different target and cleaned up from the right wrapper.
Static properties
_bodyWrappers: Map<ShadowRoot | HTMLElement, HTMLElement>privatestaticmodule:ui/editorui/bodycollection~BodyCollection._bodyWrappersThe shared wrapper elements that hold the
_bodyCollectionContainerelements, keyed by the mount target (the element or shadow root the wrapper is attached to – not the editor's editing root). Body collections attached to the same target (e.g. the same shadow root) share a single wrapper; body collections attached to different targets get separate wrappers.
Methods
constructor( locale, initialItems )module:ui/editorui/bodycollection~BodyCollection#constructorCreates a new instance of the
BodyCollection.Parameters
locale: LocaleThe editor's locale instance.
initialItems: Iterable<View<HTMLElement>>The initial items of the collection.
Defaults to
[]
Symbol.iterator() → Iterator<View<HTMLElement>>inheritedmodule:ui/editorui/bodycollection~BodyCollection#Symbol.iteratoradd( item, index? ) → thisinheritedmodule:ui/editorui/bodycollection~BodyCollection#addAdds an item into the collection.
If the item does not have an id, then it will be automatically generated and set on the item.
Parameters
item: Viewindex?: numberThe position of the item in the collection. The item is pushed to the collection when
indexnot specified.
Returns
this
Fires
addMany( items, index? ) → thisinheritedmodule:ui/editorui/bodycollection~BodyCollection#addManyAdds multiple items into the collection.
Any item not containing an id will get an automatically generated one.
Parameters
items: Iterable<View<HTMLElement>>index?: numberThe position of the insertion. Items will be appended if no
indexis specified.
Returns
this
Fires
attachToDom( target? ) → voidmodule:ui/editorui/bodycollection~BodyCollection#attachToDomAttaches the body collection to the DOM. You need to execute this method to render the content of the body collection.
By default the collection mounts in a shared wrapper under the
document.body. Pass atargetto mount it elsewhere – for example inside the shadow root an editor lives in, so that floating UI (balloons, dialogs, tooltips) can be styled within that boundary. Thetargetmay be a regular element or a shadow root, open or closed. Calling this method again with a differenttargetre-mounts the already rendered collection into the new location.Parameters
target?: ShadowRoot | HTMLElementThe element or shadow root to mount the body collection in. Defaults to
document.body.
Returns
void
bindTo( externalCollection ) → CollectionBindToChain<S, View<HTMLElement>>inheritedmodule:ui/editorui/bodycollection~BodyCollection#bindToBinds and synchronizes the collection with another one.
The binding can be a simple factory:
Copy codeclass FactoryClass { public label: string; constructor( data: { label: string } ) { this.label = data.label; } } const source = new Collection<{ label: string }>( { idProperty: 'label' } ); const target = new Collection<FactoryClass>(); target.bindTo( source ).as( FactoryClass ); source.add( { label: 'foo' } ); source.add( { label: 'bar' } ); console.log( target.length ); // 2 console.log( target.get( 1 ).label ); // 'bar' source.remove( 0 ); console.log( target.length ); // 1 console.log( target.get( 0 ).label ); // 'bar'or the factory driven by a custom callback:
Copy codeclass FooClass { public label: string; constructor( data: { label: string } ) { this.label = data.label; } } class BarClass { public label: string; constructor( data: { label: string } ) { this.label = data.label; } } const source = new Collection<{ label: string }>( { idProperty: 'label' } ); const target = new Collection<FooClass | BarClass>(); target.bindTo( source ).using( ( item ) => { if ( item.label == 'foo' ) { return new FooClass( item ); } else { return new BarClass( item ); } } ); source.add( { label: 'foo' } ); source.add( { label: 'bar' } ); console.log( target.length ); // 2 console.log( target.get( 0 ) instanceof FooClass ); // true console.log( target.get( 1 ) instanceof BarClass ); // trueor the factory out of property name:
Copy codeconst source = new Collection<{ nested: { value: string } }>(); const target = new Collection<{ value: string }>(); target.bindTo( source ).using( 'nested' ); source.add( { nested: { value: 'foo' } } ); source.add( { nested: { value: 'bar' } } ); console.log( target.length ); // 2 console.log( target.get( 0 ).value ); // 'foo' console.log( target.get( 1 ).value ); // 'bar'It's possible to skip specified items by returning null value:
Copy codeconst source = new Collection<{ hidden: boolean }>(); const target = new Collection<{ hidden: boolean }>(); target.bindTo( source ).using( item => { if ( item.hidden ) { return null; } return item; } ); source.add( { hidden: true } ); source.add( { hidden: false } ); console.log( source.length ); // 2 console.log( target.length ); // 1Note:
clearcan be used to break the binding.Type parameters
S: extends Record<string, any>The type of
externalCollectionelement.
Parameters
externalCollection: Collection<S>A collection to be bound.
Returns
CollectionBindToChain<S, View<HTMLElement>>The binding chain object.
clear() → voidinheritedmodule:ui/editorui/bodycollection~BodyCollection#clearRemoves all items from the collection and destroys the binding created using
bindTo.Returns
void
Fires
delegate( events ) → EmitterMixinDelegateChaininheritedmodule:ui/editorui/bodycollection~BodyCollection#delegateDelegates selected events coming from within views in the collection to any
Emitter.For the following views and collection:
Copy codeconst viewA = new View(); const viewB = new View(); const viewC = new View(); const views = parentView.createCollection(); views.delegate( 'eventX' ).to( viewB ); views.delegate( 'eventX', 'eventY' ).to( viewC ); views.add( viewA );the
eventXis delegated (fired by)viewBandviewCalong withcustomData:
Copy codeviewA.fire( 'eventX', customData );and
eventYis delegated (fired by)viewCalong withcustomData:
Copy codeviewA.fire( 'eventY', customData );See
delegate.Parameters
Returns
EmitterMixinDelegateChainObject with
toproperty, a function which accepts the destination of delegated events.
destroy() → voidmodule:ui/editorui/bodycollection~BodyCollection#destroyDestroys the body collection: destroys its views and removes their shared container from the DOM. Use this method when you do not need the body collection anymore. For a reversible removal that keeps the views so the collection can be attached again, use
unmountFromDominstead.Returns
void
module:ui/editorui/bodycollection~BodyCollection#filtermodule:ui/editorui/bodycollection~BodyCollection#findfire( eventOrInfo, args ) → GetEventInfo<TEvent>[ 'return' ]inheritedmodule:ui/editorui/bodycollection~BodyCollection#fireFires an event, executing all callbacks registered for it.
The first parameter passed to callbacks is an
EventInfoobject, followed by the optionalargsprovided in thefire()method call.Type parameters
Parameters
eventOrInfo: GetNameOrEventInfo<TEvent>The name of the event or
EventInfoobject if event is delegated.args: TEvent[ 'args' ]Additional arguments to be passed to the callbacks.
Returns
GetEventInfo<TEvent>[ 'return' ]By default the method returns
undefined. However, the return value can be changed by listeners through modification of theevt.return's property (the event info is the first param of every callback).
forEach( callback, ctx? ) → voidinheritedmodule:ui/editorui/bodycollection~BodyCollection#forEachPerforms the specified action for each item in the collection.
Parameters
callback: ( item: View, index: number ) => unknownctx?: anyContext in which the
callbackwill be called.
Returns
void
module:ui/editorui/bodycollection~BodyCollection#getGets an item by its ID or index.
Parameters
idOrIndex: string | numberThe item ID or index in the collection.
Returns
View<HTMLElement> | nullThe requested item or
nullif such item does not exist.
getIndex( itemOrId ) → numberinheritedmodule:ui/editorui/bodycollection~BodyCollection#getIndexGets an index of an item in the collection. When an item is not defined in the collection, the index will equal -1.
Parameters
itemOrId: string | View<HTMLElement>The item or its ID in the collection.
Returns
numberThe index of a given item.
has( itemOrId ) → booleaninheritedmodule:ui/editorui/bodycollection~BodyCollection#hasReturns a Boolean indicating whether the collection contains an item.
Parameters
itemOrId: string | View<HTMLElement>The item or its ID in the collection.
Returns
booleantrueif the collection contains the item,falseotherwise.
listenTo( emitter, event, callback, options? ) → voidinheritedmodule:ui/editorui/bodycollection~BodyCollection#listenTo:BASE_EMITTERRegisters a callback function to be executed when an event is fired in a specific (emitter) object.
Events can be grouped in namespaces using
:. When namespaced event is fired, it additionally fires all callbacks for that namespace.
Copy code// myEmitter.on( ... ) is a shorthand for myEmitter.listenTo( myEmitter, ... ). myEmitter.on( 'myGroup', genericCallback ); myEmitter.on( 'myGroup:myEvent', specificCallback ); // genericCallback is fired. myEmitter.fire( 'myGroup' ); // both genericCallback and specificCallback are fired. myEmitter.fire( 'myGroup:myEvent' ); // genericCallback is fired even though there are no callbacks for "foo". myEmitter.fire( 'myGroup:foo' );An event callback can stop the event and set the return value of the
firemethod.Type parameters
Parameters
emitter: EmitterThe object that fires the event.
event: TEvent[ 'name' ]The name of the event.
callback: GetCallback<TEvent>The function to be called on event.
options?: GetCallbackOptions<TEvent>Additional options.
Returns
void
map( callback, ctx? ) → Array<U>inheritedmodule:ui/editorui/bodycollection~BodyCollection#mapExecutes the callback for each item in the collection and composes an array or values returned by this callback.
Type parameters
UThe result type of the callback.
Parameters
callback: ( item: View, index: number ) => Uctx?: anyContext in which the
callbackwill be called.
Returns
Array<U>The result of mapping.
off( event, callback ) → voidinheritedmodule:ui/editorui/bodycollection~BodyCollection#offStops executing the callback on the given event. Shorthand for
this.stopListening( this, event, callback ).Parameters
event: stringThe name of the event.
callback: FunctionThe function to stop being called.
Returns
void
on( event, callback, options? ) → voidinheritedmodule:ui/editorui/bodycollection~BodyCollection#onRegisters a callback function to be executed when an event is fired.
Shorthand for
this.listenTo( this, event, callback, options )(it makes the emitter listen on itself).Type parameters
Parameters
event: TEvent[ 'name' ]The name of the event.
callback: GetCallback<TEvent>The function to be called on event.
options?: GetCallbackOptions<TEvent>Additional options.
Returns
void
once( event, callback, options? ) → voidinheritedmodule:ui/editorui/bodycollection~BodyCollection#onceRegisters a callback function to be executed on the next time the event is fired only. This is similar to calling
onfollowed byoffin the callback.Type parameters
Parameters
event: TEvent[ 'name' ]The name of the event.
callback: GetCallback<TEvent>The function to be called on event.
options?: GetCallbackOptions<TEvent>Additional options.
Returns
void
module:ui/editorui/bodycollection~BodyCollection#removeRemoves a child view from the collection. If the parent element of the collection has been set, the element of the view is also removed in DOM, reflecting the order of the collection.
See the
addmethod.Parameters
subject: string | number | View<HTMLElement>The view to remove, its id or index in the collection.
Returns
ViewThe removed view.
setParent( elementOrDocFragment ) → voidinheritedmodule:ui/editorui/bodycollection~BodyCollection#setParentstopDelegating( event?, emitter? ) → voidinheritedmodule:ui/editorui/bodycollection~BodyCollection#stopDelegatingStops delegating events. It can be used at different levels:
- To stop delegating all events.
- To stop delegating a specific event to all emitters.
- To stop delegating a specific event to a specific emitter.
Parameters
event?: stringThe name of the event to stop delegating. If omitted, stops it all delegations.
emitter?: Emitter(requires
event) The object to stop delegating a particular event to. If omitted, stops delegation ofeventto all emitters.
Returns
void
stopListening( emitter?, event?, callback? ) → voidinheritedmodule:ui/editorui/bodycollection~BodyCollection#stopListening:BASE_STOPStops listening for events. It can be used at different levels:
- To stop listening to a specific callback.
- To stop listening to a specific event.
- To stop listening to all events fired by a specific object.
- To stop listening to all events fired by all objects.
Parameters
emitter?: EmitterThe object to stop listening to. If omitted, stops it for all objects.
event?: string(Requires the
emitter) The name of the event to stop listening to. If omitted, stops it for all events fromemitter.callback?: Function(Requires the
event) The function to be removed from the call list for the givenevent.
Returns
void
syncMountTarget( target ) → voidmodule:ui/editorui/bodycollection~BodyCollection#syncMountTargetKeeps the collection mounted in the given target: attaches it there when the target differs from the current
mountTarget(seeattachToDom), unmounts it on anulltarget (seeunmountFromDom), and leaves the DOM untouched when the collection already sits in the target.Designed for repeated calls with a freshly resolved target (for example on every editor UI update, or with the result of
getOverlayMountRoot), as opposed toattachToDom, which re-appends the container even when the target did not change.Parameters
target: ShadowRoot | HTMLElement | nullThe element or shadow root to mount the body collection in, or
nullto unmount it.
Returns
void
unmountFromDom() → voidmodule:ui/editorui/bodycollection~BodyCollection#unmountFromDomRemoves the collection's container from the DOM without destroying its views, so it can be attached again later with
attachToDom– for example when the editor is temporarily disconnected from the document. For permanent teardown usedestroyinstead.Returns
void
_removeFromDom() → voidprivatemodule:ui/editorui/bodycollection~BodyCollection#_removeFromDomRemoves the collection's container (and the shared wrapper, if now empty) from the DOM, keeping the container instance so it can be re-attached.
Returns
void
Static methods
_getBodyWrapper( mountTarget ) → HTMLElementprivatestaticmodule:ui/editorui/bodycollection~BodyCollection._getBodyWrapperReturns the shared wrapper element for the given mount target, creating (and attaching) it if it does not exist yet or is no longer contained by the target. Body collections sharing a target share a wrapper.
The staleness check asks whether the target still contains the wrapper rather than testing
isConnected, so a wrapper stays reused when the target itself is legitimately detached from the document (for example a configuredui.overlayContainerthat is inserted later). TestingisConnectedthere would treat the still-attached wrapper as stale and build a duplicate wrapper for every body collection sharing that target.Parameters
mountTarget: ShadowRoot | HTMLElementThe element or shadow root the wrapper is (or should be) attached to.
Returns
HTMLElement
_removeBodyWrapperIfEmpty( mountTarget? ) → voidprivatestaticmodule:ui/editorui/bodycollection~BodyCollection._removeBodyWrapperIfEmptyRemoves the shared wrapper for the given mount target (and forgets it) once it holds no more body collections.
Parameters
mountTarget?: ShadowRoot | HTMLElementThe element or shadow root the wrapper is attached to.
Returns
void
Events
add( eventInfo, item, index )inheritedmodule:ui/editorui/bodycollection~BodyCollection#event:addFired when an item is added to the collection.
Parameters
eventInfo: EventInfoAn object containing information about the fired event.
item: TThe added item.
index: numberAn index where the addition occurred.
change( eventInfo, data )inheritedmodule:ui/editorui/bodycollection~BodyCollection#event:changeFired when the collection was changed due to adding or removing items.
Parameters
eventInfo: EventInfoAn object containing information about the fired event.
data: CollectionChangeEventData<T>Changed items.
remount( eventInfo )module:ui/editorui/bodycollection~BodyCollection#event:remountFired when the collection's mount target changes – it is attached, re-attached to a different target, or unmounted.
Parameters
eventInfo: EventInfoAn object containing information about the fired event.
remove( eventInfo, item, index )inheritedmodule:ui/editorui/bodycollection~BodyCollection#event:removeFired when an item is removed from the collection.
Parameters
eventInfo: EventInfoAn object containing information about the fired event.
item: TThe removed item.
index: numberIndex from which item was removed.