Skip to content

Extensions

The supported extension seam is direct layout implementation.

#Direct extension contract

Pass a class or object with run(ctx) directly as impl. See direct layout implementations for the supported context, tracked position writes, lifecycle and the complete custom-layout example. There is no string registry or cytoscape.use() requirement.

The extension surface documented here is the layout implementation contract. A custom layout is passed directly to cy.layout({ impl }) or eles.layout({ impl }); it is a class or object with run(ctx). There is no global layout registry, extension string, or cytoscape.use() step. The returned wrapper adds run(), promise(), stop(), cancel() and reheat() to the implementation lifecycle. Layout lifecycle events are emitted on the core.

#Direct layout example

The following skeleton is a complete, intentionally small example:

class RowLayout {
run(ctx) {
const slots = ctx.nodeSlots();
const positions = new Float32Array(slots.length * 2);
for (let i = 0; i < slots.length; i++) {
positions[2 * i] = i * 80;
positions[2 * i + 1] = 0;
}
ctx.finish(slots, positions);
}
}
const handle = cy.layout({ impl: RowLayout, fit: true });
handle.run();
await handle.promise();

This example uses only the documented layout context. It intentionally does not reach through private store fields or hold slot numbers after a run. A subset layout receives the requested collection as its scope. Custom knobs are available on ctx.options; keep them serializable when callers need to persist layout settings. See the layout context reference for its methods and the layout handle guide for completion and cancellation.

#Layout context

#Scope

#ctx.cy

// the core being laid out
ctx.cy: Core

the core being laid out

Returns Core

Example

cy.layout({ impl: { run(ctx) {
console.log(ctx.cy === cy); // true
} } }).run();

Example graph and handle setup

#ctx.eles

// The elements included in this layout
ctx.eles: Collection

The elements included in this layout. For eles.layout(), this is the supplied collection; for cy.layout(), it is the whole graph. The collection is created on first access and cached for this run.

Returns Collection

the collection of elements being laid out

Example

// Inside a custom layout, ctx is supplied by the library.
cy.layout({ impl: { run(ctx) {
console.log(ctx.eles.map(ele => ele.id())); // ["a","b","c","ab","bc"]
} } }).run();

Example graph and handle setup

#ctx.nodes

// The scope's node handles (lazy — see eles)
ctx.nodes: Collection

The scope's node handles (lazy — see eles).

Returns Collection

the node subset of eles, unfiltered — unlike nodeSlots(), this keeps locked nodes and compound parents, so a layout iterating it must apply its own rules

Example

// Inside a custom layout, ctx is supplied by the library.
cy.layout({ impl: { run(ctx) {
console.log(ctx.nodes.map(ele => ele.id())); // ["a","b","c"]
} } }).run();

Example graph and handle setup

#ctx.refreshScope()

// Drop the cached scope so the next eles / nodes read the graph as it now is (118.3): a whole-graph scope is materialized once per run, and a force layout's infinite run rebuilds its sim on an add or remove
ctx.refreshScope(): void

Drop the cached scope so the next eles / nodes read the graph as it now is (118.3): a whole-graph scope is materialized once per run, and a force layout's infinite run rebuilds its sim on an add or remove. A subset scope (eles.layout()) is the caller's collection and stays what it was.

Returns void

Example

cy.layout({ impl: { run(ctx) {
cy.add({ data: { id: 'd' } });
ctx.refreshScope();
console.log(ctx.nodes.length); // 4
} } }).run();

Example graph and handle setup

#Layout context

The LayoutContext is a supported seam between an extension and the columnar core. It exposes a cy reference and resolved options; scope and node handles can be materialized lazily. For slot-native code, nodeSlots() provides the movable nodes, edgeSlots() the scoped edges, positions()/endpoints() the live columns, and degreeOf()/components()/nodeDimensions() supply common graph and geometry reads. Do not write directly into the live position column: that bypasses dirty tracking. Use setPositions() or compute a packed coordinate array and call finish().

#ctx.nodeSlots()

// The slots to lay out: the scope's unlocked leaves, plus a collapsed parent when no scoped node lies below it
ctx.nodeSlots(): number[]

The slots to lay out: the scope's unlocked leaves, plus a collapsed parent when no scoped node lies below it. Locked nodes hold their place; parents with scoped descendants derive from those descendants. Scope order.

Returns number[]

