#ctx.cy
// the core being laid out
ctx.cy: Corethe core being laid out
CoreExample
cy.layout({ impl: { run(ctx) { console.log(ctx.cy === cy); // true} } }).run();The supported extension seam is direct layout implementation.
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.
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.
ctx.cy// the core being laid out
ctx.cy: Corethe core being laid out
CoreExample
cy.layout({ impl: { run(ctx) { console.log(ctx.cy === cy); // true} } }).run();ctx.options// the resolved layout options (custom knobs included)
ctx.options: CustomLayoutOptionsthe resolved layout options (custom knobs included)
CustomLayoutOptionsExample
cy.layout({ impl: { run(ctx) { console.log(!!ctx.options.impl); // true} } }).run();ctx.eles// The elements included in this layout
ctx.eles: CollectionThe 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.
Collectionthe 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();ctx.nodes// The scope's node handles (lazy — see eles)
ctx.nodes: CollectionThe scope's node handles (lazy — see eles).
Collectionthe 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();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(): voidDrop 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.
voidExample
cy.layout({ impl: { run(ctx) { cy.add({ data: { id: 'd' } }); ctx.refreshScope(); console.log(ctx.nodes.length); // 4} } }).run();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.
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();ctx.edgeSlots()// The scope's edge slots
ctx.edgeSlots(): number[]The scope's edge slots.
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();ctx.positions()// The live position column (x,y interleaved by slot) — read it, write through setPositions
ctx.positions(): Float32ArrayThe live position column (x,y interleaved by slot) — read it, write through setPositions.
Float32Arraythe 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();ctx.endpoints()// The live edge endpoint column (source,target node slots)
ctx.endpoints(): Uint32ArrayThe live edge endpoint column (source,target node slots).
Uint32Arraythe 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();ctx.degreeOf(slot)// O(1) degree off the CSR adjacency
ctx.degreeOf(slot: number): numberO(1) degree off the CSR adjacency.
| Name | Description |
|---|---|
slot: number | a node slot, as handed out by |
numberits 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();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): LayoutNodeDimsThe 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.
| Name | Description |
|---|---|
slots: ArrayLike<number>?Default: this.nodeSlots() | the node slots to measure (default |
options: DimsOptions?Default: {} |
|
options| Name | Description |
|---|---|
includeLabels: boolean? | union the label box into each node's box (default true here; the
layouts pass their |
padding: number? | extra room around every node, split half per side (default 0) |
LayoutNodeDimsthe boxes, parallel to slots
Example
cy.layout({ impl: { run(ctx) { console.log(ctx.nodeDimensions().n); // 3} } }).run();ctx.boundingBox()// The scope's current bounding box, labels included
ctx.boundingBox(): ReturnType<Collection['boundingBox']>The scope's current bounding box, labels included.
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();ctx.width()// The viewport width in CSS px — what a layout sizing itself to the screen should use
ctx.width(): numberThe 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.
numberthe viewport width
Example
// Inside a custom layout, ctx is supplied by the library.cy.layout({ impl: { run(ctx) { console.log(ctx.width()); // 800} } }).run();ctx.height()// The viewport height in CSS px
ctx.height(): numberThe viewport height in CSS px.
numberthe viewport height
Example
// Inside a custom layout, ctx is supplied by the library.cy.layout({ impl: { run(ctx) { console.log(ctx.height()); // 600} } }).run();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): voidWrite 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.
| Name | Description |
|---|---|
slots: number[] | the node slots to move |
xy: number[] | Float32Array | the packed positions: |
voidExample
// 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')); // 40ctx.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(): ComponentsThe 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().
Componentsthe component assignment, ids in first-seen node order
Example
cy.layout({ impl: { run(ctx) { console.log(ctx.components().count); // 1} } }).run();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; }): voidSeparate 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).
| Name | Description |
|---|---|
spacing: number?Default: 40 | the gap between packed component boxes (default 40, the force layout's |
options: { bodies?: boolean; includeLabels?: boolean; positions?: Float32Array | Float64Array; }?Default: {} |
|
options| Name | Description |
|---|---|
bodies: boolean? | |
includeLabels: boolean? | |
positions: Float32Array | Float64Array? |
voidExample
cy.layout({ impl: { run(ctx) { ctx.packComponents(20); console.log(ctx.components().count); // 1} } }).run();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): voidThe 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).
| Name | Description |
|---|---|
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. |
overrides| Name | Description |
|---|---|
eles: unknown? | the elements to lay out (set automatically by |
fit: boolean? | |
padding: number? | |
boundingBox: BoundingBoxInput? | |
nodeDimensionsIncludeLabels: boolean? | include labels in the node dimensions a layout spaces by — default
|
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 |
voidExample
// 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')); // 40ctx.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): voidLand 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.
| Name | Description |
|---|---|
slots: number[] | the node slots the positions land on |
xy: ArrayLike<number> | the packed positions: |
overrides: LayoutBaseOptions?Default: {} | the impl's defaults, merged as |
overrides| Name | Description |
|---|---|
eles: unknown? | the elements to lay out (set automatically by |
fit: boolean? | |
padding: number? | |
boundingBox: BoundingBoxInput? | |
nodeDimensionsIncludeLabels: boolean? | include labels in the node dimensions a layout spaces by — default
|
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 |
voidExample
// 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')); // 40Custom layouts use the direct layout interface described here. There are no core, collection or renderer extension points.