the slots to place, in exactly cy.nodes() order — which is load-bearing rather than incidental, since grid and circle assign positions by index, so a different enumeration order is a different layout

Example

// Inside a custom layout, ctx is supplied by the library.
cy.layout({ impl: { run(ctx) {
console.log(ctx.nodeSlots()); // [0, 1, 2]
} } }).run();

Example graph and handle setup

#ctx.edgeSlots()

// The scope's edge slots
ctx.edgeSlots(): number[]

The scope's edge slots.

Returns number[]

every live edge of the scope in cy.edges() order, with no filtering — the counterpart of nodeSlots(), which does filter

Example

// Inside a custom layout, ctx is supplied by the library.
cy.layout({ impl: { run(ctx) {
console.log(ctx.edgeSlots()); // [0, 1]
} } }).run();

Example graph and handle setup

#ctx.positions()

// The live position column (x,y interleaved by slot) — read it, write through setPositions
ctx.positions(): Float32Array

The live position column (x,y interleaved by slot) — read it, write through setPositions.

Returns Float32Array

the store's own column, not a copy: it changes underneath a held reference as positions are written, and writing into it directly bypasses the dirty tracking the renderer depends on

Example

cy.layout({ impl: { run(ctx) {
const b = ctx.nodeSlots()[1];
console.log(ctx.positions()[b * 2]); // 50
} } }).run();

Example graph and handle setup

#ctx.endpoints()

// The live edge endpoint column (source,target node slots)
ctx.endpoints(): Uint32Array

The live edge endpoint column (source,target node slots).

Returns Uint32Array

the store's own column, indexed by edge slot — node slots, not ids, so it pairs directly with positions() without a lookup

Example

cy.layout({ impl: { run(ctx) {
console.log(ctx.endpoints()[0]); // 0
} } }).run();

Example graph and handle setup

#ctx.degreeOf(slot)

// O(1) degree off the CSR adjacency
ctx.degreeOf(slot: number): number

O(1) degree off the CSR adjacency.

Parameters
NameDescription
slot: number

a node slot, as handed out by nodeSlots()

Returns number

its whole-graph degree, loops counted twice

Example

// Inside a custom layout, ctx is supplied by the library.
cy.layout({ impl: { run(ctx) {
const slots = ctx.nodeSlots();
console.log(ctx.degreeOf(slots[0])); // 1
} } }).run();

Example graph and handle setup

#ctx.nodeDimensions(slots?, options?)

// The layout boxes of the scope's nodes: slot-parallel node-local extents read off the size, border and label columns — the one reading every built-in spaces by
ctx.nodeDimensions(slots?: ArrayLike<number>, options?: DimsOptions): LayoutNodeDims

The layout boxes of the scope's nodes: slot-parallel node-local extents read off the size, border and label columns — the one reading every built-in spaces by. Labels are included when the run's nodeDimensionsIncludeLabels is true (default false), making the box asymmetric when a label hangs below the body; take max( -y1, y2) for a symmetric half. Headless label dimensions are estimates (16.4), exact once a renderer has laid the glyphs.

Parameters
NameDescription
slots: ArrayLike<number>?Default: this.nodeSlots()

the node slots to measure (default nodeSlots())

options: DimsOptions?Default: {}

includeLabels (default: the run's option, itself defaulting to false) and padding (split half per side)

Fields of options
NameDescription
includeLabels: boolean?

union the label box into each node's box (default true here; the layouts pass their nodeDimensionsIncludeLabels, default false)

padding: number?

extra room around every node, split half per side (default 0)

Returns LayoutNodeDims

the boxes, parallel to slots

Example

cy.layout({ impl: { run(ctx) {
console.log(ctx.nodeDimensions().n); // 3
} } }).run();

Example graph and handle setup

#Bounds

#ctx.boundingBox()

// The scope's current bounding box, labels included
ctx.boundingBox(): ReturnType<Collection['boundingBox']>

The scope's current bounding box, labels included.

Returns ReturnType<Collection['boundingBox']>

{ x1, y1, x2, y2, w, h } in model coordinates

Example

cy.layout({ impl: { run(ctx) {
console.log(ctx.boundingBox().w); // 130
} } }).run();

Example graph and handle setup

#ctx.width()

// The viewport width in CSS px — what a layout sizing itself to the screen should use
ctx.width(): number

The viewport width in CSS px — what a layout sizing itself to the screen should use. Headless instances report the configured headless width, so a layout still works without a DOM.

Returns number

the viewport width

Example

// Inside a custom layout, ctx is supplied by the library.
cy.layout({ impl: { run(ctx) {
console.log(ctx.width()); // 800
} } }).run();

Example graph and handle setup

#ctx.height()

// The viewport height in CSS px
ctx.height(): number

The viewport height in CSS px.

Returns number

the viewport height

Example

// Inside a custom layout, ctx is supplied by the library.
cy.layout({ impl: { run(ctx) {
console.log(ctx.height()); // 600
} } }).run();

Example graph and handle setup

#Writing positions and finishing

finish(slots, xy) applies the shared layout options and, when requested, routes the placement through the common animation finisher. It also owns layoutready/layoutstop for that path. A layout that writes positions directly still gets the wrapper's lifecycle when run() settles. run(ctx) may be asynchronous. A stop() method supports normal early stop; a cancel() method can abandon work so the wrapper restores the pre-run positions after the implementation settles. reheat() is used by live layouts whose fields can become active again.

#ctx.setPositions(slots, xy)

// Write model-space coordinates for the supplied node slots
ctx.setPositions(slots: number[], xy: number[] | Float32Array): void

Write model-space coordinates for the supplied node slots. For each index i, xy[i * 2] and xy[i * 2 + 1] are the x and y values for slots[i]. Use this helper to keep rendering and compound bounds up to date.

Parameters
NameDescription
slots: number[]

the node slots to move

xy: number[] | Float32Array

the packed positions: xy[i*2], xy[i*2+1] land on slots[i]

Returns void

Example

// Inside a custom layout, ctx is supplied by the library.
cy.layout({ impl: { run(ctx) {
const slots = Array.from(ctx.nodeSlots());
ctx.setPositions(slots, slots.flatMap((slot, i) => [i * 40, 0]));
} } }).run();
console.log(cy.getElementById('b').position('x')); // 40

Example graph and handle setup

#ctx.components()

// The scope's connected components over nodeSlots() ( factored out of packComponents for layouts that pack their own arrays): union-find over the scope's own edges — an edge with an endpoint outside the scope connects nothing here — indexed by position in nodeSlots()
ctx.components(): Components

The scope's connected components over nodeSlots() (* factored out of packComponents for layouts that pack their own arrays): union-find over the scope's own edges — an edge with an endpoint outside the scope connects nothing here — indexed by position in nodeSlots().

Returns Components

the component assignment, ids in first-seen node order

Example

cy.layout({ impl: { run(ctx) {
console.log(ctx.components().count); // 1
} } }).run();

Example graph and handle setup

#ctx.packComponents(spacing?, options?)

// Separate the scope's disconnected components: a one-call, translation-only post-pass
ctx.packComponents(spacing?: number, options?: { bodies?: boolean; includeLabels?: boolean; positions?: Float32Array | Float64Array; }): void

Separate the scope's disconnected components: a one-call, translation-only post-pass. Per-component bounding boxes at the current positions are shelf-packed largest-first with spacing between them, every member translated with its component, and the largest component's centre held fixed — the dominant structure keeps its place and the strays come to it.

The boxes are body boxes (nodeDimensions(), labels included by the run's option), so two singleton components end up spacing apart edge to edge rather than centre to centre; bodies: false restores the 87.1 point boxes.

Components are computed over the scope's own edges (an edge with an endpoint outside the scope connects nothing here), and only the nodeSlots() nodes move — a locked node neither moves nor holds its component in place, so a scope mixing locked and unlocked members of one component can separate them. The write lands through setPositions (one dirty span).

Parameters
NameDescription
spacing: number?Default: 40

the gap between packed component boxes (default 40, the force layout's componentSpacing default)

options: { bodies?: boolean; includeLabels?: boolean; positions?: Float32Array | Float64Array; }?Default: {}

bodies (default true) packs the nodes' boxes rather than their positions; includeLabels overrides the run's nodeDimensionsIncludeLabels for those boxes; positions packs that array (2n, parallel to nodeSlots()) in place instead of the store — for a layout that lands through finish() and must not write positions before the tween starts

Fields of options
NameDescription
bodies: boolean?
includeLabels: boolean?
positions: Float32Array | Float64Array?
Returns void

Example

cy.layout({ impl: { run(ctx) {
ctx.packComponents(20);
console.log(ctx.components().count); // 1
} } }).run();

Example graph and handle setup

#ctx.layoutPositions(fn, overrides?)

// The discrete layout finisher over the scope — spacingFactor, transform, animate (with the fit-at-final-positions viewport animation), fit/zoom/pan, and the layoutready/layoutstop events
ctx.layoutPositions(fn: (node: Collection, i: number) => Position, overrides?: LayoutBaseOptions): void

The discrete layout finisher over the scope — spacingFactor, transform, animate (with the fit-at-final-positions viewport animation), fit/zoom/pan, and the layoutready/layoutstop events. The wrapper's layoutstart covers the start (no double emit).

Parameters
NameDescription
fn: (node: Collection, i: number) => Position

called per scoped node with the node and its index, returning the model position to place it at

overrides: LayoutBaseOptions?Default: {}

an impl's own defaults, merged over the run's options Shared options apply consistently to built-in and custom layouts. ready and stop are never overridden — the wrapper's stop is what resolves promise()

Fields of overrides
NameDescription
eles: unknown?

the elements to lay out (set automatically by eles.layout()); defaults to the whole graph

fit: boolean?
padding: number?
boundingBox: BoundingBoxInput?
nodeDimensionsIncludeLabels: boolean?

include labels in the node dimensions a layout spaces by — default false. Every built-in's overlap avoidance reads the same boxes, so true keeps labels apart too. Headless label dimensions are estimates.

spacingFactor: number?
transform: (node: unknown, position: Position) => Position?

transform a computed position (e.g. to flip an axis)

animate: boolean?

whether to animate node positions into place

animationDuration: number?
animationEasing: string?
animateFilter: (node: unknown, i: number) => boolean?

which nodes animate (others jump); all by default

ready: () => void?

callback on layoutready

stop: () => void?

callback on layoutstop

zoom: number?

zoom to set when fit is false

pan: Position?

pan to set when fit is false

Returns void

Example

// Inside a custom layout, ctx is supplied by the library.
cy.layout({ impl: { run(ctx) {
ctx.layoutPositions((node, i) => ({ x: i * 40, y: 0 }), { fit: false });
} } }).run();
console.log(cy.getElementById('b').position('x')); // 40

Example graph and handle setup

#ctx.finish(slots, xy, overrides?)

// Land computed positions the way a built-in does: the finisher when the run asks for anything it owns — animate, animateFilter, transform, spacingFactor — and otherwise the bulk slot write followed by fit / zoom / pan
ctx.finish(slots: number[], xy: ArrayLike<number>, overrides?: LayoutBaseOptions): void

Land computed positions the way a built-in does: the finisher when the run asks for anything it owns — animate, animateFilter, transform, spacingFactor — and otherwise the bulk slot write followed by fit / zoom / pan. One rule for flow, force and any extension that computes into an array.

Parameters
NameDescription
slots: number[]

the node slots the positions land on

xy: ArrayLike<number>

the packed positions: xy[i*2], xy[i*2+1] for slots[i]

overrides: LayoutBaseOptions?Default: {}

the impl's defaults, merged as layoutPositions merges them

Fields of overrides
NameDescription
eles: unknown?

the elements to lay out (set automatically by eles.layout()); defaults to the whole graph

fit: boolean?
padding: number?
boundingBox: BoundingBoxInput?
nodeDimensionsIncludeLabels: boolean?

include labels in the node dimensions a layout spaces by — default false. Every built-in's overlap avoidance reads the same boxes, so true keeps labels apart too. Headless label dimensions are estimates.

spacingFactor: number?
transform: (node: unknown, position: Position) => Position?

transform a computed position (e.g. to flip an axis)

animate: boolean?

whether to animate node positions into place

animationDuration: number?
animationEasing: string?
animateFilter: (node: unknown, i: number) => boolean?

which nodes animate (others jump); all by default

ready: () => void?

callback on layoutready

stop: () => void?

callback on layoutstop

zoom: number?

zoom to set when fit is false

pan: Position?

pan to set when fit is false

Returns void

Example

// Inside a custom layout, ctx is supplied by the library.
cy.layout({ impl: { run(ctx) {
const slots = Array.from(ctx.nodeSlots());
ctx.finish(slots, slots.flatMap((slot, i) => [i * 40, 0]), { fit: false });
} } }).run();
console.log(cy.getElementById('b').position('x')); // 40

Example graph and handle setup

#Supported extension scope

Custom layouts use the direct layout interface described here. There are no core, collection or renderer extension points.

All guides · Alphabetical API index · Read continuously